branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import sys
import pytest
try:
import unittest2 as unittest
except ImportError:
import unittest
import ast
from astmonkey import visitors, transformers, utils
class TestGraphNodeVisitor(object):
@pytest.fixture
def visitor(self):
return visitors.GraphNodeVisitor()
def test_has_edge(self, visitor):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('x = 1'))
visitor.visit(node)
assert visitor.graph.get_edge(str(node), str(node.body[0]))
def test_does_not_have_edge(self, visitor):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('x = 1'))
visitor.visit(node)
assert not visitor.graph.get_edge(str(node), str(node.body[0].value))
def test_node_label(self, visitor):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('x = 1'))
visitor.visit(node)
dot_node = visitor.graph.get_node(str(node.body[0].value))[0]
if sys.version_info >= (3, 8):
assert dot_node.get_label() == 'ast.Constant(value=1, kind=None)'
else:
assert dot_node.get_label() == 'ast.Num(n=1)'
def test_edge_label(self, visitor):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('x = 1'))
visitor.visit(node)
dot_edge = visitor.graph.get_edge(str(node), str(node.body[0]))[0]
assert dot_edge.get_label() == 'body[0]'
def test_multi_parents_node_label(self, visitor):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('x = 1\nx = 2'))
visitor.visit(node)
dot_node = visitor.graph.get_node(str(node.body[0].targets[0]))[0]
assert dot_node.get_label() == "ast.Name(id='x', ctx=ast.Store())"
class TestSourceGeneratorNodeVisitor(object):
EOL = '\n'
SIMPLE_ASSIGN = 'x = 1'
PASS = 'pass'
INDENT = ' ' * 4
CLASS_DEF = 'class Sample:'
EMPTY_CLASS = CLASS_DEF + EOL + INDENT + PASS
FUNC_DEF = 'def f():'
EMPTY_FUNC = FUNC_DEF + EOL + INDENT + PASS
SINGLE_LINE_DOCSTRING = "''' This is a single line docstring.'''"
MULTI_LINE_DOCSTRING = "''' This is a multi line docstring." + EOL + EOL + 'Further description...' + EOL + "'''"
LINE_CONT = '\\'
roundtrip_testdata = [
# assign
SIMPLE_ASSIGN,
'(x, y) = z',
'x += 1',
'a = b = c',
'(a, b) = enumerate(c)',
SIMPLE_ASSIGN + EOL + SIMPLE_ASSIGN,
SIMPLE_ASSIGN + EOL + EOL + SIMPLE_ASSIGN,
EOL + SIMPLE_ASSIGN,
EOL + EOL + SIMPLE_ASSIGN,
'x = \'string assign\'',
# class definition
EMPTY_CLASS,
EOL + EMPTY_CLASS,
CLASS_DEF + EOL + INDENT + EOL + INDENT + PASS,
EMPTY_FUNC,
EOL + EMPTY_FUNC,
CLASS_DEF + EOL + INDENT + FUNC_DEF + EOL + INDENT + INDENT + SIMPLE_ASSIGN,
'class A(B, C):' + EOL + INDENT + PASS,
# function definition
FUNC_DEF + EOL + INDENT + PASS,
'def f(x, y=1, *args, **kwargs):' + EOL + INDENT + PASS,
'def f(a, b=\'c\', *args, **kwargs):' + EOL + INDENT + PASS,
FUNC_DEF + EOL + INDENT + 'return',
FUNC_DEF + EOL + INDENT + 'return 5',
FUNC_DEF + EOL + INDENT + 'return x == ' + LINE_CONT + EOL + INDENT + INDENT + 'x',
# yield
FUNC_DEF + EOL + INDENT + 'yield',
FUNC_DEF + EOL + INDENT + 'yield 5',
# importing
'import x',
'import x as y',
'import x.y.z',
'import x, y, z',
'from x import y',
'from x import y, z, q',
'from x import y as z',
'from x import y as z, q as p',
'from . import x',
'from .. import x',
'from .y import x',
# operators
'(x and y)',
'x < y',
'not x',
'x + y',
'(x + y) / z',
'-((-x) // y)',
'(-1) ** x',
'-(1 ** x)',
'0 + 0j',
'(-1j) ** x',
# if
'if x:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + 'elif y:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + 'elif y:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + 'elif y:' + EOL + INDENT + PASS + EOL + 'elif z:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + 'elif y:' + EOL + INDENT + PASS + EOL + 'elif z:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + 'if y:' + EOL + INDENT + INDENT + PASS + EOL + INDENT + SIMPLE_ASSIGN,
'x if y else z',
'y * (z if z > 1 else 1)',
'if x < y == z < x:' + EOL + INDENT + PASS,
'if (x < y) == (z < x):' + EOL + INDENT + PASS,
'if not False:' + EOL + INDENT + PASS,
'if x:' + EOL + INDENT + PASS + EOL + EOL + 'elif x:' + EOL + INDENT + PASS, # Double EOL
# while
'while not (i != 1):' + EOL + INDENT + SIMPLE_ASSIGN,
'while True:' + EOL + INDENT + 'if True:' + EOL + INDENT + INDENT + 'continue',
'while True:' + EOL + INDENT + 'if True:' + EOL + INDENT + INDENT + 'break',
SIMPLE_ASSIGN + EOL + EOL + 'while False:' + EOL + INDENT + PASS,
# for
'for x in y:' + EOL + INDENT + 'break',
'for x in y:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + PASS,
# try ... except
'try:' + EOL + INDENT + PASS + EOL + 'except Y:' + EOL + INDENT + PASS,
'try:' + EOL + INDENT + PASS + EOL + EOL + EOL + 'except Y:' + EOL + INDENT + PASS,
'try:' + EOL + INDENT + PASS + EOL + 'except Y as y:' + EOL + INDENT + PASS,
'try:' + EOL + INDENT + PASS + EOL + 'finally:' + EOL + INDENT + PASS,
'try:' + EOL + INDENT + PASS + EOL + 'except Y:' + EOL + INDENT + PASS + EOL + 'except Z:' + EOL + INDENT + PASS,
'try:' + EOL + INDENT + PASS + EOL + 'except Y:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + PASS,
# del
'del x',
'del x, y, z',
# with
'with x:' + EOL + INDENT + 'pass',
'with x as y:' + EOL + INDENT + 'pass',
# assert
'assert True, \'message\'',
'assert True',
# lambda
'lambda x: (x)',
'lambda x: (((x ** 2) + (2 * x)) - 5)',
'lambda: (1)',
'(lambda: (yield))()',
# subscript
'x[y]',
# slice
'x[y:z:q]',
'x[1:2,3:4]',
'x[:2,:2]',
'x[1:2]',
'x[::2]',
# global
'global x',
# raise
'raise Exception()',
# format
'\'a %s\' % \'b\'',
'\'a {}\'.format(\'b\')',
'(\'%f;%f\' % (point.x, point.y)).encode(\'ascii\')',
# decorator
'@x(y)' + EOL + EMPTY_FUNC,
# call
'f(a)',
'f(a, b)',
'f(b=\'c\')',
'f(*args)',
'f(**kwargs)',
'f(a, b=1, *args, **kwargs)',
# list
'[]',
'[1, 2, 3]',
# dict
'{}',
'{a: 3, b: \'c\'}',
# list comprehension
'x = [y.value for y in z if y.value >= 3]',
# generator expression
'(x for x in y if x)',
# tuple
'()',
'(1,)',
'(1, 2)',
# attribute
'x.y',
# ellipsis
'x[...]',
# str
"x = 'y'",
"x = '\"'",
'x = "\'"',
# num
'1',
# docstring
SINGLE_LINE_DOCSTRING,
MULTI_LINE_DOCSTRING,
CLASS_DEF + EOL + INDENT + MULTI_LINE_DOCSTRING,
FUNC_DEF + EOL + INDENT + MULTI_LINE_DOCSTRING,
SIMPLE_ASSIGN + EOL + MULTI_LINE_DOCSTRING,
MULTI_LINE_DOCSTRING + EOL + MULTI_LINE_DOCSTRING,
# line continuation
'x = ' + LINE_CONT + EOL + INDENT + 'y = 5',
'raise TypeError(' + EOL + INDENT + '\'data argument must be a bytes-like object, not str\')'
]
if utils.check_version(from_inclusive=(2, 7)):
roundtrip_testdata += [
# set
'{1, 2}',
# set comprehension
'{x for x in y if x}',
# dict comprehension
'x = {y: z for (y, z) in a}',
]
if utils.check_version(to_exclusive=(3, 0)):
roundtrip_testdata += [
# print
'print \'a\'',
'print \'a\',',
'print >> sys.stderr, \'a\'',
# raise with msg and tb
'raise x, y, z',
# repr
'`a`',
]
if utils.check_version(from_inclusive=(3, 0)):
roundtrip_testdata += [
# nonlocal
'nonlocal x',
# starred
'*x = y',
# raise from
'raise Exception() from exc',
# byte string
'b\'byte_string\'',
# unicode string
'x = \'äöüß\'',
# metaclass
'class X(Y, metaclass=Z):' + EOL + INDENT + 'pass',
# type hinting
'def f(a: str) -> str:' + EOL + INDENT + PASS,
"def f(x: 'x' = 0):" + EOL + INDENT + PASS,
"def f(x: 'x' = 0, *args: 'args', y: 'y' = 1, **kwargs: 'kwargs') -> 'return':" + EOL + INDENT + PASS,
# extended iterable unpacking
'(x, *y) = z',
'[x, *y, x] = z',
# kwonly arguments
'def f(*, x):' + EOL + INDENT + PASS,
'def f(*, x: int = 5):' + EOL + INDENT + PASS,
'def f(x, *, y):' + EOL + INDENT + PASS,
# function definition
'def f(self, *args, x=None, **kwargs):' + EOL + INDENT + PASS,
]
if utils.check_version(from_inclusive=(3, 3)):
roundtrip_testdata += [
# with multiple
'with x, y:' + EOL + INDENT + 'pass',
# yield from
FUNC_DEF + EOL + INDENT + 'yield from x',
]
if utils.check_version(from_inclusive=(3, 5)):
roundtrip_testdata += [
# unpack into dict
'{**kwargs}',
# async/await
'async ' + FUNC_DEF + EOL + INDENT + PASS,
'async ' + FUNC_DEF + EOL + INDENT + 'async for line in reader:' + EOL + INDENT + INDENT + PASS,
'async ' + FUNC_DEF + EOL + INDENT + 'await asyncio.sleep(1)',
'async ' + FUNC_DEF + EOL + INDENT + 'async with x:' + EOL + INDENT + INDENT + PASS,
# matrix multiplication operator
'x @ y',
]
if utils.check_version(from_inclusive=(3, 6)):
roundtrip_testdata += [
# f-strings
'f\'He said his name is {name}.\'',
"f'{x!r}'",
"f'{x!s}'",
"f'{x!a}'",
]
if utils.check_version(from_inclusive=(3, 8)):
roundtrip_testdata += [
# assignment expressions
'if n := len(a) > 10:' + EOL + INDENT + PASS,
# positional-only parameters
'def f(a, /, b, *, c):' + EOL + INDENT + PASS,
# positional-only parameters with defaults
'def f(a=1, /, b=2, *, c=3):' + EOL + INDENT + PASS,
]
# add additional tests for semantic testing
semantic_testdata = list(roundtrip_testdata)
semantic_testdata += [
'x = ' + MULTI_LINE_DOCSTRING,
'b\'\'\'byte string' + EOL + 'next line' + EOL + '\'\'\'',
r'r"""\a\b\f\n\r\t\v"""',
'if x:' + EOL + INDENT + PASS + EOL + 'else:' + EOL + INDENT + 'if x:' + EOL + INDENT + INDENT + PASS,
]
if utils.check_version(from_inclusive=(3, 6)):
semantic_testdata += [
'raise TypeError(' + EOL + INDENT + 'f"data argument must be a bytes-like object, "' + EOL + INDENT +
'f"not {type(data).__name__}")',
'f"a\'b"',
]
@pytest.mark.parametrize("source", roundtrip_testdata)
def test_codegen_roundtrip(self, source):
"""Check if converting code into AST and converting it back to code yields the same code."""
node = ast.parse(source)
generated = visitors.to_source(node)
assert source == generated
@pytest.mark.parametrize("source", semantic_testdata)
def test_codegen_semantic_preservation(self, source):
"""Check if converting code into AST, converting it back to code
and converting it into an AST again yields the same AST.
"""
node = ast.parse(source)
generated = visitors.to_source(node)
node_from_generated = ast.parse(generated)
assert ast.dump(node) == ast.dump(node_from_generated)
def test_fix_linen_umbers(self):
"""Check if an AST with wrong lineno attribute is corrected in the process."""
node = ast.parse('x = 1' + self.EOL + 'y = 2')
# set both line numbers to 1
node.body[1].lineno = 1
visitors.to_source(node)
assert node.body[1].lineno == 2
<file_sep># -*- coding: utf-8 -*-
from setuptools import setup
import astmonkey
with open('README.rst') as f:
long_description = f.read()
setup(
name='astmonkey',
version=astmonkey.__version__,
description='astmonkey is a set of tools to play with Python AST.',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/mutpy/astmonkey',
packages=['astmonkey'],
install_requires=['pydot'],
long_description=long_description,
classifiers=[
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: Apache Software License'
]
)
<file_sep>import ast
from astmonkey import utils, transformers
node = ast.parse('def foo(x):\n\t"""doc"""')
node = transformers.ParentChildNodeTransformer().visit(node)
docstring_node = node.body[0].body[0].value
assert(not utils.is_docstring(node))
assert(utils.is_docstring(docstring_node))
<file_sep>=========
astmonkey
=========
|Python Versions| |Build Status| |Coverage Status| |Code Climate|
``astmonkey`` is a set of tools to play with Python AST.
Installation
------------
You can install ``astmonkey`` from PyPI:
::
$ pip install astmonkey
If you want to have latest changes you should clone this repository and use ``setup.py``:
::
$ git clone https://github.com/mutpy/astmonkey.git
$ cd astmonkey
$ python setup.py install
visitors.SourceGeneratorNodeVisitor
-----------------------------------
This visitor allow AST to Python code generation. It was originally written by
<NAME> (2008, license BSD) as ``codegen.py`` module. ``astmonkey`` version
fixes few bugs and it has good code coverage.
Example usage:
::
import ast
from astmonkey import visitors
code = 'x = (y + 1)'
node = ast.parse(code)
generated_code = visitors.to_source(node)
assert(code == generated_code)
transformers.ParentChildNodeTransformer
---------------------------------------
This transformer adds few fields to every node in AST:
* ``parent`` - link to parent node,
* ``parents`` - list of all parents (only ``ast.expr_context`` nodes have more than one parent node, in other causes this is one-element list),
* ``parent_field`` - name of field in parent node including child node,
* ``parent_field_index`` - parent node field index, if it is a list.
* ``children`` - link to children nodes.
Example usage:
::
import ast
from astmonkey import transformers
node = ast.parse('x = 1')
node = transformers.ParentChildNodeTransformer().visit(node)
assert(node == node.body[0].parent)
assert(node.body[0].parent_field == 'body')
assert(node.body[0].parent_field_index == 0)
assert(node.body[0] in node.children)
visitors.GraphNodeVisitor
-------------------------
This visitor creates Graphviz graph from Python AST (via ``pydot``). Before you use
``GraphNodeVisitor`` you need to add parents links to tree nodes (with
``ParentChildNodeTransformer``).
Example usage:
::
import ast
from astmonkey import visitors, transformers
node = ast.parse('def foo(x):\n\treturn x + 1')
node = transformers.ParentChildNodeTransformer().visit(node)
visitor = visitors.GraphNodeVisitor()
visitor.visit(node)
visitor.graph.write_png('graph.png')
Produced ``graph.png`` (you need to have installed ``graphviz`` binaries if you want generate
images):
.. image:: examples/graph.png
utils.is_docstring
------------------
This routine checks if target node is a docstring. Before you use
``is_docstring`` you need to add parents links to tree nodes (with
``ParentChildNodeTransformer``).
Example usage:
::
import ast
from astmonkey import utils, transformers
node = ast.parse('def foo(x):\n\t"""doc"""')
node = transformers.ParentChildNodeTransformer().visit(node)
docstring_node = node.body[0].body[0].value
assert(not utils.is_docstring(node))
assert(utils.is_docstring(docstring_node))
License
-------
Copyright [2013] [<NAME>]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/astmonkey.svg
:target: https://github.com/mutpy/astmonkey
.. |Build Status| image:: https://travis-ci.org/mutpy/astmonkey.png
:target: https://travis-ci.org/mutpy/astmonkey
.. |Coverage Status| image:: https://coveralls.io/repos/github/mutpy/astmonkey/badge.svg?branch=master
:target: https://coveralls.io/github/mutpy/astmonkey?branch=master
.. |Code Climate| image:: https://codeclimate.com/github/mutpy/astmonkey/badges/gpa.svg
:target: https://codeclimate.com/github/mutpy/astmonkey
<file_sep>import ast
import unittest
from astmonkey import utils, transformers
class TestIsDocstring(unittest.TestCase):
def test_non_docstring_node(self):
node = transformers.ParentChildNodeTransformer().visit(ast.parse(''))
assert not utils.is_docstring(node)
def test_module_docstring_node(self):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('"""doc"""'))
assert utils.is_docstring(node.body[0].value)
def test_function_docstring_node(self):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('def foo():\n\t"""doc"""'))
assert utils.is_docstring(node.body[0].body[0].value)
def test_class_docstring_node(self):
node = transformers.ParentChildNodeTransformer().visit(ast.parse('class X:\n\t"""doc"""'))
assert utils.is_docstring(node.body[0].body[0].value)
<file_sep>import pytest
try:
import unittest2 as unittest
except ImportError:
import unittest
import ast
from astmonkey import transformers
class TestParentChildNodeTransformer(object):
@pytest.fixture
def transformer(self):
return transformers.ParentChildNodeTransformer()
def test_module_node(self, transformer):
node = ast.parse('')
transformed_node = transformer.visit(node)
assert transformed_node.parent is None
assert transformed_node.children == []
def test_non_module_node(self, transformer):
node = ast.parse('x = 1')
transformed_node = transformer.visit(node)
assign_node = transformed_node.body[0]
assert transformed_node == assign_node.parent
assert assign_node.parent_field == 'body'
assert assign_node.parent_field_index == 0
assert transformed_node.children == [assign_node]
assert len(assign_node.children) == 2
def test_expr_context_nodes(self, transformer):
node = ast.parse('x = 1\nx = 2')
transformer.visit(node)
ctx_node = node.body[0].targets[0].ctx
first_name_node = node.body[0].targets[0]
second_name_node = node.body[1].targets[0]
assert first_name_node in ctx_node.parents
assert second_name_node in ctx_node.parents
assert ctx_node in first_name_node.children
assert ctx_node in second_name_node.children
<file_sep>#!/usr/bin/env python
"""This example was kindly provided by https://github.com/oozie.
This script draws the AST of a Python module as graph with simple points as nodes.
Astmonkey's GraphNodeVisitor is subclassed for custom representation of the AST.
Usage: python3 edge-graph-node-visitor.py some_file.py
"""
import ast
import os
import sys
import pydot
from astmonkey import transformers
from astmonkey.visitors import GraphNodeVisitor
class EdgeGraphNodeVisitor(GraphNodeVisitor):
"""Simple point-edge-point graphviz representation of the AST."""
def __init__(self):
super(self.__class__, self).__init__()
self.graph.set_node_defaults(shape='point')
def _dot_graph_kwargs(self):
return {}
def _dot_node_kwargs(self, node):
return {}
def _dot_edge(self, node):
return pydot.Edge(id(node.parent), id(node))
def _dot_node(self, node):
return pydot.Node(id(node), **self._dot_node_kwargs(node))
if __name__ == '__main__':
filename = sys.argv[1]
node = ast.parse(open(filename).read())
node = transformers.ParentChildNodeTransformer().visit(node)
visitor = EdgeGraphNodeVisitor()
visitor.visit(node)
visitor.graph.write(filename + '.dot')
os.system('sfdp -Tpng -o {} {}'.format(filename + '.png', filename + '.dot'))
<file_sep>import ast
from astmonkey import visitors
code = 'x = y + 1'
node = ast.parse(code)
generated_code = visitors.to_source(node)
assert(code == generated_code)
<file_sep>[tox]
envlist =
coverage-erase
test-py{27,34,35,36,37,38}
coverage-report
[testenv]
deps=
coverage
test-py26: unittest2
test: pydot
test: pytest
test: pytest-cov
commands =
coverage-erase: coverage erase
test: py.test --cov=astmonkey --cov-report= --cov-append astmonkey/tests
coverage-report: coverage report
<file_sep>import ast
from astmonkey import transformers
node = ast.parse('x = 1')
node = transformers.ParentChildNodeTransformer().visit(node)
assert(node == node.body[0].parent)
assert(node.body[0].parent_field == 'body')
assert(node.body[0].parent_field_index == 0)
<file_sep>import ast
from astmonkey import visitors, transformers
node = ast.parse('def foo(x):\n\treturn x + 1')
node = transformers.ParentChildNodeTransformer().visit(node)
visitor = visitors.GraphNodeVisitor()
visitor.visit(node)
visitor.graph.write_png('graph.png')
| b6db2adde1b92b670bee37e1b4506fc0613af449 | [
"Python",
"reStructuredText",
"INI"
] | 11 | Python | smgrey/astmonkey | 16b1817fd022b60b1369281af74b465db6db85ff | acbb1a9f4ef467668eb13e3f351578d504a433ff |
refs/heads/main | <file_sep>labels = ['RFI', 'Noise', 'Known Pulsars','Candidates']
rfi_total = 500
rfi_1 = 100
rfi_2 = 100
rfi_3 = 100
rfi_4 = 100
rfi_5 = 100
if rfi_total != rfi_1 + rfi_2 + rfi_3 + rfi_4 + rfi_5:
print("RFI totals do not match")
noise_total = 500
noise_1 = 100
noise_2 = 100
noise_3 = 100
noise_4 = 100
noise_5 = 100
if noise_total != noise_1 + noise_2 + noise_3 + noise_4 + noise_5:
print("Noise totals do not match")
known_total = 500
known_1 = 100
known_2 = 100
known_3 = 100
known_4 = 100
known_5 = 100
if known_total != known_1 + known_2 + known_3 + known_4 + known_5:
print("Known Pulsars totals do not match")
cands_total = 500
cands_1 = 100
cands_2 = 100
cands_3 = 100
cands_4 = 100
cands_5 = 100
if cands_total != cands_1 + cands_2 + cands_3 + cands_4 + cands_5:
print("Candidates totals do not match")
sizes = [rfi_total,noise_total, known_total, cands_total]
labels_small = ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5', '1', '2', '3', '4', '5', '1', '2', '3', '4', '5']
sizes_small = [rfi_1, rfi_2, rfi_3, rfi_4, rfi_5, noise_1, noise_2, noise_3, noise_4, noise_5, known_1, known_2, known_3, known_4,known_5, cands_1, cands_2, cands_3, cands_4, cands_5]
colors = ['#bae4bc', '#7bccc4', '#43a2ca', '#0868ac']
colors_small = ['#43a2ca', '#43a2ca', '#43a2ca', '#43a2ca', '#43a2ca' ,'#0868ac', '#0868ac', '#0868ac', '#0868ac', '#0868ac','#bae4bc', '#bae4bc', '#bae4bc','#bae4bc', '#bae4bc', '#7bccc4', '#7bccc4', '#7bccc4', '#7bccc4', '#7bccc4']
wp_big = { 'linewidth' : 2, 'edgecolor' : "white" }
bigger = plt.pie(sizes, labels=labels, colors=colors,
startangle=90, wedgeprops = wp_big, frame=True)
wp_small = { 'linewidth' : 1.5, 'edgecolor' : "white" }
smaller = plt.pie(sizes_small, labels=labels_small,
colors=colors_small, radius=0.65,
startangle=90, wedgeprops = wp_small, labeldistance=0.7, textprops = dict(color ="black"))
centre_circle = plt.Circle((0, 0), 0.3, color='white', linewidth=0)
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.title("Ratings of Signal to Noise of Plots")
plt.axis('equal')
plt.tight_layout()
plt.show()
<file_sep>import numpy as np
import matplotlib.pyplot as plt
# creating the dataset
data = {'RFI':20, 'Noise':15, 'Known Pulsars':30,
'Candidates':35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(courses, values, color ='maroon',
width = 0.4)
plt.xlabel("Catagories")
plt.ylabel("Number of plots")
plt.title("Labeling of Prepfold and Single Pulse Plots")
plt.show()
<file_sep>import pylab as plt
import numpy as np
lll_known=np.asarray([117.327, 108.172])
bbb_known = np.asarray([-0.074, -42.985])
distance_known= np.asarray([218.6, 11.41])
lll_cand=np.asarray([117.327, 108.172])
bbb_cand = np.asarray([-10.074, -4.985])
distance_cand= np.asarray([218.6, 11.41])
l_axis_name ='latitude l (deg)'
b_axis_name = 'longitude b (deg)'
for i in range(len(lll_known)):
if lll_known[i]>180:
lll_known[i] -= 360
for i in range(len(lll_cand)):
if lll_cand[i]>180:
lll_cand[i] -= 360
fig = plt.figure(figsize=(12,9))
ax = fig.add_subplot(111, projection="mollweide")
ax.set_xlabel("Galactic Longitude")
ax.set_ylabel("Galactic Latitude")
ax.set_title("Galactic Location and DM of Pulsars and Candidates")
ax.grid(True)
sc = ax.scatter(np.array(lll_known)*np.pi/180., np.array(bbb_known)*np.pi/180., c=distance_known, marker= ".", label= "Known Pulsars")
sc = ax.scatter(np.array(lll_cand)*np.pi/180., np.array(bbb_cand)*np.pi/180., c=distance_cand, marker= "*", label = "Candidates")
#plt.colorbar(sc)
cbar = plt.colorbar(sc)
cbar.set_label('Distance')
plt.legend(loc='upper right', fontsize="9")
plt.show()
<file_sep>import matplotlib.pyplot as plt
import numpy as np
p_x_known = np.asarray([0.1153635682680, 0.69374767047, 0.3158731909, 1.240699038946, 0.00353632915276244 ])
p_dot_y_known = np.log10(np.asarray([5.96703E-15,2.097E-15, 3.6039E-13, 5.6446E-16, 9.85103E-20]))
p_x_cand = np.asarray([1.1153635682680, 1.69374767047, 1.3158731909, 0.240699038946, 1.00353632915276244 ])
p_dot_y_cand = np.log10(np.asarray([5.96703E-15,2.097E-15, 3.6039E-13, 5.6446E-16, 9.85103E-20]))
fig, ax = plt.subplots(1,1)
import matplotlib.ticker
from matplotlib.ticker import FormatStrFormatter
ax.get_xaxis().set_major_formatter(FormatStrFormatter("%.4f"))
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
fig.suptitle('Period Derivative vs Pulsar Period (pdot vs p)')
plt.xlabel('period (s)', fontsize =14)
plt.ylabel('log_10(Pdot)', fontsize=14)
otherspulsars, = plt.plot(p_x_known , p_dot_y_known, 'o', color = '#003D30', markersize = 4, label = "Known Pulsars")
candidates, = plt.plot(p_x_cand , p_dot_y_cand, '*', color = '#009175', markersize = 6, label = "Candidates")
xscale = ax.set_xscale('log')
plt.legend(loc='upper left', fontsize="9")
| dcd99e58d018e58ea9e2ba15251075c9dfd231fa | [
"Python"
] | 4 | Python | livsguidetothegalaxy/ROAR_plots | 56bff60aaaeeb4dbebdeafe0df266fcb950d09e2 | 7b5f43793c969e2c5321d4141c3d187459a4f602 |
refs/heads/main | <repo_name>ArtyomSenokosov/Project<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/constant/OrderPaginateConstant.java
package ru.mail.senokosov.artem.service.constant;
public interface OrderPaginateConstant {
int MAXIMUM_ORDERS_ON_PAGE = 10;
}<file_sep>/service-module/src/test/java/ru/mail/senokosov/artem/service/impl/ArticleServiceImplTest.java
package ru.mail.senokosov.artem.service.impl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import ru.mail.senokosov.artem.repository.ArticleRepository;
import ru.mail.senokosov.artem.repository.UserRepository;
import ru.mail.senokosov.artem.repository.model.Article;
import ru.mail.senokosov.artem.repository.model.User;
import ru.mail.senokosov.artem.service.converter.ArticleConverter;
import ru.mail.senokosov.artem.service.exception.ServiceException;
import ru.mail.senokosov.artem.service.model.change.ChangeArticleDTO;
import ru.mail.senokosov.artem.service.model.PageDTO;
import ru.mail.senokosov.artem.service.model.add.AddArticleDTO;
import ru.mail.senokosov.artem.service.model.show.ShowArticleDTO;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ArticleServiceImplTest {
@Mock
private ArticleRepository articleRepository;
@Mock
private ArticleConverter articleConverter;
@Mock
private UserRepository userRepository;
@InjectMocks
private ArticleServiceImpl articleService;
@Test
void shouldGetArticlesByNumberPage() {
int startPosition = 0;
int maximumItemsOnPage = 10;
List<Article> articles = new ArrayList<>();
when(articleRepository.findAll(startPosition, maximumItemsOnPage)).thenReturn(articles);
List<ShowArticleDTO> articleDTOS = articles.stream()
.map(articleConverter::convert)
.collect(Collectors.toList());
PageDTO pageDTO = new PageDTO();
pageDTO.getArticles().addAll(articleDTOS);
PageDTO itemsByPage = articleService.getArticlesByPage(1);
assertEquals(pageDTO.getItems(), itemsByPage.getItems());
}
@Test
void shouldGetAllArticles() {
List<Article> articlesWithMock = new ArrayList<>();
when(articleRepository.findAll()).thenReturn(articlesWithMock);
List<ShowArticleDTO> articlesDTOSWithMock = articlesWithMock.stream()
.map(articleConverter::convert)
.collect(Collectors.toList());
List<Article> articles = articleRepository.findAll();
List<ShowArticleDTO> articleDTOS = articles.stream()
.map(articleConverter::convert)
.collect(Collectors.toList());
assertEquals(articlesDTOSWithMock, articleDTOS);
}
@Test
void shouldFindArticleByIdAndReturnExceptionIfArticleNotFound() {
Long id = 1L;
assertThrows(ServiceException.class, () -> articleService.getArticleById(id));
}
@Test
void shouldFindArticleByIdAndReturnNotNullIfArticleWasFound() {
Long id = 1L;
Article article = new Article();
article.setId(id);
when(articleRepository.findById(id)).thenReturn(article);
ShowArticleDTO articleDTO = new ShowArticleDTO();
assertNotNull(articleDTO);
}
@Test
void shouldGetArticleById() throws ServiceException {
Long id = 1L;
Article article = new Article();
article.setId(id);
when(articleRepository.findById(id)).thenReturn(article);
ShowArticleDTO articleDTO = new ShowArticleDTO();
when(articleConverter.convert(article)).thenReturn(articleDTO);
ShowArticleDTO articleById = articleService.getArticleById(id);
assertEquals(articleDTO, articleById);
}
@Test
void shouldDeleteArticleById() {
Long id = 1L;
boolean isDeleteArticle = articleService.isDeleteById(id);
assertTrue(isDeleteArticle);
}
@Test
void shouldAddArticleAndReturnRightAddDateIfAddedSuccessfully() throws ServiceException {
User user = new User();
user.setId(1L);
user.setLastName("<NAME>");
Authentication authentication = getAuthenticationWithUserName();
SecurityContextHolder.getContext().setAuthentication(authentication);
when(userRepository.findUserByUsername(authentication.getName())).thenReturn(user);
AddArticleDTO addArticleDTO = new AddArticleDTO();
addArticleDTO.setId(1L);
addArticleDTO.setTitle("test title");
addArticleDTO.setContent("test content");
addArticleDTO.setSellerId(user.getId());
Article article = new Article();
when(articleConverter.convert(addArticleDTO)).thenReturn(article);
ShowArticleDTO showArticleDTO = new ShowArticleDTO();
when(articleConverter.convert(article)).thenReturn(showArticleDTO);
ShowArticleDTO showArticle = articleService.add(addArticleDTO);
assertEquals(showArticle.getDate(), showArticleDTO.getDate());
}
@Test
void shouldAddArticleAndReturnExceptionIfUserWasNotAuthentication() {
AddArticleDTO addArticleDTO = new AddArticleDTO();
assertThrows(ServiceException.class, () -> articleService.add(addArticleDTO));
}
@Test
void shouldAddArticleAndReturnExceptionIfUserWasNotFoundWithUserName() {
Authentication authentication = getAuthenticationWithUserName();
SecurityContextHolder.getContext().setAuthentication(authentication);
when(userRepository.findUserByUsername(authentication.getName())).thenReturn(null);
AddArticleDTO addArticleDTO = new AddArticleDTO();
Article article = new Article();
when(articleConverter.convert(addArticleDTO)).thenReturn(article);
assertThrows(ServiceException.class, () -> articleService.add(addArticleDTO));
}
@Test
void shouldChangeParameterByIdAndReturnExceptionIfArticleWithIdNotFound() {
Long id = 1L;
assertThrows(ServiceException.class, () -> articleService.getArticleById(id));
}
@Test
void shouldChangeParameterByIdAndReturnNotNullObject() throws ServiceException {
Long id = 1L;
Article article = new Article();
when(articleRepository.findById(id)).thenReturn(article);
ChangeArticleDTO changeArticleDTO = new ChangeArticleDTO();
ShowArticleDTO showArticleDTO = new ShowArticleDTO();
when(articleService.changeParameterById(changeArticleDTO, id)).thenReturn(showArticleDTO);
assertNotNull(showArticleDTO);
}
private Authentication getAuthenticationWithUserName() {
return new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return null;
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
return "<EMAIL>";
}
};
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/impl/ItemServiceImpl.java
package ru.mail.senokosov.artem.service.impl;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import ru.mail.senokosov.artem.repository.ItemInfoRepository;
import ru.mail.senokosov.artem.repository.ItemRepository;
import ru.mail.senokosov.artem.repository.model.Item;
import ru.mail.senokosov.artem.repository.model.ItemInfo;
import ru.mail.senokosov.artem.service.ItemService;
import ru.mail.senokosov.artem.service.converter.ItemConverter;
import ru.mail.senokosov.artem.service.exception.ServiceException;
import ru.mail.senokosov.artem.service.model.PageDTO;
import ru.mail.senokosov.artem.service.model.add.AddItemDTO;
import ru.mail.senokosov.artem.service.model.show.ShowItemDTO;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import static ru.mail.senokosov.artem.service.constant.ItemConstant.MAXIMUM_ITEMS_ON_PAGE;
import static ru.mail.senokosov.artem.service.util.ServiceUtil.getPageDTO;
@Service
@Log4j2
@RequiredArgsConstructor
public class ItemServiceImpl implements ItemService {
private final ItemRepository itemRepository;
private final ItemConverter itemConverter;
private final ItemInfoRepository itemInfoRepository;
@Override
@Transactional
public PageDTO getItemsByPage(int page) {
Long countItems = itemRepository.getCountItems();
PageDTO pageDTO = getPageDTO(page, countItems, MAXIMUM_ITEMS_ON_PAGE);
List<Item> items = itemRepository.findAll(pageDTO.getStartPosition(), MAXIMUM_ITEMS_ON_PAGE);
pageDTO.getItems().addAll(items.stream()
.map(itemConverter::convert)
.collect(Collectors.toList()));
return pageDTO;
}
@Override
@Transactional
public List<ShowItemDTO> getItems() {
List<Item> items = itemRepository.findAll();
return items.stream()
.map(itemConverter::convert)
.collect(Collectors.toList());
}
@Override
@Transactional
public ShowItemDTO getItemById(Long id) throws ServiceException {
Item item = itemRepository.findById(id);
if (Objects.nonNull(item)) {
return itemConverter.convert(item);
} else {
throw new ServiceException(String.format("Item with id: %s was not found", id));
}
}
@Override
@Transactional
public ShowItemDTO persist(AddItemDTO addItemDTO) {
Item item = itemConverter.convert(addItemDTO);
UUID uuid = UUID.randomUUID();
item.setUuid(uuid);
itemRepository.persist(item);
return itemConverter.convert(item);
}
@Override
@Transactional
public boolean isDeleteById(Long id) {
itemRepository.removeById(id);
return true;
}
@Override
@Transactional
public ShowItemDTO getItemByUuid(UUID uuid) throws ServiceException {
Item item = itemRepository.findByUuid(uuid);
if (Objects.nonNull(item)) {
return itemConverter.convert(item);
} else {
throw new ServiceException(String.format("Item with uuid: %s was not found", uuid));
}
}
@Override
@Transactional
public boolean isDeleteByUuid(UUID uuid) throws ServiceException {
Item item = itemRepository.findByUuid(uuid);
if (Objects.nonNull(item)) {
itemRepository.removeById(item.getId());
return true;
} else {
throw new ServiceException(String.format("Item with uuid: %s was not found", uuid));
}
}
@Override
@Transactional
public ShowItemDTO CopyItemByUuid(UUID uuid) throws ServiceException {
Item item = itemRepository.findByUuid(uuid);
if (Objects.nonNull(item)) {
Item cloneItem = copyFieldsByItem(item);
itemRepository.merge(cloneItem);
ShowItemDTO showItemDTO = itemConverter.convert(cloneItem);
return showItemDTO;
} else {
throw new ServiceException(String.format("Item with uuid: %s was not found", uuid));
}
}
private Item copyFieldsByItem(Item item) {
itemRepository.detach(item);
item.setId(null);
UUID uuid = UUID.randomUUID();
item.setUuid(uuid);
String title = item.getTitle();
item.setTitle(String.format("copy of %s", title));
ItemInfo itemInfo = item.getItemInfo();
if (Objects.nonNull(itemInfo)) {
itemInfoRepository.detach(itemInfo);
itemInfo.setId(null);
}
return item;
}
}
<file_sep>/web-module/src/main/resources/application.properties
spring.main.banner-mode=off
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/project_db
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.liquibase.change-log=classpath:/database/changelog.xml
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true
spring.mail.host=127.0.0.1
spring.mail.port=1025
spring.mail.username=<EMAIL><file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/converter/impl/CommentConverterImpl.java
package ru.mail.senokosov.artem.service.converter.impl;
import org.springframework.stereotype.Component;
import ru.mail.senokosov.artem.repository.model.Comment;
import ru.mail.senokosov.artem.repository.model.User;
import ru.mail.senokosov.artem.service.converter.CommentConverter;
import ru.mail.senokosov.artem.service.model.add.AddCommentDTO;
import ru.mail.senokosov.artem.service.model.show.ShowCommentDTO;
import java.time.LocalDateTime;
import java.util.Objects;
import static ru.mail.senokosov.artem.service.util.ServiceUtil.getFormatDateTime;
@Component
public class CommentConverterImpl implements CommentConverter {
@Override
public ShowCommentDTO convert(Comment comment) {
ShowCommentDTO showCommentDTO = new ShowCommentDTO();
Long id = comment.getId();
showCommentDTO.setId(id);
LocalDateTime localDateTime = comment.getLocalDateTime();
if (Objects.nonNull(localDateTime)) {
String formatDateTime = getFormatDateTime(localDateTime);
showCommentDTO.setDate(formatDateTime);
}
String fullContent = comment.getFullContent();
showCommentDTO.setFullContent(fullContent);
User user = comment.getUser();
if (Objects.nonNull(user)) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String fullName = String.format("%s %s", firstName, lastName);
showCommentDTO.setFullName(fullName);
}
return showCommentDTO;
}
@Override
public Comment convert(AddCommentDTO addCommentDTO) {
Comment comment = new Comment();
LocalDateTime localDateTime = LocalDateTime.now();
comment.setLocalDateTime(localDateTime);
String fullContent = addCommentDTO.getFullContent();
comment.setFullContent(fullContent);
return comment;
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/MailService.java
package ru.mail.senokosov.artem.service;
import ru.mail.senokosov.artem.service.model.show.ShowUserDTO;
public interface MailService {
void sendPasswordToEmailAfterAddUser(ShowUserDTO userDTO);
void sendPasswordToEmailAfterResetPassword(ShowUserDTO userDTO);
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/model/OrderStatus.java
package ru.mail.senokosov.artem.repository.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Data
@ToString(exclude = "orders")
@EqualsAndHashCode(exclude = "orders")
@Entity
@Table(name = "status_order")
public class OrderStatus {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "status_name")
private String status;
@OneToMany(cascade = CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "order_status_id")
private Set<Order> orders = new HashSet<>();
}<file_sep>/web-module/src/test/resources/scripts/init_item.sql
INSERT INTO item(id, title, unique_number, price)
VALUES (1, 'test title', 'e5b0f808-ccf1-488f-ace7-2d48e50dea5c', 500);<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/ItemRepository.java
package ru.mail.senokosov.artem.repository;
import ru.mail.senokosov.artem.repository.model.Item;
import java.util.List;
import java.util.UUID;
public interface ItemRepository extends GenericRepository<Long, Item> {
Long getCountItems();
List<Item> findAll(Integer startPosition, int maximumItemsOnPage);
Item findByUuid(UUID uuid);
}<file_sep>/service-module/src/test/java/ru/mail/senokosov/artem/service/impl/UserServiceTest.java
package ru.mail.senokosov.artem.service.impl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import ru.mail.senokosov.artem.repository.RoleRepository;
import ru.mail.senokosov.artem.repository.UserRepository;
import ru.mail.senokosov.artem.repository.model.Role;
import ru.mail.senokosov.artem.repository.model.User;
import ru.mail.senokosov.artem.service.converter.UserConverter;
import ru.mail.senokosov.artem.service.model.show.ShowUserDTO;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private RoleRepository roleRepository;
@Mock
private UserConverter userConverter;
@Test
void shouldChangeRoleById() {
Long id = 1L;
String roleName = "newTestNameRole";
Role role = new Role();
role.setId(2L);
role.setRoleName(roleName);
User user = new User();
user.setId(id);
String oldRoleName = "oldTestNameRole";
Role roleTwo = new Role();
roleTwo.setId(3L);
roleTwo.setRoleName(oldRoleName);
user.setRole(roleTwo);
when(roleRepository.findByRoleName(roleName)).thenReturn(role);
when(userRepository.findById(id)).thenReturn(user);
user.setRole(role);
ShowUserDTO showUserDTO = new ShowUserDTO();
showUserDTO.setId(id);
showUserDTO.setRoleName(roleName);
when(userConverter.convert(user)).thenReturn(showUserDTO);
assertEquals(roleName, showUserDTO.getRoleName());
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/converter/OrderConverter.java
package ru.mail.senokosov.artem.service.converter;
import ru.mail.senokosov.artem.repository.model.Order;
import ru.mail.senokosov.artem.service.model.show.ShowOrderDTO;
public interface OrderConverter {
ShowOrderDTO convert(Order order);
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/model/Article.java
package ru.mail.senokosov.artem.repository.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@Data
@Entity
@Table(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "date")
private LocalDateTime localDateTime;
@Column
private String title;
@Column(name = "content")
private String fullContent;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(cascade = CascadeType.REFRESH, orphanRemoval = true)
@JoinColumn(name = "article_id")
@ToString.Exclude
@EqualsAndHashCode.Exclude
private Set<Comment> comments = new HashSet<>();
}
<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/show/ShowReviewDTO.java
package ru.mail.senokosov.artem.service.model.show;
import lombok.Data;
@Data
public class ShowReviewDTO {
private Long id;
private String lastName;
private String firstName;
private String middleName;
private String review;
private String localDateTime;
private String status;
}<file_sep>/web-module/src/test/resources/scripts/init_user.sql
INSERT INTO users(id, last_name, first_name, middle_name, email, password, role_id)
VALUES (1, 'test lastname', 'test firstname', 'test middlename', '<EMAIL>', '<PASSWORD>', 2);<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/add/AddUserDTO.java
package ru.mail.senokosov.artem.service.model.add;
import lombok.Data;
import ru.mail.senokosov.artem.service.model.enums.RoleDTOEnum;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import static ru.mail.senokosov.artem.service.constant.UserValidationConstant.*;
@Data
public class AddUserDTO {
private Long id;
@NotBlank
@NotNull
@Size(max = MAXIMUM_LAST_NAME_SIZE)
@Pattern(regexp = ONLY_LATIN_LETTERS_REGEXP)
private String lastName;
@NotBlank
@NotNull
@Size(max = MAXIMUM_FIRST_NAME_SIZE)
@Pattern(regexp = ONLY_LATIN_LETTERS_REGEXP)
private String firstName;
@NotBlank
@NotNull
@Size(max = MAXIMUM_MIDDLE_NAME_SIZE)
@Pattern(regexp = ONLY_LATIN_LETTERS_REGEXP)
private String middleName;
@NotBlank
@NotNull
@Size(max = MAXIMUM_EMAIL_NAME_SIZE)
@Pattern(regexp = EMAIL_REGEXP)
private String email;
@Enumerated(EnumType.STRING)
private RoleDTOEnum role;
@NotBlank
@NotNull
@Size(max = MAXIMUM_ADDRESS_SIZE)
private String address;
@NotBlank
@NotNull
@Size(max = MAXIMUM_TELEPHONE_SIZE)
private String telephone;
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/UserInfoDTO.java
package ru.mail.senokosov.artem.service.model;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import static ru.mail.senokosov.artem.service.constant.UserValidationConstant.*;
@Data
public class UserInfoDTO {
private Long id;
@NotBlank
@NotNull
@Size(max = MAXIMUM_FIRST_NAME_SIZE)
@Pattern(regexp = ONLY_LATIN_LETTERS_REGEXP, message = "The first name must be written in Latin letters and start with a capital letter")
private String firstName;
@NotBlank
@NotNull
@Size(max = MAXIMUM_LAST_NAME_SIZE)
@Pattern(regexp = ONLY_LATIN_LETTERS_REGEXP, message = "The last name must be written in Latin letters and start with a capital letter")
private String lastName;
@NotBlank
@NotNull
@Size(max = MAXIMUM_TELEPHONE_SIZE)
private String telephone;
@NotBlank
@NotNull
@Size(max = MAXIMUM_ADDRESS_SIZE)
private String address;
@NotBlank
@NotNull
private String oldPassword;
@NotBlank
@NotNull
private String newPassword;
}<file_sep>/web-module/src/main/java/ru/mail/senokosov/artem/web/config/ApplicationConfig.java
package ru.mail.senokosov.artem.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.util.Random;
@Configuration
@ComponentScan(basePackages = {"ru.mail.senokosov.artem.repository", "ru.mail.senokosov.artem.service"})
public class ApplicationConfig {
@Bean
public Random random() {
return new Random();
}
}<file_sep>/web-module/src/test/resources/scripts/init_article.sql
INSERT INTO article(id, date, title, content, user_id)
VALUES (1, '2021-07-01 00:00:00', 'test title', 'test content', 2);<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/converter/impl/ArticleConverterImpl.java
package ru.mail.senokosov.artem.service.converter.impl;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import ru.mail.senokosov.artem.repository.model.Article;
import ru.mail.senokosov.artem.repository.model.Comment;
import ru.mail.senokosov.artem.repository.model.User;
import ru.mail.senokosov.artem.service.converter.ArticleConverter;
import ru.mail.senokosov.artem.service.converter.CommentConverter;
import ru.mail.senokosov.artem.service.model.add.AddArticleDTO;
import ru.mail.senokosov.artem.service.model.show.ShowArticleDTO;
import ru.mail.senokosov.artem.service.model.show.ShowCommentDTO;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static ru.mail.senokosov.artem.service.constant.ArticleConstant.MAXIMUM_CHARS_FOR_SHORT_CONTENT_FIELD;
import static ru.mail.senokosov.artem.service.util.ServiceUtil.getFormatDateTime;
@Component
@Log4j2
@RequiredArgsConstructor
public class ArticleConverterImpl implements ArticleConverter {
private final CommentConverter commentConverter;
@Override
public ShowArticleDTO convert(Article article) {
ShowArticleDTO showArticleDTO = new ShowArticleDTO();
Long id = article.getId();
showArticleDTO.setId(id);
LocalDateTime localDateTime = article.getLocalDateTime();
if (Objects.nonNull(localDateTime)) {
String formatDateTime = getFormatDateTime(localDateTime);
showArticleDTO.setDate(formatDateTime);
}
String title = article.getTitle();
if (Objects.nonNull(title)) {
showArticleDTO.setTitle(title);
}
User user = article.getUser();
if (Objects.nonNull(user)) {
String firstName = user.getFirstName();
showArticleDTO.setFirstName(firstName);
String lastName = user.getLastName();
showArticleDTO.setLastName(lastName);
}
String fullContent = article.getFullContent();
if (Objects.nonNull(fullContent)) {
showArticleDTO.setFullContent(fullContent);
addShortContent(showArticleDTO, fullContent);
}
Set<Comment> comments = article.getComments();
if (!comments.isEmpty()) {
List<ShowCommentDTO> commentDTOs = comments.stream()
.map(commentConverter::convert)
.collect(Collectors.toList());
showArticleDTO.getComments().addAll(commentDTOs);
}
return showArticleDTO;
}
private void addShortContent(ShowArticleDTO showArticleDTO, String fullContent) {
if (fullContent.length() > MAXIMUM_CHARS_FOR_SHORT_CONTENT_FIELD) {
String shortContent = fullContent.substring(0, MAXIMUM_CHARS_FOR_SHORT_CONTENT_FIELD);
showArticleDTO.setShortContent(shortContent);
} else {
showArticleDTO.setShortContent(fullContent);
}
}
@Override
public Article convert(AddArticleDTO addArticleDTO) {
Article article = new Article();
String title = addArticleDTO.getTitle();
article.setTitle(title);
String content = addArticleDTO.getContent();
article.setFullContent(content);
return article;
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/show/ShowCommentDTO.java
package ru.mail.senokosov.artem.service.model.show;
import lombok.Data;
@Data
public class ShowCommentDTO {
private Long id;
private String fullName;
private String date;
private String fullContent;
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/constant/UserPaginateConstant.java
package ru.mail.senokosov.artem.service.constant;
public interface UserPaginateConstant {
int MAXIMUM_USERS_ON_PAGE = 10;
}<file_sep>/web-module/src/test/java/ru/mail/senokosov/artem/web/controller/api/OrderAPIControllerIT.java
package ru.mail.senokosov.artem.web.controller.api;
import org.junit.jupiter.api.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.test.context.jdbc.Sql;
import ru.mail.senokosov.artem.service.model.show.ShowOrderDTO;
import ru.mail.senokosov.artem.web.config.BaseIT;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static ru.mail.senokosov.artem.web.constant.PathConstant.ORDERS_PATH;
import static ru.mail.senokosov.artem.web.constant.PathConstant.REST_API_USER_PATH;
@Sql({"/scripts/clean_orders.sql", "/scripts/init_orders.sql"})
class OrderAPIControllerIT extends BaseIT {
@Test
void shouldGetAllOrders() {
HttpEntity<String> request = new HttpEntity<>(null, new HttpHeaders());
ResponseEntity<List<ShowOrderDTO>> response = testRestTemplate
.withBasicAuth("<EMAIL>", "test")
.exchange(
REST_API_USER_PATH + ORDERS_PATH,
HttpMethod.GET,
request,
new ParameterizedTypeReference<>() {
}
);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(1, Objects.requireNonNull(response.getBody()).size());
assertEquals(UUID.fromString("de05425c-da35-45ba-be2f-61284704662e"), response.getBody().get(0).getNumberOfOrder());
assertEquals(BigDecimal.valueOf(500), response.getBody().get(0).getTotalPrice());
}
@Test
void shouldGetArticleById() {
HttpEntity<String> request = new HttpEntity<>(null, new HttpHeaders());
ResponseEntity<ShowOrderDTO> response = testRestTemplate
.withBasicAuth("<EMAIL>", "test")
.exchange(
REST_API_USER_PATH + ORDERS_PATH + "/1",
HttpMethod.GET,
request,
new ParameterizedTypeReference<>() {
}
);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(BigDecimal.valueOf(500), Objects.requireNonNull(response.getBody()).getTotalPrice());
assertEquals(UUID.fromString("de05425c-da35-45ba-be2f-61284704662e"), (response.getBody()).getNumberOfOrder());
}
}<file_sep>/web-module/src/test/java/ru/mail/senokosov/artem/web/config/BaseIT.java
package ru.mail.senokosov.artem.web.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MySQLContainer;
import ru.mail.senokosov.artem.web.SpringMvcApplication;
@SpringBootTest(classes = SpringMvcApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseIT {
@Autowired
protected TestRestTemplate testRestTemplate;
public static final MySQLContainer mySQLContainer;
static {
mySQLContainer = (MySQLContainer) new MySQLContainer("mysql:8.0")
.withUsername("test")
.withPassword("<PASSWORD>")
.withReuse(true);
mySQLContainer.start();
}
@DynamicPropertySource
public static void setDataSourceProperties(DynamicPropertyRegistry dynamicPropertyRegistry) {
dynamicPropertyRegistry.add("spring.datasource.url", mySQLContainer::getJdbcUrl);
dynamicPropertyRegistry.add("spring.datasource.username", mySQLContainer::getUsername);
dynamicPropertyRegistry.add("spring.datasource.password", mySQLContainer::getPassword);
}
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/impl/CommentRepositoryImpl.java
package ru.mail.senokosov.artem.repository.impl;
import org.springframework.stereotype.Repository;
import ru.mail.senokosov.artem.repository.CommentRepository;
import ru.mail.senokosov.artem.repository.model.Comment;
import javax.persistence.Query;
import java.util.List;
@Repository
public class CommentRepositoryImpl extends GenericRepositoryImpl<Long, Comment> implements CommentRepository {
@Override
@SuppressWarnings("unchecked")
public List<Comment> findCommentByArticleId(Long id) {
String hql = "SELECT c FROM Comment as c WHERE c.article.id=:articleId ORDER BY c.localDateTime DESC";
Query query = entityManager.createQuery(hql);
query.setParameter("articleId", id);
return query.getResultList();
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/add/AddCommentDTO.java
package ru.mail.senokosov.artem.service.model.add;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import static ru.mail.senokosov.artem.service.constant.CommentValidationConstant.MAXIMUM_FULL_CONTENT_SIZE;
@Data
public class AddCommentDTO {
@NotBlank
@NotNull
@Size(max = MAXIMUM_FULL_CONTENT_SIZE)
private String fullContent;
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/impl/UserDetailsServiceImpl.java
package ru.mail.senokosov.artem.service.impl;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.mail.senokosov.artem.repository.UserRepository;
import ru.mail.senokosov.artem.repository.model.User;
import ru.mail.senokosov.artem.service.model.UserLogin;
import javax.transaction.Transactional;
import java.util.Objects;
@Log4j2
@RequiredArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("username:{}", username);
User user = userRepository.findUserByUsername(username);
log.info("user with username: {} found with role: {}", user.getEmail(), user.getRole());
if (Objects.isNull(user)) {
throw new UsernameNotFoundException("User with username: " + username + " was not found");
}
return new UserLogin(user);
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/constant/ReviewPaginateConstant.java
package ru.mail.senokosov.artem.service.constant;
public interface ReviewPaginateConstant {
int MAXIMUM_REVIEWS_ON_PAGE = 10;
}<file_sep>/web-module/src/test/java/ru/mail/senokosov/artem/web/config/TestUserDetailsServiceConfig.java
package ru.mail.senokosov.artem.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import ru.mail.senokosov.artem.service.model.enums.RoleDTOEnum;
import java.util.Collection;
import java.util.Collections;
@Profile("security")
@Configuration
public class TestUserDetailsServiceConfig {
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
switch (username) {
case "<EMAIL>":
return getRestUserDetails();
case "<EMAIL>":
return getAdminUserDetails();
case "<EMAIL>":
return getSellerUserDetails();
case "<EMAIL>":
return getCustomerUserDetails();
default:
throw new UsernameNotFoundException(String.format("User with %s was not found", username));
}
}
private UserDetails getRestUserDetails() {
return new UserDetails() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
String role = RoleDTOEnum.SECURE_API_USER.name();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
return Collections.singletonList(grantedAuthority);
}
@Override
public String getPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode("test");
}
@Override
public String getUsername() {
return "<EMAIL>";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
};
}
private UserDetails getAdminUserDetails() {
return new UserDetails() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
String role = RoleDTOEnum.ADMINISTRATOR.name();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
return Collections.singletonList(grantedAuthority);
}
@Override
public String getPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode("test");
}
@Override
public String getUsername() {
return "<EMAIL>";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
};
}
private UserDetails getSellerUserDetails() {
return new UserDetails() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
String role = RoleDTOEnum.SALE_USER.name();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
return Collections.singletonList(grantedAuthority);
}
@Override
public String getPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode("test");
}
@Override
public String getUsername() {
return "<EMAIL>";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
};
}
private UserDetails getCustomerUserDetails() {
return new UserDetails() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
String role = RoleDTOEnum.CUSTOMER_USER.name();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
return Collections.singletonList(grantedAuthority);
}
@Override
public String getPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode("test");
}
@Override
public String getUsername() {
return "<EMAIL>";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
};
}
};
}
}<file_sep>/service-module/src/test/java/ru/mail/senokosov/artem/service/impl/OrderServiceTest.java
package ru.mail.senokosov.artem.service.impl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import ru.mail.senokosov.artem.repository.OrderRepository;
import ru.mail.senokosov.artem.repository.model.Order;
import ru.mail.senokosov.artem.service.converter.OrderConverter;
import ru.mail.senokosov.artem.service.model.show.ShowOrderDTO;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@Mock
private OrderConverter orderConverter;
@InjectMocks
private OrderServiceImpl orderService;
@Test
void shouldGetEmptyList() {
List<ShowOrderDTO> orders = orderService.getOrders();
assertTrue(orders.isEmpty());
}
@Test
void shouldGetOrdersList() {
ShowOrderDTO showOrderDTO = new ShowOrderDTO();
showOrderDTO.setId(1L);
showOrderDTO.setNumberOfItems(1L);
Order order = new Order();
when(orderRepository.findAll()).thenReturn(Collections.singletonList(order));
when(orderConverter.convert(order)).thenReturn(showOrderDTO);
List<ShowOrderDTO> orders = orderService.getOrders();
assertEquals(orders.get(0).getId(), showOrderDTO.getId());
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/OrderItemDTO.java
package ru.mail.senokosov.artem.service.model;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class OrderItemDTO {
@NotNull
private Long numberOfItems;
}<file_sep>/web-module/src/main/java/ru/mail/senokosov/artem/web/config/handler/WebExceptionHandler.java
package ru.mail.senokosov.artem.web.config.handler;
public class WebExceptionHandler {
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/impl/OrderRepositoryImpl.java
package ru.mail.senokosov.artem.repository.impl;
import org.springframework.stereotype.Repository;
import ru.mail.senokosov.artem.repository.OrderRepository;
import ru.mail.senokosov.artem.repository.model.Order;
import javax.persistence.Query;
import java.util.List;
@Repository
public class OrderRepositoryImpl extends GenericRepositoryImpl<Long, Order> implements OrderRepository {
@Override
public Long getCountOrders() {
String hql = "SELECT COUNT(o.id) FROM Order as o";
Query query = entityManager.createQuery(hql);
return (Long) query.getSingleResult();
}
@Override
@SuppressWarnings("unchecked")
public List<Order> findAll(Integer startPosition, int maximumOrdersOnPage) {
String hql = "SELECT o FROM Order as o ORDER BY o.localDateTime DESC";
Query query = entityManager.createQuery(hql);
query.setFirstResult(startPosition);
query.setMaxResults(maximumOrdersOnPage);
return query.getResultList();
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/show/ShowUserInfoDTO.java
package ru.mail.senokosov.artem.service.model.show;
import lombok.Data;
@Data
public class ShowUserInfoDTO {
private Long id;
private String firstName;
private String lastName;
private String telephone;
private String address;
private String oldPassword;
private String newPassword;
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/model/Review.java
package ru.mail.senokosov.artem.repository.model;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "review")
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "date")
private LocalDateTime localDate;
@Column(name = "review")
private String review;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "user_id")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "status_id")
private Status status;
}<file_sep>/web-module/src/main/java/ru/mail/senokosov/artem/web/config/SecurityConfig.java
package ru.mail.senokosov.artem.web.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import ru.mail.senokosov.artem.web.config.handler.CustomAccessDeniedHandler;
import ru.mail.senokosov.artem.web.config.handler.CustomAuthenticationSuccessHandler;
import ru.mail.senokosov.artem.web.model.RoleDTOEnum;
@Configuration
@RequiredArgsConstructor
@Profile("!test")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final int BCRYPT_STRENGTH = 12;
private final UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**")
.hasAuthority(RoleDTOEnum.ADMINISTRATOR.name())
.antMatchers("/customer/**")
.hasAuthority(RoleDTOEnum.CUSTOMER_USER.name())
.antMatchers("/seller/**")
.hasAuthority(RoleDTOEnum.SALE_USER.name())
.antMatchers("/", "/login", "/access-denied")
.permitAll()
.and()
.formLogin()
.successHandler(authenticationSuccessHandler())
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler())
.and()
.csrf()
.disable();
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder(BCRYPT_STRENGTH);
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new CustomAuthenticationSuccessHandler();
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/converter/ReviewConverter.java
package ru.mail.senokosov.artem.service.converter;
import ru.mail.senokosov.artem.repository.model.Review;
import ru.mail.senokosov.artem.service.model.add.AddReviewDTO;
import ru.mail.senokosov.artem.service.model.show.ShowReviewDTO;
public interface ReviewConverter {
ShowReviewDTO convert(Review review);
Review convert(AddReviewDTO addReviewDTO);
}<file_sep>/web-module/src/test/resources/scripts/init_item_info.sql
INSERT INTO item_info(id, content, item_id)
VALUES (1, 'test content', 1);<file_sep>/web-module/src/test/resources/scripts/init_orders.sql
INSERT INTO orders(id, number_of_order, order_status_id, item_id, number_of_items, total_price, date)
VALUES (1, 'e5b0f808-ccf1-488f-ace7-2d48e50dea5c', 1, 1, 5, 500, '2021-05-21 00:00:00');<file_sep>/README.md
Project
=========
The project of an internet store was developed as part of a training course from the IT academy. Spring boot application with role-based authorization and authentication using the most popular Java tools and technologies: Maven, Spring MVC, Security, JPA (Hibernate), REST API, Bootstrap (css, js), Thymeleaf, Java 11, MySQL database storage, and migrating data to a database using liquibase.
## Table of Contents
* [General Info](#general-information)
* [Technologies Used](#technologies-used)
* [Features](#features)
* [Screenshots](#screenshots)
* [Setup](#setup)
* [Project Status](#project-status)
* [Room for Improvement](#room-for-improvement)
* [Acknowledgements](#acknowledgements)
* [Contact](#contact)
## <a name="general-information"></a> General information
The project of an internet store was developed as part of a training course from the IT academy. Spring boot
application with role-based authorization and authentication using the most popular Java tools and technologies: Maven,
Spring MVC, Security, JPA (Hibernate), REST API, Bootstrap (css, js), Thymeleaf, Java 11, MySQL database storage, and
migrating data to a database using liquibase.
## <a name="technologies-used"></a> Technologies Used
* Java - version 11
* Hibernate - version 5.4.27
* Spring boot starter - version 2.4.2
* Liquibase - version 3.10.3
* MySQL - version 8.0.22
* Lombok - version 1.18.16
## <a name="features"></a> Features
The project was developed according to 4 technical specifications:_
* [First specification](#first)
* [Second specification](#second)
* [Third specification](#third)
* [Four specification](#four)
## <a name="first"></a> First specification
### User with administrator role:
#### _Page title: Login page_
The page should display a form to enter the web version of the site. The following data should be displayed:
* Email
* Password
#### _Page Title: Users_
The page should display a list of users. The following data should be displayed:
* Full name
* Email
* Role
Entries should be sorted alphabetically by email. If there are more than 10 records, paging should be performed. Each
entry must be marked for deletion (checkbox). Below the list-tables there should be a “Delete” button, when you click on
it, all marked records are deleted. One of the administrators with the "administrator" role must be unavailable for
deletion (and must be blocked from being able to "lower" privileges) so that all users cannot be deleted. For each
entry, it should be possible to change the password, which is automatically generated randomly and sent to the user's
email. Each entry must be able to change privileges.
#### _Page Title: Add Users_
The page should display a form to add a user. The following data must be filled in:
* Surname (40 characters, only Latin letters).
* Name (20 characters, only Latin letters).
* Patronymic (40 characters, only Latin letters).
* Email (50 characters, standard template).
* Role (administrator, merchant, client, secured REST API)
#### _Page Title: Reviews_
The page should display a list of reviews. The following data should be displayed:
* Full name
* Feedback
* Date added
* "Show" status (checkbox)
If there are more than 10 records, paging should be performed. Also, on this page it should be possible to delete the
review.
## <a name="second"></a> Second specification
### User with role Customer user:
#### _Page Title: Articles_
The page must display a list of news. The following data should be displayed:
* Date
* Title
* Name and Surname of the author
* Content (200 characters)
* More link that leads to the article page
Entries must be sorted by date in descending order. If there are more than 10 records, paging should be done.
#### _Page Title: Article_
One news item must be displayed on the page The following data should be displayed:
* Date
* Title
* Full content (up to 1000 characters)
* Name and Surname of the author
The page should display comments from previous users:
* First and Last name of the user
* Date
* Full content (up to 200 characters)
Entries must be sorted by date in descending order.
#### _Page Title: Profile Page_
The page needs to display a user profile form The following data should be displayed:
* Name
* Surname
* Residence address
* Telephone
The page should be able to change all fields and user password
### REST API (Basic authentication) for a user with the SECURE REST API role:
| URL | METHOD | ACTION |
| ------ | ------ | ------ |
| /api/users | POST | Add new user |
| /api/articles | GET | Show list of all articles |
| /api/articles/{id} | GET | Show article with id |
| /api/articles | POST | Add new article |
| /api/articles/{id} | DELETE | Delete article with id |
## <a name="third"></a> Third specification
### A user with the Sale User role:
#### _Page Title: Articles Page_
The page must display a list of news. The following data should be displayed:
* Date
* Title
* Name and Surname of the author
* Content (200 characters)
* More link that leads to the article page
Entries must be sorted by date in descending order. If there are more than 10 records, paging should be done. It should
be possible to delete the article.
#### _Page Title: new article Page_
The page must display fields to create a new article The following data should be displayed:
* Date
* Title
* Full content (up to 1000 characters)
#### _Page Title: Page article_
One news item must be displayed on the page The following data should be displayed:
* Date
* Title
* Full content (up to 1000 characters)
* Name and Surname of the author
The page should display comments from previous users:
* First and Last name of the user
* Date
* Full content (up to 200 characters)
Entries must be sorted by date in descending order. It should be possible to change the title and content of the
article, the date of the article must change. It should be possible to delete any user's comment
#### _Page Title: Items Page_
The page needs to display a list of items. The following data should be displayed:
* Title
* Unique number (optional format)
* Price
* Details link that leads to the subject page
Entries should be sorted by title. If there are more than 10 records, paging should be done. It should be possible to
delete or copy an item.
#### _Page Title: Item Page_
The item must be displayed on the page. The following data should be displayed:
* Title
* Unique number (optional format)
* Price
* Short description (up to 200 characters)
### REST API (Basic authentication) for a user with the SECURE REST API role:
| URL | METHOD | ACTION |
| ------ | ------ | ------ |
| /api/items | GET | Show list of all items |
| /api/items/{id} | GET | Show item with id |
| /api/items | POST | Add new item |
| /api/items/{id} | DELETE | Delete item with id |
## <a name="four"></a> Four specification
### A user with the Sale User role:
#### _Page Title: Orders Page_
The page must display a list of orders. The following data should be displayed:
* Order number
* Order status (NEW, IN_PROGRESS, DELIVERED, REJECTED)
* Name of ordered item
* Number of items
* Total price
Entries must be sorted by date in descending order. If there are more than 10 records, paging should be done. It should
be possible to go to order details
#### _Page Title: Order Page_
The following data should be displayed:
* Order number
* Order status (NEW, IN_PROGRESS, DELIVERED, REJECTED)
* Name of ordered item
* ID of the user who made the order
* Phone of the user who made the order
* Number of items
* Total price
It should be possible to change the order status
### User with role Customer User:
#### _Page Title: Item Page_
The page needs to display a list of items. The following data should be displayed:
* Title
* Unique number (optional format)
* Price
* Details link that leads to the item page
Entries should be sorted by title. If there are more than 10 records, paging should be done. It should be possible to
order an item by specifying the quantity.
### _Page Title: Orders Page_
The page needs to display a list of orders for the user. The following data should be displayed:
* Order number
* Order status (NEW, IN_PROGRESS, DELIVERED, REJECTED)
* Name of ordered item
* Number of items
* Total price
Entries must be sorted by date in descending order. If there are more than 10 records, paging should be done.
### _Page Title: Create Review Page_
The following data should be displayed:
* Review form
| URL | METHOD | ACTION |
| ------ | ------ | ------ |
| /api/orders | GET | Show list of all orders |
| /api/items/{id} | GET | Show order with id |
## <a name="screenshots"></a> Screenshots
## <a name="setup"></a> Setup
### 1. Install Apache Maven
#### _build with:_ ```mvn -clean -package```
### 2. Install Docker
#### _run docker with settings:_
```
version: '3.3'
services:
db:
image: mysql:latest
restart: always
environment:
MYSQL_DATABASE: 'project_db'
MYSQL_ROOT_PASSWORD: '<PASSWORD>'
ports:
- '3306:3306'
expose:
- '3306'
```
## <a name="project-status"></a> Project Status
Project is: _complete_.
## <a name="room-for-improvement"></a> Room for Improvement
- Interaction with the storage when placing an order
- Sorting and filters for the product list
## <a name="acknowledgements"></a> Acknowledgements
Many thanks to: _IT Academy, my teacher <NAME> and my groupmates._
## <a name="contact"></a> Contact
Created by _<EMAIL>_ - feel free to contact me!
<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/ReviewDTO.java
package ru.mail.senokosov.artem.service.model;
import lombok.Data;
@Data
public class ReviewDTO {
private Long id;
}<file_sep>/service-module/src/test/java/ru/mail/senokosov/artem/service/converter/impl/ItemConverterImplTest.java
package ru.mail.senokosov.artem.service.converter.impl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import ru.mail.senokosov.artem.repository.model.Item;
import ru.mail.senokosov.artem.repository.model.ItemInfo;
import ru.mail.senokosov.artem.service.model.add.AddItemDTO;
import ru.mail.senokosov.artem.service.model.show.ShowItemDTO;
import java.math.BigDecimal;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ItemConverterImplTest {
@InjectMocks
private ItemConverterImpl itemConverter;
@Test
void shouldConvertItemToShowItemDTOAndReturnRightId() {
Item item = new Item();
Long id = 1L;
item.setId(id);
ShowItemDTO showItemDTO = itemConverter.convert(item);
assertEquals(id, showItemDTO.getId());
}
@Test
void shouldConvertItemToShowItemDTOAndReturnRightTitle() {
Item item = new Item();
String title = "test title";
item.setTitle(title);
ShowItemDTO showItemDTO = itemConverter.convert(item);
assertEquals(title, showItemDTO.getTitle());
}
@Test
void shouldConvertItemToShowItemDTOAndReturnRightUuid() {
Item item = new Item();
UUID uuid = UUID.fromString("de05425c-da35-45ba-be2f-61284704662e");
item.setUuid(uuid);
ShowItemDTO showItemDTO = itemConverter.convert(item);
assertEquals(uuid, showItemDTO.getUuid());
}
@Test
void shouldConvertItemToShowItemDTOAndReturnRightPrice() {
Item item = new Item();
BigDecimal price = BigDecimal.valueOf(100);
item.setPrice(price);
ShowItemDTO showItemDTO = itemConverter.convert(item);
assertEquals(price, showItemDTO.getPrice());
}
@Test
void shouldConvertItemToShowItemDTOAndReturnRightContent() {
ItemInfo itemInfo = new ItemInfo();
String content = "test content";
itemInfo.setShortContent(content);
Item item = new Item();
item.setItemInfo(itemInfo);
ShowItemDTO showItemDTO = itemConverter.convert(item);
assertEquals(content, showItemDTO.getContent());
}
@Test
void shouldConvertAddItemDTOToItemAndReturnRightTitle() {
AddItemDTO addItemDTO = new AddItemDTO();
String title = "test title";
addItemDTO.setTitle(title);
Item item = itemConverter.convert(addItemDTO);
assertEquals(title, item.getTitle());
}
@Test
void shouldConvertAddItemDTOToItemAndReturnRightPrice() {
AddItemDTO addItemDTO = new AddItemDTO();
BigDecimal price = BigDecimal.valueOf(100);
addItemDTO.setPrice(price);
Item item = itemConverter.convert(addItemDTO);
assertEquals(price, item.getPrice());
}
@Test
void shouldConvertAddItemDTOToItemAndReturnRightContent() {
AddItemDTO addItemDTO = new AddItemDTO();
String content = "test content";
addItemDTO.setContent(content);
Item item = itemConverter.convert(addItemDTO);
assertEquals(content, item.getItemInfo().getShortContent());
}
}<file_sep>/web-module/src/main/java/ru/mail/senokosov/artem/web/controller/api/ItemsAPIController.java
package ru.mail.senokosov.artem.web.controller.api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.mail.senokosov.artem.service.ItemService;
import ru.mail.senokosov.artem.service.exception.ServiceException;
import ru.mail.senokosov.artem.service.model.ErrorDTO;
import ru.mail.senokosov.artem.service.model.add.AddItemDTO;
import ru.mail.senokosov.artem.service.model.show.ShowItemDTO;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import static ru.mail.senokosov.artem.web.constant.PathConstant.ITEMS_PATH;
import static ru.mail.senokosov.artem.web.constant.PathConstant.REST_API_USER_PATH;
@RestController
@RequestMapping(REST_API_USER_PATH)
@RequiredArgsConstructor
@Log4j2
public class ItemsAPIController {
private final ItemService itemService;
@GetMapping(value = ITEMS_PATH)
public List<ShowItemDTO> getItems() {
return itemService.getItems();
}
@GetMapping(value = ITEMS_PATH + "/{id}")
public ResponseEntity<ShowItemDTO> getItemById(@PathVariable Long id) throws ServiceException {
ShowItemDTO itemById = itemService.getItemById(id);
if (Objects.nonNull(itemById)) {
return new ResponseEntity<>(itemById, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping(value = ITEMS_PATH)
public ResponseEntity<Object> addItem(@RequestBody @Valid AddItemDTO addItemDTO,
BindingResult result) {
if (result.hasErrors()) {
ErrorDTO errorDTO = new ErrorDTO();
errorDTO.getErrors().addAll(result.getFieldErrors());
return new ResponseEntity<>(errorDTO, HttpStatus.BAD_REQUEST);
} else {
itemService.persist(addItemDTO);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
@DeleteMapping(value = ITEMS_PATH + "/{id}")
public ResponseEntity<Void> deleteItem(@PathVariable Long id) {
boolean deleteById = itemService.isDeleteById(id);
if (deleteById) {
return new ResponseEntity<>(HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/show/ShowArticleDTO.java
package ru.mail.senokosov.artem.service.model.show;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class ShowArticleDTO {
private Long id;
private String date;
private String title;
private String firstName;
private String lastName;
private String shortContent;
private String fullContent;
private List<ShowCommentDTO> comments = new ArrayList<>();
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/converter/impl/ItemConverterImpl.java
package ru.mail.senokosov.artem.service.converter.impl;
import org.springframework.stereotype.Component;
import ru.mail.senokosov.artem.repository.model.Item;
import ru.mail.senokosov.artem.repository.model.ItemInfo;
import ru.mail.senokosov.artem.service.converter.ItemConverter;
import ru.mail.senokosov.artem.service.model.add.AddItemDTO;
import ru.mail.senokosov.artem.service.model.show.ShowItemDTO;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.UUID;
@Component
public class ItemConverterImpl implements ItemConverter {
@Override
public ShowItemDTO convert(Item item) {
ShowItemDTO showItemDTO = new ShowItemDTO();
Long id = item.getId();
showItemDTO.setId(id);
String title = item.getTitle();
showItemDTO.setTitle(title);
UUID uuid = item.getUuid();
showItemDTO.setUuid(uuid);
BigDecimal price = item.getPrice();
showItemDTO.setPrice(price);
ItemInfo itemInfo = item.getItemInfo();
if (Objects.nonNull(itemInfo)) {
String shortContent = itemInfo.getShortContent();
showItemDTO.setContent(shortContent);
}
return showItemDTO;
}
@Override
public Item convert(AddItemDTO addItemDTO) {
Item item = new Item();
String title = addItemDTO.getTitle();
item.setTitle(title);
BigDecimal price = addItemDTO.getPrice();
item.setPrice(price);
ItemInfo itemInfo = new ItemInfo();
String content = addItemDTO.getContent();
itemInfo.setShortContent(content);
itemInfo.setItem(item);
item.setItemInfo(itemInfo);
return item;
}
}<file_sep>/service-module/src/test/java/ru/mail/senokosov/artem/service/converter/impl/ArticleConverterImplTest.java
package ru.mail.senokosov.artem.service.converter.impl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import ru.mail.senokosov.artem.repository.model.Article;
import ru.mail.senokosov.artem.repository.model.Comment;
import ru.mail.senokosov.artem.service.converter.CommentConverter;
import ru.mail.senokosov.artem.service.model.add.AddArticleDTO;
import ru.mail.senokosov.artem.service.model.show.ShowArticleDTO;
import ru.mail.senokosov.artem.service.model.show.ShowCommentDTO;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static ru.mail.senokosov.artem.service.constant.FormatConstant.DATE_FORMAT_PATTERN;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ArticleConverterImplTest {
@Mock
private CommentConverter commentConverter;
@InjectMocks
private ArticleConverterImpl articleConverter;
@Test
void shouldConvertArticleToShowArticleDTOAndReturnRightId() {
Article article = new Article();
Long id = 1L;
article.setId(id);
ShowArticleDTO showArticleDTO = articleConverter.convert(article);
assertEquals(id, showArticleDTO.getId());
}
@Test
void shouldConvertArticleToShowArticleDTOAndReturnRightTitle() {
Article article = new Article();
String title = "test title";
article.setTitle(title);
ShowArticleDTO showArticleDTO = articleConverter.convert(article);
assertEquals(title, showArticleDTO.getTitle());
}
@Test
void shouldConvertArticleToShowArticleDTOAndReturnRightDate() {
Article article = new Article();
LocalDateTime localDateTime = LocalDateTime.now();
article.setLocalDateTime(localDateTime);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN);
String formatLocalDate = formatter.format(localDateTime);
ShowArticleDTO showArticleDTO = articleConverter.convert(article);
assertEquals(formatLocalDate, showArticleDTO.getDate());
}
@Test
void shouldConvertArticleToShowArticleDTOAndReturnRightContent() {
Article article = new Article();
String content = "test content";
article.setFullContent(content);
ShowArticleDTO showArticleDTO = articleConverter.convert(article);
assertEquals(content, showArticleDTO.getFullContent());
assertEquals(content, showArticleDTO.getShortContent());
}
@Test
void shouldConvertArticleToShowArticleDTOAndReturnRightComments() {
Set<Comment> comments = new HashSet<>();
Comment comment = new Comment();
Long commentId = 1L;
comment.setId(commentId);
LocalDateTime localDateTimeCommit = LocalDateTime.now();
comment.setLocalDateTime(localDateTimeCommit);
String contentComment = "test content comment";
comment.setFullContent(contentComment);
comments.add(comment);
Comment comment2 = new Comment();
Long commentId2 = 2L;
comment2.setId(commentId2);
LocalDateTime localDateTimeCommit2 = LocalDateTime.now();
comment2.setLocalDateTime(localDateTimeCommit2);
String contentComment2 = "test content comment2";
comment2.setFullContent(contentComment2);
comments.add(comment2);
Article article = new Article();
article.setComments(comments);
List<ShowCommentDTO> commentDTOs = comments.stream()
.map(commentConverter::convert)
.collect(Collectors.toList());
ShowArticleDTO showArticleDTO = articleConverter.convert(article);
assertEquals(commentDTOs, showArticleDTO.getComments());
}
@Test
void shouldConvertAddArticleDTOToArticleAndReturnRightTitle() {
AddArticleDTO addArticleDTO = new AddArticleDTO();
String title = "test";
addArticleDTO.setTitle(title);
Article article = articleConverter.convert(addArticleDTO);
assertEquals(title, article.getTitle());
}
@Test
void shouldConvertAddArticleDTOToArticleAndReturnRightContent() {
AddArticleDTO addArticleDTO = new AddArticleDTO();
String content = "test";
addArticleDTO.setContent(content);
Article article = articleConverter.convert(addArticleDTO);
assertEquals(content, article.getFullContent());
}
@Test
void shouldFormatLocalDateTime() {
LocalDateTime localDateTime = LocalDateTime.of(2021, 7, 1, 00, 00, 00);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN);
String formatData = "2021-07-01 00:00:00";
assertEquals(formatData, localDateTime.format(formatter));
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/PageDTO.java
package ru.mail.senokosov.artem.service.model;
import lombok.Data;
import ru.mail.senokosov.artem.service.model.show.*;
import java.util.ArrayList;
import java.util.List;
@Data
public class PageDTO {
private Long countOfPages;
private Long currentPage;
private Long beginPage;
private Long endPage;
private List<ShowUserDTO> users = new ArrayList<>();
private List<ShowReviewDTO> reviews = new ArrayList<>();
private List<ShowArticleDTO> articles = new ArrayList<>();
private List<ShowItemDTO> items = new ArrayList<>();
private List<ShowOrderDTO> orders = new ArrayList<>();
private Integer startPosition;
}<file_sep>/web-module/src/test/java/ru/mail/senokosov/artem/web/security/UserSecurityAPITest.java
package ru.mail.senokosov.artem.web.security;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import ru.mail.senokosov.artem.service.UserService;
import ru.mail.senokosov.artem.web.config.TestUserDetailsServiceConfig;
import ru.mail.senokosov.artem.web.controller.api.UserAPIController;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static ru.mail.senokosov.artem.web.constant.PathConstant.REST_API_USER_PATH;
import static ru.mail.senokosov.artem.web.constant.PathConstant.USERS_PATH;
@ActiveProfiles("security")
@WebMvcTest(controllers = UserAPIController.class,
excludeAutoConfiguration = UserDetailsServiceAutoConfiguration.class)
@Import(TestUserDetailsServiceConfig.class)
public class UserSecurityAPITest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void shouldUserWithRoleRestAPIHasAccessToAddUser() throws Exception {
mockMvc.perform(
post(REST_API_USER_PATH + USERS_PATH)
.contentType(MediaType.APPLICATION_JSON)
.with(SecurityMockMvcRequestPostProcessors.httpBasic("<EMAIL>", "test"))
).andExpect(status().isBadRequest());
}
@Test
void shouldUserWithAdminRoleHasNotAccessDeniedToAddUser() throws Exception {
mockMvc.perform(
get(REST_API_USER_PATH + USERS_PATH)
.contentType(MediaType.APPLICATION_JSON)
.with(SecurityMockMvcRequestPostProcessors.httpBasic("<EMAIL>", "test"))
).andExpect(status().isForbidden());
}
@Test
void shouldUserWithSellerRoleHasNotAccessDeniedToAddUser() throws Exception {
mockMvc.perform(
get(REST_API_USER_PATH + USERS_PATH)
.contentType(MediaType.APPLICATION_JSON)
.with(SecurityMockMvcRequestPostProcessors.httpBasic("<EMAIL>", "test"))
).andExpect(status().isForbidden());
}
@Test
void shouldUserWithCustomerRoleHasNotAccessDeniedToAddUser() throws Exception {
mockMvc.perform(
get(REST_API_USER_PATH + USERS_PATH)
.contentType(MediaType.APPLICATION_JSON)
.with(SecurityMockMvcRequestPostProcessors.httpBasic("<EMAIL>", "test"))
).andExpect(status().isForbidden());
}
}<file_sep>/docker-compose.yml
version: '3.3'
services:
db:
image: mysql:latest
restart: always
environment:
MYSQL_DATABASE: 'project_db'
MYSQL_ROOT_PASSWORD: '<PASSWORD>'
ports:
- '3306:3306'
expose:
- '3306'
command: [ 'mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci' ]
mailhog:
image: mailhog/mailhog:latest
restart: always
ports:
- 1025:1025
- 8025:8025<file_sep>/web-module/src/main/java/ru/mail/senokosov/artem/web/config/PersistenceConfig.java
package ru.mail.senokosov.artem.web.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EntityScan("ru.mail.senokosov.artem.repository.model")
public class PersistenceConfig {
}<file_sep>/web-module/src/main/java/ru/mail/senokosov/artem/web/config/handler/CustomAccessDeniedHandler.java
package ru.mail.senokosov.artem.web.config.handler;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import static ru.mail.senokosov.artem.web.constant.PathConstant.ACCESS_DENIED_PATH;
@Log4j2
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (Objects.nonNull(authentication)) {
String name = authentication.getName();
String uri = request.getRequestURI();
log.info("User {} attempted to access the protected URL: {}", name, uri);
}
response.sendRedirect(ACCESS_DENIED_PATH);
}
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/model/Role.java
package ru.mail.senokosov.artem.repository.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Data
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(cascade = CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "role_id")
@ToString.Exclude
@EqualsAndHashCode.Exclude
private Set<User> users = new HashSet<>();
@Column(name = "role_name")
private String roleName;
}<file_sep>/repository-module/src/main/java/ru/mail/senokosov/artem/repository/UserRepository.java
package ru.mail.senokosov.artem.repository;
import ru.mail.senokosov.artem.repository.model.User;
import java.util.List;
public interface UserRepository extends GenericRepository<Long, User> {
User findUserByUsername(String email);
Long getCountUsers();
List<User> findAll(int startPosition, int maximumUsersOnPage);
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/constant/FormatConstant.java
package ru.mail.senokosov.artem.service.constant;
public interface FormatConstant {
String DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/converter/impl/UserConverterImpl.java
package ru.mail.senokosov.artem.service.converter.impl;
import org.springframework.stereotype.Component;
import ru.mail.senokosov.artem.repository.model.Role;
import ru.mail.senokosov.artem.repository.model.User;
import ru.mail.senokosov.artem.repository.model.UserInfo;
import ru.mail.senokosov.artem.service.converter.UserConverter;
import ru.mail.senokosov.artem.service.model.add.AddUserDTO;
import ru.mail.senokosov.artem.service.model.show.ShowUserDTO;
import ru.mail.senokosov.artem.service.model.show.ShowUserInfoDTO;
import java.util.Objects;
@Component
public class UserConverterImpl implements UserConverter {
@Override
public ShowUserDTO convert(User user) {
ShowUserDTO showUserDTO = new ShowUserDTO();
Long id = user.getId();
showUserDTO.setId(id);
String lastName = user.getLastName();
showUserDTO.setLastName(lastName);
String firstName = user.getFirstName();
showUserDTO.setFirstName(firstName);
String middleName = user.getMiddleName();
showUserDTO.setMiddleName(middleName);
String email = user.getEmail();
showUserDTO.setEmail(email);
if (Objects.nonNull(user.getRole())) {
Role role = user.getRole();
String roleName = role.getRoleName();
showUserDTO.setRoleName(roleName);
}
return showUserDTO;
}
@Override
public User convert(AddUserDTO addUserDTO) {
User user = new User();
String lastName = addUserDTO.getLastName();
user.setLastName(lastName);
String firstName = addUserDTO.getFirstName();
user.setFirstName(firstName);
String middleName = addUserDTO.getMiddleName();
user.setMiddleName(middleName);
String email = addUserDTO.getEmail();
user.setEmail(email);
UserInfo userInfo = new UserInfo();
String address = addUserDTO.getAddress();
userInfo.setAddress(address);
String telephone = addUserDTO.getTelephone();
userInfo.setTelephone(telephone);
userInfo.setUser(user);
user.setUserInfo(userInfo);
return user;
}
@Override
public ShowUserInfoDTO convertUserToUserDetailsDTO(User user) {
ShowUserInfoDTO showUserInfoDTO = new ShowUserInfoDTO();
Long id = user.getId();
showUserInfoDTO.setId(id);
String firstName = user.getFirstName();
showUserInfoDTO.setFirstName(firstName);
String lastName = user.getLastName();
showUserInfoDTO.setLastName(lastName);
UserInfo userInfo = (UserInfo) user.getUserInfo();
if (Objects.nonNull(userInfo)) {
String address = userInfo.getAddress();
showUserInfoDTO.setAddress(address);
String telephone = userInfo.getTelephone();
showUserInfoDTO.setTelephone(telephone);
}
return showUserInfoDTO;
}
}<file_sep>/service-module/src/main/java/ru/mail/senokosov/artem/service/model/UserDTO.java
package ru.mail.senokosov.artem.service.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.lang.NonNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.UUID;
@Getter
@Setter
public class UserDTO {
private Long id;
private UUID uuid;
@NonNull
@Size(min = 2, max = 40, message = "characters count should be in the range between 2 and 40")
private String secondname;
@NonNull
@Size(min = 2, max = 20, message = "characters count should be in the range between 2 and 20")
private String firstname;
@NonNull
@Size(min = 2, max = 40, message = "characters count should be in the range between 2 and 40")
private String middlename;
@NonNull
@Pattern(regexp = "^[-\\w.]+@([A-z0-9][-A-z0-9]+\\/)+[A-z](2,4)$")
private String email;
private String password;
private String roleName;
} | 8c6ececce64de9393bd7a54db47245f6a30925bc | [
"SQL",
"YAML",
"Markdown",
"INI",
"Java"
] | 55 | Java | ArtyomSenokosov/Project | ff762095a3d4546941c1fedfab83174019468e13 | 9a58bc1d05e0083be5742d1e022214f27a229ce9 |
refs/heads/master | <file_sep>//
// RealVectorOperations.swift
// SMUGMath
//
// Created by <NAME> on 2014-06-21.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
import Accelerate
// MARK: Utilities
func operateOn<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( x: C, y: C, operation: (UnsafePointer<Float>, UnsafePointer<Float>, inout [Float], vDSP_Length) -> Void ) -> [Float] {
assert( count(x) == count(y) )
var result = [Float](count: count(x), repeatedValue: 0)
x.withUnsafeBufferPointer { (xPointer: UnsafeBufferPointer<Float>) -> Void in
y.withUnsafeBufferPointer { (yPointer: UnsafeBufferPointer<Float>) -> Void in
operation(xPointer.baseAddress, yPointer.baseAddress, &result, vDSP_Length(count(result)))
}
}
return result
}
func operateOn<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( x: C, y: C, operation: (UnsafePointer<Double>, UnsafePointer<Double>, inout [Double], vDSP_Length) -> Void ) -> [Double] {
assert( count(x) == count(y) )
var result = [Double](count: count(x), repeatedValue: 0)
x.withUnsafeBufferPointer { (xPointer: UnsafeBufferPointer<Double>) -> Void in
y.withUnsafeBufferPointer { (yPointer: UnsafeBufferPointer<Double>) -> Void in
operation(xPointer.baseAddress, yPointer.baseAddress, &result, vDSP_Length(count(result)))
}
}
return result
}
// MARK: Multiplication
public func mul<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( var x: C, y: C ) -> [Float] {
return operateOn(x, y) {
vDSP_vmul($0, 1, $1, 1, &$2, 1, $3)
return
}
}
public func mul<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( var x: C, y: C ) -> [Double] {
return operateOn(x, y) {
vDSP_vmulD($0, 1, $1, 1, &$2, 1, $3)
return
}
}
public func *<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( var x: C, y: C ) -> [Float] {
return mul( x, y )
}
public func *<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( var x: C, y: C ) -> [Double] {
return mul( x, y )
}
// MARK: Division
public func div<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( var x: C, y: C ) -> [Float] {
return operateOn(x, y) {
// Note: Operands flipped because vdiv does 2nd param / 1st param
vDSP_vdiv($1, 1, $0, 1, &$2, 1, $3)
return
}
}
public func div<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( var x: C, y: C ) -> [Double] {
return operateOn(x, y) {
// Note: Operands flipped because vdiv does 2nd param / 1st param
vDSP_vdivD($1, 1, $0, 1, &$2, 1, $3)
return
}
}
public func /<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( var x: C, y: C ) -> [Float] {
return div(x, y)
}
public func /<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( var x: C, y: C ) -> [Double] {
return div(x, y)
}
// MARK: Addition
public func add<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( var x: C, y: C ) -> [Float] {
return operateOn(x, y) {
vDSP_vadd($0, 1, $1, 1, &$2, 1, $3)
return
}
}
public func add<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( var x: C, y: C ) -> [Double] {
return operateOn(x, y) {
vDSP_vaddD($0, 1, $1, 1, &$2, 1, $3)
return
}
}
// The below operators are ambiguous, as arrays can also be "added" together for appending
//public func +<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>( var x: C, y: C ) -> [Float] {
// return add(x, y)
//}
//
//public func +<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>( var x: C, y: C ) -> [Double] {
// return add(x, y)
//}<file_sep>//
// FFTOperations.swift
// SMUGMath
//
// Created by <NAME> on 2014-06-21.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
import Accelerate
public func create_fft_setup( length: Int ) -> FFTSetup {
return vDSP_create_fftsetup( vDSP_Length(log2(CDouble(length))), FFTRadix(kFFTRadix2) );
}
public func create_fft_setupD( length: Int ) -> FFTSetup {
return vDSP_create_fftsetupD( vDSP_Length(log2(CDouble(length))), FFTRadix(kFFTRadix2) );
}
public func fft<C: Unsafeable where C.Generator.Element == Float, C.Index == Int>(setup: FFTSetup, x: C, fft_length: Int) -> SplitComplexVector<Float> {
var splitComplex = SplitComplexVector<Float>(count: count(x) / 2, repeatedValue: Complex<Float>(real: 0, imag: 0))
var dspSplitComplex = DSPSplitComplex( realp: &splitComplex.real, imagp: &splitComplex.imag )
x.withUnsafeBufferPointer { (xPointer: UnsafeBufferPointer<Float>) -> Void in
var xAsComplex = UnsafePointer<DSPComplex>( xPointer.baseAddress )
vDSP_ctoz(xAsComplex, 2, &dspSplitComplex, 1, vDSP_Length(splitComplex.count))
vDSP_fft_zrip(setup, &dspSplitComplex, 1, vDSP_Length(log2(CDouble(fft_length))), FFTDirection(kFFTDirection_Forward))
}
return splitComplex
}
public func fft<C: Unsafeable where C.Generator.Element == Double, C.Index == Int>(setup: FFTSetup, x: C, fft_length: Int) -> SplitComplexVector<Double> {
var splitComplex = SplitComplexVector<Double>(count: count(x) / 2, repeatedValue: Complex<Double>(real: 0, imag: 0))
var dspSplitComplex = DSPDoubleSplitComplex( realp: &splitComplex.real, imagp: &splitComplex.imag )
x.withUnsafeBufferPointer { (xPointer: UnsafeBufferPointer<Double>) -> Void in
var xAsComplex = UnsafePointer<DSPDoubleComplex>( xPointer.baseAddress )
vDSP_ctozD(xAsComplex, 2, &dspSplitComplex, 1, vDSP_Length(splitComplex.count))
vDSP_fft_zripD(setup, &dspSplitComplex, 1, vDSP_Length(log2(CDouble(fft_length))), FFTDirection(kFFTDirection_Forward))
}
return splitComplex
}
public func ifft(setup: FFTSetup, var X: SplitComplexVector<Float>, fft_length: Int) -> [Float] {
var result = [Float](count: fft_length, repeatedValue: 0)
var dspSplitComplex = DSPSplitComplex( realp: &X.real, imagp: &X.imag )
result.withUnsafeBufferPointer { (resultPointer: UnsafeBufferPointer<Float>) -> Void in
var resultAsComplex = UnsafeMutablePointer<DSPComplex>( resultPointer.baseAddress )
vDSP_fft_zrip(setup, &dspSplitComplex, 1, vDSP_Length(log2(CDouble(fft_length))), FFTDirection(kFFTDirection_Inverse))
vDSP_ztoc(&dspSplitComplex, 1, resultAsComplex, 2, vDSP_Length(X.count))
}
return result
}
public func ifft(setup: FFTSetup, var X: SplitComplexVector<Double>, fft_length: Int) -> [Double] {
var result = [Double](count: fft_length, repeatedValue: 0)
var dspSplitComplex = DSPDoubleSplitComplex( realp: &X.real, imagp: &X.imag )
result.withUnsafeBufferPointer { (resultPointer: UnsafeBufferPointer<Double>) -> Void in
var resultAsComplex = UnsafeMutablePointer<DSPDoubleComplex>( resultPointer.baseAddress )
vDSP_fft_zripD(setup, &dspSplitComplex, 1, vDSP_Length(log2(CDouble(fft_length))), FFTDirection(kFFTDirection_Inverse))
vDSP_ztocD(&dspSplitComplex, 1, resultAsComplex, 2, vDSP_Length(X.count))
}
return result
} | b8e38cc47d85d7d2c86953fb637654beea1203c5 | [
"Swift"
] | 2 | Swift | vitoziv/SMUGMath-Swift | e7d91197a8a29dfcd692f992ea6d35a158178f89 | 5a5e849f04e8139a72e865570a306d2b6592b209 |
refs/heads/master | <repo_name>ipmanlk/EasySystem<file_sep>/tasks/getItem.php
<?php
// 1 - all done
// 2 - item ID duplicate
// 3 - input details are missing
require_once 'checkSession.php';
if (isset($_GET['itemID']) && !empty($_GET['itemID'])) {
require_once '../setup/config.php';
$itemID = trim($_GET['itemID']);
$stmt = mysqli_prepare($link, "SELECT * FROM item_stock WHERE itemID=?");
mysqli_stmt_bind_param($stmt, "s", $itemID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$itemData = [];
while ($row = mysqli_fetch_assoc($result)) {
$itemData[] = $row;
}
mysqli_stmt_close($stmt);
mysqli_close($link);
echo (json_encode($itemData));
} else {
echo "3";
}
?>
<file_sep>/index.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Easy System : Index</title>
<link rel="stylesheet" href="./res/css/bootstrap.min.css">
</head>
<body>
<?php
require_once './tasks/checkSession.php';
require_once './res/content/navBar.php';
?>
<div class="container-fluid mt-4">
<div class="row">
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">Items</h4>
<p>Things you can do.</p>
<ul class="list-group">
<li class="list-group-item">Add Items</li>
<li class="list-group-item">Update Items</li>
<li class="list-group-item">Remove Items</li>
</ul>
<a href="items.php" class="btn btn-primary btn-block mt-3">Go to Items</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">Deliver</h4>
<p>Things you can do.</p>
<ul class="list-group">
<li class="list-group-item">Deliver items.</li>
<li class="list-group-item">-</li>
<li class="list-group-item">-</li>
</ul>
<a href="deliver.php" class="btn btn-primary btn-block mt-3">Go to Deliver</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">Reports</h4>
<p>Things you can do.</p>
<ul class="list-group">
<li class="list-group-item">Search log.</li>
<li class="list-group-item">Get reports.</li>
<li class="list-group-item">Download PDF.</li>
</ul>
<a href="reports.php" class="btn btn-primary btn-block mt-3">Go to Reports</a>
</div>
</div>
</div>
</div>
</div>
<!-- scripts -->
<script src="./res/js/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="./res/js/bootstrap.min.js" charset="utf-8"></script>
</body>
</html>
<file_sep>/items.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Easy System : Stock Items</title>
<link rel="stylesheet" href="./res/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/r-2.2.2/datatables.min.css"/>
</head>
<body>
<?php
require_once './tasks/checkSession.php';
require_once './res/content/navBar.php';
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="pb-2 mt-4 mb-2 border-bottom">
<h2>Items</h2>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-4">
<button type="button" class="btn btn-warning" onclick="receiveItems();">Receive Item Stock</button>
<button type="button" class="btn btn-success" onclick="addItems();">Add New Item</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>Item ID</th>
<th>Item Description</th>
<th>Stocking U/M</th>
<th>Part Number</th>
<th>Qty on Hand</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
require_once("./setup/config.php");
$result=mysqli_query($link,"SELECT * FROM item_stock");
while ($row=mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['itemID'] . '</td>';
echo '<td>' . $row['itemDes'] . '</td>';
echo '<td>' . $row['stockingUM'] . '</td>';
echo '<td>' . $row['partNum'] . '</td>';
echo '<td>' . $row['qty'] . '</td>';
echo '<td>' .
'<button type="button" class="btn btn-primary" onclick="editItem(' ."'" . $row['itemID'] . "'". ')">Edit</button>'
.
'<button type="button" class="btn btn-danger ml-2" onclick="deleteItem(' ."'" . $row['itemID'] . "'". ')">Delete</button>'
. '</td>';
echo '</tr>';
}
mysqli_close($link);
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- add items -->
<div class="modal fade" id="addItemModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Items</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post" id="addItemModalForm" autocomplete="off">
<div class="form-group">
<label for="itemID">Item ID (*):</label>
<input type="text" class="form-control" id="itemID" name="itemID" maxlength="20">
</div>
<div class="form-group">
<label for="itemDes">Item Description:</label>
<input type="text" class="form-control" id="itemDes" name="itemDes" maxlength="200">
</div>
<div class="form-group">
<label for="stockingUM">Stocking U/M:</label>
<input type="text" class="form-control" id="stockingUM" name="stockingUM" maxlength="20">
</div>
<div class="form-group">
<label for="partNum">Part Number:</label>
<input type="text" class="form-control" id="partNum" name="partNum" maxlength="20">
</div>
<div class="form-group">
<label for="qty">Qty on Hand(*):</label>
<input type="number" class="form-control" id="qty" name="qty" maxlength="10">
</div>
<button id="addItemBtn" onclick="addItem();" class="btn btn-primary">Add New Item</button>
<button id="updateItemBtn" style="display:none" onclick="updateItem();" class="btn btn-warning">Update Item</button>
<div style="display:none;" class="alert alert-success mt-3" id="addItemModalOutput">
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- confirm modal -->
<div class="modal fade" id="confirmModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Confirm Delete</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Do you really want to delete this item?
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button id="confirmDelete" type="button" class="btn btn-danger">Yes, Delete!</button>
</div>
</div>
</div>
</div>
<!-- receive modal -->
<!-- add items -->
<div class="modal fade" id="receiveItemModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Item Qty to Stock</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="post" id="receiveItemModalForm" autocomplete="off">
<div class="form-group">
<label for="receiveItemID">Item ID (*):</label>
<input type="text" class="form-control" id="receiveItemID" name="receiveItemID" maxlength="20">
<ul class="list-group" id="receiveItemIDSuggestions">
</ul>
</div>
<div class="form-group">
<label for="receiveQty">Qty (*):</label>
<input type="number" class="form-control" id="receiveQty" name="receiveQty" maxlength="10">
</div>
<button id="receiveItemBtn" onclick="receiveItem();" class="btn btn-primary">Receive Item Stock</button>
<div style="display:none;" class="alert alert-success mt-3" id="receiveItemModalOutput">
</div>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- scripts -->
<script src="./res/js/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="./res/js/bootstrap.min.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/r-2.2.2/datatables.min.js"></script>
<script src="./res/js/items.js" charset="utf-8"></script>
<script type="text/javascript">
</script>
</body>
</html>
<file_sep>/deliver.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Easy System : Deliver</title>
<link rel="stylesheet" href="./res/css/bootstrap.min.css">
</head>
<body>
<?php
require_once './tasks/checkSession.php';
require_once './res/content/navBar.php';
?>
<div class="container mt-2">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 col-sm-12">
<div class="card">
<div class="card-header"><h4>Deliver Item</h4></div>
<div class="card-body">
<form method="post" id="deliverItemForm" autocomplete="off">
<div class="form-group">
<label for="itemID">Item ID (*):</label>
<input type="text" class="form-control" id="itemID" name="itemID" maxlength="20">
<ul class="list-group" id="itemIDSuggestions">
</ul>
</div>
<div class="form-group">
<label for="qty">Qty (*):</label>
<input type="number" class="form-control" id="qty" name="qty" maxlength="10">
</div>
<div class="form-group">
<label for="itemDes">Deliver Note:</label>
<input type="text" class="form-control" id="dNote" name="dNote" maxlength="20">
</div>
<div class="form-group">
<label for="stockingUM">MRN:</label>
<input type="text" class="form-control" id="mrn" name="mrn" maxlength="20">
</div>
<div class="form-group">
<label for="partNum">Location:</label>
<input type="text" class="form-control" id="location" name="location" maxlength="200">
<ul class="list-group" id="locationSuggestions">
</ul>
</div>
<button id="deliverItemBtn" type="submit" onclick="deliverItem();" class="btn btn-primary">Deliver Item</button>
<div style="display:none;" class="alert alert-success mt-3" id="deliverItemOutput">
</div>
</form>
</div>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
<!-- scripts -->
<script src="./res/js/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="./res/js/bootstrap.min.js" charset="utf-8"></script>
<script src="./res/js/deliver.js" charset="utf-8"></script>
</body>
</html>
<file_sep>/tasks/addItem.php
<?php
// 1 - all done
// 2 - item ID duplicate
// 3 - input details are missing
require_once 'checkSession.php';
if (isset($_POST['itemID']) && !empty($_POST['itemID']) && isset($_POST['qty']) && !empty($_POST['qty'])) {
require_once '../setup/config.php';
$itemID = trim($_POST['itemID']);
$itemDes = trim($_POST['itemDes']);
$stockingUM = trim($_POST['stockingUM']);
$partNum = trim($_POST['partNum']);
$qty = trim($_POST['qty']);
$stmt = mysqli_prepare($link, "SELECT itemID FROM item_stock WHERE itemID=?");
mysqli_stmt_bind_param($stmt,'s',$itemID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
echo "2";
exit();
} else {
$stmt = mysqli_prepare($link, "INSERT INTO item_stock VALUES (?,?,?,?,?)");
mysqli_stmt_bind_param($stmt, "ssssd", $itemID,$itemDes,$stockingUM,$partNum,$qty);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "1";
mysqli_close($link);
}
} else {
echo "3";
exit();
}
?>
<file_sep>/tasks/getItems.php
<?php
require_once '../setup/config.php';
$stmt = mysqli_prepare($link, "SELECT * FROM item_stock");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$itemData = [];
while ($row = mysqli_fetch_assoc($result)) {
$itemData[] = $row;
}
mysqli_stmt_close($stmt);
mysqli_close($link);
echo (json_encode($itemData));
?>
<file_sep>/README.md
# Easy System
*Simple stock management system for a small warehouse*
## Instructions
- Run **./install/index.php** for instructions & installation.
- You can setup everything manually if you want.
- Database can be found in **./db** directory.
## Website
- https://navinda.xyz/
## Contact Me
- EMail : <EMAIL>
## Download
1. You can download this project in zip format.
2. You can also clone the project with Git by running,
```git
$ git clone https://github.com/ipmanlk/EasySystem.git
```
<file_sep>/tasks/receiveItem.php
<?php
// 1 - all done
// 2 - item ID duplicate
// 3 - input details are missing
// 4 - error
require_once 'checkSession.php';
if (isset($_POST['receiveItemID']) && !empty($_POST['receiveItemID']) && isset($_POST['receiveQty']) && !empty($_POST['receiveQty'])) {
require_once '../setup/config.php';
$itemID = trim($_POST['receiveItemID']);
$qty = trim($_POST['receiveQty']);
$stmt = mysqli_prepare($link, "SELECT qty FROM item_stock WHERE itemID=?");
mysqli_stmt_bind_param($stmt,'s',$itemID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$stockQty = (mysqli_fetch_array($result))['qty'];
mysqli_stmt_close($stmt);
$newQty = $stockQty + $qty;
$stmt = mysqli_prepare($link, "UPDATE item_stock SET qty=? WHERE itemID=?");
mysqli_stmt_bind_param($stmt,'ds',$newQty, $itemID);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$stmt = mysqli_prepare($link, "INSERT INTO item_received(itemID, qty) VALUES (?,?)");
mysqli_stmt_bind_param($stmt, "sd", $itemID, $qty);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
if ($result == TRUE) {
echo "1";
} else {
echo "4";
}
} else {
echo "3";
exit();
}
?>
<file_sep>/db/easysystem.sql
-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Aug 28, 2018 at 10:23 AM
-- Server version: 10.1.35-MariaDB
-- PHP Version: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `navindax_easysystem`
--
-- --------------------------------------------------------
--
-- Table structure for table `item_delivered`
--
CREATE TABLE `item_delivered` (
`deliverID` int(10) NOT NULL,
`itemID` varchar(20) NOT NULL,
`dateTime` datetime DEFAULT CURRENT_TIMESTAMP,
`qty` decimal(10,2) NOT NULL,
`dNote` varchar(20) DEFAULT NULL,
`mrn` varchar(20) DEFAULT NULL,
`location` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `item_delivered`
--
INSERT INTO `item_delivered` (`deliverID`, `itemID`, `dateTime`, `qty`, `dNote`, `mrn`, `location`) VALUES
(12, 'ELE00010103', '2018-08-06 05:19:54', '10.00', '45464', '466', '664');
-- --------------------------------------------------------
--
-- Table structure for table `item_received`
--
CREATE TABLE `item_received` (
`receiveID` int(10) NOT NULL,
`itemID` varchar(20) NOT NULL,
`dateTime` datetime DEFAULT CURRENT_TIMESTAMP,
`qty` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `item_received`
--
INSERT INTO `item_received` (`receiveID`, `itemID`, `dateTime`, `qty`) VALUES
(9, 'ELE00010103', '2018-08-06 05:19:06', '20.00');
-- --------------------------------------------------------
--
-- Table structure for table `item_stock`
--
CREATE TABLE `item_stock` (
`itemID` varchar(20) NOT NULL,
`itemDes` varchar(200) DEFAULT NULL,
`stockingUM` varchar(20) DEFAULT NULL,
`partNum` varchar(20) DEFAULT NULL,
`qty` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `item_stock`
--
INSERT INTO `item_stock` (`itemID`, `itemDes`, `stockingUM`, `partNum`, `qty`) VALUES
('ELE00010101', 'DMC117035', 'NOS', 'DMC117035', '0.00'),
('ELE00010102', 'Excel CSE 4PR Grey X 305M', 'BOXES', '', '36.00'),
('ELE00010103', 'DMC117060', 'NOS', 'DMC117060', '59.00'),
('ELE00010108', 'DMC117140', 'NOS', 'DMC117140', '209.00'),
('ELE00020104', 'DMC122042', 'NOS', 'DMC122042', '125.00'),
('ELE00030101', 'DMC115022', 'NOS', 'DMC115022', '1625.00'),
('ELE00030102', 'DMC115028', 'NOS', 'DMC115028', '1380.00'),
('ELE00030103', 'DMC115035', 'NOS', 'DMC115035', '4112.00'),
('ELE00030104', 'DMC115040', 'NOS', 'DMC115040', '373.00'),
('ELE00030105', 'DMC115048', 'NOS', 'DMC115048', '3106.00'),
('ELE00030107', 'DMC115063', 'NOS', 'DMC115063', '1973.00'),
('ELE00030108', 'DMC115075', 'NOS', 'DMC115075', '760.00'),
('ELE00030110', 'DMC115110', 'NOS', 'DMC115110', '2050.00'),
('ELV00010101', 'EXCEL cat 6 UPT cable', 'BOX', '', '84.00'),
('ELV00010301', 'CAT 6 plus 23 AWG', 'BOXES', '', '2.00'),
('ELV00020102', 'RFID MIFARE white Blank card', 'NOS', '', '1700.00'),
('ELV00030101', 'Battery ASSY 6V ALK AMP', 'NOS', 'A28110', '75.00'),
('ELV00030201', 'Battery ASSY 6V ALK AMP', 'NOS', 'A21100', '1.00'),
('ELV00040201', 'PCB ASSY MT4', 'NOS', 'A38660-DAKOM', '2.00'),
('ELV00040301', 'PCB ASSY MT4', 'NOS', 'A38660-RFIDB', '8.00'),
('ELV00040401', 'PCB MT4 RUC/ECu/MECU RFID', 'NOS', 'A38670-RMGC', '1.00'),
('ELV00050201', 'CONTROL PANEL', 'NOS', 'CLV-33-RL-B-IR', '1.00'),
('ELV00050401', 'CONTROL PANEL', 'NOS', 'CRP073-SS', '1.00'),
('ELV00050501', '19BUTTON CONTROL PANEL', 'NOS', 'CRP193-SS', '1.00'),
('ELV00050601', '10 BURRON CONTROL PANEL', 'NOS', 'CSR103-SS', '2.00'),
('ELV00060201', 'CONFIDANT KIT', 'NOS', 'CS000ES-AAEB-NPS10L', '1.00'),
('ELV00060202', 'CONFIDANT KIT', 'NOS', 'CS000ES-AAEB-NPS10R', '3.00'),
('ELV00060301', 'CONFIDANT KIT', 'NOS', 'CS000EASAEBNPS30L', '3.00'),
('ELV00070101', 'QUNTUM II RFID', 'NOS', 'QPI-12NAHGOLBNOOOBSC', '0.00');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`userID` int(11) NOT NULL,
`username` varchar(10) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`userID`, `username`, `password`) VALUES
(1, 'ShaNiraj', <PASSWORD>');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `item_delivered`
--
ALTER TABLE `item_delivered`
ADD PRIMARY KEY (`deliverID`),
ADD KEY `fk_itemDelivered_itemStock_idx` (`itemID`);
--
-- Indexes for table `item_received`
--
ALTER TABLE `item_received`
ADD PRIMARY KEY (`receiveID`),
ADD KEY `fk_itemReceived_itemStock1_idx` (`itemID`);
--
-- Indexes for table `item_stock`
--
ALTER TABLE `item_stock`
ADD PRIMARY KEY (`itemID`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`userID`),
ADD UNIQUE KEY `username_UNIQUE` (`username`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `item_delivered`
--
ALTER TABLE `item_delivered`
MODIFY `deliverID` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `item_received`
--
ALTER TABLE `item_received`
MODIFY `receiveID` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `userID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `item_delivered`
--
ALTER TABLE `item_delivered`
ADD CONSTRAINT `fk_itemDelivered_itemStock` FOREIGN KEY (`itemID`) REFERENCES `item_stock` (`itemID`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `item_received`
--
ALTER TABLE `item_received`
ADD CONSTRAINT `fk_itemReceived_itemStock1` FOREIGN KEY (`itemID`) REFERENCES `item_stock` (`itemID`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/tasks/updateItem.php
<?php
// 1 - all done
// 2 - item ID duplicate
// 3 - input details are missing
// 4 - error
require_once 'checkSession.php';
if (isset($_POST['itemID']) && !empty($_POST['itemID']) && isset($_POST['qty']) && !empty($_POST['qty'])) {
require_once '../setup/config.php';
$itemID = $_POST['itemID'];
$itemDes = $_POST['itemDes'];
$stockingUM = $_POST['stockingUM'];
$partNum = $_POST['partNum'];
$qty = $_POST['qty'];
$stmt = mysqli_prepare($link, "UPDATE item_stock SET itemID=?, itemDes=?, stockingUM=?, partNum=?, qty=? WHERE itemID=?");
mysqli_stmt_bind_param($stmt,'ssssds',$itemID, $itemDes, $stockingUM, $partNum, $qty, $itemID);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
if ($result == TRUE) {
echo "1";
} else {
echo "4";
}
} else {
echo "3";
exit();
}
?>
<file_sep>/tasks/deliverItem.php
<?php
// 1 - all done
// 2 - item ID does not exist
// 3 - input details are missing
// 4 - stock qty is low
require_once 'checkSession.php';
if (isset($_POST['itemID']) && !empty($_POST['itemID']) && isset($_POST['qty']) && !empty($_POST['qty'])) {
require_once '../setup/config.php';
$itemID = trim($_POST['itemID']);
$qty = trim($_POST['qty']);
$dNote = trim($_POST['dNote']);
$mrn = trim($_POST['mrn']);
$location = trim($_POST['location']);
$stmt = mysqli_prepare($link, "SELECT itemID FROM item_stock WHERE itemID=?");
mysqli_stmt_bind_param($stmt,'s',$itemID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) == 0) {
mysqli_stmt_close($stmt);
echo "2";
exit();
} else {
$stmt = mysqli_prepare($link, "SELECT qty FROM item_stock WHERE itemID=?");
mysqli_stmt_bind_param($stmt,'s',$itemID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$stockQty = (mysqli_fetch_array($result))['qty'];
mysqli_stmt_close($stmt);
if ($qty <= $stockQty) {
//create record in item deliverd
$stmt = mysqli_prepare($link, "INSERT INTO item_delivered(itemID, dNote, mrn, location, qty) VALUES (?,?,?,?,?)");
mysqli_stmt_bind_param($stmt, "ssssd", $itemID,$dNote,$mrn,$location,$qty);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
//update stock
$stmt = mysqli_prepare($link, "UPDATE item_stock SET qty=? WHERE itemID=?");
$currentQty = $stockQty - $qty;
mysqli_stmt_bind_param($stmt,'ds',$currentQty, $itemID);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
//close connection
mysqli_close($link);
echo "1";
} else {
echo "4";
exit();
}
}
} else {
echo "3";
exit();
}
?>
<file_sep>/res/js/items.js
// data table settings
const dataTable = $('.table').DataTable( {
dom: 'Bfrtip',
buttons: [
{
extend: 'pdfHtml5',
exportOptions: {
columns: [ 0, ':visible' ]
}
},
{
extend: 'excelHtml5',
exportOptions: {
columns: [ 0, 1, 2, 3, 4]
}
},
{
extend: 'print',
exportOptions: {
columns: [ 0, 1, 2, 3, 4]
}
}
],
responsive: true
});
$(document).ready(function() {
//submit form
submit();
} );
//load items to data table
function loadItems() {
dataTable.clear();
$.get("./tasks/getItems.php" , function(data) {
const itemsData = JSON.parse(data);
for (item in itemsData) {
dataTable.row.add([
itemsData[item].itemID,
itemsData[item].itemDes,
itemsData[item].stockingUM,
itemsData[item].partNum,
itemsData[item].qty,
`<button type="button" class="btn btn-primary" onclick="editItem('${itemsData[item].itemID}')">Edit</button> <button type="button" class="btn btn-danger" onclick="deleteItem('${itemsData[item].itemID}')">Delete</button>`
]).draw();
}
});
}
function submit() {
$("#addItemModalForm").submit(function(e) {
e.preventDefault();
});
$("#receiveItemModalForm").submit(function(e) {
e.preventDefault();
});
}
//hide output alerts when user type on input field
$('input').on('keyup', function(){
$("#addItemModalOutput").fadeOut();
$("#receiveItemModalOutput").fadeOut();
});
function addItems() {
$("#addItemBtn").show();
$("#updateItemBtn").hide();
$("#itemID").val("");
$("#itemDes").val("");
$("#stockingUM").val("");
$("#partNum").val("");
$("#qty").val("");
$("#addItemModalOutput").hide();
$("#addItemModal").modal('show');
}
function addItem() {
$.ajax({
type: 'POST',
url: './tasks/addItem.php',
data: $('#addItemModalForm').serialize(),
dataType: "html",
async: true,
success: function(msg) {
$("#addItemModalOutput").fadeIn();
if (msg == 1) {
loadItems();
showOutputMsg("#addItemModalOutput","good","Item added.");
//clear input form
$('#addItemModalForm').find('input').val('');
} else if (msg == 2) {
showOutputMsg("#addItemModalOutput","bad","Item ID is already in the database!.");
} else {
showOutputMsg("#addItemModalOutput","bad","Input details are missing!.");
}
}
});
}
// edit item
function editItem(itemID) {
$.get("./tasks/getItem.php?itemID=" + itemID, function(data) {
let itemData = JSON.parse(data);
$("#itemID").val(itemData[0].itemID);
$("#itemDes").val(itemData[0].itemDes);
$("#stockingUM").val(itemData[0].stockingUM);
$("#partNum").val(itemData[0].partNum);
$("#qty").val(itemData[0].qty);
$("#addItemBtn").hide();
$("#updateItemBtn").show();
$("#addItemModalOutput").hide();
$("#addItemModal").modal('show');
});
}
//update item
function updateItem() {
$.ajax({
type: 'POST',
url: './tasks/updateItem.php',
data: $('#addItemModalForm').serialize(),
dataType: "html",
async: true,
success: function(msg) {
$("#addItemModalOutput").fadeIn();
if (msg == 1) {
loadItems();
showOutputMsg("#addItemModalOutput","good","Item updated.");
} else if (msg == 4) {
showOutputMsg("#addItemModalOutput","bad","Error.");
} else {
showOutputMsg("#addItemModalOutput","bad","Input details are missing!.");
}
}
});
}
//delete item
function deleteItem(itemID) {
$('#confirmModal').modal('show');
$('#confirmDelete').click(function() {
$.get("./tasks/deleteItem.php?itemID=" + itemID, function(data) {
if (data == '1') {
dataTable.clear().draw();
loadItems();
$('#confirmModal').modal('hide');
} else {
alert("Something went wrong!");
}
});
})
}
function receiveItems() {
$("#receiveItemModal").modal('show');
}
function receiveItem() {
$.ajax({
type: 'POST',
url: './tasks/receiveItem.php',
data: $('#receiveItemModalForm').serialize(),
dataType: "html",
async: true,
success: function(msg) {
$("#receiveItemModalOutput").fadeIn();
if (msg == 1) {
loadItems();
showOutputMsg("#receiveItemModalOutput","good","New stock added!");
$('#receiveItemModalForm').find('input').val('');
} else if (msg == 4) {
showOutputMsg("#receiveItemModalOutput","bad","Error.");
} else {
showOutputMsg("#receiveItemModalOutput","bad","Input details are missing!.");
}
}
});
}
//show suggestions
$('#receiveItemID').on('input propertychange', function(){
$('#receiveItemIDSuggestions').empty();
suggestItemIDs();
});
function suggestItemIDs() {
if (notEmpty($('#receiveItemID').val())) {
$.get("./tasks/suggestItemID.php?itemID=" + $('#receiveItemID').val(), function(data) {
const itemIDs = JSON.parse(data);
if (itemIDs[0] !== null) {
for (item in itemIDs) {
$('#receiveItemIDSuggestions').append(`<a href="#"><li class="list-group-item" onclick="setReceiveItemID('${itemIDs[item]}')">${itemIDs[item]}</li></a>`);
}
}
});
}
}
function setReceiveItemID(val) {
$('#receiveItemID').val(val);
$('#receiveItemIDSuggestions').empty();
}
//show output msg
function showOutputMsg(id,type,msg) {
if (type == "bad") {
$(id).removeClass("alert-success");
$(id).addClass("alert-danger");
} else {
$(id).removeClass("alert-danger");
$(id).addClass("alert-success");
}
$(id).text(msg);
$(id).fadeIn();
}
// //on modal Close
// $('#addItemModal').on('hidden.bs.modal', function () {
// loadItems();
// })
//
// $('#receiveItemModal').on('hidden.bs.modal', function () {
// loadItems();
// })
//check values is not null & empty
function notEmpty(val) {
if (val !== null && val!=="") {
return true;
} else {
return false;
}
}
<file_sep>/res/js/login.js
$(document).ready(function() {
submit();
} );
function submit() {
$("#formLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: './tasks/login.php',
data: $('form').serialize(),
dataType: "html",
async: true,
success: function(msg) {
$("#deliverItemOutput").fadeIn();
if (msg !== '1') {
alert("Wrong Username or Password!");
} else {
window.location='index.php';
}
}
});
});
}
<file_sep>/tasks/suggestItemID.php
<?php
require_once 'checkSession.php';
if (isset($_GET['itemID']) && !empty($_GET['itemID'])) {
require_once '../setup/config.php';
$itemID = trim($_GET['itemID']) . '%';
$stmt = mysqli_prepare($link, "SELECT itemID FROM item_stock WHERE itemID LIKE ? ORDER BY itemID LIMIT 4");
mysqli_stmt_bind_param($stmt, "s", $itemID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$itemIDs = [];
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$itemIDs[] = $row['itemID'];
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
echo (json_encode($itemIDs));
}
?>
<file_sep>/tasks/login.php
<?php
require_once '../setup/config.php';
if (isset($_POST['pwd']) && !empty($_POST['pwd']) && isset($_POST['uname']) && !empty($_POST['uname'])) {
$pwd = $_POST['pwd'];
$username = $_POST['uname'];
$stmt = mysqli_prepare($link, "SELECT password FROM user WHERE username=?");
mysqli_stmt_bind_param($stmt,'s', $username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
if (mysqli_num_rows($result) == 1) {
$hash = (mysqli_fetch_array($result))['password'];
if (password_verify($pwd, $hash)) {
session_start();
$_SESSION['username'] = $username;
echo "1";
} else {
echo "2";
}
} else {
echo "2";
}
}
?>
<file_sep>/res/js/deliver.js
$(document).ready(function() {
submit();
} );
function submit() {
$("#deliverItemForm").submit(function(e) {
e.preventDefault();
});
}
function deliverItem() {
$.ajax({
type: 'POST',
url: './tasks/deliverItem.php',
data: $('form').serialize(),
dataType: "html",
async: true,
success: function(msg) {
$("#deliverItemOutput").fadeIn();
if (msg == 1) {
showOutputMsg("good","Deliver completed.");
$('form').find('input').val('');
} else if (msg == 2) {
showOutputMsg("bad","Item ID not found!.");
} else if(msg ==3){
showOutputMsg("bad","Input details are missing!.");
} else {
showOutputMsg("bad","Stock is low!.");
}
}
});
}
//show suggestions
$('#itemID').on('input propertychange', function(){
$('#itemIDSuggestions').empty();
suggestItemIDs();
});
function suggestItemIDs() {
if (notEmpty($('#itemID').val())) {
$.get("./tasks/suggestItemID.php?itemID=" + $('#itemID').val(), function(data) {
const itemIDs = JSON.parse(data);
if (itemIDs[0] !== null) {
for (item in itemIDs) {
$('#itemIDSuggestions').append(`<a href="#"><li class="list-group-item" onclick="setItemID('${itemIDs[item]}')">${itemIDs[item]}</li></a>`);
}
}
});
}
}
function setItemID(val) {
$('#itemID').val(val);
$('#itemIDSuggestions').empty();
}
$('#location').on('input propertychange', function(){
$('#locationSuggestions').empty();
suggestLocations();
});
function suggestLocations() {
if (notEmpty($('#location').val())) {
$.get("./tasks/suggestLocations.php?location=" + $('#location').val(), function(data) {
const locations = JSON.parse(data);
if (locations[0] !== null) {
for (item in locations) {
$('#locationSuggestions').append(`<a href="#"><li class="list-group-item" onclick="setLocation('${locations[item]}')">${locations[item]}</li></a>`);
}
}
});
}
}
function setLocation(val) {
$('#location').val(val);
$('#locationSuggestions').empty();
}
//check values is not null & empty
function notEmpty(val) {
if (val !== null && val!=="") {
return true;
} else {
return false;
}
}
//show output msg
function showOutputMsg(type,msg) {
if (type == "bad") {
$("#deliverItemOutput").removeClass("alert-success");
$("#deliverItemOutput").addClass("alert-danger");
} else {
$("#deliverItemOutput").removeClass("alert-danger");
$("#deliverItemOutput").addClass("alert-success");
}
$("#deliverItemOutput").text(msg);
$("#deliverItemOutput").fadeIn();
}
//hide output alerts when user type on input field
$('input').on('keyup', function(){
$("#deliverItemOutput").fadeOut();
});
<file_sep>/tasks/suggestLocations.php
<?php
require_once 'checkSession.php';
if (isset($_GET['location']) && !empty($_GET['location'])) {
require_once '../setup/config.php';
$location = trim($_GET['location']) . '%';
$stmt = mysqli_prepare($link, "SELECT location FROM item_delivered WHERE location LIKE ? ORDER BY location LIMIT 4");
mysqli_stmt_bind_param($stmt, "s", $location);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$locations = [];
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$locations[] = $row['location'];
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
echo (json_encode($locations));
}
?>
<file_sep>/install/index.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!--
This is a simple install script for Easy System.
I wrote this in a hurry. So, code may look messy.
Really sorry about that. Trust me, you actually
don't need this to get this project up & running!.
-->
<meta charset="utf-8">
<title>Install EasySystem</title>
<link rel="stylesheet" href="../res/css/bootstrap.min.css">
<style>
<?php if (($_SERVER["REQUEST_METHOD"] == "POST") && (!empty($_POST['submit']))) {echo ".container {display:none;}";} ?>
li { font-size: 20px; font-weight: bold;}
h2 { color: blue;}
.good { color: green ;}
.bad { color: red; }
</style>
</head>
<body>
<?php
if (($_SERVER["REQUEST_METHOD"] == "POST") && (!empty($_POST['submit']))) {
$server = $_POST['server'];
$db_name = $_POST['dbname'];
$db_user = $_POST['dbuser'];
$db_pass = $_POST['dbpass'];
$login_user = $_POST['loginuser'];
$login_pass = $_POST['login<PASSWORD>'];
echo "<h2><u>Output</u></h2><ol>";
// connect to database
$link = mysqli_connect($server, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno()){
echo '<li>Connect to database - <span class="bad">failed!</span> : ' . mysqli_connect_error() . '</li>';
exit();
} else {
echo '<li>Connect to database - <span class="good">done!</span></li>';
}
//create easy system user
$login_pass = password_hash($login_pass, PASSWORD_DEFAULT);
//reset user table
if (mysqli_query($link, "TRUNCATE TABLE user")) {
echo '<li>Empty user table - <span class="good">done!</span></li>';
} else {
echo '<li>Empty user table - <span class="bad">failed!</span></li>';
}
//create new user
if (mysqli_query($link, "INSERT INTO user(username,password) VALUES('<PASSWORD>','$login_<PASSWORD>')")) {
echo '<li>Insert new user - <span class="good">done!</span></li>';
} else {
echo '<li>Insert new user - <span class="bad">failed!</span></li>';
}
//write config file
$config_file = fopen("../setup/config.php", "w") or die("Unable to open config file!");
$txt = '<?php' ."\n" . 'define("DB_SERVER", "'. $server . '");'."\n" .'define("DB_USERNAME", "' . $db_user . '");'."\n" .'define("DB_PASSWORD", "' . $<PASSWORD> . '");' . "\n" . 'define("DB_NAME", "' . $db_name . '");'."\n\n" .'$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);'."\n\n" .'if ($link === false) {die("ERROR: Could not connect." . mysqli_connect_error());}' . "\n" . '?>';
fwrite($config_file, $txt);
fclose($config_file);
echo '<li>Setup config file - <span class="good">done!</span></li></ol>';
echo "<h3>Everything is done!. Please delete the <i>install</i> directory from this project!</h3>";
mysqli_close($link);
}
?>
<div class="container">
<div class="row">
<div class="col-md-12 mt-4">
<h1>EasySystem Installer</h1>
<hr>
<form action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>' method="post">
<div class="alert alert-dark">
<ol>
<li>Creata a database manually (Using phpmyadmin or commandline).</li>
<li>Import '<strong>easysystem.sql</strong>' in <strong>db directory</strong> to that database (Using phpmyadmin or any other method).</li>
<li>Fill the form below and click the install button.</li>
</ol>
</div>
<fieldset>
<legend>Database setup</legend>
<div class="alert alert-danger">
<div class="form-group">
<label for="server">Server (HOST):</label>
<input class="form-control" type="text" name="server" id="server" value="localhost">
</div>
<div class="form-group">
<label for="dbname">Database Name:</label>
<input class="form-control" type="text" name="dbname" id="dbname" value="" autofocus>
</div>
<div class="form-group">
<label for="dbuser">Database User:</label>
<input class="form-control" type="text" name="dbuser" id="dbuser" value="">
</div>
<div class="form-group">
<label for="dbpass">Database User's Password:</label>
<input class="form-control" type="password" name="dbpass" id="dbpass" value="">
</div>
</div>
</fieldset>
<fieldset>
<legend>EasySystem user login setup</legend>
<div class="alert alert-primary">
<div class="form-group">
<label for="loginusername">Login Username:</label>
<input class="form-control" type="text" name="loginuser" id="loginuser" value="">
</div>
<div class="form-group">
<label for="loginpass">Login Password:</label>
<input class="form-control" type="password" name="loginpass" id="loginpass" value="">
</div>
</div>
</fieldset>
<input type="submit" class="btn btn-primary btn-block mb-4" name="submit" value="submit">
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep>/deliverReport.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Easy System : Deliver Report</title>
<link rel="stylesheet" href="./res/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/r-2.2.2/datatables.min.css"/>
</head>
<body>
<?php
require_once './tasks/checkSession.php';
require_once './res/content/navBar.php';
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="pb-2 mt-4 mb-2 border-bottom">
<h2>Deliver Report</h2>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>Item ID</th>
<th>Location</th>
<th>Deliver Date & Time</th>
<th>Deliver Note</th>
<th>MRN</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
require_once("./setup/config.php");
$result=mysqli_query($link,"SELECT stock.itemID, d.location, d.dateTime, d.qty, d.dNote, d.mrn, d.location FROM item_stock stock, item_delivered d WHERE stock.itemID = d.itemID");
while ($row=mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['itemID'] . '</td>';
echo '<td>' . $row['location'] . '</td>';
$dateTime= new DateTime($row['dateTime']);
$dateTime->setTimezone(new DateTimeZone('Asia/Colombo'));
$lkDateTime = $dateTime->format('Y-m-d - g:i A');
echo '<td>' . $lkDateTime . '</td>';
echo '<td>' . $row['dNote'] . '</td>';
echo '<td>' . $row['mrn'] . '</td>';
echo '<td>' . $row['qty'] . '</td>';
echo '</tr>';
}
mysqli_close($link);
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- scripts -->
<script src="./res/js/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="./res/js/bootstrap.min.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/r-2.2.2/datatables.min.js"></script>
<script type="text/javascript">
// data table settings
$(document).ready(function() {
$('.table').DataTable( {
dom: 'Bfrtip',
buttons: ['pdf','excel','print'],
responsive: true
} );
} );
</script>
</body>
</html>
| c1f2cf1204127ae4225c3142a934ff7789fe5eef | [
"Markdown",
"SQL",
"JavaScript",
"PHP"
] | 19 | PHP | ipmanlk/EasySystem | ccfb9c4c57a20134f0d403265c27d0291c549a2f | 1bdd85582477d3a4889dec86c03e52960537c734 |
refs/heads/master | <file_sep>import cv2
import numpy as np
from collections import defaultdict
'''
img = cv2.imread('binary_image.png',0)
img_num = np.array(img)
cv2.imshow("the image",img)
print(img_num.shape)
'''
img_num = np.array([[255,255,255,255],[255,0,0,255],[255,0,0,255],[255,255,255,255]])
img_num = np.array([ [i//255 for i in j] for j in img_num])
print(img_num)
dim = img_num.shape
graph = np.zeros((dim[0]*dim[1]+2,dim[0]*dim[1]+2))
print(graph.shape)
for i in range(1,dim[0]*dim[1]+1):
graph[0][i] = graph[i][dim[0]*dim[1]+1]=10000000000
for i in range(1,dim[0]-1):
for j in range(1,dim[1]-1):
graph[dim[1]*i+j+1][dim[1]*i+j+2] = graph[dim[1]*i+j+2][dim[1]*i+j+1] = max(1 - abs(img_num[i][j]-img_num[i][j+1]),0.1)
graph[dim[1]*(i+1)+j+1][dim[1]*i+j+1] = graph[dim[1]*i+j+1][dim[1]*(i+1)+j+1] = max(1 - abs(img_num[i][j]-img_num[i+1][j]),0.1)
print(graph)
# This class represents a directed graph using adjacency matrix representation
class Graph:
def __init__(self,graph):
self.graph = graph # residual graph
self.org_graph = [i[:] for i in graph]
self. ROW = len(graph)
self.COL = len(graph[0])
self.edges = []
def BFS(self,s, t, parent):
# Mark all the vertices as not visited
visited =[False]*(self.ROW)
# Create a queue for BFS
queue=[]
# Mark the source node as visited and enqueue it
queue.append(s)
visited[s] = True
# Standard BFS Loop x
while queue:
#Dequeue a vertex from queue and print it
u = queue.pop(0)
# Get all adjacent vertices of the dequeued vertex u
# If a adjacent has not been visited, then mark it
# visited and enqueue it
for ind, val in enumerate(self.graph[u]):
if visited[ind] == False and val > 0 :
queue.append(ind)
visited[ind] = True
parent[ind] = u
# If we reached sink in BFS starting from source, then return
# true, else false
return True if visited[t] else False
# Returns the min-cut of the given graph
def minCut(self, source, sink):
# This array is filled by BFS and to store path
parent = [-1]*(self.ROW)
max_flow = 0 # There is no flow initially
# Augment the flow while there is path from source to sink
while self.BFS(source, sink, parent) :
# Find minimum residual capacity of the edges along the
# path filled by BFS. Or we can say find the maximum flow
# through the path found.
path_flow = float("Inf")
s = sink
while(s != source):
path_flow = min (path_flow, self.graph[parent[s]][s])
s = parent[s]
# Add path flow to overall flow
max_flow += path_flow
# update residual capacities of the edges and reverse edges
# along the path
v = sink
while(v != source):
u = parent[v]
self.graph[u][v] -= path_flow
self.graph[v][u] += path_flow
v = parent[v]
# print the edges which initially had weights
# but now have 0 weight
for i in range(self.ROW):
for j in range(self.COL):
if self.graph[i][j] == 0 and self.org_graph[i][j] > 0:
self.edges.append((i,j))
print('ak;df')
# Create a graph given in the above diagram
g = Graph(graph)
source = 0
sink = dim[0]*dim[1]+1
g.minCut(source, sink)
print(g.edges)
#color_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
for ele in g.edges:
color_img[ele[0]][ele[1]] = [255,0,0]
#cv2.imshow('ASDF',color_img)
#cv2.imwrite("bounded_image.png",color_img)
| 79e178bca0712ded0b15ebac53416ae16c21dc6d | [
"Python"
] | 1 | Python | krushnapavan9/Image-segmentation-using-max-flow-min-cut | 025e6be08de92728adbbb907b67e49988674bac2 | fc646cfbd8d94ec114bdf762bad55ce2fbcb5c28 |
refs/heads/master | <file_sep>setwd("~/Desktop")
BF<- read.csv(file="BudgetFood.csv")
attach(BF)
#AND in R is the ampersand &.
data.frame<-subset(BF,wfood>0.75 & size>10)
#combine the two criteria with OR instead of AND using |
some<-subset(BF,wfood>0.75|size>10)
#keep the records with missing values by using the is.na
data<-subset(BF,is.na(size))
#keep the records without missing by using the is.na command and the exclamation point
data<-subset(BF,!is.na(size))
#replace values by missing
BFR<-within(BF,{
size[size==0]<-NA
wfood[wfood==0]<-NA
age[size==0&age==0]<-NA})
<file_sep>set.seed(731)
Male<-c(1445927,513970,13822223)
Female<-c(508029,1976807,26228128)
stem.occupation.by.sex<-as.data.frame(rbind(Male,Female))
names(stem.occupation.by.sex)<-c("STEM","STEM-Related","Non-STEM")
chisq.test(stem.occupation.by.sex)
#Bachelor degree of STEM by gender
M<-c(39545,38773,81270,10723,15972)
F<-c(56304,8611,17270,8119,10691)
BAstem<-as.data.frame(rbind(M,F))
names(BAstem)<-c("Biology","Computer Science","Engineering","Math&Stat","Physical Science")
BAstem
chisq.test(BAstem)
hist(BAstem)
<file_sep># Script to get started with Christenson network data.
# Install and load the 'foreign' package for R.
library('foreign')
# Read in the STATA file
getwd()
rawdata <- read.dta("Dropbox/ma consultants/civrightsnetwork_updated3_statav12.dta")
# Attach data, so as not to have to write name repeatedly.
# Only need to do this once.
attach(rawdata)
# Install and load the 'igraph' package for R.
library("igraph")
# Create an edge-list, with each row indicating from-to
# for a directed edge (i.e., precedent to opinion)
el <- cbind(as.character(opin_id),as.character(precID))
g <- graph.edgelist(el,directed=TRUE)
# Plot the graph.
plot(g,vertex.size=3,vertex.label=NA,edge.arrow.size=0.3)
# For completeness, detach data when finished.
detach(rawdata)
attach(rawdata)
View(rawdata)
table(opin_id)
length(table(opin_id))
length(table(precID))
unique(rawdata["casename"])
| 60386832d02e42259bbcdf80cdd2e04e3bff6447 | [
"R"
] | 3 | R | graceshang/882-deno | 090c9c5dbd32b10f8d68b0b7db3ad90ef4839ead | a2b4732f429b83896605949ad034f0eb8f982c89 |
refs/heads/master | <file_sep>package com.example.suyx_processor_lib.processor.utils;
/**
* @author Created by suyxin on 2018/3/16 14:08.
*/
public class StringUtils {
//首字母大写
public static String captureName(String name) {
// name = name.substring(0, 1).toUpperCase() + name.substring(1);
// return name;
char[] cs=name.toCharArray();
cs[0]-=32;
return String.valueOf(cs);
}
}
<file_sep>apply plugin: 'java-library'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//Google开发用来生成META-INF/services/javax.annotation.processing.Processor文件
implementation 'com.google.auto.service:auto-service:1.0-rc2'
//JAVA文件输出辅助类
implementation 'com.squareup:javapoet:1.7.0'
implementation project(':suyx-annotation-lib')
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
// 解决build警告:编码GBK的不可映射字符
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
<file_sep>package com.example.suyxin.suyxprocessor.di;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.suyx_annotation_lib.annotation.dependency_inject.Inject;
import com.example.suyxin.suyxprocessor.R;
public class DiTestActivity extends AppCompatActivity {
@Inject
public ITestObject testObject;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_di_test);
TextView tv1 = (TextView) findViewById(R.id.tv1);
// tv1.setText(testObject.getText());
}
}
<file_sep>package com.example.suyx_api_lib.inject;
import android.app.Activity;
/**
* Created by suyxin on 2018/3/3.
*/
public interface IInject {
void inject(Activity activity);
String typeName();
}
<file_sep>package com.example.suyx_processor_lib.processor;
import com.example.suyx_annotation_lib.annotation.router.Path;
import com.google.auto.service.AutoService;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
/**
* @author Created by suyxin on 2018/3/7 14:27.
*/
@AutoService(Processor.class)
public class RouterProcessor extends BaseProcessor {
private Map<String, String> map = new HashMap<>();
@Override
public void processCollectInfo(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
Set<? extends Element> elements= roundEnvironment.getElementsAnnotatedWith(Path.class);
for (Element element : elements) {
String path = element.getAnnotation(Path.class).value();
if (path != null && path != "") {
TypeElement typeElement = (TypeElement) element;
map.put(path, typeElement.asType().toString());
}
}
}
private static final String PACKAGE = "com.example.suyxin.router";
private static final String CLASS_SIMPLE_NAME = "Router$$Group";
@Override
public void processWriteToFile() {
String classFullName = PACKAGE + CLASS_SIMPLE_NAME;
StringBuilder builder = new StringBuilder()
.append("package " + PACKAGE + ";\n\n")
.append("import java.util.HashMap;\n" +
"import java.util.Map;\n")
.append("public class ")
.append(CLASS_SIMPLE_NAME)
.append(" {\n\n") // open class
.append("\tpublic Map<String,String> buildMap() {\n") // open method
.append("\t\tMap<String, String> map = new HashMap<>();\n");
for (Map.Entry<String, String> entry :map.entrySet()){
String str = "\t\tmap.put(\"%s\",\"%s\");\n";
builder.append(String.format(str, entry.getKey(), entry.getValue()));
}
builder.append("\t\treturn map;\n")
.append("\t}\n") // close method
.append("}\n"); // close class
try { // write the file
JavaFileObject source = mFiler.createSourceFile(PACKAGE + "." + CLASS_SIMPLE_NAME);
Writer writer = source.openWriter();
writer.write(builder.toString());
writer.flush();
writer.close();
} catch (IOException e) {
// Note: calling e.printStackTrace() will print IO errors
// that occur from the file already existing after its first run, this is normal
}
info(">>> findViewById is finish... <<<");
}
@Override
public Set<String> supportedAnnotationTypes() {
Set<String> set = new LinkedHashSet<>();
set.add(Path.class.getName());
return set;
}
}
<file_sep>package com.suyxin.test.reflex.impl;
import com.suyxin.test.reflex.ITest;
import java.lang.reflect.Method;
/**
* @author Created by suyxin on 2018/3/9 11:49.
*/
public class ReflexInvoke implements ITest {
@Override
public void test() {
try {
TestOjbect ojbect = (TestOjbect) Class.forName("com.suyxin.test.reflex.impl.TestOjbect").newInstance();
Method method = ojbect.getClass().getDeclaredMethod("test");
method.setAccessible(true);
method.invoke(ojbect);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String name() {
return "反射调用";
}
}
<file_sep>package com.example.suyx_processor_lib.processor.di;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
/**
* @author Created by suyxin on 2018/3/16 11:30.
*/
public class ComponnetInfo {
//Componnet 元素
private TypeElement typeElement;
// //依赖提供者
// private String[] moduleNames;
// //key是modules注解的类名
// private Map<String,ModulesInfo> modules;
//key是modules注解的类名
private Map<String,TypeElement> modules;
//key是注入对象的类名,值是要注入的变量列名
private Map<String,List<VariableElement>> injectFieldMap;
//key是提供对象的类名,值对应的方法
private Map<String,ExecutableElement> providerMap;
public TypeElement getTypeElement() {
return typeElement;
}
public void setTypeElement(TypeElement typeElement) {
this.typeElement = typeElement;
}
public Map<String, ExecutableElement> getProviderMap() {
return providerMap;
}
public void setProviderMap(Map<String, ExecutableElement> providerMap) {
this.providerMap = providerMap;
}
public Map<String, List<VariableElement>> getInjectFieldMap() {
return injectFieldMap;
}
public void setInjectFieldMap(Map<String, List<VariableElement>> injectFieldMap) {
this.injectFieldMap = injectFieldMap;
}
}
<file_sep>package com.example.suyxin.suyxprocessor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.suyx_annotation_lib.annotation.Hello;
import com.example.suyx_annotation_lib.annotation.router.Path;
import com.example.suyx_annotation_lib.annotation.viewinject.ViewInject;
import com.example.suyx_api_lib.inject.InjectManager;
@Path("/main/test1")
@Hello(name = "hello",text = "MainActivity1")
public class MainActivity1 extends AppCompatActivity {
@ViewInject(R.id.name)
TextView name1;
@ViewInject(R.id.value)
TextView value1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InjectManager.getInstance().inject(this);
name1.setText("我成功注入了name11111111111");
value1.setText("去成功注入了value111111111111");
}
}
<file_sep>package com.example.suyxin.suyxprocessor;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.suyx_annotation_lib.annotation.Hello;
import com.example.suyx_annotation_lib.annotation.router.Path;
import com.example.suyx_annotation_lib.annotation.viewinject.ViewInject;
import com.example.suyx_api_lib.inject.InjectManager;
import com.example.suyxin.suyxprocessor.di.DiTestActivity;
@Path("/main/home")
@Hello(name = "hello",text = "suyxin")
public class MainActivity extends AppCompatActivity {
@ViewInject(R.id.name)
TextView name;
@ViewInject(R.id.value)
TextView value;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InjectManager.getInstance().inject(this);
name.setText("我成功注入了name");
value.setText("去成功注入了value");
// Router.getInstance().toActivity(this, "/main/test1");
// TestFacade.startTest();
startActivity(new Intent(this, DiTestActivity.class));
}
}
<file_sep>package com.example.suyx_processor_lib.processor.di;
import javax.lang.model.element.VariableElement;
/**
* @author Created by suyxin on 2018/3/16 16:30.
*/
public class InjectFieldInfo {
private VariableElement fieldElement;
}
<file_sep>include ':app', ':suyx-processor-lib', ':suyx-annotation-lib', ':suyx-api-lib'
<file_sep>package com.suyxin.test.reflex;
import com.suyxin.test.reflex.impl.NewObjectTest;
import com.suyxin.test.reflex.impl.ReflexInvoke;
import com.suyxin.test.reflex.impl.ReflexNewInstance;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author Created by suyxin on 2018/3/9 11:40.
*/
public class TestFacade {
private static List<ITest> list = new ArrayList<>();
public static void startTest(){
buildTest();
Iterator<ITest> iTestIterator = list.iterator();
while (iTestIterator!=null&&iTestIterator.hasNext()) {
ITest test = iTestIterator.next();
long startTime = System.currentTimeMillis();
long cout = 100000;
for (int i = 0; i < cout; i++) {
test.test();
}
long time = System.currentTimeMillis() - startTime;
System.out.println(String.format("测试:%s,耗时:%s ms",test.name(),time));
}
}
private static void buildTest(){
list.clear();
list.add(new NewObjectTest());
list.add(new ReflexInvoke());
list.add(new ReflexNewInstance());
}
}
<file_sep>package com.example.suyx_processor_lib.processor;
import com.example.suyx_annotation_lib.annotation.Hello;
import com.google.auto.service.AutoService;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
/**
* Created by suyxin on 2018/3/3.
*/
@AutoService(Processor.class)
public class HelloProcessor extends BaseProcessor {
private List<Element> annotationElements = new ArrayList<>();
@Override
public void processCollectInfo(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(Hello.class)) {
if (annotatedElement.getKind() != ElementKind.CLASS) {
error(annotatedElement, "Only classes can be annotated with @%s",
Hello.class.getSimpleName());
return;
}
annotationElements.add(annotatedElement);
}
}
@Override
public void processWriteToFile() {
for (Element classElement : annotationElements) {
genarateClassFile(classElement);
}
}
private static final String SUFFIX = "$$TestHello";
private static final String PACKAGE = "com.example.suyxin.suyxprocessor";
private void genarateClassFile(Element classElement) {
Hello annotation = classElement.getAnnotation(Hello.class);
String name = annotation.name();
String text = annotation.text();
// TypeElement superClassName = mElementUtils.getTypeElement(name);
String newClassName = name + SUFFIX;
StringBuilder builder = new StringBuilder()
.append("package " + PACKAGE + ";\n\n")
.append("public class ")
.append(newClassName)
.append(" {\n\n") // open class
.append("\tpublic String getMessage() {\n") // open method
.append("\t\treturn \"");
// this is appending to the return statement
builder.append(text).append(name).append(" !\\n");
builder.append("\";\n") // end return
.append("\t}\n") // close method
.append("}\n"); // close class
try { // write the file
JavaFileObject source = mFiler.createSourceFile(PACKAGE + "." + newClassName);
Writer writer = source.openWriter();
writer.write(builder.toString());
writer.flush();
writer.close();
} catch (IOException e) {
// Note: calling e.printStackTrace() will print IO errors
// that occur from the file already existing after its first run, this is normal
}
info(">>> genarateClassFile is finish... <<<");
}
@Override
public Set<String> supportedAnnotationTypes() {
Set<String> sets = new LinkedHashSet<>();
sets.add(Hello.class.getCanonicalName());
return sets;
}
}
<file_sep># 注解处理器的实践
findViewByID注入
<file_sep>package com.example.suyxin.suyxprocessor.di;
/**
* @author Created by suyxin on 2018/3/16 10:40.
*/
public interface ITestObject {
String getText();
}
| 07d150b228d5cdca65df01a32a402fe84557fa2e | [
"Markdown",
"Java",
"Gradle"
] | 15 | Java | suyxin/SuyxProcessor | 34006556c6ab7128902e5aad5b653280135437c7 | 0e83770415545fad60ed09d39034ff827bf9f840 |
refs/heads/master | <file_sep>/**
* @name Tik-Tac-Toe
* @version 1.0
* @author Xfordation
*/
// Game Initializer
const gameInit = function () {
/*Constants*/
//current Player
let currentPlayer;
//Message or Whose Turn it will be
let turnStatus = document.getElementById("turnStat");
turnStatus.innerHTML = `<i class="fa fa-circle-o fa-lg fa-circle-color"></i>`;
//Array of the Board
let boxes = Array.from(document.querySelectorAll(".boxes div"));
this.start = function () {
document.getElementById("main-box").addEventListener("click", (e) => {
boxes.forEach((box) => {
if (e.target == box) {
// Current Player Selection & Setting the turn Status
box.innerHTML = this.turnHandler();
// Winner Object
const win = new getWinner();
win.isWin();
}
});
});
};
// Turn Function
this.turnHandler = function () {
currentPlayer =
currentPlayer === `<i class="fa fa-circle-o fa-lg fa-circle-color"></i>`
? `<i class="fa fa-close fa-lg fa-close-color"></i>`
: `<i class="fa fa-circle-o fa-lg fa-circle-color"></i>`;
//Turn Status
turnStatus.innerHTML =
currentPlayer === `<i class="fa fa-close fa-lg fa-close-color"></i>`
? `<i class="fa fa-circle-o fa-lg fa-circle-color"></i>`
: `<i class="fa fa-close fa-lg fa-close-color"></i>`;
return currentPlayer;
};
// Reset Function
this.reset = function () {
boxes.forEach((box) => {
box.innerHTML = "";
});
turnStatus.innerHTML = `<i class="fa fa-circle-o fa-lg fa-circle-color"></i>`;
currentPlayer = "";
document.getElementById("gamebox").style.display = "block";
document.getElementById("select").style.display = "flex";
document.getElementById("result-dec").style.display = "none";
document.getElementById("footer").style.position = "relative";
};
document.getElementById("reset").addEventListener("click", this.reset);
document.getElementById("result-dec").addEventListener("click", this.reset);
};
// Initializing the game Obj
const obj = new gameInit();
obj.start();
| 2acc12884b0a8b33228baf68652e7456070993b7 | [
"JavaScript"
] | 1 | JavaScript | Xfordation/Tik-Tac-Toe-using-Vanilla-JavaScript | 8bd0d17e25f022481d2e0ad468f27c107100e140 | 6b47c3b791c2ce5e98ec36ce9ffc052e15ec2cef |
refs/heads/master | <file_sep>package data
import (
"database/sql"
_ "github.com/lib/pq"
"github.com/maikeulb/national-parks/app/models"
)
func GetStates(db *sql.DB, start, count int) ([]models.State, error) {
rows, err := db.Query(
`SELECT id, name
FROM states
LIMIT $1
OFFSET $2`,
count, start)
if err != nil {
return nil, err
}
defer rows.Close()
states := []models.State{}
for rows.Next() {
var s models.State
if err := rows.Scan(&s.ID, &s.Name); err != nil {
return nil, err
}
states = append(states, s)
}
return states, nil
}
func GetState(db *sql.DB, s models.State) error {
return db.QueryRow(
`SELECT name
FROM states
WHERE id=$1`,
s.ID).Scan(&s.Name)
}
func CreateState(db *sql.DB, s models.State) error {
err := db.QueryRow(
`INSERT INTO states(name)
VALUES($1)
RETURNING id`,
s.Name).Scan(&s.ID)
if err != nil {
return err
}
return nil
}
func UpdateState(db *sql.DB, s models.State) error {
_, err := db.Exec(
`UPDATE states
SET name=$1
WHERE id=$2`,
s.Name, s.ID)
return err
}
func DeleteState(db *sql.DB, s models.State) error {
_, err := db.Exec(
`DELETE
FROM states
WHERE id=$1`,
s.ID)
return err
}
<file_sep>package handlers
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
"github.com/maikeulb/national-parks/app/data"
"github.com/maikeulb/national-parks/app/models"
)
func GetParks(db *sql.DB, w http.ResponseWriter, r *http.Request) {
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))
vars := mux.Vars(r)
if count > 10 || count < 1 {
count = 10
}
if start < 0 {
start = 0
}
sid, err := strconv.Atoi(vars["sid"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
parks, err := data.GetParks(db, start, count, sid)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
type Env struct {
Data []models.Park `json:"data"`
}
env := Env{Data: parks}
respondWithJSON(w, http.StatusOK, env)
}
func GetPark(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid park ID")
return
}
sid, err := strconv.Atoi(vars["sid"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
p := models.Park{ID: id, StateID: sid}
if err := data.GetPark(db, &p); err != nil {
switch err {
case sql.ErrNoRows:
respondWithError(w, http.StatusNotFound, "Park not found")
default:
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
respondWithJSON(w, http.StatusOK, p)
}
func CreatePark(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sid, err := strconv.Atoi(vars["sid"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
p := models.Park{StateID: sid}
// var p models.Park
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&p); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
if err := data.CreatePark(db, p); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusCreated, p)
}
func UpdatePark(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid park ID")
return
}
sid, err := strconv.Atoi(vars["sid"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
var p models.Park
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&p); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid resquest payload")
return
}
defer r.Body.Close()
p.ID = id
p.StateID = sid
if err := data.UpdatePark(db, p); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, p)
}
func DeletePark(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid park ID")
return
}
p := models.Park{ID: id}
if err := data.DeletePark(db, p); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
}
<file_sep>package models
import (
// "errors"
"time"
)
type ParkRequest struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
NearestCity string `json:"nearestCity,omitempty"`
Visitors int `json:"visitors,omitempty"`
Established *time.Time `json:"established,omitempty"`
}
func (jp ParkRequest) Park(p Park) Park {
p.Name = jp.Name
p.Description = jp.Description
p.NearestCity = jp.NearestCity
p.Visitors = jp.Visitors
p.Established = jp.Established
return p
}
func (jp *ParkRequest) validate() error {
// if jp.FolloweeID <= 0 {
// return errors.New("FolloweeID must not be empty")
// }
return nil
}
type ParkResponse struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
NearestCity string `json:"nearestCity,omitempty"`
Visitors int `json:"visitors,omitempty"`
Established *time.Time `json:"established,omitempty"`
StateID int `json:"stateId,omitempty"`
}
func ParksResponse(p Park) ParkResponse {
var jp ParkResponse
jp.ID = p.ID
jp.StateID = p.StateID
jp.Name = p.Name
jp.Description = p.Description
jp.NearestCity = p.NearestCity
jp.Visitors = p.Visitors
return jp
}
<file_sep>package main_test
import (
"bytes"
"encoding/json"
"github.com/maikeulb/national-parks/app"
"log"
"net/http"
"net/http/httptest"
"os"
"strconv"
"testing"
)
var a app.App
func TestMain(m *testing.M) {
a = app.App{}
a.Initialize(
os.Getenv("TEST_DB_HOST"),
os.Getenv("TEST_DB_PORT"),
os.Getenv("TEST_DB_USERNAME"),
os.Getenv("TEST_DB_PASSWORD"),
os.Getenv("TEST_DB_DB"))
ensureTableExists()
code := m.Run()
clearTable()
os.Exit(code)
}
func TestEmptyTable(t *testing.T) {
clearTable()
req, _ := http.NewRequest("GET", "/api/states", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
if body := response.Body.String(); body != "{'data':[]}" {
t.Errorf("Expected an empty array. Got %s", body)
}
}
func TestGetNonExistentState(t *testing.T) {
clearTable()
req, _ := http.NewRequest("GET", "/api/states/1", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusNotFound, response.Code)
var m map[string]string
json.Unmarshal(response.Body.Bytes(), &m)
if m["error"] != "State not found" {
t.Errorf("Expected the 'error' key of the response to be set to 'Invalid state ID'. Got '%s'", m["error"])
}
}
func TestCreateState(t *testing.T) {
clearTable()
payload := []byte(`{"name":"test state"}`)
req, _ := http.NewRequest("POST", "/api/states", bytes.NewBuffer(payload))
response := executeRequest(req)
checkResponseCode(t, http.StatusCreated, response.Code)
var m map[string]interface{}
json.Unmarshal(response.Body.Bytes(), &m)
if m["name"] != "test state" {
t.Errorf("Expected state name to be 'test state'. Got '%v'", m["name"])
}
}
func TestGetState(t *testing.T) {
clearTable()
addStates(1)
req, _ := http.NewRequest("GET", "/api/states/1", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
}
func TestUpdateState(t *testing.T) {
clearTable()
addStates(1)
req, _ := http.NewRequest("GET", "/api/states/1", nil)
response := executeRequest(req)
var originalState map[string]interface{}
json.Unmarshal(response.Body.Bytes(), &originalState)
payload := []byte(`{"name":"test state - updated name"}`)
req, _ = http.NewRequest("PUT", "/api/states/1", bytes.NewBuffer(payload))
response = executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
var m map[string]interface{}
json.Unmarshal(response.Body.Bytes(), &m)
if m["name"] == originalState["name"] {
t.Errorf("Expected the name to change from '%v' to '%v'. Got '%v'", originalState["name"], m["name"], m["name"])
}
}
func TestDeleteState(t *testing.T) {
clearTable()
addStates(1)
req, _ := http.NewRequest("GET", "/api/states/1", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
req, _ = http.NewRequest("DELETE", "/api/states/1", nil)
response = executeRequest(req)
checkResponseCode(t, http.StatusOK, response.Code)
req, _ = http.NewRequest("GET", "/api/states/1", nil)
response = executeRequest(req)
checkResponseCode(t, http.StatusNotFound, response.Code)
}
func TestGetNonExistentPark(t *testing.T) {
clearTable()
req, _ := http.NewRequest("GET", "/api/states/1", nil)
response := executeRequest(req)
checkResponseCode(t, http.StatusNotFound, response.Code)
var m map[string]string
json.Unmarshal(response.Body.Bytes(), &m)
if m["error"] != "State not found" {
t.Errorf("Expected the 'error' key of the response to be set to 'Invalid state ID'. Got '%s'", m["error"])
}
}
func TestCreatePark(t *testing.T) {
clearTable()
addStates(1)
payload := []byte(`{"name":"test park"}`)
req, _ := http.NewRequest("POST", "/api/states/1/park", bytes.NewBuffer(payload))
response := executeRequest(req)
checkResponseCode(t, http.StatusCreated, response.Code)
var m map[string]interface{}
json.Unmarshal(response.Body.Bytes(), &m)
if m["name"] != "test park" {
t.Errorf("Expected state name to be 'test state'. Got '%v'", m["name"])
}
}
// func TestGetPark(t *testing.T) {
// clearTable()
// addStatesAndParks(1)
// req, _ := http.NewRequest("GET", "/api/states/1/parks/1", nil)
// response := executeRequest(req)
// checkResponseCode(t, http.StatusOK, response.Code)
// }
// func TestUpdatePark(t *testing.T) {
// clearTable()
// addStates(1)
// addParks(1)
// req, _ := http.NewRequest("GET", "/api/states/1/parks/1", nil)
// response := executeRequest(req)
// var originalPark map[string]interface{}
// json.Unmarshal(response.Body.Bytes(), &originalPark)
// payload := []byte(
// `{"name":"<NAME> - updated name"}`)
// req, _ = http.NewRequest("PATCH", "/api/states/1/parks/1", bytes.NewBuffer(payload))
// response = executeRequest(req)
// checkResponseCode(t, http.StatusOK, response.Code)
// var m map[string]interface{}
// json.Unmarshal(response.Body.Bytes(), &m)
// if m["name"] == originalPark["name"] {
// t.Errorf("Expected the name to change from '%v' to '%v'. Got '%v'", originalPark["name"], m["name"], m["name"])
// }
// }
// func TestDeletePark(t *testing.T) {
// clearTable()
// addStates(1)
// addParks(1)
// req, _ := http.NewRequest("GET", "/api/states/1/parks/1", nil)
// response := executeRequest(req)
// checkResponseCode(t, http.StatusOK, response.Code)
// req, _ = http.NewRequest("DELETE", "/api/states/1/parks/1", nil)
// response = executeRequest(req)
// checkResponseCode(t, http.StatusOK, response.Code)
// req, _ = http.NewRequest("GET", "/api/states/1/parks/1", nil)
// response = executeRequest(req)
// checkResponseCode(t, http.StatusNotFound, response.Code)
// }
func executeRequest(req *http.Request) *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
a.Router.ServeHTTP(rr, req)
return rr
}
func checkResponseCode(t *testing.T, expected, actual int) {
if expected != actual {
t.Errorf("Expected response code %d. Got %d\n", expected, actual)
}
}
func ensureTableExists() {
if _, err := a.DB.Exec(tableCreationQuery); err != nil {
log.Fatal(err)
}
}
func clearTable() {
a.DB.Exec("DELETE FROM states")
a.DB.Exec("DELETE FROM parks")
a.DB.Exec("ALTER SEQUENCE states_id_seq RESTART WITH 1")
a.DB.Exec("ALTER SEQUENCE parks_id_seq RESTART WITH 1")
}
func addStates(count int) {
if count < 1 {
count = 1
}
for i := 0; i < count; i++ {
a.DB.Exec(`
INSERT INTO states(name)
VALUES($1)`,
"State "+strconv.Itoa(i))
}
}
func addStatesAndParks(count int) {
if count < 1 {
count = 1
}
for i := 0; i < count; i++ {
a.DB.Exec(`
INSERT INTO states(name)
VALUES($1)`,
"State "+strconv.Itoa(i))
a.DB.Exec(`
INSERT INTO parks(name, description, nearest_city, visitors, state_id)
VALUES($1,$2,$3,$4,$5)`,
"State "+strconv.Itoa(i),
"Description "+strconv.Itoa(i),
"Nearest_city "+strconv.Itoa(i),
i,
i)
}
}
const tableCreationQuery = `CREATE TABLE IF NOT EXISTS states
(
id SERIAL,
name varchar(50) NOT NULL,
CONSTRAINT products_pkey PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS parks
(
id serial,
name varchar(50) NOT NULL,
description TEXT NOT NULL,
nearest_city varchar(50) NOT NULL,
visitors integer NOT NULL,
established timestamp NULL,
state_id integer NULL,
CONSTRAINT parks_pkey PRIMARY KEY (id),
FOREIGN KEY (state_id) REFERENCES states(id)
);
`
<file_sep>package main
import (
"github.com/maikeulb/national-parks/app"
"os"
)
func main() {
a := app.App{}
a.Initialize(
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_USERNAME"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_DB"))
a.Run(":5000")
}
<file_sep>package models
import (
"encoding/json"
// "fmt"
// "time"
)
type State struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
func (s State) MarshalJSON() ([]byte, error) {
return json.Marshal(StateResponse(s))
}
func (s *State) UnmarshalJSON(data []byte) error {
var js StateRequest
if err := json.Unmarshal(data, &js); err != nil {
return err
}
if err := js.validate(); err != nil {
return err
}
*s = js.State(*s)
return nil
}
<file_sep># National Parks
Restful API for US National Park Service (unofficial). The resources are the
states and their parks. Additional features include pagination and
rate-limiting. The API is written with minimal dependencies (the
only external dependency is the router).
Technology
----------
* Go
* PostgreSQL
Endpoints
---------
| Method | URI | Action |
|------------|---------------------------------|---------------------------------------|
| `GET` | `/api/states` | `Retrieve all states`<sup>1</sup> |
| `GET` | `/api/states/{sid}` | `Retrieve state` |
| `POST` | `/api/states` | `Add state` |
| `PUT` | `/api/states/{sid}` | `Update state` |
| `DELETE` | `/api/states/{sid}` | `Remove state` |
| `GET` | `/api/states/{sid}/parks` | `Retrieve all state parks`<sup>1</sup>|
| `GET` | `/api/states/{sid}/parks/{id}` | `Retrieve state park` |
| `POST` | `/api/states/{sid}/parks` | `Add state park` |
| `PATCH` | `/api/states/{sid}/parks/{id}` | `Partially update state park`<sup>2</sup> |
| `DELETE` | `/api/states/{sid}/parks/{id}` | `Delete state's park` |
1. Optional query parameters: count, start
2. Send only the fields you need to update (or all fields for full updates)
Sample Responses
---------------
`http get http://localhost:5000/api/states`
```
{
"data": [
{
"id": 1,
"name": "California"
},
{
"id": 2,
"name": "Arizona"
},
{
"id": 3,
"name": "New York"
},
...
```
`http get http://localhost:5000/api/states/1/parks`
```
{
"data": [
{
"description": "Recognized by its granite cliffs, waterfalls, clear streams, giant sequoia groves, lakes, mountains, glaciers, and biological diversity.",
"id": 1,
"name": "Yosemite",
"nearestCity": "Mariposa",
"stateId": 1,
"visitors": 4336890
},
...
```
Run
---
With docker:
```
docker-compose build
docker-compose up -d db
docker-compose up
Go to http://localhost:5000 and visit one of the above endpoints
```
Alternatively, create a database named 'national_parks', run the migration
scripts (located in `./migrations/`), and then open `main.go` and
point the PostgreSQL URI to your server.
`cd` into `./national-parks` (if you are not already); then run:
```
go build
./national-parks
Go to http://localhost:5000 and visit one of the above endpoints
```
TODO
---
Add hypermedia links and meta data
Add sort (by visitors and name)
Add number of parks per state
Add more unit tests
<file_sep>package models
import (
"errors"
// "time"
)
type StateRequest struct {
Name string `json:"name,omitempty"`
}
func (js StateRequest) State(s State) State {
s.Name = js.Name
return s
}
func (js *StateRequest) validate() error {
if js.Name == "" {
return errors.New("Name is required")
}
return nil
}
type StateResponse struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
func StatesResponse(s State) StateResponse {
var js StateResponse
js.ID = s.ID
js.Name = s.Name
return js
}
<file_sep>CREATE TABLE states (
id serial PRIMARY KEY,
name varchar(50) NOT NULL
);
CREATE TABLE parks (
id serial PRIMARY KEY,
name varchar(50) NOT NULL,
description TEXT NOT NULL,
nearest_city varchar(50) NOT NULL,
visitors integer NOT NULL,
established timestamp NOT NULL,
state_id integer NULL
);
ALTER TABLE parks
ADD CONSTRAINT fk_states_parks
FOREIGN KEY (state_id)
REFERENCES states(id)
ON DELETE CASCADE;
<file_sep>package app
import (
"database/sql"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/maikeulb/national-parks/app/handlers"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (a *App) Initialize(host, port, user, password, dbname string) {
connectionString :=
fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
var err error
a.DB, err = sql.Open("postgres", connectionString)
if err != nil {
log.Fatal(err)
}
a.Router = mux.NewRouter()
a.initializeRoutes()
}
func (a *App) Run(addr string) {
fmt.Println("Listening on port: 5000")
log.Fatal(http.ListenAndServe(addr, a.Router))
}
func (a *App) initializeRoutes() {
a.Router.HandleFunc("/api/states", a.GetStates).Methods("GET")
a.Router.HandleFunc("/api/states", a.CreateState).Methods("POST")
a.Router.HandleFunc("/api/states/{id:[0-9]+}", a.GetState).Methods("GET")
a.Router.HandleFunc("/api/states/{id:[0-9]+}", a.UpdateState).Methods("PUT")
a.Router.HandleFunc("/api/states/{id:[0-9]+}", a.DeleteState).Methods("DELETE")
a.Router.HandleFunc("/api/states/{sid}/parks", a.GetParks).Methods("GET")
a.Router.HandleFunc("/api/states/{sid}/parks", a.CreatePark).Methods("POST")
a.Router.HandleFunc("/api/states/{sid}/parks/{id:[0-9]+}", a.GetPark).Methods("GET")
a.Router.HandleFunc("/api/states/{sid}/parks/{id:[0-9]+}", a.UpdatePark).Methods("PATCH")
a.Router.HandleFunc("/api/states/{sid}/parks/{id:[0-9]+}", a.DeletePark).Methods("DELETE")
// a.Router.Use(limitMiddleware)
}
func (a *App) GetStates(w http.ResponseWriter, r *http.Request) {
handlers.GetStates(a.DB, w, r)
}
func (a *App) CreateState(w http.ResponseWriter, r *http.Request) {
handlers.CreateState(a.DB, w, r)
}
func (a *App) GetState(w http.ResponseWriter, r *http.Request) {
handlers.GetState(a.DB, w, r)
}
func (a *App) UpdateState(w http.ResponseWriter, r *http.Request) {
handlers.UpdateState(a.DB, w, r)
}
func (a *App) DeleteState(w http.ResponseWriter, r *http.Request) {
handlers.DeleteState(a.DB, w, r)
}
func (a *App) GetParks(w http.ResponseWriter, r *http.Request) {
handlers.GetParks(a.DB, w, r)
}
func (a *App) CreatePark(w http.ResponseWriter, r *http.Request) {
handlers.CreatePark(a.DB, w, r)
}
func (a *App) GetPark(w http.ResponseWriter, r *http.Request) {
handlers.GetPark(a.DB, w, r)
}
func (a *App) UpdatePark(w http.ResponseWriter, r *http.Request) {
handlers.UpdatePark(a.DB, w, r)
}
func (a *App) DeletePark(w http.ResponseWriter, r *http.Request) {
handlers.DeletePark(a.DB, w, r)
}
<file_sep>version: '3'
services:
web:
build: .
ports:
- "5000:5000"
environment:
- DB_HOST=db
- DB_PORT=5432
- DB_USERNAME=postgres
- DB_PASSWORD=<PASSWORD>!
- DB_DB=postgres
depends_on:
- db
flyway:
build: ./migrations
command: -url=jdbc:postgresql://db/postgres -user=postgres -password=<PASSWORD>! migrate
depends_on:
- db
db:
image: postgres
environment:
POSTGRES_PASSWORD: "<PASSWORD>!"
<file_sep>package models
import (
"encoding/json"
// "fmt"
"time"
)
type Park struct {
ID int
Name string
Description string
NearestCity string
Visitors int
Established *time.Time
StateID int
}
func (p Park) MarshalJSON() ([]byte, error) {
return json.Marshal(ParksResponse(p))
}
func (p *Park) UnmarshalJSON(data []byte) error {
var jp ParkRequest
if err := json.Unmarshal(data, &jp); err != nil {
return err
}
if err := jp.validate(); err != nil {
return err
}
*p = jp.Park(*p)
return nil
}
<file_sep>package data
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"github.com/maikeulb/national-parks/app/models"
)
func GetParks(db *sql.DB, start, count, sid int) ([]models.Park, error) {
rows, err := db.Query(
`SELECT *
FROM parks
WHERE state_id = $1
LIMIT $2
OFFSET $3`,
sid, count, start)
if err != nil {
return nil, err
}
defer rows.Close()
parks := []models.Park{}
for rows.Next() {
var p models.Park
if err := rows.Scan(
&p.ID,
&p.Name,
&p.Description,
&p.NearestCity,
&p.Visitors,
&p.Established,
&p.StateID); err != nil {
return nil, err
}
parks = append(parks, p)
}
return parks, nil
}
func GetPark(db *sql.DB, p *models.Park) error {
return db.QueryRow(
`SELECT id,
name,
description,
nearest_city,
visitors,
established,
state_id
FROM parks
WHERE id=$1 AND state_id = $2`,
p.ID, p.StateID).Scan(
&p.ID,
&p.Name,
&p.Description,
&p.NearestCity,
&p.Visitors,
&p.Established,
&p.StateID)
}
func CreatePark(db *sql.DB, p models.Park) error {
err := db.QueryRow(
`INSERT INTO parks(name, description, nearest_city, visitors, established, state_id)
VALUES($1, $2, $3, $4, $5, $6)
RETURNING id`,
p.Name, p.Description, p.NearestCity, p.Visitors, p.Established, p.StateID).Scan(&p.ID)
if err != nil {
return err
}
return nil
}
func UpdatePark(db *sql.DB, p models.Park) error {
fmt.Println(p.Established)
_, err := db.Exec(
`UPDATE parks as p
SET name=case
when $1='' then p.name
else $1
end,
description=case
when $2='' then p.description
else $2
end,
nearest_city=case
when $3='' then p.nearest_city
else $3
end,
visitors=case
when $4=0 then p.visitors
else $4
end,
established=p.established
WHERE id=$5`,
p.Name, p.Description, p.NearestCity, p.Visitors, p.ID)
return err
}
func DeletePark(db *sql.DB, p models.Park) error {
_, err := db.Exec(
`DELETE
FROM parks
WHERE id=$1 AND state_id=$2`,
p.ID, p.StateID)
return err
}
<file_sep>package handlers
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
"github.com/maikeulb/national-parks/app/data"
"github.com/maikeulb/national-parks/app/models"
)
func GetStates(db *sql.DB, w http.ResponseWriter, r *http.Request) {
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))
if count > 10 || count < 1 {
count = 10
}
if start < 0 {
start = 0
}
states, err := data.GetStates(db, start, count)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
type Env struct {
Data []models.State `json:"data"`
}
env := Env{Data: states}
respondWithJSON(w, http.StatusOK, env)
}
func GetState(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
s := models.State{ID: id}
if err := data.GetState(db, s); err != nil {
switch err {
case sql.ErrNoRows:
respondWithError(w, http.StatusNotFound, "State not found")
default:
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
respondWithJSON(w, http.StatusOK, s)
}
func CreateState(db *sql.DB, w http.ResponseWriter, r *http.Request) {
var s models.State
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&s); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
if err := data.CreateState(db, s); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusCreated, s)
}
func UpdateState(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
var s models.State
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&s); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid resquest payload")
return
}
defer r.Body.Close()
s.ID = id
if err := data.UpdateState(db, s); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, s)
}
func DeleteState(db *sql.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid state ID")
return
}
s := models.State{ID: id}
if err := data.DeleteState(db, s); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
}
| 58d5ecc61ad15767a5f9e6486b9b5fb551652141 | [
"Markdown",
"SQL",
"Go",
"YAML"
] | 14 | Go | maikeulb/national-parks | 74aef5ba6b0b011835d265075094155879060804 | dbe35896cfb73a06dd2e32e0defabac14e85cd9a |
refs/heads/master | <file_sep>#include <iostream>
#include <Reactor/Reactor.hpp>
void test_int()
{
sw::Function<sw::Int(sw::Int, sw::Int)> function;
{
sw::Int x = function.Arg<0>();
sw::Int y = function.Arg<1>();
sw::Int sum = x + y;
sw::Return(sum);
}
sw::Routine* routine = function(L"sum_function");
int (*callable)(int,int) = (int(*)(int,int))routine->getEntry();
int result = callable(2, 3);
std::cout << "test_int: " << (result == (2+3)) << std::endl;
delete routine;
}
void test_double_assignement()
{
sw::Function<sw::Void(sw::Double, sw::Pointer<sw::Double>)> function;
{
sw::Double x = function.Arg<0>();
sw::Pointer<sw::Double> y = function.Arg<1>();
*y = x;
sw::Return();
}
sw::Routine* routine = function(L"sum_function");
void (*callable)(double,double*) = (void(*)(double,double*))routine->getEntry();
double dest = 0.0;
callable(1e150, &dest);
std::cout << "test_double_assignement: " << (dest == 1e150) << std::endl;
delete routine;
}
void test_double_const_assignement()
{
double value = 1e-150;
sw::Function<sw::Void(sw::Pointer<sw::Double>)> function;
{
sw::Pointer<sw::Double> y = function.Arg<0>();
*y = sw::Double(value);
sw::Return();
}
sw::Routine* routine = function(L"sum_function");
void (*callable)(double*) = (void(*)(double*))routine->getEntry();
double dest = 0.0;
callable(&dest);
std::cout << "test_double_const_assignement: " << (dest == value) << std::endl;
delete routine;
}
void test_double_simple_math()
{
sw::Function<sw::Void(sw::Double, sw::Double, sw::Double, sw::Pointer<sw::Double>)> function;
{
sw::Double x = function.Arg<0>();
sw::Double y = function.Arg<1>();
sw::Double z = function.Arg<2>();
sw::Pointer<sw::Double> res = function.Arg<3>();
sw::Double w = x + y * z / x - sw::Double(0.00000000010);
w += z;
w *= x;
w -= z;
w /= sw::Double(2.0);
*res = w;
sw::Return();
}
double a = 0.001;
double b = 0.101;
double c = 0.011;
double d = a + b * c / a - 0.00000000010;
d += c;
d *= a;
d -= c;
d /= 2.0;
double ref_value = d;
sw::Routine* routine = function(L"sum_function");
void (*callable)(double,double,double,double*) = (void(*)(double,double,double,double*))routine->getEntry();
double dest = 0.0;
callable(a, b, c, &dest);
std::cout << "test_double_simple_math: " << (dest == ref_value) << std::endl;
delete routine;
}
void test_double_min_max_abs()
{
sw::Function<sw::Void(sw::Pointer<sw::Double>)> function;
{
sw::Pointer<sw::Double> y = function.Arg<0>();
*y = sw::Abs(sw::Double(-5.0));
*sw::Pointer<sw::Double>(sw::Pointer<sw::Byte>(y) + sizeof(double)) = sw::Min(sw::Double(5.0), sw::Double(6.0));
*sw::Pointer<sw::Double>(sw::Pointer<sw::Byte>(y) + 2*sizeof(double)) = sw::Max(sw::Double(5.0), sw::Double(6.0));
sw::Return();
}
sw::Routine* routine = function(L"sum_function");
void (*callable)(double*) = (void(*)(double*))routine->getEntry();
double dest[3] {0.0};
callable(dest);
double ref_values[3] {5.0, 5.0, 6.0};
bool ok = dest[0]==ref_values[0] && dest[1]==ref_values[1] && dest[2]==ref_values[2];
std::cout << "test_double_min_max_abs: " << ok << std::endl;
delete routine;
}
void test_double_return()
{
double value = 1e-150;
sw::Function<sw::Void(sw::Double)> function;
{
sw::Double y = function.Arg<0>();
sw::Double ret_val = y;
sw::Return(ret_val);
}
sw::Routine* routine = function(L"return_double");
double (*callable)(double) = (double(*)(double))routine->getEntry();
double ret = callable(value);
std::cout << "test_double_return: " << (ret == value) << std::endl;
delete routine;
}
int main(int argc, char *argv[])
{
test_int();
test_double_assignement();
test_double_const_assignement();
test_double_simple_math();
test_double_min_max_abs();
test_double_return();
return 0;
}
<file_sep># jit test
Simple tests using Google [SwiftShader'](https://swiftshader.googlesource.com/SwiftShader) jit.
For more details see [Reactor](https://swiftshader.googlesource.com/SwiftShader/+/HEAD/docs/Reactor.md) documentation.
<file_sep>project(jit_test)
cmake_minimum_required(VERSION 2.8)
macro(set_cpp_flag FLAG)
if(${ARGC} GREATER 1)
set(CMAKE_CXX_FLAGS_${ARGV1} "${CMAKE_CXX_FLAGS_${ARGV1}} ${FLAG}")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLAG}")
endif()
endmacro()
set_cpp_flag("--std=c++11")
set_cpp_flag("-Wall")
set_cpp_flag("-Wl,--no-as-needed -ldl")
# Path to the SwiftShader git clone.
# SwiftShader libraries must be in PATH_TO_SWIFTSHADER_ROOT/build
# directory
set(PATH_TO_SWIFTSHADER_ROOT ../swiftshader)
get_filename_component(PATH_TO_SWIFTSHADER_ROOT ${PATH_TO_SWIFTSHADER_ROOT} ABSOLUTE)
message(STATUS "swiftshader path is ${PATH_TO_SWIFTSHADER_ROOT}")
include_directories(${PATH_TO_SWIFTSHADER_ROOT}/src)
include_directories(${PATH_TO_SWIFTSHADER_ROOT}/third_party/LLVM/include)
link_directories(${PATH_TO_SWIFTSHADER_ROOT}/build)
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} pthread Reactor llvm SwiftShader)
| 7a871285565a0713ccc878f7776f949f6ce72bf9 | [
"Markdown",
"CMake",
"C++"
] | 3 | C++ | allebacco/jit_test | 7675599ec564762405e78729e77e61a28b97ff69 | 96573399a473b15522c5abec662b59ea55d54ae5 |
refs/heads/master | <file_sep>console.log('url');<file_sep>require('../../css/base.css');
require('../../css/common.less');
// import $ from 'jquery';
/* import('jquery').then($ => {
console.log($);
}); */
/* import('lodash').then(_ => {
// Do something with lodash (a.k.a '_')...
}) */
console.log('user home',$);<file_sep>const path = require('path');
const webpack = require('webpack');
const ROOT = process.cwd(); // 根目录
const ENV = process.env.NODE_ENV;
const IsProduction = (ENV === 'production') ? true : false;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PostcssConfigPath = './config/postcss.config.js';
const Glob = require('glob');
const HappyPack = require('happypack');
const HappyThreadPool = HappyPack.ThreadPool({ size: (IsProduction ? 10 : 4) });
const CopyWebpackPlugin = require('copy-webpack-plugin');
const staticUrl = '//cdn.com';
const publicPath = IsProduction ? staticUrl : '/';
const extraPath = IsProduction ? '/' : '';
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
let runtime = require('art-template/lib/runtime');
// @see http://aui.github.io/art-template/webpack/index.html#Filter
// 模板变量
runtime.Date = () => {
return global.Date
}
let entryHtml = getEntryHtml('./src/view/**/*.html'),
entryJs = getEntry('./src/js/**/*.js'),
configPlugins = [
// @see https://doc.webpack-china.org/plugins/provide-plugin/
// jQuery 设为自动加载,不必 import 或 require
/* new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}), */
new webpack.optimize.ModuleConcatenationPlugin(),
new HappyPack({
id: 'js',
// @see https://github.com/amireh/happypack
threadPool: HappyThreadPool,
loaders: ['babel-loader']
}),
new HappyPack({
id: 'styles',
threadPool: HappyThreadPool,
loaders: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'common',
minChunks: 3 // 包含 3 次即打包到 commons chunk @see https://doc.webpack-china.org/plugins/commons-chunk-plugin/
}),
// @see https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle
new ExtractTextPlugin({
filename: 'css/[name].css?[contenthash:8]',
allChunks: true
}),
// 手动 copy 一些文件
// @see https://github.com/kevlened/copy-webpack-plugin
new CopyWebpackPlugin([
{
from: 'src/js/lib/queries.min.js',
to: 'js/lib/queries.min.js'
},
{
from: 'src/js/lib/zepto.min.js',
to: 'js/lib/zepto.min.js'
}
]),
];
// html
entryHtml.forEach(function (v) {
configPlugins.push(new HtmlWebpackPlugin(v));
});
// 开发环境不压缩 js
if (IsProduction) {
configPlugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: true,
pure_funcs: ['console.log']
}
}));
} else {
// @see https://github.com/th0r/webpack-bundle-analyzer
configPlugins.push(new BundleAnalyzerPlugin({
openAnalyzer: false
}));
}
// 开发环境不压缩图片,提升热更新效率
let imageMin = [{
loader: 'url-loader',
options: {
limit: 100,
publicPath: publicPath + extraPath,
outputPath: function (path) {
return path.replace('src/img', 'img');
},
name: '[path][name].[ext]?[hash:8]'
}
}]
if (IsProduction) {
imageMin.push({
// @see https://github.com/tcoopman/image-webpack-loader
loader: 'image-webpack-loader',
query: {
mozjpeg: {
quality: 65
},
pngquant: {
quality: '65-90',
speed: 4
}
}
})
}
// 配置
const config = {
entry: entryJs,
// @see https://github.com/webpack-contrib/extract-text-webpack-plugin/blob/master/example/webpack.config.js
output: {
filename: 'js/[name].js?[chunkhash:8]',
chunkFilename: 'js/[name].js?[chunkhash:8]',
path: path.resolve(ROOT, 'dist'),
publicPath: publicPath
},
module: {
// @see https://doc.webpack-china.org/configuration/module/#module-noparse
// 排除不需要 webpack 解析的文件,提高速度
/* noParse: function (content) {
return /jquery|zepto/.test(content);
}, */
noParse: /jquery|lodash|zepto/,
rules: [
{
test: /\.js$/i,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader?id=js',
options: {
presets: ['env']
}
}
},
{
test: /\.(less|css)$/i,
use: ExtractTextPlugin.extract({
fallback: 'style-loader?id=styles',
use: [{
loader: 'css-loader?id=styles',
options: {
minimize: IsProduction
}
},
{
loader: 'less-loader?id=styles'
},
{
loader: 'postcss-loader?id=styles',
options: {
config: {
path: PostcssConfigPath
}
}
}
]
})
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: imageMin
},
{
test: /\.(eot|svg|ttf|woff)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 100,
publicPath: publicPath + extraPath,
name: 'font/[name].[ext]?[hash:8]'
}
}
]
},
// @see http://aui.github.io/art-template/webpack/index.html#Options
{
test: /\.(htm|html|art)$/i,
loader: 'art-template-loader',
options: {
imports: require.resolve('art-template/lib/runtime')
}
},
// @see https://github.com/wzsxyz/html-withimg-loader
/*{
test: /\.(htm|html)$/i,
loader: 'html-withimg-loader?min=false'
}*/
]
},
resolve: {
alias: {
views: path.resolve(ROOT, './src/view'),
}
},
plugins: configPlugins,
/**
* @see https://doc.webpack-china.org/configuration/externals/
* CDN 引入 jQuery,jQuery 不打包到 bundle 中
*/
externals: {
jquery: 'jQuery'
},
// @see http://webpack.github.io/docs/webpack-dev-server.html
// @see http://www.css88.com/doc/webpack2/configuration/dev-server/
devServer: {
contentBase: [
path.join(ROOT, 'src/')
],
disableHostCheck: true, // https://stackoverflow.com/questions/43650550/invalid-host-header-in-when-running-react-app
hot: false,
host: '0.0.0.0',
port: 9000,
/**
* http://localhost:8080/api/get => http://httpbin.org/get
*/
proxy: {
'/api': {
target: 'http://httpbin.org',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};
/**
* 根据目录获取入口
* @param {[type]} globPath [description]
* @return {[type]} [description]
*/
function getEntry (globPath) {
let entries = {};
Glob.sync(globPath).forEach(function (entry) {
let basename = path.basename(entry, path.extname(entry)),
pathname = path.dirname(entry),
fileDir = pathname.split('/').splice(3).join('/');
// js/lib/*.js 不作为入口
if (!entry.match(/\/js\/(lib|commons)\//)) {
entries[(fileDir ? fileDir + '/' : fileDir) + basename] = pathname + '/' + basename;
}
});
return entries;
}
/**
* 根据目录获取 Html 入口
* @param {[type]} globPath [description]
* @return {[type]} [description]
*/
function getEntryHtml (globPath) {
let entries = [];
Glob.sync(globPath).forEach(function (entry) {
let basename = path.basename(entry, path.extname(entry)),
pathname = path.dirname(entry),
fileDir = pathname.split('/').splice(3).join('/'),
// @see https://github.com/kangax/html-minifier#options-quick-reference
minifyConfig = !IsProduction ? '' : {
removeComments: true,
// collapseWhitespace: true,
minifyCSS: true,
minifyJS: true
};
entries.push({
filename: entry.split('/').splice(2).join('/'),
template: entry,
chunks: ['common', (fileDir ? fileDir + '/' : fileDir) + basename],
minify: minifyConfig
});
});
return entries;
}
module.exports = config;
<file_sep>require('../../css/base.css');
require('../../css/common.less');
import template from '../commons/template';
var data = {
title: '用户列表',
list: [
'001',
'002',
'003',
'004',
'005'
]
};
var html = template('user-list', data);
$('#wrapper').html(html);
console.log('user list', $);
<file_sep>function getUrl () {
console.log('get url');
}
function setUrl () {
console.log('set url');
}
module.exports = {
getUrl: getUrl,
setUrl: setUrl
}<file_sep>require('../css/base.css');
require('../css/common.less');
require('../css/iconfont.css');
import url from "./commons/url";
import Dialog from '../component/dialog/GB-dialog';
import Toast from '../component/toast/GB-message';
// import $ from 'jquery';
// import $ from './lib/zepto';
init();
function init () {
url.getUrl();
url.setUrl();
/*const render = require('../view/index.html');
const data = {
tit: 'tits'
};
const html = render(data)
console.log(html)
if (typeof document === 'object') {
document.body.innerHTML = html;
}*/
console.log('page home', Dialog);
events();
}
function events () {
document.getElementById('btnDialog').addEventListener('click', function () {
Dialog.show({
title: '标题',
content: '这里是弹出层内容'
});
}, false);
/* document.getElementById('btnToast').addEventListener('click', function () {
Toast.show('Toast');
}, false); */
$('#btnToast').on('click', function () {
Toast.show('Toast');
});
}
<file_sep>/**
* GB-dialog.js
* @class gbDialog
* @see https://github.com/givebest/GB-dialog
* @author <EMAIL>
* @(c) 2016
**/
require('./GB-dialog.less');
(function() {
var domBody = document.body, $,
overlayId = 'GB-overlay', dialogId = 'createDialog',
overlay, dialog,
dialogs,
bodyScrollTop = 0,
fnEvent = {};
function init() {
build();
}
/**
* @param {String} id
* @return {Object} HTML element
*/
$ = function(id) {
return document.getElementById(id);
};
/**
* Build dialog box
*/
function build() {
if ($(overlayId)) {
var eleChild = document.createElement('div');
eleChild.id = dialogId;
eleChild.className = 'gb-dialog';
$(overlayId).appendChild(eleChild);
} else {
var ele = document.createElement('section'),
eleChild = document.createElement('div');
ele.id = overlayId;
ele.className = 'gb-overlay';
ele.style.display = 'none';
eleChild.id = dialogId;
eleChild.className = 'gb-dialog';
ele.appendChild(eleChild);
domBody.appendChild(ele);
}
overlay = $(overlayId);
}
/**
* 显示一个dialog
* @param {Object} opts
*/
function show(opts) {
var opts = opts || {};
// bodyScrollTop = domBody.scrollTop || domBody.style.top.replace(/\D|\s/g, '') || 0;
bodyScrollTop = domBody.scrollTop || -parseFloat(domBody.style.top) || 0;
if (opts.id) {
dialog = $(opts.id);
} else {
dialog = overlay.lastElementChild || overlay.children[overlay.children.length];
var btnConfirm = opts.btnConfirm === undefined ? '确定' : (opts.btnConfirm ? opts.btnConfirm : false),
btnCancel = opts.btnCancel === undefined ? '取消' : (opts.btnCancel ? opts.btnCancel : false);
var html = [];
html.push('<div class="gb-dialog-head ' + (!opts.title && !opts.btnClose ? 'gb-hide' : '') + '">');
if (opts.title) {
html.push('<div class="gb-dialog-title">' + opts.title + '</div>');
}
if (opts.btnClose) {
html.push('<a href="javascript:;" class="gb-dialog-close icono-cross">X</a>');
}
html.push('</div>');
html.push('<div class="gb-dialog-container">');
html.push(opts.content);
html.push('</div>');
html.push('<div class="gb-dialog-foot gb-btn-group ' + (!btnConfirm && !btnCancel ? 'gb-hide' : '') + '">');
if (btnConfirm) {
html.push('<a href="javascript:;" class="gb-btn gb-dialog-confirm">' + btnConfirm + '</a>');
}
if (btnCancel) {
html.push('<a href="javascript:;" class="gb-btn gb-dialog-cancel">' + btnCancel + '</a>');
}
html.push('</div>');
dialog.innerHTML = html.join('');
}
// 隐藏所有 dialog
dialogs = dialog.querySelectorAll('div.gb-dialog');
for (var i = 0; i < dialogs.length; i++) {
dialogs[i].style.display = 'none';
}
domBody.style.top = -bodyScrollTop + 'px';
domBody.style.position = 'fixed';
domBody.style.overflowY = 'hidden';
dialog.style.display = 'block';
overlay.style.display = 'block';
opts.confirm && (fnEvent.confirm = opts.confirm);
opts.cancel && (fnEvent.cancel = opts.cancel);
opts.verify && (fnEvent.verify = opts.verify);
opts.close && (fnEvent.close = opts.close);
bind(dialog, 'click', events);
}
/*
* 隐藏一个dialog并解绑 click 事件
*/
function hide(dialog) {
unbind(dialog, 'click', events);
fnEvent = {};
domBody.style.position = 'static';
domBody.style.top = 0;
domBody.style.overflowY = 'auto';
domBody.scrollTop = bodyScrollTop;
overlay.style.display = 'none';
dialog.style.display = 'none';
}
/**
* 事件委托判断点击按钮功能
*/
function events(e) {
e = e || window.event;
var target = e.target || e.srcElement;
var dialog = this;
if (hasClass(target, 'gb-dialog-confirm')) {
typeof fnEvent.confirm === 'function' && fnEvent.confirm();
hide(dialog);
} else if (hasClass(target, 'gb-dialog-cancel')) {
typeof fnEvent.cancel === 'function' && fnEvent.cancel();
hide(dialog);
} else if (hasClass(target, 'gb-dialog-close')) {
typeof fnEvent.close === 'function' && fnEvent.close();
hide(dialog);
} else if (hasClass(target, 'gb-dialog-verify')) {
e.preventDefault(); //阻止默认事件
typeof fnEvent.verify === 'function' && fnEvent.verify() && typeof fnEvent.confirm === 'function' && fnEvent.confirm();
}
}
/**
* Bind events to elements
* @param {Object} ele HTML Object
* @param {Event} event Event to detach
* @param {Function} fn Callback function
*/
function bind(ele, event, fn) {
if (typeof addEventListener === 'function') {
ele.addEventListener(event, fn, false);
} else if (ele.attachEvent) {
ele.attachEvent('on' + event, fn);
}
}
/**
* Unbind events to elements
* @param {Object} ele HTML Object
* @param {Event} event Event to detach
* @param {Function} fn Callback function
*/
function unbind(ele, event, fn) {
if (typeof removeEventListener === 'function') {
ele.removeEventListener(event, fn, false);
} else if (ele.detachEvent) {
ele.detach('on' + event, fn);
}
}
/**
* hasClass
* @param {Object} ele HTML Object
* @param {String} cls className
* @return {Boolean}
*/
function hasClass(ele, cls) {
if (!ele || !cls) return false;
if (ele.classList) {
return ele.classList.contains(cls);
} else {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
}
// addClass
/* function addClass(ele, cls) {
if (ele.classList) {
ele.classList.add(cls);
} else {
if (!hasClass(ele, cls)) ele.className += '' + cls;
}
}
// removeClass
function removeClass(ele, cls) {
if (ele.classList) {
ele.classList.remove(cls);
} else {
ele.className = ele.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}*/
// init
init();
var gbDialog = {
show: function(opts) {
return show(opts);
}
};
// AMD (@see https://github.com/jashkenas/underscore/blob/master/underscore.js)
if (typeof define == 'function' && define.amd) {
define('GB-dialog', [], function() {
return gbDialog;
});
} else {
// (@see https://github.com/madrobby/zepto/blob/master/src/zepto.js)
window.gbDialog === undefined && (window.gbDialog = gbDialog);
}
}());
<file_sep># Webpack multiple entry
基于 webpack 实现的多入口项目脚手架。
主要使用 `extract-text-webpack-plugin` 实现 `js` 、`css` 公共代码提取,`html-webpack-plugin` 实现 `html` 多入口,`less-loader` 实现 `less` 编译,`postcss-loader` 配置 `autoprefixer` 实现自动添加浏览器兼容前缀,删除~~`html-withimg-loader` 实现 `html` 内引入图片版本号添加和模板功能,~~`art-template`实现`html`模板功能,具有 layout 母模板(布局模板)功能更加强大、同时通过修改解析规则界定符支持浏览器端使用 `art-template-web.js`,babel-loader` 实现 `ES6` 转码功能,`imagemin` 实现图片优化压缩, `happypack` 多线程加速构建速度。
## 使用
### 安装
```
npm install
```
### 开发
```
npm start
```
> http://localhost:8080/view
### 构建
| 命令 | 说明 |
| --------------- | ------------ |
| `npm run dev` | 开发环境构建,不压缩代码 |
| `npm run build` | 生产环境构建,压缩代码 |
### art-template
> 项目同时用了 `art-template-loader` 和 `art-template-web.js`,默认情况下模板解析规则界定符会冲突,通过修改 `art-template-web.js` 解析界定符避免冲突。
```javascript
// 修改 <% %> 为 <? ?>
// @see http://aui.github.io/art-template/zh-cn/docs/rules.html
var rule = template.defaults.rules[0];
rule.test = new RegExp(rule.test.source.replace('<%', '<\\\?').replace('%>', '\\\?>'));
```
#### 使用
> 与[原始语法](http://aui.github.io/art-template/zh-cn/docs/syntax.html)保持一致,仅需替换 `<%` 为 `<?` 、`%>` 为 `?>`
##### JavaScript
```javascript
import template from '../commons/template';
var data = {
title: '用户列表',
list: [
'001',
'002',
'003',
'004',
'005'
]
};
var html = template('user-list', data);
document.getElementById('wrapper').innerHTML = html;
```
##### HTML
```html
<div id="wrapper"></div>
<script id="user-list" type="text/html">
<h1><?= title ?></h1>
<ul>
<? for (var i =0; i < list.length; i++) { ?>
<li><?= list[i] ?></li>
<? } ?>
</ul>
</script>
```
## 目录
```
├── dist # 构建后的目录
├── config # 项目配置文件
│ ├── webpack.config.js # webpack 配置文件
│ └── postcss.config.js # postcss 配置文件
├── src # 程序源文件
│ └── js # 入口
│ ├ └── index.js # 匹配 view/index.html
│ ├ └── user
│ ├ ├ ├── index.js # 匹配 view/user/index.html
│ ├ ├ ├── list.js # 匹配 view/user/list.html
│ ├ └── lib # JS 库等,不参与路由匹配
│ ├ ├── jquery.js
│ ├ └── commons # JS 公共模块等,不参与路由匹配
│ ├ ├── app-callphone.js
│ └── view
│ ├ └── index.html # 对应 js/index.js
│ ├ └── user
│ ├ ├── index.html # 对应 js/user/index.js
│ ├ ├── list.html # 对应 js/user/list.js
│ └── component # 组件
│ ├ └── dialog # Dialog 弹出层组件
│ ├ └── other
│ └── css # css 文件目录
│ ├ └── base.css
│ ├ └── iconfont.css
│ └── font # iconfont 文件目录
│ ├ └── iconfont.ttf
│ ├ └── iconfont.css
│ └── img # 图片文件目录
│ ├ └── pic1.jpg
│ ├ └── pic2.png
│ └── template # html 模板目录
│ └── layout.art # layout 母模板
│ └── head.art
│ └── foot.art
```
## 常见问题
#### MacOS png 图片处理失败
现象:
```
Module build failed: Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib
```
解决:
`brew install libpng`,详见:https://github.com/tcoopman/image-webpack-loader#libpng-issues
## License
[ISC](./LICENSE) © 2017 [givebest](https://github.com/givebest)
<file_sep>import template from '../lib/art-template-web';
// 默认解析规则界定符与 'art-template-loader' 冲突,修改界定符避免冲突
// @see http://aui.github.io/art-template/zh-cn/docs/rules.html
var rule = template.defaults.rules[0];
rule.test = new RegExp(rule.test.source.replace('<%','<\\\?').replace('%>', '\\\?>'));
export default template
<file_sep><!-- Layout 母模板 -->
<% extend('../../template/layout.art') %>
<!-- 标题 -->
<% block('title', function(){ %>About us<% }) %>
<!-- body -->
<% block('content', function(){ %>
<% include('../../template/nav.art') %>
<h1>About us</h1>
<h2>Dialog组件</h2>
<a id="btnDialog" href="javascript:;">试一下</a>
<% }) %>
<file_sep>require('../../css/base.css');
require('../../css/common.less');
require('./index.less');
// require('../lib/zepto.js');
console.log('About us');
import Dialog from '../../component/dialog/GB-dialog';
document.getElementById('btnDialog').addEventListener('click', function () {
Dialog.show({
title: '标题',
content: '这里是弹出层内容'
});
}, false);
// Arrow FN
var c = x => x * x;
console.log(c(3));
console.log(c(4))
<file_sep>// GB-Message.js
// (c) 2016-2016 givebest(<EMAIL>)
/**
* GBMessage
* @class gbmsg
* @see https://github.com/givebest/gb-message
* @author <EMAIL>
**/
/*
使用:
gbmsg.success('恭喜', '您的提供已经成功。');
gbmsg.failure('抱歉', '网络异常,请重试。');
gbmsg.info('警告', '您确定要删除这个吗?');
gbmsg.waitting('加载中,请稍候。');
gbmsg.loading('加载中...');
gbmsg.loading();
gbmsg.frown('很遗憾', '亲未能抽中大奖');
gbmsg.smile('恭喜', '小手一点,大奖到手');
*/
require('./gb-message.less');
(function (root, factory) {
'use strict';
// @see https://github.com/umdjs/umd
// @see https://github.com/ruyadorno/generator-umd
if (typeof module === "object" && typeof module.exports === "object") {
// @see https://github.com/mzabriskie/axios/blob/master/dist/axios.js
// @see https://github.com/jquery/jquery/blob/master/src/wrapper.js
// Node. Does not work with strict CommonJS, but only CommonJs-like
// environments that support module.exports, like Node.
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], function () {
return (root.returnExportsGlobal = factory());
});
} else {
// Browser globals ( root is window )
root.gbmsg = factory();
}
}(this, function () {
var domBody = document.body,
overlay, // 遮罩层
dialog, // 信息层
hideTimeoutId = undefined,
timeoutId = undefined;
function init(){
var eleDiv = document.createElement('div');
eleDiv.id = 'GBMsg';
eleDiv.className = 'gbmsg-overlay';
eleDiv.innerHTML = '<div class="gbmsg-dialog"></div>';
domBody.appendChild(eleDiv);
overlay = document.getElementById('GBMsg');
dialog = overlay.firstElementChild || overlay.children[0];
}
function showDialog(title, msg, opts){
var _this = this,
title = title,
msg = msg,
opts = opts || {},
optsTime = opts.timeout || 1,
html = [],
htmlContainer = '',
iconClass = opts.iconClass;
if (iconClass) {
html.push('<div class="gbmsg-dialog-icon">');
html.push('<i class="' + iconClass + '"></i>');
html.push('</div>');
}
// msg为空,移除title,msg展示title内容
/* !!msg ?
html.push('<div class="gbmsg-dialog-container"><h5 class="gbmsg-dialog-title">' + title + '</h5>') :
msg = title;*/
if(!!msg){
html.push('<div class="gbmsg-dialog-container">');
html.push('<h5 class="gbmsg-dialog-title">' + title + '</h5>')
}else{
msg = title;
htmlContainer = '<div class="gbmsg-dialog-container">';
}
// msg依然为空,移除msg,只展示icon
!!msg ?
html.push( htmlContainer + '<div class="gbmsg-dialog-content">' + msg + '</div>') :
'';
html.push('</div></div>');
dialog.innerHTML = html.join('');
overlay.style.display = 'block';
// @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout
if(!!optsTime && optsTime < 100){
timeoutId && clearTimeout(timeoutId);
timeoutId = setTimeout(function(){
// hide();
overlay.style.display = 'none';
timeoutId = undefined;
}, optsTime * 1500);
}
}
function hideDialog(){
var hideTimeoutId = undefined;
addClass(overlay, 'gbmsg-fadeOut');
clearTimeout && clearTimeout(timeoutId);
hideTimeoutId = setTimeout(function(){
removeClass(overlay, 'gbmsg-fadeOut');
overlay.style.display = 'none';
clearTimeout = undefined;
}, 400);
}
// success
function success(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-checkCircle'
});
}
// failure
function failure(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-crossCircle'
});
}
// info
function info(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-exclamationCircle'
});
}
// waitting
function waitting(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-clock',
'timeout': 100
});
}
// loading
function loading(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-reset',
'timeout': 100
});
}
// frown
function frown(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-frown'
});
}
// smile
function smile(title, msg){
showDialog(title, msg, {
'iconClass': 'icono-smile'
});
}
// no icon
function noicon (title, msg) {
showDialog(title, msg);
}
// hide
function hide(){
timeoutId && clearTimeout(timeoutId);
overlay.style.display = 'none';
timeoutId = undefined;
}
/*
classList (@see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
support: http://caniuse.com/#search=classList
so: 以下 hasClass/addClass/removeClass 仅满足此处需求
*/
// hasClass
function hasClass(ele, name){
if(!ele || !name) return;
return ele.classList.contains(name);
}
// addClass
function addClass(ele, name){
if(!ele || !name) return;
ele.classList.add(name);
}
// removeClass
function removeClass(ele, name){
if(!ele || !name) return;
ele.classList.remove(name);
}
// 初始化
init();
return {
success: success,
failure: failure,
info: info,
waitting: waitting,
loading: loading,
frown: frown,
smile: smile,
hide: hide,
show: noicon
}
}));
| cd4b5964c8fc728784bb29e9646c44af0f0db855 | [
"JavaScript",
"HTML",
"Markdown"
] | 12 | JavaScript | givebest/webpack-multiple-entry | 7ddf5cff09d8379adbb7f34d60a185a68e2c422d | 1f8ebfe406da511c96ecfd948b9277f403c5d1ac |
refs/heads/master | <repo_name>dipbd1/stack-api<file_sep>/src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const Bar = { template: '<div></div>' }
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/blank',
component: Bar,
},
];
const router = new VueRouter({
routes,
mode: 'history',
});
export default router;
| f54dadf97fa82cdea47f5040d69a4e8bec4ed0e3 | [
"JavaScript"
] | 1 | JavaScript | dipbd1/stack-api | b531f52b3c29a10c77e8ff0a6755348b4a39fecf | 486a32e985c5bc238b02b40a35deea225d7cbc41 |
refs/heads/master | <repo_name>WahaWaher/node-api-common-template<file_sep>/src/services/README.md
The standalone services (e.g. Database service, Email service, ...)<file_sep>/src/models/README.md
The model data (e.g. Mongoose model)<file_sep>/src/controllers/account/get-profile.ctrl.js
module.exports = (req, res, next) => {
// Get user profile implementation...
res.send({
message: 'Get user profile..'
});
};<file_sep>/src/routes/users.router.js
const express = require('express');
const router = express.Router();
// Controllers
const { login, registration } = require('../controllers/users');
/**
* Login route
* @route {GET} /api/v1/login/
* @body
*/
router.get('/login', login);
/**
* Registration route
* @route {GET} /api/v1/registration/
* @body
*/
router.get('/registration', registration);
module.exports = router;<file_sep>/src/middlewares/check-auth.mw.js
module.exports = (req, res, next) => {
// Check auth implementation...
next();
};<file_sep>/src/controllers/users/registration.ctrl.js
module.exports = (req, res, next) => {
// registration implementation...
res.send({
message: 'registration...',
});
};
<file_sep>/README.md
Common Template for Node/Express/Mongo API Apps <sup>1.1.3</sup>
-------
## Get started:
```sh
git clone https://github.com/WahaWaher/node-api-common-template.git
cd node-api-common-template
npm i
- Create config.js from config.example.js
(config.development.js and config.production.js - optional)
# Start development
npm run dev
# Start production
npm run prod
```<file_sep>/src/utils/common/README.md
Common not specific simple utils<file_sep>/src/responses/README.md
Contains errors/success response body data<file_sep>/src/routes/account.router.js
const express = require('express');
const router = express.Router();
// Controllers
const { getProfile } = require('../controllers/account');
// Middlewares
const { checkAuth } = require('../middlewares');
/**
** Login route
** @route {GET} /api/v1/profile/
** @body
*/
router.get('/profile', checkAuth, getProfile);
module.exports = router;<file_sep>/src/database.js
// Libs
const mongoose = require('mongoose');
// Config
const {
db_host,
db_port,
db_name,
db_user,
db_pass,
db_auth,
} = require('./utils/get-config').database;
const connect = () => {
return mongoose.connect(
`mongodb://${db_user}:${db_pass}@${db_host}:${db_port}/${db_name}?&authSource=${db_auth}`,
{ useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true }
);
};
module.exports = {
connect,
};
<file_sep>/src/models/User.js
// User mongoose model<file_sep>/src/app.js
// Libs
const express = require('express');
// Middlewares
const {
setCors,
addSuccessMethod,
addErrorMethod,
handleNotFound,
handleErrors,
} = require('./middlewares');
// Routes
const { mainRouter, usersRouter, accountRouter } = require('./routes');
// Modules
const database = require('./database');
// Configs
const { project, mode } = require('./utils/get-config');
const { host, port, base } = require('./utils/get-config').server;
const app = express();
/**
* Middlewares: main
*/
app.use(setCors);
app.use(addSuccessMethod);
app.use(addErrorMethod);
/**
* Routes
*/
app.use(`/`, mainRouter);
app.use(`${base}/`, usersRouter);
app.use(`${base}/me`, accountRouter);
/**
* Middlewares: errors
*/
app.use(handleNotFound);
app.use(handleErrors);
/**
* Start app
*/
Promise.resolve('Starting app...')
.then(init => {
console.log(init);
console.log('Database connecting...');
return database.connect();
})
.then(
() => console.log('Database connected successfully'),
() => console.log('Database connection error')
)
.then(success => {
console.log('Starting server...');
return app.listen(port);
})
.then(
() => {
console.log('Server started successfully');
console.log(
`\n ${project}\n mode: ${mode}\n url: http://${host}:${port}\n`
);
},
() => console.log('Error starting server')
)
.catch(error => console.log('Something went wrong'));
| 97e679333715b2c0c0199068a5da4a87df482752 | [
"Markdown",
"JavaScript"
] | 13 | Markdown | WahaWaher/node-api-common-template | a395094e1ae076434aef3da1458c775acf987d6c | f7263d954c9aac265cd0ed4c21aed00532026481 |
refs/heads/master | <repo_name>bkn/frontpage<file_sep>/extractor/test.py
# coding: utf-8
import re
import codecs
import urllib
import urllib2
import simplejson
from bkn_wsf import *
'''
TO EXPERIMENT
Edit bkn_wsf.wsf_test() function or coment out the call below add whatever you want.
I put the tests in a bkn_wsf function so bkn_wsf can be imported without side effects
but if one prefers they can use just the bkn_wsf file for experiments.
'''
def test_data():
objref1 = {
'id':'objref1',
'in':'nested object string',
'nested_array':['four', 'five']
}
objref2 = {
"id":"objref2",
"in":"array of objects index one"
}
objref3 = {
"id":"objref3",
"in":"second object in nested array"
}
objref4 = {
"id":"objref4",
"key":"object key value in mixed array"
}
mixed = {
"key": "value",
"mixed_array": [
"basic string in array",
{
"ref":"objref4"
}
]
}
record_id = 'sample1'
bibjson = {"name": "<NAME>",
"id": record_id,
"type":"Object",
"test": "try overwrite record using update with less data. Old data should not remain",
"value":"a string",
"value_array":["one", "two", "three"],
"object": {
"ref":"objref1"
},
"object_array": [{
"ref":"objref2"
},
{
"ref":"objref3"
}]
}
return bibjson
#Test.wsf_test()
response = {}
#instance = 'http://www.bibkn.org/wsf/'
#instance = 'http://people.bibkn.org/wsf/'
instance = 'http://datasets.bibsoup.org/wsf/'
Logger.set(0,'level')
#Test.autotest(instance)
BKNWSF.set(instance,'root')
Service.set(BKNWSF.get()+'ws/','root')
Dataset.set(BKNWSF.get()+'datasets/','root')
Dataset.set('dod')
#response = Dataset.set(Dataset.get(), 'public_access')
#response = Dataset.list('access')
#response = BKNWSF.browse()
#print simplejson.dumps(response, indent=2)
if 1:
# Dataset.set('dod')
Dataset.set('id_test')
# datasource = 'dod.bib.json'
# datasource = 'test.json'
testlimit = 0
import_interval = 5
print Dataset.get()
response = Dataset.delete(Dataset.get())
# response = Dataset.set(Dataset.get(), 'default_access')
# response = Dataset.set(Dataset.get(), 'public_access')
# instance_ip = '172.16.31.10'
# instance_ip = '0.0.0.0'
# response = Dataset.auth_registrar_access(Dataset.get(), 'update', instance_ip, 'read_update', access_uri)
response = Dataset.list('ids')
# response = Dataset.list('description')
# response = Dataset.list('access_detail')
# response = Dataset.read('all') #THIS GIVE BAD JSON ERROR
# response = Dataset.access()
# UPDATE ACCESS FOR PUBLIC READ_ONLY
# instance_ip = '0.0.0.0'
# access_uri = 'http://datasets.bibsoup.org/wsf/access/c252265a5b60d426d8e4ac3a0d6e4d66'
# response = Dataset.auth_registrar_access(Dataset.get(), 'update', instance_ip, 'read_only', access_uri)
# print simplejson.dumps(response, indent=2)
# print 'access list'
# response = Dataset.list('access')
# response = BKNWSF.browse()
# response = Dataset.list('access')
print simplejson.dumps(response, indent=2)
print '\n'
response = {}
if (('recordList' in response) and response['recordList']):
# you can get total results by calling
facets = get_result_facets(response)
if (facets):
print 'facets'
print simplejson.dumps(facets, indent=2)
print '\nNOTE: not all things are people. See facets[\"type\"]'
print 'for counts: (there are a few things to check)'
print '\t owl_Thing - \t should represent everything if it exists'
print '\t Object - \t not sure why this does not represent everything'
print '\t Person - \t just people'
<file_sep>/extractor/metadata_extractor.py
import json, glob, codecs, datetime, sys, os, time, getopt, re, arg_parse
files = []
def spec_files(f, rlvl):
global files
for i in range(rlvl+1):
for fp in f:
temp = glob.glob('./' + '*/'*i + fp)
if len(temp)> 0:
for string in temp:
if not(string in files):
files.append(string)
def type_file(f, rlvl):
global files
for i in range(rlvl+1):
for ftype in f:
temp = glob.glob('./' + '*/'*i + '*.' +ftype)
if len(temp)>0:
files.extend(temp)
def all_files():
global files
files = glob.glob('./*/*.json')
def extract():
global files
datasets = []
exclude_id = re.compile('identifiers')
exclude_type = re.compile('type_hints')
if 'metaset.bibjs' in files:
files.remove('metaset.bibjs')
for i in range(len(files)):
if not(exclude_id.search(files[i]) or exclude_type.search(files[i])):
datasets.append(files[i])
for fp in datasets:
fin = codecs.open(fp, 'r', 'utf-8')
try:
bibjs_obj = json.load(fin)
except:
print 'failed to load file: ' + fp
fin.close()
continue
if type(bibjs_obj).__name__ != 'dict':
print 'not dictionary: ' + fp
fin.close()
else:
if not ('dataset' in bibjs_obj):
bibjs_obj['dataset'] = {}
# bibjs_obj['dataset']['type'] = 'dataset'
# bibjs_obj['dataset']['id'] = ''
# bibjs_obj['dataset']['description'] = fp + ' dataset'
# bibjs_obj['dataset']['source'] = ''
# bibjs_obj['dataset']['creator'] = ''
# bibjs_obj['dataset']['curator'] = ''
# bibjs_obj['dataset']['schema'] = ''
# bibjs_obj['dataset']['linkage'] = ''
file_name = fp.split('/')
filename_rm_ext = file_name[len(file_name)-1].split('.')[0]
bibjs_obj['dataset']['name'] = filename_rm_ext
bibjs_obj['dataset']['id'] = '@' + filename_rm_ext.lower()
try:
bibjs_obj['dataset']['records'] = len(bibjs_obj['recordList'])
except:
print 'No recordList property in: ' + fp
fin.close()
continue
fin.close()
fout = codecs.open(fp, 'w', 'utf-8')
json.dump(bibjs_obj, fout, indent=2)
fout.close()
file_stats = os.stat(fp)
fin = codecs.open(fp, 'r', 'utf-8')
metaset = json.load(fin)
fin.close()
if file_stats.st_size < 1024:
metaset['dataset']['size'] = str(file_stats.st_size) + ' B'
elif file_stats.st_size < 1048576:
metaset['dataset']['size'] = ("%.2f" % (file_stats.st_size/1023.0)) + ' KB'
else:
metaset['dataset']['size'] = ("%.2f" % (file_stats.st_size/1048575.0)) + ' MB'
metaset['dataset']['createdDate'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_stats.st_ctime))
fout = codecs.open(fp, 'wa', 'utf-8')
json.dump(metaset, fout, indent=2)
fout.close()
#parser = argparse.ArgumentParser(description='Extract metadata from bibjs datasets.')
#parser.add_argument('files', metavar='file.bibjs', nargs='+',
# help='Files to create/update metadata.')
#parser.add_argument('-f', dest='extract', action='store_const',
# const=spec_files, default=all_files,
# help='Extract metadata from specified .bibjs datasets in same directory. (default: extract all .bibjs datasets in same directory.)')
#args = parser.parse_args()
#args.extract(args.files)
def usage():
print 'usage: metadata_extracter.py [option] ... [-s files] [-t type] [-r num] [-h] default= all *.json files in 1 lvl of recursion.'
print 'Options and arguments'
print '-s: exact files'
print '-t: specify file type'
print '-r: directory depth of search'
print '-h: print usage'
def main():
arg_handler = arg_parse.Argparse()
arg_list = arg_handler.extract(sys.argv[1:])
if len(arg_list) == 0:
all_files()
for key in arg_list:
if key == '-s' or key == '--specific':
if '-r' in arg_list:
if type(arg_list['-r']).__name__ == 'list':
if len(arg_list['-r']) == 1:
if type(arg_list['-r'][0]).__name__ == 'str':
type_file(arg_list[key], int(arg_list['-r'][0]))
elif type(arg_list['-r'][0]).__name__ == 'int':
type_file(arg_list[key], arg_list['-r'][0])
else:
print 'incorrect type to -r'
sys.exit(2)
else:
print 'incorrect num of args to -r'
sys.exit(2)
elif type(arg_list['-r']).__name__ == 'int':
type_file(arg_list[key], arg_list['-r'])
else:
print 'value specified for -r must be an int'
sys.exit(2)
else:
spec_files(arg_list[key],1)
elif key == '-t' or key == '--file-type':
if '-r' in arg_list:
if type(arg_list['-r']).__name__ == 'list':
if len(arg_list['-r']) == 1:
if type(arg_list['-r'][0]).__name__ == 'str':
type_file(arg_list[key], int(arg_list['-r'][0]))
elif type(arg_list['-r'][0]).__name__ == 'int':
type_file(arg_list[key], arg_list['-r'][0])
else:
print 'incorrect type to -r'
sys.exit(2)
else:
print 'incorrect num of args to -r'
sys.exit(2)
elif type(arg_list['-r']).__name__ == 'int':
type_file(arg_list[key], arg_list['-r'])
else:
print 'value specified for -r must be an int'
sys.exit(2)
else:
type_file(arg_list[key], 1)
elif key == '-h' or key == '--help':
usage()
elif key != '-r':
print 'unhandled option: \"' + key + '\"'
sys.exit(2)
extract()
"""
try:
# opts, args = getopt.getopt(sys.argv[1:], "hes", ["help", "--files-type=", "specific="])
except getopt.GetoptError, err:
# print help information and exit:
# will print something like "option -a not recognized"
print str(err)
usage()
sys.exit(2)
for key, value in opts:
if key in ("-s", "--specific"):
print args
# spec_files(args)
# sys.exit()
elif key in ("-e", "--file-type"):
print args
elif key in ("-h", "--help"):
usage()
sys.exit()
else:
assert False, "unhandled option"
# all_files()
"""
if __name__ == "__main__":
main()
<file_sep>/extractor/arg_parse.py
import re
class Argparse:
# Stores actions to take with options as keys.
opt_arg = {}
# Extracts matching option-argument pairs from an array. Returns a dictionary mapping options to args.
def extract(self,arg_list):
option = re.compile('-.')
arg_dict = {}
temp = []
while len(arg_list) > 0:
s = arg_list.pop()
if option.match(str(s)):
arg_dict[s] = temp
temp = []
else:
temp.append(s)
return arg_dict
# Pairs specified option array with action array. Must be string to function mapping.
def match(self,option, action):
if (type(option).__name__=='list' and type(action).__name__!='list') or (type(option).__name__!='list' and type(action).__name__=='list'):
print 'incorrect type of args to arg_parse.match'
elif type(option).__name__ == 'list' and type(action).__name__ == 'list':
for i in range(len(option)):
try:
if type(action[i]).__name__ != 'function':
print str(action[i]) + ' must be a function'
sys.exit(2)
elif type(option[i]).__name__!= 'str':
print str(option[i]) + ' must be a string'
sys.exit(2)
else:
self.opt_arg[option[i]] = action[i]
except IndexError:
print 'Length of action argument list shorter than option argument list'
sys.exit(2)
else:
if type(action).__name__ != 'function':
print str(action) + ' must be a function'
sys.exit(2)
elif type(option).__name__!= 'str':
print str(option) + ' must be a string'
sys.exit(2)
else:
self.opt_arg[option] = action
# Executes the function related to the option with the passed in argument dictionary. ex {'-s':['hi','hello'], '-g':['hey']}
def execute(self, arg_list):
if len(arg_list) == 0:
try:
self.opt_arg['default']()
except KeyError:
print 'Default action not specified'
try:
self.opt_arg['usage']()
except KeyError:
print 'Usage not specified'
sys.exit(2)
else:
for key in arg_list:
if key != 'default' and key != 'usage':
if key in self.opt_arg:
try:
self.opt_arg[key](arg_list[key])
except:
self.opt_arg[key]()
else:
print 'Unrecognized option: ' + key
# Default function mapping.
def default(self, funct):
if type(funct).__name__ == 'function':
self.opt_arg['default'] = funct
else:
print 'default action must be a function'
# Usage mapping.
def usage(self, funct):
if type(funct).__name__ == 'function':
self.opt_arg['usage'] = funct
else:
print 'usage must be a function'
<file_sep>/frontpage/dataset_frontpage.js
function show_json(response){
deb(formattedJSON(response));
}
// Create namespace object to avoid collisions.
var org;
if (!org) {
org = {};
}
if (!org.bibkn) {
org.bibkn = {};
}
if (!org.bibkn.Dataset) {
org.bibkn.Dataset = {};
}
org.bibkn.Dataset.json_file_req = function(){
// Test if IE and allow support for versions of IE before 7.
if (window.ActiveXObject){
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (exception) {
//Silence error.
}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (exception) {
//Silence error.
}
} else {
// Everyone else (Firefox, Safari, Chrome, etc.)
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return false;
}
}
}
org.bibkn.Dataset.load = function() {
var Dataset = org.bibkn.Dataset;
// XMLHttpRequest object.
var jsonRequest = new Dataset.json_file_req();
// On state change, load information. So when info is loaded into request or request is sent.
jsonRequest.onreadystatechange= function() {
// Check all data of request has been received.
if (jsonRequest.readyState==4){
// Check http response status is OK (200).
if (jsonRequest.status==200 || window.location.href.indexOf("http")==-1){
// Convert request(json) to javascript object.
var jsondata = eval("("+jsonRequest.responseText+")");
Dataset.datasets = jsondata.recordList;
Dataset.schema = jsondata.dataset.table_cols;
Dataset.reorder(Dataset.schema[0],'ascending');
} else {
alert("Error; something went wrong with the request.");
}
}
}
jsonRequest.open("GET", "dod.bib.json", true);
jsonRequest.send();
}
org.bibkn.Dataset.reorder = function(topic, ordering, record_num, property, pg_num, num_pp) {
var Dataset = org.bibkn.Dataset;
var output = '<table class="data_table">';
if (topic == undefined) {
topic = Dataset.schema[0];
}
if (ordering == undefined) {
ordering = 'ascending';
}
if (record_num == undefined) {
record_num = -1;
}
if (property == undefined) {
property = null;
}
if (pg_num == undefined || pg_num < 0) {
pg_num = 0;
}
if (num_pp == undefined) {
num_pp = 25; //5; //changed by <NAME>
}
output += '<col id="col1"><col id="col2"><col id="col3"><col id="col4"><tr>';
for (var c = 0; c < Dataset.schema.length; c++) {
if (topic == Dataset.schema[c]) {
if (ordering == 'ascending') {
output += '<th class="data_header" id="selected_des" onmousedown="org.bibkn.Dataset.reorder(\'' + Dataset.schema[c] + '\', \'descending\');"><u>' + Dataset.display(Dataset.schema[c]) + '</u></th>';
} else {
output += '<th class="data_header" id="selected_asc" onmousedown="org.bibkn.Dataset.reorder(\'' + Dataset.schema[c] + '\', \'ascending\');"><u>' + Dataset.display(Dataset.schema[c]) + '</u></th>';
}
} else {
output += '<th class="data_header" onmousedown="org.bibkn.Dataset.reorder(\'' + Dataset.schema[c] + '\', \'ascending\');">' + Dataset.display(Dataset.schema[c]) + '</th>';
}
}
output += '</tr>';
if (topic == 'size' || topic == 'records') {
if (ordering == 'ascending') {
Dataset.datasets = Dataset.datasets.sort(function(a,b) {return a[topic] > b[topic];});
} else {
Dataset.datasets = Dataset.datasets.sort(function(a,b) {return a[topic] < b[topic];});
}
} else {
if (ordering == 'ascending') {
Dataset.datasets = Dataset.datasets.sort(function(a,b) {return (a[topic]+"").substring(0,1).toLowerCase() > (b[topic]+"").substring(0,1).toLowerCase();});
} else {
Dataset.datasets = Dataset.datasets.sort(function(a,b) {return (a[topic]+"").substring(0,1).toLowerCase() < (b[topic]+"").substring(0,1).toLowerCase();});
}
}
for (var i = pg_num*num_pp; i < Dataset.datasets.length && i < pg_num*num_pp+num_pp; i++){
output+='<tr>';
for (var x=0; x < Dataset.schema.length; x++) {
var prop = Dataset.schema[x];
if (prop == 'description') {
output += '<td class="data_entry' + i%2 + '" id="td_descript">';
// output += '<table>'
for (var other_properties in Dataset.datasets[i]) {
if (other_properties != 'name' && other_properties !='size' && other_properties !='records') {
if (record_num == i && other_properties == property) {
// modified by <NAME> to simplify display
// output += '<form><b>' + Dataset.display(other_properties) + ': </b>';
// output += '<textarea rows=1>' + Dataset.datasets[record_num][property];
// output += '</textarea><br>';
// output += '<input type="submit" value="Change">  ';
// output += '<button onmousedown="org.bibkn.Dataset.reorder(\'';
// output += topic + '\',\'' + ordering + '\', undefined, undefined,' + pg_num + ',' + num_pp;
// output += ')">Cancel</button>';
// output += '</form>';
} else {
// output+='<b onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\',' + i + ',\'' + other_properties + '\',' + pg_num + ',' + num_pp + ')">' + Dataset.display(other_properties) + ': </b>' + Dataset.display(Dataset.datasets[i][other_properties]) + '<br><br>';
// other_properties = other_properties.toLowerCase();
switch (other_properties) {
// creator, source, createdDate, download, schema, browse
case 'description':
output += '<div class="other_prop">';
output += other_properties;
output += '</div>';
output += '<div class="other_value">'
output += Dataset.datasets[i][other_properties];
output += '</div>';
break;
case 'collected':
output += '<div>'; //'<tr>';
output += '<span class="other_prop">';//'<td class="other_prop">';
output += 'collected';//other_properties;
output += '</span>'; //'</td>';
output += '<span class="other_value">';//'<td class="other_value">';
output += Dataset.datasets[i][other_properties];
output += '</span>'; //'</td>';
output += '</div>'; //'</tr>';
break;
case 'download':
case 'browse':
output += ''; //'<tr>';
output += '<div class="other_prop">';//'<td class="other_value">';
output += '<a href="'+ Dataset.datasets[i][other_properties]+'">' + other_properties +'</a>';
output += '</div>'; //'</td>';
output += ''; //'</tr>';
break;
case 'schema':
output += '<div>'; //'<tr>';
output += '<span class="other_prop">';//'<td class="other_prop">';
output += 'schema ';
output += '</span>'; //'</td>';
// output += '<span class="other_value">';//'<td class="other_value">';
var v = Dataset.datasets[i][other_properties];
if ((typeof(v) === 'object') && (v instanceof Array)) {
output += '<div class="other_list_horizontal">'; //'<tr>';
for (var vx=0; vx < v.length; vx++) {
if (v[vx] && (typeof v[vx] == 'string')) {
var vf = ''
var vf_index = v[vx].lastIndexOf('\/')+1;
if (vf_index > 0) {
vf = v[vx].substring(vf_index);
}
output += '<span><a href="'+v[vx]+'">'+vf+'</a> </span>';
// output += ' '
// if (vf && (vf != 'bibjson_schema\.json') &&
// (vf != 'identifiers\.json')) {
// output += '<span><a href="'+v[vx]+'">'+vf+'</a></span>';
// output += ' '
// }
}
}
output += '</div>'; //'<tr>';
}
else {
output += v;
}
// output += '</span>'; //'</td>';
output += '</div>'; //'</tr>';
break;
case 'creator':
break; // drop this from display
output += '<div>'; //'<tr>';
output += '<span class="other_prop">';//'<td class="other_prop">';
output += 'creator ';
output += '</span>'; //'</td>';
output += '<span class="other_value">';//'<td class="other_value">';
var v = Dataset.datasets[i][other_properties];
if (typeof(v) === 'object') {
if ('name' in v) {
output += v['name'];
}
}
else {
output += v;
}
output += '</span>'; //'</td>';
output += '</div>'; //'</tr>';
break;
case 'source':
output += '<div>'; //'<tr>';
output += '<span class="other_prop">';//'<td class="other_prop">';
output += 'source ';//other_properties;
output += '</span>'; //'</td>';
output += '<span class="other_value">';//'<td class="other_value">';
var v = Dataset.datasets[i][other_properties];
if (typeof(v) === 'object') {
if (v instanceof Array) {
for (var vx=0; vx < v.length; vx++) {
if (v[vx] && (typeof v[vx] == 'string')) {
output += '<a href="'+v[vx] +'">'+v[vx]+'</a>';
// output += '<div>'+v[vx]+'</div>';
}
}
}
else {
var v_url = null;
if ('href' in v) {
v_url = v['href'];
}
if ('url' in v) {
v_url = v['url'];
}
if (v_url) {
output += '<a href="'+v_url +'">';
if ('name' in v) {
output += v['name']+'</a>';
}
else {
output += v_url+'</a>';
}
}
else if ('name' in v) {
output += v['name'];
}
}
}
else {
output += '<a href="'+v +'">'+v+'</a>';
}
output += '</span>'; //'</td>';
output += '</div>'; //'</tr>';
break;
default:
break;
}
}
}
}
// output += '</table>'; // nested table for other properties
output += '</td>';
} else {
if (record_num == i && prop == property) {
// output+='<td class="data_entry' + i%2 + '"><form><textarea rows=1>' + Dataset.datasets[record_num][property] + '</textarea><br><input type="submit" value="Change">  <button onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\', undefined, undefined,' + pg_num + ',' + num_pp + ')">Cancel</button></form></td>';
output+='<td class="data_entry' + i%2 + '">' + Dataset.datasets[record_num][property] + '</td>';
} else {
output+='<td class="data_entry' + i%2 + '" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\',' + i + ',\'' + prop + '\',' + pg_num + ',' + num_pp + ')">' + Dataset.display(Dataset.datasets[i][prop]) + '</td>';
}
}
}
output+='</tr>';
}
if (pg_num >= 0) {
if (pg_num == 0) {
output+='<tr><td class="page_num" colspan="'+Dataset.schema.length +'">Prev...';
} else {
output+='<tr><td class="page_num" colspan="'+Dataset.schema.length +'"><a class="valid_pg" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\','+record_num+',\''+property+'\','+(pg_num-1)+')">Prev...</a>';
}
if (pg_num < 3) {
for (var p = 0; p < 5; p++) {
if (p == pg_num) {
output+='<a class="valid_pg" id="current_page" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\','+record_num+',\''+property+'\','+ p +')">'+ p +'</a>';
} else {
if (p*num_pp < Dataset.datasets.length) {
output+='<a class="valid_pg" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\','+record_num+',\''+property+'\','+ p +')">'+ p +'</a>';
}
}
}
} else {
for (var p = -2; p < 3; p++) {
if (p == 0) {
output+='<a class="valid_pg" id="current_page" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\','+record_num+',\''+property+'\','+ pg_num +')">'+ pg_num +'</a>';
} else {
if ((pg_num+p)*num_pp < Dataset.datasets.length) {
output+='<a class="valid_pg" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\','+record_num+',\''+property+'\','+ (pg_num+p) +')">'+ (pg_num+p) +'</a>';
}
}
}
}
if ((pg_num+1)*num_pp < Dataset.datasets.length) {
output+='<a class="valid_pg" onmousedown="org.bibkn.Dataset.reorder(\'' + topic + '\',\'' + ordering + '\','+record_num+',\''+property+'\','+(pg_num+1)+')">...Next</a></td></tr></table>';
} else {
output+='...Next</td></tr></table>';
}
} else {
alert("Page numbering has failed.");
}
document.getElementById("request").innerHTML=output;
}
org.bibkn.Dataset.display = function(property) {
var output = '';
var url = /http/;
var display;
if (property instanceof Array) {
for (var i = 0; i < property.length; i++) {
if (i != (property.length-1)) {
if (url.exec(property[i])) {
display = property[i].split('/');
if (parseFloat(display[display.length-1]) == parseInt(display[display.length-1])) {
output += '<a href="' + property[i] + '">' + display[display.length-1] + '</a>, ';
} else {
output += '<a href="' + property[i] + '">' + display[display.length-1].substr(0,1).toUpperCase() + display[display.length-1].substr(1) + '</a>, ';
}
} else {
if (parseFloat(property[i]) == parseInt(property[i])) {
output += property[i];
} else {
output += property[i].substr(0,1).toUpperCase() + property[i].substr(1) + ', ';
}
}
} else {
if (url.exec(property[i])) {
display = property[i].split('/');
if (parseFloat(display[display.length-1]) == parseInt(display[display.length-1])) {
output += '<a href="' + property[i] + '">' + display[display.length-1] + '</a>, ';
} else {
output += '<a href="' + property[i] + '">' + display[display.length-1].substr(0,1).toUpperCase() + display[display.length-1].substr(1) + '</a>';
}
} else {
if (parseFloat(property[i]) == parseInt(property[i])) {
output += property[i];
} else {
output += property[i].substr(0,1).toUpperCase() + property[i].substr(1);
}
}
}
}
return output;
} else {
if (property instanceof Object) {
output += '<br>';
for (attribute in property) {
output+= '<b>'+attribute+': </b>' + org.bibkn.Dataset.display(property[attribute]) + '<br>';
}
return output.substring(0,output.length-4);
} else {
if (url.exec(property)) {
display = property.split('/');
if (display[display.length-1] == '') {
output += '<a href="' + property + '">' + property + '</a>';
} else {
if (parseFloat(display[display.length-1]) == parseInt(display[display.length-1])) {
output += '<a href="' + property + '">' + display[display.length-1] + '</a>';
} else {
output += '<a href="' + property + '">' + display[display.length-1].substr(0,1).toUpperCase() + display[display.length-1].substr(1) + '</a>';
}
}
return output;
} else {
if (parseFloat(property) == parseInt(property)) {
return property;
} else {
return property.substr(0,1).toUpperCase() + property.substr(1);
}
}
}
}
}
function show_data(jsondata) {
// Convert request(json) to javascript object.
// var jsondata = eval("("+jsonRequest.responseText+")");
org.bibkn.Dataset.datasets = jsondata.recordList;
org.bibkn.Dataset.schema = jsondata.dataset.table_cols;
org.bibkn.Dataset.reorder(org.bibkn.Dataset.schema[0],'ascending');
}
function getJSON_data(callback, file) {
// var location = "http://" + window.location.hostname + "/";
// var service = ""+location+ "bkn/frontpage/" + file;
$.ajax({
url: file,
// data: service_params,
type: "get",
cache: false,
dataType: "json",
error: function(xobj, status, error){
show_json({'xobj':xobj, 'status':status,'error':error});
},
success: callback
});
}
getJSON_data(show_data,"dod.bib.json");
//org.bibkn.Dataset.load();
<file_sep>/extractor/metaset_extractor.py
import json, glob, codecs, time, os, arg_parse, sys, re
files = []
meta_records = []
file_types = []
rlvl = 0
def update():
global files, meta_records, rlvl, file_types
metaset_bibjs = re.compile('metaset.bibjs')
for i in range(rlvl+1):
for types in file_types:
temp = glob.glob('./' + '*/'*i + '*.' + types)
if len(temp) > 0:
for string in temp:
if not(string in files):
files.append(string)
temp = glob.glob('metaset.bibjs')
for file_records in files:
if metaset_bibjs.search(file_records):
files.remove(file_records)
metaset_file = codecs.open(file_records, 'r', 'utf-8')
update_file = json.load(metaset_file)
meta_records = update_file['recordList']
metaset_file.close()
elif len(temp)>0:
metaset_file = codecs.open('metaset.bibjs', 'r', 'utf-8')
try:
update_file = json.load(metaset_file)
meta_records = update_file['recordList']
except:
print 'ill formatted metaset.bibjs'
metaset_file.close()
extract()
def find(name):
global meta_records
if len(meta_records) != 0:
for i in range(len(meta_records)):
if name == meta_records[i]['name']:
return i
return -1
else:
return -1
def extract():
global meta_records, files
meta_format = {'dataset':{}, 'recordList':[]}
meta_format['dataset']['name'] = 'metaset.bibjs'
meta_format['dataset']['type'] = 'metadataset'
meta_format['dataset']['id'] = ''
meta_format['dataset']['description'] = 'Metadata Set'
meta_format['dataset']['source'] = ''
meta_format['dataset']['table_cols'] = ["name", "size", "records", "description"]
meta_format['dataset']['creator'] = ''
meta_format['dataset']['curator'] = ''
meta_format['dataset']['linkage'] = ["http://www.bibkn.org/drupal/bibjson/iron_linkage.json"]
for fp in files:
fin = codecs.open(fp, 'r', 'utf-8')
try:
bibjs_obj = json.load(fin)
except:
print 'failed to load file: ' + fp
continue
if type(bibjs_obj).__name__ != 'dict':
print 'not dictionary: ' + fp
continue
else:
try:
meta_data = bibjs_obj['dataset']
i = find(fp)
if i == -1:
meta_data['name'] = bibjs_obj['dataset']['name']
meta_records.append(meta_data)
else:
if meta_data['createdDate'] != meta_records[i]['createdDate']:
meta_records.pop(i)
meta_records.append(meta_data)
fin.close()
except:
print 'no dataset property in: ' + fp
meta_format['recordList'] = meta_records
meta_format['dataset']['records'] = len(meta_format['recordList'])
fout = codecs.open('metaset.bibjs', 'wa', 'utf-8')
json.dump(meta_format, fout, indent=2)
fout.close()
file_stats = os.stat('metaset.bibjs')
fin = codecs.open('metaset.bibjs', 'r', 'utf-8')
metaset = json.load(fin)
fin.close()
if file_stats.st_size < 1024:
metaset['dataset']['size'] = str(file_stats.st_size) + ' B'
elif file_stats.st_size < 1048576:
metaset['dataset']['size'] = ("%.2f" % (file_stats.st_size/1023.0)) + ' KB'
else:
metaset['dataset']['size'] = ("%.2f" % (file_stats.st_size/1048575.0)) + ' MB'
metaset['dataset']['createdDate'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_stats.st_ctime))
fout = codecs.open('metaset.bibjs', 'wa', 'utf-8')
json.dump(metaset, fout, indent=2)
fout.close()
def type_file(types):
global file_types
file_types.extend(types)
def set_recursion_lvl(x):
global rlvl
if type(x).__name__ == 'list':
if len(x) ==1:
rlvl = int(x[0])
else:
print 'Incorrect num of args to -r'
def default():
global file_types, rlvl
file_types.append('json')
rlvl = 1
def usage():
print 'usage: metaset_extracter.py [option] ... [-t type] [-r num] [-h] default= all *.json files in 1 lvl of recursion.'
print 'Options and arguments'
print '-t: specify file type'
print '-r: directory depth of search'
print '-h: print usage'
def main():
arg_handler = arg_parse.Argparse()
arg_list = arg_handler.extract(sys.argv[1:])
arg_handler.match(['-t','-r','-h'], [type_file, set_recursion_lvl, usage])
arg_handler.default(default)
arg_handler.usage(usage)
arg_handler.execute(arg_list)
update()
if __name__ == "__main__":
main()
| 2d6a61c8e65ef0e22c1acec7366e11c801afb9e3 | [
"JavaScript",
"Python"
] | 5 | Python | bkn/frontpage | 8b54476116716b7ca3180a2e475737c9287734a6 | fd09aea1ad054810c1399b047f23f2e20029a00a |
refs/heads/master | <repo_name>jdugan1024/django-kiosk<file_sep>/kiosk/views.py
import StringIO
from django.http import Http404, HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseBadRequest
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.http import Http404
from django.core.files.storage import FileSystemStorage
try:
import json
except ImportError:
import simplejson as json
from kiosk.models import KioskItem, KioskPageLinkLocation, KioskItemForm
def index(request, page=None):
if not page:
page = "index"
page = get_object_or_404(KioskItem, name=page, type='page')
return render_to_response('kiosk/index.html',
{"page": page}, context_instance=RequestContext(request))
#@csrf_exempt
def loc_data(request, page_name, pk=None):
page = get_object_or_404(KioskItem, name=page_name, type='page')
if request.method == 'GET':
l = []
for link in page.link_locations.all():
l.append(link.serialize())
return HttpResponse(json.dumps(l))
if not request.user.is_staff:
return HttpResponseForbidden("Permission denied.")
if request.method == 'POST':
data = json.loads(request.body)
data['page'] = page
data['link'] = get_object_or_404(KioskItem, type=data['type'], name=data['name'])
del data['name']
del data['type']
obj = KioskPageLinkLocation(**data)
obj.save()
r = json.dumps(obj.serialize())
elif request.method == 'PUT':
obj = get_object_or_404(KioskPageLinkLocation, pk=pk)
data = json.loads(request.body)
del data['id']
del data['page']
data['link'] = get_object_or_404(KioskItem, type=data['type'], name=data['name'])
del data['name']
del data['type']
for k, v in data.iteritems():
setattr(obj, k, v)
obj.save()
r = json.dumps(obj.serialize())
elif request.method == 'DELETE':
obj = get_object_or_404(KioskPageLinkLocation, pk=pk)
obj.delete()
return HttpResponse()
else:
raise Http404()
return HttpResponse(r)
def kiosk_item(request, item_type=None, item_name=None):
r = None
if request.method == 'GET':
if not item_name:
r = []
for obj in KioskItem.objects.all():
r.append(obj.serialize())
else:
obj = get_object_or_404(KioskItem, name=item_name)
r = obj.serialize()
return HttpResponse(json.dumps(r))
if not request.user.is_staff:
return HttpResponseForbidden("Permission denied.")
if request.method == "POST":
data = json.loads(request.body)
print "POST data", data
if KioskItem.objects.filter(name=data['name'], type=data['type']).count() > 0:
return HttpResponseBadRequest("Duplicate item")
obj = KioskItem(**data)
obj.save()
r = obj.serialize()
elif request.method == "PUT":
obj = get_object_or_404(KioskItem, type=item_type, name=item_name)
data = json.loads(request.body)
print "PUT data", data
del data['id']
del data['page_image']
del data['popup_image1']
del data['popup_image2']
for k, v in data.iteritems():
setattr(obj, k, v)
obj.save()
r = obj.serialize()
elif request.method == "DELETE":
obj = get_object_or_404(KioskItem, type=item_type, name=item_name)
obj.delete()
r = ""
else:
raise Http404()
return HttpResponse(json.dumps(r))
def kiosk_item_image(request, item_type, item_name):
if request.method != 'POST':
return Http404()
if item_type not in ['page', 'popup']:
return Http404()
if not request.user.is_staff:
return HttpResponseForbidden("Permission denied.")
obj = get_object_or_404(KioskItem, type=item_type, name=item_name)
old_files = []
for k, v in request.FILES.items():
old_files.append(getattr(obj, k).name)
setattr(obj, k, v)
obj.save()
fs = FileSystemStorage()
for f in old_files:
if f:
fs.delete(f)
#print json.dumps(obj.serialize(), indent=4)
r = obj.serialize()
return HttpResponse(json.dumps(r))<file_sep>/kiosk/models.py
import os
import time
from django.db import models
from django.forms import ModelForm, ValidationError
from django.core.files.storage import FileSystemStorage
from django.conf import settings
def rename_wrapper(suffix=""):
def rename(inst, filename):
"""Normalize file name.
A timestamp in seconds since the epoch is appended to the filename to
prevent any issues with caching."""
r = ""
if suffix == "":
r = 'kiosk_%s/%s' % (inst.type, inst.name)
else:
r = 'kiosk_%s/%s__%s' % (inst.type, inst.name, suffix)
ts = int(time.time() * 1000)
return "{0}.{1}".format(r, ts)
return rename
class KioskItem(models.Model):
ITEM_TYPES = (
('page', 'Page'),
('popup', 'Popup'),
)
name = models.SlugField(max_length=256, unique=True)
title = models.CharField(max_length=256, blank=True, null=True)
type = models.CharField(max_length=8, choices=ITEM_TYPES)
# only valid when type == 'page'
page_image = models.ImageField(blank=True, null=True,
upload_to=rename_wrapper())
# only valid when type == 'popup'
popup_image1 = models.ImageField(blank=True, null=True,
upload_to=rename_wrapper(suffix="1"))
popup_image2 = models.ImageField(blank=True, null=True,
upload_to=rename_wrapper(suffix="2"))
url = models.URLField(blank=True, null=True)
text = models.TextField(blank=True, null=True)
class Meta:
ordering = ('name', )
unique_together = (("name", "type"),)
def __str__(self):
return "%s %s" % (self.name, self.type)
@property
def backbone_id(self):
return "/".join((self.type, self.name))
def serialize(self):
d = {}
d['id'] = self.backbone_id
d['name'] = self.name
d['title'] = self.title
d['type'] = self.type
if self.page_image:
d['page_image'] = self.page_image.url
else:
d['page_image'] = None
d['url'] = self.url
d['text'] = self.text
if self.popup_image1:
d['popup_image1'] = self.popup_image1.url
else:
d['popup_image1'] = None
if self.popup_image2:
d['popup_image2'] = self.popup_image2.url
else:
d['popup_image2'] = None
return d
class KioskPageLinkLocation(models.Model):
top = models.IntegerField()
left = models.IntegerField()
width = models.IntegerField()
height = models.IntegerField()
page = models.ForeignKey("KioskItem", related_name="link_locations")
link = models.ForeignKey("KioskItem", related_name="linked_pages")
class Meta:
ordering = ('page__name', 'link__name', 'left', 'top')
def __str__(self):
return "%s -> %s" % (self.page.name, self.link.name)
@property
def backbone_id(self):
return "/".join((self.page.name, str(self.pk)))
def serialize(self):
d = {}
d['id'] = self.backbone_id
d['top'] = self.top
d['left'] = self.left
d['width'] = self.width
d['height'] = self.height
d['link'] = self.link.backbone_id
d['name'] = self.link.name
d['type'] = self.link.type
d['page'] = self.page.name
return d
# --- Forms for the models above
class KioskItemForm(ModelForm):
class Meta:
model = KioskItem
def clean(self):
cleaned_data = super(KioskItemForm, self).clean()
item_type = cleaned_data.get('type')
if item_type == 'page':
pass
elif item_type == 'popup':
img1 = cleaned_data.get('popup_image1')
img2 = cleaned_data.get('popup_image2')
if img1 is None and img2 is None:
raise ValidationError("Must have at least one image")
if cleaned_data.get('text') is None:
raise ValidationError("Must supply text")
return cleaned_data
class KioskPageLinkLocationForm(ModelForm):
class Meta:
model = KioskPageLinkLocation
<file_sep>/requirements.txt
django==1.4.2
PIL==1.1.7
sphinx
-e .
<file_sep>/kiosk/admin.py
from django.contrib import admin
from kiosk.models import KioskItem, KioskPageLinkLocation
class KioskItemAdmin(admin.ModelAdmin):
list_display = ['name', 'type', 'page_image', 'popup_image1',
'popup_image2', 'url']
class KioskPageLinkLocationAdmin(admin.ModelAdmin):
list_display = ['page', 'link', 'left', 'top', 'width', 'height']
admin.site.register(KioskItem, KioskItemAdmin)
admin.site.register(KioskPageLinkLocation, KioskPageLinkLocationAdmin)
<file_sep>/kiosk/static/kiosk/kiosk.js
(function(kiosk, Backbone, $, _) {
// borrowed from: https://github.com/thomasdavis/backbonetutorials/tree/gh-pages/videos/beginner#jquery-serializeobject
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// similar function to get values of file elements
$.fn.serializeFormFiles = function() {
var o = {};
$(this).find(":file").each(function(i,e) {
o[$(e).attr("name")] = $(e).val();
});
return o;
};
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
kiosk.Controller = {
init: function(canEdit) {
var self = this;
console.log("canEdit", canEdit);
this.canEdit = canEdit;
this.dispatcher = _.clone(Backbone.Events);
this.idleTimeout = 30; // seconds
this.idleMessageTimeout = 10; // seconds
this.idleTimerInhibit = false; // globally disable idle timer
console.log("models");
this.models = {
"rootModel": new kiosk.RootModel(),
"pageModel": new kiosk.ItemModel(),
"linkCollection": new kiosk.LinkCollection(),
"itemCollection": new kiosk.ItemCollection()
}
this.models.itemCollection.fetch({
'success': function(popups) {
console.log("loaded ItemCollection: ", popups, popups.get("infinera"));
}
});
console.log("view");
this.views = {
"bodyView": new kiosk.BodyView({model: this.models.rootModel, "controller": this}),
"pageView": new kiosk.PageView({model: this.models.pageModel, "controller": this}),
"linksView": new kiosk.LinkCollectionDisplayView({collection: this.models.linkCollection, "controller": this}),
"editView": new kiosk.EditView({"controller": this})
};
console.log("router");
this.router = new kiosk.Router({"controller": this});
this.models.rootModel.on("change:mode", this.views.editView.render, this.views.editView);
this.models.rootModel.on("change:mode", this.toggleIdleTimer, this);
this.models.pageModel.bind('sync', this.views.pageView.render, this.views.pageView);
this.models.linkCollection.bind('sync', this.views.linksView.render, this.views.linksView);
this.models.linkCollection.bind('remove', this.views.linksView.render, this.views.linksView);
this.models.linkCollection.bind('add', this.views.linksView.render, this.views.linksView);
//
// setup page resizing
//
$(window).bind("resize.app", _.bind(this.views.bodyView.render, this.views.bodyView));
this.views.bodyView.render();
self.in_dialog = false;
self.mode = "view";
_.bindAll(this, "handleKeypress", "idle", "idleCountdown", "idleReset",
"idleActive", "startIdleTimer", "stopIdleTimer");
$(document).keypress(kiosk.Controller.handleKeypress);
var csrf = readCookie("csrftoken");
if (csrf) {
Backbone.originalSync = Backbone.sync;
Backbone.sync = function(method, model, options) {
options || (options = {});
options.headers = { "X-CSRFToken": csrf };
return Backbone.originalSync(method,model,options);
};
}
Backbone.history.start();
kiosk.Controller.startIdleTimer();
},
handleKeypress: function (event) {
if(this.models.rootModel.get("inDialog")) {
//if (event.which == 13) { event.preventDefault(); }
//console.log("kb event, in dialog");
return;
}
console.log("keypress_this", this);
console.log("keypress", event.which);
if(event.which == 101 && this.canEdit) { // e
console.log("root mode", this.models.rootModel.get("mode"));
if(this.models.rootModel.get("mode") == "edit") {
this.models.rootModel.set("mode", "view");
} else {
this.models.rootModel.set("mode", "edit");
}
console.log(this.models.rootModel.get("mode") + " mode")
} else if(event.which == 107) { // k
console.log("kiosk toggle");
if($("body").css("overflow") == 'hidden') {
$("body").css("overflow", "visible");
} else {
$("body").css("overflow", "hidden");
}
} else if(event.which == 84) { // T
if(!this.idleTimerInhibit) {
console.log("globally disabling idle timer");
this.stopIdleTimer();
this.idleTimerInhibit = true;
} else {
console.log("globally enabling idle timer");
this.startIdleTimer();
this.idleTimerInhibit = false;
}
} else if(this.models.rootModel.get("mode") === "edit") {
console.log("check edit keys");
switch (event.which) {
case 108: // l
event.preventDefault();
this.dispatcher.trigger("new-link-key");
break;
case 110: // n
event.preventDefault();
this.dispatcher.trigger("new-page-key");
break;
case 112: // p
event.preventDefault();
this.dispatcher.trigger("new-popup-key");
break;
case 116: // t
event.preventDefault();
this.dispatcher.trigger("edit-this-page-key");
break;
}
} else {
console.log("unknown keypress");
}
},
idle: function() {
console.log("idle timeout")
$("#countdown").html(this.idleMessageTimeout);
this.idleFor = 1;
$.timer('idle_message_timer', kiosk.Controller.idleCountdown, 1, {
timeout: this.idleMessageTimeout,
finishCallback: kiosk.Controller.idleReset
}).start();
$("#resetPopup").modal("show");
},
idleCountdown: function() {
$("#countdown").html(this.idleMessageTimeout - this.idleFor);
this.idleFor++;
},
idleReset: function() {
console.log("reset")
$("#resetPopup").modal("hide");
$("#popup").modal("hide");
if(this.models.pageModel.get("name") !== "index") {
this.router.navigate("index", {trigger: true});
}
},
idleActive: function() {
console.log("activate")
$.timer('idle_message_timer', null);
$("#resetPopup").modal("hide");
},
startIdleTimer: function() {
this.idle_for = 0;
$.idleTimer(this.idleTimeout * 1000);
$(document).bind("idle.idleTimer", kiosk.Controller.idle);
$(document).bind("active.idleTimer", kiosk.Controller.idleActive);
},
stopIdleTimer: function() {
$.idleTimer('destroy');
$.timer('idle_message_timer', null);
},
toggleIdleTimer: function() {
if(this.models.rootModel.get("mode") === "edit") {
this.stopIdleTimer();
} else {
if(!this.idleTimerInhibit) {
this.startIdleTimer();
}
}
}
}
//
// Router
//
// handles transitions between pages
//
kiosk.Router = Backbone.Router.extend({
routes: {
'': "showIndex",
":page": "showPage"
},
initialize: function(options) {
this.controller = options.controller;
_.bindAll(this, 'showIndex', 'showPage');
},
showIndex: function() {
console.log("came in through index, redirect to #index")
this.navigate("index", {trigger: true});
},
showPage: function(page) {
console.log("show page " + page)
this.controller.models.pageModel.set("id", "page/" + page, {"silent": true});
this.controller.models.pageModel.fetch();
this.controller.models.linkCollection.page = page;
this.controller.models.linkCollection.loaded = false;
this.controller.models.linkCollection.fetch({
reset: true,
success: function(links) { links.loaded = true; }
});
console.log("show page done");
}
}),
//
// RootModel
//
// keeps global state
kiosk.RootModel = Backbone.Model.extend({
defaults: {
mode: "view",
inDialog: false
}
});
//
// Item model
//
// details about a kiosk item, either a Page or a Popup
// A page is a the top level item and can be though of as a section of the kiosk
// The valid fields for an Item of type page are:
//
// name: string which is used to refer to the page, it is the id of the page
// title: string which is used when displaying this page
// type: string, always set to 'page' for pages
// page_image: the image to use for the page
//
//
// A popup has details about some section of a page and pops up a small window
// with that information. The valid fields for an Item of type popup are:
//
// name: string which is used to refer to the popup, it is the id of the popup
// title: string which is used when displaying this popup
// type: string, always set to 'popup' for popups
// text: string, HTML allowed, text for the body of the popup
// url: a string providing a URL for more information
// popup_image1: an image to be used in the popup
// popup_image2: an image to be used in the popup
//
// Note: files don't play nicely with PUT
kiosk.ItemModel = Backbone.Model.extend({
urlRoot: "_kiosk_item/",
imageUrlRoot: "_kiosk_item_image/",
//
// we don't want to encode our id since we're intentionally gaming it with a /
// (that's the only difference between this url function and backbone's default)
//
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + this.id;
},
defaults: {
"name": undefined,
"title": undefined,
"type": undefined,
// pages only
"page_image": undefined,
// popups only
"text": undefined,
"url": undefined,
"popup_image1": undefined,
"popup_image2": undefined
},
formFilenameValue: function(name) {
if(this.get(name)) {
var parts = this.get(name).split("/");
return 'value="' + parts[parts.length - 1] + '"';
} else {
return;
}
},
//
// uploadFile
//
// workaround for lack of support for files in backbone.js, we POST to a separate resource
//
uploadFiles: function(data, callback) {
//var data = new FormData($("#addNewPopup form")[0]);
var self = this;
data.append('csrfmiddlewaretoken', readCookie("csrftoken"));
$.ajax({
url: this.imageUrlRoot + this.get("type") + "/" + this.get("name"),
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(response) {
var data = $.parseJSON(response);
console.log("image success:", response);
self.filesSaved = true;
self.set(data);
if(callback) {
callback(response);
}
}
});
},
validate: function(attr, options) {
console.log("validate", this, attr);
err = {}
if(!attr.name || attr.name === "") {
err.name = "must not be empty";
}
// we also validate the the name is unique in the view where we have
// access to the collection
if(!attr.title || attr.title === "") {
err.title = "must not be empty";
}
if(!attr.type) {
err.type = "type must be set";
} else if(attr.type === "page") {
if(this.isNew() && !attr.page_image) {
err.page_image = "must specify a page image";
}
} else if(attr.type == "popup") {
if(this.isNew() && !attr.popup_image1) {
err.popup_image1 = "must specify at least one popup image";
}
if(!attr.text) {
err.text = "must specify some text";
}
} else {
err.type = "unknown type: " + attr.type;
}
if (!$.isEmptyObject(err)) {
return err
}
}
}),
//
// ItemCollection
//
// All kiosk items
//
kiosk.ItemCollection = Backbone.Collection.extend({
model: kiosk.ItemModel,
comparator: 'id',
url: "_kiosk_item/"
});
//
// Link model
//
// location and detail of a link
//
kiosk.Link = Backbone.Model.extend({
defaults: {
top: 50,
left: 10,
width: 200,
height: 50
},
url: function() {
console.log("Link url", this)
if (this.isNew()) {
return "_loc/" + this.get("page");
} else {
return "_loc/" + this.get("id");
}
}
}),
//
// LinkCollection
//
// Links for this page
//
kiosk.LinkCollection = Backbone.Collection.extend({
model: kiosk.Link,
comparator: 'id',
url: function() {
var url = "_loc/" + this.page;
console.log("linkcollection url:", url);
return url;
}
}),
//
// LinkCollectionDisplayView
//
// manages all the links on the page for "display" mode
//
kiosk.LinkCollectionDisplayView = Backbone.View.extend({
el: "#LinkCollection",
events: {
"click .image_button": "click",
},
render: function() {
var self = this;
console.log("render LinkCollectionView", this.linkViews, this.options);
this.$(".linkItem").remove();
_.each(this.collection.models, function(model) {
view = new kiosk.LinkView({
model: model,
parentEl: self.$el,
itemCollection: self.options.controller.models.itemCollection,
linkCollection: self.options.controller.models.linkCollection,
rootModel: self.options.controller.models.rootModel,
controller: self.options.controller
});
self.options.controller.models.rootModel.bind("change:mode", view.changeMode, view);
view.render();
});
}
}),
//
// LinkView
//
// view for each link in LinkCollectionDisplayView in "display" mode
// handles clicks on each link by:
// informing the router if it is a page
// rendering a PopupView if it is a popup
//
// In edit mode:
// handles edit clicks on the link name
// handles delete clicks on the link delete button
kiosk.LinkView = Backbone.View.extend({
events: {
"click": "click",
"click .linkName": "edit",
"click .linkDelete": "delete"
},
initialize: function () {
_.bindAll(this, "updatePosition", "updateSize", "changeMode");
},
render: function() {
var props = {
link: this.model.get("link"),
top: this.model.get("top"),
left: this.model.get("left"),
width: this.model.get("width"),
height:this.model.get("height")
}
var link = $(_.template($("#linkTemplate").html(), props));
this.setElement(link);
// XXX the append must come before the changeMode, why?
this.options.parentEl.append(this.$el);
this.changeMode();
return this;
},
changeMode: function() {
var mode = this.options.rootModel.get("mode");
if (mode === "view") {
this.$el.resizable('destroy').draggable('destroy').css({
"border": "none",
"background": "none",
"color": "none"
});
this.$el.removeClass("linkVisible");
this.$(".linkName").css({"display": "none"});
this.$(".linkDelete").css({"display": "none"});
//this.$el.bind("click", this.click, this);
} else {
this.$el.resizable({
handles: "all",
stop: this.updateSize
}).draggable({
stop: this.updatePosition
});
this.$el.addClass("linkVisible");
this.$(".linkName").css({"display": "inline"});
this.$(".linkDelete").css({"display": "inline"});
}
},
updatePosition: function(event, ui) {
console.log("drag stop", ui.position.left, ui.position.top);
this.model.set("left", ui.position.left);
this.model.set("top", ui.position.top);
this.model.save();
},
updateSize: function(event, ui) {
console.log("resize stop", ui.size);
this.model.set("width", ui.size.width);
this.model.set("height", ui.size.height);
this.model.save();
},
click: function(e) {
if (this.options.rootModel.get("mode") === "edit") {
if (!e.shiftKey) { return; }
new kiosk.LinkDialogView({
model: this.model,
itemCollection: this.options.controller.models.itemCollection,
linkCollection: this.options.controller.models.linkCollection,
rootModel: this.options.controller.models.rootModel,
action: "Update"
}).render();
return;
}
console.log("LinkItem click", this.model);
if (this.model.get("type") == "page") {
this.options.controller.router.navigate(this.model.get("name"), {"trigger": true});
} else {
console.log("item collection", this.options.itemCollection);
var popup_details = this.options.itemCollection.findWhere({
name: this.model.get("name"),
type: "popup"
});
console.log("popup_details", popup_details);
var template = _.template($('#popupTemplate').html(), {popup: popup_details});
var popup = $("#popup");
popup.html(template);
popup.modal();
popup.modal("show");
}
},
edit: function(e) {
// the parent div also has a handler but for other events
e.stopPropagation();
console.log("LinkItem edit click", e, this.model, this.options.itemCollection);
var model = this.options.itemCollection.get(this.model.get("link"));
console.log("MModel", model);
var dialog = new kiosk.EditItemDialogView({
model: model,
action: "Update",
itemCollection: this.options.controller.models.itemCollection,
linkCollection: this.options.controller.models.linkCollection,
rootModel: this.options.controller.models.rootModel
});
dialog.render();
},
delete: function(e) {
e.stopPropagation();
console.log("LinkItem delete click", e);
this.options.linkCollection.remove(this.model);
this.model.destroy();
}
}),
kiosk.BodyView = Backbone.View.extend({
el: "#Body",
render: function() {
if ($(window).height() < 1070 || $(window).width() < 1910) {
// show scrollbars if the window size is clearly less than 1080p
// (1920x1080)
this.$el.css("overflow", "visible");
} else {
this.$el.css("overflow", "hidden");
}
}
}),
//
// PageView
//
// manages setting the page image and other housekeeping
//
kiosk.PageView = Backbone.View.extend({
el: "#Page",
initialize: function() {
this.listenTo(this.model, "change:page_image", this.backgroundChange);
},
backgroundChange: function() {
if (this.model.filesSaved) {
console.log("background change", this.model.get("page_image"));
var url = this.model.get("page_image");
this.$el.css("background-image", "url(" + url + ")");
}
},
render: function () {
console.log("render PageView", this, this.model.loaded);
if (this.model.get("name")) {
var url = this.model.get('page_image');
console.log("updating to", url);
this.$el.css("background-image", "url(" + url + ")");
} else {
console.log("do nothing or show loader?")
}
},
});
kiosk.EditView = Backbone.View.extend({
el: "#EditMenu",
events: {
"click #newPopupButton": "newPopup",
"click #newPageButton": "newPage",
"click #newLinkButton": "newLink",
"click #editThisPageButton": "editThisPage"
},
initialize: function() {
_.bindAll(this, "newPopup", "newPage", "newLink");
this.listenTo(this.options.controller.dispatcher, "new-page-key", this.newPage);
this.listenTo(this.options.controller.dispatcher, "new-popup-key", this.newPopup);
this.listenTo(this.options.controller.dispatcher, "new-link-key", this.newLink);
this.listenTo(this.options.controller.dispatcher, "edit-this-page-key", this.editThisPage);
},
render: function () {
var mode = this.options.controller.models.rootModel.get("mode");
console.log("EditView", mode);
if(mode === "edit") {
this.$el.show();
} else {
this.$el.hide();
}
},
newPage: function(e) {
if (e) { e.preventDefault(); }
console.log("newPage");
var model = new kiosk.ItemModel({type: "page"});
var popup = new kiosk.EditItemDialogView({
model: model,
action: "Add",
itemCollection: this.options.controller.models.itemCollection,
linkCollection: this.options.controller.models.linkCollection,
rootModel: this.options.controller.models.rootModel
});
popup.render();
},
newPopup: function(e) {
if (e) { e.preventDefault(); }
console.log("newItem");
var model = new kiosk.ItemModel({type: "popup"});
var popup = new kiosk.EditItemDialogView({
model: model,
action: "Add",
itemCollection: this.options.controller.models.itemCollection,
linkCollection: this.options.controller.models.linkCollection,
rootModel: this.options.controller.models.rootModel
});
popup.render();
},
newLink: function(e) {
if(e) { e.preventDefault(); }
console.log("new link", this.options.controller.models);
new kiosk.LinkDialogView({
model: new kiosk.Link({page: this.options.controller.models.pageModel.get("name")}),
itemCollection: this.options.controller.models.itemCollection,
linkCollection: this.options.controller.models.linkCollection,
rootModel: this.options.controller.models.rootModel,
action: "Add"
}).render();
},
editThisPage: function(e) {
if(e) { e.preventDefault(); }
console.log("edit this page", this);
var popup = new kiosk.EditItemDialogView({
model: this.options.controller.models.pageModel,
action: "Update",
itemCollection: this.options.controller.models.itemCollection,
linkCollection: this.options.controller.models.linkCollection,
rootModel: this.options.controller.models.rootModel
});
popup.render();
}
});
//
// EditItemDialogView
//
// Handles editing, creating and deleting Kiosk Items
//
kiosk.EditItemDialogView = Backbone.View.extend({
el: "#editItemDialog",
events: {
"click .btn-primary": "click",
"click .btn-danger": "delete"
},
initialize: function() {
_.bindAll(this, "click", "delete", "_set_form_error");
},
render: function() {
var self = this;
console.log("render item edit", this);
var template = _.template($('#editItemDialogTemplate').html(), {
model: this.model,
action: this.options.action
});
this.popup = $("#editItemDialog");
this.popup.html(template);
this.popup.find(".image-file-button").each(function() {
$(this).off('click').on('click', function() {
$(this).siblings('.image-file').trigger('click');
});
});
this.popup.find(".image-file").each(function() {
$(this).change(function () {
$(this).siblings('.image-file-chosen').val(this.files[0].name);
});
});
this.popup.modal();
this.options.rootModel.set("inDialog", true);
this.popup.modal("show");
this.popup.on("hidden", function() {
self.options.rootModel.set("inDialog", false);
self.undelegateEvents();
});
},
click: function() {
var self = this;
console.log("click in edit page form, this:", this);
var formData = this.$("form").serializeObject();
var fileData = this.$("form").serializeFormFiles();
formData = _.extend(formData, fileData);
console.log("form data", formData);
var fileFormData = new FormData();
var numFiles = 0;
_.each(fileData, function(v, k) {
if (v) {
console.log("file to upload", k, this.$("form [name=" + k + "]")[0].files[0]);
fileFormData.append(k, this.$("form [name=" + k + "]")[0].files[0]);
numFiles += 1;
}
});
if (numFiles > 0) {
this.model.filesSaved = false;
}
if (this.model.isNew() || this.model.get("name") !== formData.name) {
var dups = this.options.itemCollection.where({
name: formData.name,
type: formData.type
});
if (dups.length) {
this._set_form_error("name", "that name is already in use");
return false;
}
}
this.model.set(formData);
this.model.on("invalid", function(model, errors) {
console.log("ERROR", model, errors);
self.$("form .text-error").remove();
_.each(errors, function(msg, field) {
console.log("err", field, msg);
self._set_form_error(field, msg);
});
self.model.off("invalid");
});
this.model.save({}, {
success: function(model, response) {
console.log("model save successful, now to save images:", numFiles);
if(numFiles) {
model.uploadFiles(fileFormData, function (response) {
console.log("total success", response, model);
// ugh, can't seem to get this to work without going to get them all
self.options.itemCollection.fetch();
});
}
self.popup.modal("hide");
},
error: function(model, xhr) {
console.log("save failed", model, xhr);
}
});
},
_set_form_error: function(field, msg) {
var control = this.$("form [name="+ field +"]");
var target = control.prev();
if (!target.length) {
target = this.$("#" + field + "_error");
}
target.append(" <span class='text-error'>"+ msg +"</div>");
},
delete: function() {
console.log("delete! item!", this.model.get("id"), this.model);
this.options.itemCollection.remove(this.model);
this.options.linkCollection.remove(
this.options.linkCollection.where({link: this.model.get("id")}));
this.model.destroy();
this.popup.modal("hide");
}
});
//
// LinkDialogView
//
kiosk.LinkDialogView = Backbone.View.extend({
el: "#LinkDialog",
events: {
"click .btn-primary": "click"
},
initialize: function() {
_.bindAll(this, "click");
},
render: function() {
var self = this;
var template = _.template($("#LinkDialogTemplate").html());
this.dialog = $("#LinkDialog");
this.dialog.html(template({
items: this.options.itemCollection.models,
action: this.options.action,
link: this.model.get("link")
}));
this.dialog.modal();
this.options.rootModel.set("inDialog", true);
this.dialog.modal("show");
this.dialog.on("hidden", function() {
self.options.rootModel.set("inDialog", false);
// XXX: without this there were zombies attached to the submit button
// XXX: is this the last of the references to this view or are we leaking memory?
self.undelegateEvents();
});
},
click: function() {
var self = this;
var link = this.$("select")[0].value;
this.model.set("link", link);
var parts = link.split("/");
this.model.set("type", parts[0]);
this.model.set("name", parts[1]);
this.model.save({}, {
success: function(model, response) {
self.options.linkCollection.add(model);
},
error: function(model, xhr) {
console.log("error saving link", model, xhr);
}
});
this.dialog.modal("hide");
}
});
})(window.kiosk = window.kiosk || {}, Backbone, jQuery, _);
<file_sep>/README.rst
scinet-kiosk
============
This Django app can be used to develop simple interactive kiosks using a
touchscreen or a tablet.
This code was orginally developed for SC12/SCinet.
Quickstart for development
--------------------------
You need to be sure that the LANG environment variable is set. All shell
examples assume a sh/bash/zsh like shell. If you use csh/tcsh/etc you may
need to tweak a few things. Here's an example of setting LANG::
$ export LANG=en_US.UTF-8
To get started with this project you can do the following::
$ ./mkdevenv
$ source scinet-kiosk.env
$ python kiosk_example/manage.py syncdb
$ python kiosk_example/manage.py runserver
Then visit http://localhost:8000/admin/kiosk/. You will need to use the
username and password you created during the syncdb step above.
Creating pages
..............
You can create pages by creating a KioskItem of type Page. A page is an image
that you define clickable regions for. The root page is called index, so the
first page you should create should have a name of index. Create this index
page and upload an image via the admin interface. Once that page is created
you should be able to see your image by going to: http://localhost:8000/. The
current templates assume that the pages are 1080p (1920x1080 pixels).
Creating popups
...............
You can create popups by creating a KioskItem of type Popup. A popup is the
content for a popup. The default template expects the images included to be
300 pixels wide.
Creating links
..............
You can create links by defining regions on pages. Links can either point to
other pages or to popups. To create a link be sure that you have logged into
the admin interface and then visit the page you wish to make links for. So
for example to update the index page, visit: http://localhost:8000/. Once
there type 'e'. You should see a green box saying EDIT in the upper left
corner. Then you can type 'n' and you will be given a popup that will allow
you to select the target of the link. Select the target and click OK. You
can then move and resize the rectangle. Once it's in the location you want,
type 's' to save the link info. You can now turn off editing mode and try
your link.
<NAME>
26 Dec 2012
<file_sep>/mkdevenv
#!/bin/sh
export VENV_ROOT=`pwd`
export DJANGO_SETTINGS_MODULE=esxsnmp.settings
# create the virtualenv
virtualenv --prompt="(django-kiosk)" .
. bin/activate
# XXX(jdugan) FreeBSD hack look for headers and libraries in /usr/local
# ObRant: WTF is with distutils/setuputils/pip not offerring a way to handle this?!?
# ObRantRant: OR maybe it's crappy behaviour on the part of pysqlite? dunno
if [ x`uname` = x"FreeBSD" ]; then
echo patching pysqlite to build under FreeBSD
pip install --no-install pysqlite
echo 'include_dirs=/usr/local/include' >> build/pysqlite/setup.cfg
echo 'library_dirs=/usr/local/lib' >> build/pysqlite/setup.cfg
fi
pip install -r requirements.txt
cat <<EOF > django-kiosk.env
export DJANGO_SETTINGS_MODULE="kiosk_example.settings"
. ${VENV_ROOT}/bin/activate
EOF
echo environment variables and activation put in ${VENV_ROOT}/django-kiosk.env:
cat ${VENV_ROOT}/django-kiosk.env
echo run: source ${VENV_ROOT}/django-kiosk.env to set up your environment for development
<file_sep>/kiosk/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('kiosk.views',
# index
url(r'^(?P<page>[a-zA-Z0-9-]+)?/?$', 'index', name="kiosk-index"),
url(r'^_loc/(?P<page_name>[a-zA-Z0-9-]+)(/(?P<pk>[0-9]+))?/?$', 'loc_data', name="kiosk-loc-data"),
url(r'^_kiosk_item/((?P<item_type>[a-zA-Z0-9-]+)/(?P<item_name>[a-zA-z0-9-]+))?/?$', 'kiosk_item', name='kiosk-item'),
url(r'^_kiosk_item_image/(?P<item_type>[a-zA-z0-9-]+)/(?P<item_name>[a-zA-z0-9-]+)/?$',
'kiosk_item_image', name='kiosk-item-image'),
)
<file_sep>/kiosk/__init__.py
__version__ = "0.5 dev"
| f86afc0acb00aab915b1b6fe621fc48c6b141349 | [
"reStructuredText",
"JavaScript",
"Python",
"Text",
"Shell"
] | 9 | Python | jdugan1024/django-kiosk | 864463687a341d3bd8079125e1750871e8e23af3 | 57d65a32fb2e2aaed3086763d6bf2de9134386d7 |
refs/heads/master | <file_sep>#include <stdio.h>
void main(int argc, char* argv[]){
FILE *f;
//char* file_name = (char*)malloc(50*sizeof(char));
char* file_name[50];
strcpy(file_name, argv[1]);
strcat(file_name, ".txt");
if(file_name == NULL)
{
printf("File is not open!\n");
exit(0);
}
f = fopen(file_name, "w");
if(f == NULL)
printf("File open error %s\n", argv[1]);
fprintf(f, "miehahahaha, ID=%s\n", argv[1]);
fclose(f);
printf("Hello World from Ethan! FFS!!!!!! ID = %s\n", argv[1]);
// free(file_name);
printf("FXXX the world!\n");
}
<file_sep>#!/bin/bash
#$ -N CYANG
#$ -j y
#$ -t 1-2
echo $SGE_TASK_ID
./helloworld.exe $SGE_TASK_ID
##sed -n ${SGE_TASK_ID}p input_argument.txt
<file_sep>
for pattern in `echo 1 2 3 4`; do
for pattern_size in `echo 4 8 16`; do
for packet in `echo 1 2 4 8 16`; do
for gap in `echo 0 1 2 4 8`; do
echo ./ClusterFPGASim.exe -i $pattern -s $pattern_size -p $packet -g $gap >> input_argument.txt;
done
done
done
done
<file_sep>import os
import re
# clean the file from previous run
os.system('rm execution_command.txt')
# declare the input variables
PATTERN = [0, 1, 2, 3, 4, 5, 6]
PATTERN_SIZE = [4, 8]
PACKET_SIZE = [1, 2 ,4, 8, 16]
INJECTION_GAP = [0, 1, 3, 5, 11]
# generate the command line and store in the file
with open('execution_command.txt', 'w') as COMMAND:
for i, pattern in enumerate(PATTERN):
for j, pattern_size in enumerate(PATTERN_SIZE):
for k, packet_size in enumerate(PACKET_SIZE):
for l, injection_gap in enumerate(INJECTION_GAP):
#print("./ClusterFPGASim.exe -i %d -s %d -p %d -g %d" % (pattern, pattern_size, packet_size, injection_gap))
COMMAND.write('./ClusterFPGASim.exe -i '+str(pattern)+' -s '+str(pattern_size)+' -p '+str(packet_size)+' -g '+str(injection_gap)+'\n')
with open('execution_command.txt', 'r') as COMMAND:
for i, input_command in enumerate(COMMAND):
# print out the commandline and remove the '\n'
#print(input_command.rstrip())
# extract the numbers of the executed command and appendix it to the job name
input_param = re.findall(r'\d+', input_command.rstrip());
#print("%s %s %s %s" % (input_param[0], input_param[1], input_param[2], input_param[3]))
# execute the qsub in command mode by adding '-b y' flag
os.system('qsub -q bme.q -cwd -N CYANG_'+input_param[0]+'_'+input_param[1]+'_'+input_param[2]+'_'+input_param[3]+' -j y -b y '+input_command.rstrip())
| 87c5b20a8b3b779d66e12014b84cb16cb5b8d638 | [
"C",
"Python",
"Shell"
] | 4 | C | FPGA-Bot-Yang/Batch_Run | 7de49272834fbbd7c0e0823baccac0652251de91 | 50725f7a587d22b907fd30931a46bebd1fc7ffb5 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'lib-fb-login',
templateUrl: './fb-login.component.html',
styleUrls: ['./fb-login.component.css']
})
export class FbLoginComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
authenticate(): void {
// tslint:disable-next-line:only-arrow-functions
FB.login(function(response) {
console.log('fac login ');
});
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AngularSocialLoginButtonsComponent } from './angular-social-login-buttons.component';
import { FbLoginComponent } from './components/fb-login/fb-login.component';
import { GoogleLoginComponent } from './components/google-login/google-login.component';
import { AngularSocialLoginButtonsService } from './angular-social-login-buttons.service';
import { LinkedinLoginComponent } from './components/linkedin-login/linkedin-login.component';
@NgModule({
declarations: [AngularSocialLoginButtonsComponent, FbLoginComponent, GoogleLoginComponent, LinkedinLoginComponent
],
imports: [
],
exports: [AngularSocialLoginButtonsComponent,
FbLoginComponent, GoogleLoginComponent, LinkedinLoginComponent]
})
export class AngularSocialLoginButtonsModule { }
<file_sep>/*
* Public API Surface of angular-social-login-buttons
*/
export * from './lib/angular-social-login-buttons.service';
export * from './lib/angular-social-login-buttons.component';
export * from './lib/components/google-login/google-login.component';
export * from './lib/components/fb-login/fb-login.component';
export * from './lib/components/linkedin-login/linkedin-login.component';
export * from './lib/angular-social-login-buttons.module';
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AngularSocialLoginButtonsService } from '../../angular-social-login-buttons.service';
@Component({
selector: 'lib-linkedin-login',
templateUrl: './linkedin-login.component.html',
styleUrls: ['./linkedin-login.component.css']
})
export class LinkedinLoginComponent implements OnInit {
data: any;
linkedInCredentials: any;
constructor(private http: HttpClient, private configService: AngularSocialLoginButtonsService) {}
ngOnInit(): void {
this.data = this.configService.getLinkedinId();
this.linkedInCredentials = {
clientId: this.data,
redirectUrl: 'https://dev-5uchuarw.us.auth0.com/login/callback'
};
}
authenticate() {
window.location.href = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${
this.linkedInCredentials.clientId
}&redirect_uri=${this.linkedInCredentials.redirectUrl}&scope=r_emailaddress`;
}
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AngularSocialLoginButtonsService {
googleClientId: any;
linkedinClientId: any;
constructor() { }
addGoogle(clientId: any) {
this.googleClientId = clientId;
}
addLinkedin(clientId: any) {
this.linkedinClientId = clientId;
}
getGoogleId() {
return this.googleClientId;
}
getLinkedinId() {
return this.linkedinClientId;
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { AngularSocialLoginButtonsService } from './angular-social-login-buttons.service';
describe('AngularSocialLoginButtonsService', () => {
let service: AngularSocialLoginButtonsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AngularSocialLoginButtonsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>export class SocialID {
config = [
{ googleClientID: '997007092677-7si65ru2k74be0ms4431k568f6sb655n.apps.googleusercontent.com'},
{ LinkedinClientID: '86vu9nihqqxe76'}
];
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap, retry } from 'rxjs/operators';
@Component({
selector: 'app-github',
templateUrl: './github.component.html',
styleUrls: ['./github.component.scss']
})
export class GithubComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
authenticate() {
console.log('authenticate github....');
// tslint:disable-next-line:max-line-length
return this.http.get('https://github.com/login/oauth/authorize?client_id=f57d11b3beb91330a759&type=user_agent&redirect_uri=https://www.google.com/')
.pipe(
tap(
// Log the result or error
data => this.log(data),
error => this.logError(error)
)
);
}
/** Log a message */
private log(res) {
console.log(`log service: `, res );
}
private logError(res) {
console.log(`log error: `, res );
}
}
<file_sep># Angular social login buttons
simple npm package to display social login buttons using Angular.\
Signin with Google, Linkedin, Facebook \
- 👉 [live demo](https://angular-social-login-buttons.herokuapp.com/)
## Install
- npm \
npm install --save angular-social-login-buttons
- yarn \
yarn add angular-social-login-buttons
## Import
add in top of the body tag in index.html the facebook sdk and google sdk
like the below image

or in raw version: \
<pre>
<body>
<script async defer src="https://apis.google.com/js/api.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '1207524632976216',
cookie : true,
xfbml : true,
version : 'v9.0'
});
FB.AppEvents.logPageView();
};
(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'));
</script>
....
</body>
</pre>
in app.module.ts
import the AngularSocialLoginButtonsModule module and provide your clientId for the google \
or linkedin

<pre>
import { AngularSocialLoginButtonsModule, AngularSocialLoginButtonsService } from 'angular-social-login-buttons';
// Configs
export function getAuthServiceConfigs() {
const config = new AngularSocialLoginButtonsService();
config.addGoogle('your-google-client-id');
config.addLinkedin('your-linkedin-client-id');
return config;
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
AngularSocialLoginButtonsModule,
....
],
providers: [ {provide: AngularSocialLoginButtonsService,
useFactory: getAuthServiceConfigs}
],
bootstrap: [AppComponent]
})
</pre>
## Usage
to use the facebook Signin button add in your html file \
`<lib-fb-login></lib-fb-login>` \
to use the google Signin button add in your html file \
`<lib-google-login></lib-google-login>` \
to use the linkedin Signin button add in your html file \
`<lib-linkedin-login></lib-linkedin-login>`
## Example
An example using the angular-social-login-buttons package is in the github repo.
[repo](https://github.com/miminerd/socialLoginExample/)
## Author
[<NAME>](https://juda-landing-cv.herokuapp.com/home) \
-[Github](https://github.com/miminerd)<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { SocialID } from '../../../assets/SocialID';
@Component({
selector: 'app-linkedin',
templateUrl: './linkedin.component.html',
styleUrls: ['./linkedin.component.scss']
})
export class LinkedinComponent implements OnInit {
client = new SocialID();
linkedInCredentials = {
clientId: this.client.config[1].LinkedinClientID,
redirectUrl: 'https://dev-5uchuarw.us.auth0.com/login/callback'
};
ngOnInit(): void {
}
constructor(private http: HttpClient) {}
authenticate() {
window.location.href = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${
this.linkedInCredentials.clientId
}&redirect_uri=${this.linkedInCredentials.redirectUrl}&scope=r_emailaddress`;
}
}
<file_sep># Angular social login buttons
simple npm package to display social login buttons using Angular.\
Signin with Google, Linkedin, Facebook \
- 👉 [demo](https://angular-social-login-buttons.herokuapp.com/)

## Features
The project contains 2 parts:
- in the projects folder: the actual npm package (where the library is developed)
- the other is a regular angular project using the npm package, you can check it.
## Install
to install the npm package via
- npm \
npm install --save angular-social-login-buttons
- yarn \
yarn add angular-social-login-buttons
## Import
add in top of the body tag in index.html the facebook sdk and google sdk

in app.module.ts
import the AngularSocialLoginButtonsModule module and provide your clientId for the google \
or linkedin

## Usage
to use the facebook Signin button add in your html file \
`<lib-fb-login></lib-fb-login>` \
to use the google Signin button add in your html file \
`<lib-google-login></lib-google-login>` \
to use the linkedin Signin button add in your html file \
`<lib-linkedin-login></lib-linkedin-login>`
## Example
here is an the repo of the demo using the angular-social-login-buttons package [repo](https://github.com/miminerd/socialLoginExample)
## Contribution
I welcome issues and pull requests on [pr](https://github.com/miminerd/ngSocialBtnLogin)
## Author👩🏻💻
[<NAME>](https://juda-landing-cv.herokuapp.com)
| 6d484f85b6289cb0ad8cfc3bc757a825e6cdd291 | [
"Markdown",
"TypeScript"
] | 11 | TypeScript | abdelrahman-salah/ngSocialBtnLogin | 68d7c2945ddc894db4039d6f094b55667c45e2b0 | 60f238554fc8fffdbb72c2dd108afed20f714f87 |
refs/heads/master | <repo_name>hidenny/gce<file_sep>/relaunch-mapr-cluster.sh
#!/bin/bash
#
# Script to relaunch a MapR cluster on Google Cloud intances that
# have been shut down. Google Cloud does not have the "stopped"
# concept for instances, so once nodes are shut down there is
# no way to restart them short of
# deleteinstance
# runinstance
#
# Assumptions:
# instances were created with persistent boot disks and data disks
# (this is the default for Google Cloud as of 2014)
# persistent boot disk is named <hostname> (again, the default)
# gcutil tool is in the PATH
#
# Remember:
# The nodenames must start with lower case leters, so the cluster
# name is often the wrong thing to use as a base for the hostnames.
# Always use the "--node-name" option !
#
PROGRAM=$0
NODE_NAME_ROOT=node # used in config file to define nodes for deployment
usage() {
echo "
Usage:
$PROGRAM
--project <GCE Project>
--machine-type <machine-type>
--zone gcutil-zone
--node-name <name-prefix> # hostname prefix for cluster nodes
[ --cluster <clustername> ] # unnecessary, but included for parallelism
"
echo ""
echo "EXAMPLES"
echo "$0 --project <MyProject> --node-name prod"
}
list_cluster_nodes() {
clstr=$1
cluster_nodes=""
for n in $(gcutil listinstances --project=$project \
--format=names --filter="name eq .*${clstr}[0-9]+" | sort)
do
nodename=`basename $n`
# A bit of a kludge to make sure we only work
# on OUR cluster nodes ... and it still can fail
# if there is a "MapR" and a "MapRTech" cluster
if [ ${nodename#${clstr}} != ${nodename} ] ; then
[ -z $zone ] && zone=${n%%/*}
cluster_nodes="${cluster_nodes} $nodename"
fi
done
export cluster_nodes
}
# Build up the disk argument CAREFULLY ... the shell
# addition of extra ' and " characters really confuses the
# final invocation of gcutil
#
list_persistent_data_disks() {
targetNode=$1
# Compute the disk specifications ...
# N disks of size S from the pdisk parameter
pdisk_args=""
for d in $(gcutil listdisks --project=$project --zone=$zone \
--format=names --filter="name eq .*-pdisk-[1-9]")
do
diskname=`basename $d`
[ ${diskname#${targetNode}} = ${diskname} ] && continue
pdisk_args=${pdisk_args}' '--disk' '$diskname,mode=READ_WRITE
done
export pdisk_args
}
#
# MAIN
#
while [ $# -gt 0 ]
do
case $1 in
--cluster) cluster=$2 ;;
--project) project=$2 ;;
--machine-type) machinetype=$2 ;;
--node-name) nodeName=$2 ;;
*)
echo "****" Bad argument: $1
usage
exit ;;
esac
shift 2
done
# Defaults
project=${project:-"maprtt"}
machinetype=${machinetype:-"n1-standard-2"}
nodeName=${nodeName:-$NODE_NAME_ROOT}
pboot=${pboot:-"true"}
list_cluster_nodes $nodeName
if [ -z "${cluster_nodes}" ] ; then
echo "ERROR: no nodes found with base name $nodeName"
exit 1
fi
echo CHECK: -----
echo " project $project"
echo " cluster $cluster"
echo " machine $machinetype"
echo " node-name ${nodeName:-none}"
echo -----
echo ""
echo "NODES: ---- (all instances will be deleted and relaunched in zone $zone)"
echo " $cluster_nodes"
echo ""
echo -----
echo "Proceed {y/N} ? "
read YoN
if [ -z "${YoN:-}" -o -n "${YoN%[yY]*}" ] ; then
exit 1
fi
# Always a persistent boot disk
pboot_args="--persistent_boot_disk"
# First, delete the old instances
gcutil deleteinstance \
--project=$project \
--zone=$zone \
--nodelete_boot_pd \
--force \
$cluster_nodes
# Wait for deletion to be complete
echo ""
echo "Waiting for instances to successfully terminate"
running_instances=1
while [ $running_instances -ne 0 ]
do
sleep 10
running_instances=`gcutil listinstances --project=$project --zone=$zone \
--format=names --filter="name eq .*${nodeName}[0-9]+" | wc -l`
done
# Then, add them back
for host in $cluster_nodes
do
list_persistent_data_disks $host
# Side effect ... pdisk_args is set
gcutil addinstance \
--project=$project \
--machine_type=$machinetype \
--zone=$zone \
${pboot_args:-} \
--disk $host,mode=rw,boot \
${pdisk_args:-} \
--wait_until_running \
--service_account_scopes=storage-full \
$host &
done
wait
echo ""
echo "$nodeName nodes restarted; cluster ${cluster:-${nodeName}} relaunched !!!"
| e6b33a143022246d466c3862ca36ff39efddc60b | [
"Shell"
] | 1 | Shell | hidenny/gce | 7e784c85f8854debb658a4469858a5aa30cf2c54 | ae481b75bfd50f6765e9015a7e804166907525c8 |
refs/heads/master | <repo_name>OzgeDemirel91/Workshop2020<file_sep>/03-ggplot:course_material/course_material.Rmd
---
title: "Data visualisation using ggplot"
subtitle: "RSG Turkey Student Symposium 2020 - Workshop"
author: "<NAME>"
output:
html_document:
df_print: paged
---
# Data visualisation
Data visualisation, in short, is the graphical representation of the data. More on data visualisation principles, and effective figure design can be found in our previous years' [workshop material](https://mdonertas.github.io/ScientificFigureDesign). Today we will focus on practical aspects and how to create figures using `ggplot2` library in R.
# What is ggplot / grammar of graphics?
**Grammar of graphics:** The grammar used to create a wide range of graphs. `ggplot` implements a layered grammar of graphics so that layers are combined to build the final graph which can be unique in many ways.
## Tidyverse and tidy data
* ggplot is a package included in "tidyverse" and works well with "tidy data". The tidyverse is a group of R packages that help data anlysis. The core tidyverse includes:
* ggplot2: to visualize data
* tidyr: to tidy data
* readr: to read / import data
* dplyr: to manipulate data
* tibble: tweaked data frames to make life easier
* purrr: a functional programming toolkit
To install the tidyverse package:
```{r, eval = F}
install.packages("tidyverse")
```
Tidy data concept deserves its own workshop but for now, it's important to know that there are three characteristics of tidy data:
1. Each variable must have its own column.
1. Each observation must have its own row.
1. Each value must have its own cell.
For example, the dataset you used in the previous sessions "processeddata.csv" is a nice example to tidy data. I will thus read it using `read_csv` from `readr` package, which is a part of `tidyverse`.
```{r}
library(tidyverse)
covid = read_csv('https://raw.githubusercontent.com/rsgturkey/Workshop2020/master/02-Intro_to_ML/data/processeddata.csv')
head(covid)
```
This dataset is an example of a tidy dataset because, each column shows a variable, observations are not splitted between rows, and each value has its own cell. For example, the following is exactly the same data but structured differently and it is not a 'tidy dataset'.
```{r,echo = T}
covid_nottidy = covid %>%
mutate(location = paste(latitude, longitude, sep= ' | ')) %>%
select(-latitude, -longitude) %>%
gather(key = 'type', value = 'value',-outcome, -location) %>%
select(outcome, type, value, location)
```
```{r}
head(covid_nottidy)
```
Here, variables 'age' and 'sex' are both entered under 'value' column, and thus each observation is represented with two rows. Location includes data for both latitude and longitude. This data for sure is difficult to work with. Nevertheless, we will continue with `covid` and other tidy data examples and I suggest that learning basic data wrangling and manipulation functions in tidyverse such as `spread`, `gather`, `filter`, `select`, and `mutate` worth checking. Just to make the following steps easier I will further modify the data so that outcome and sex columns are of factor type not character. This could've been done while reading the data with `read_csv`, but to examplify the use of `mutate` function, I will use it here:
```{r}
covid = covid %>%
mutate(outcome = as.factor(outcome),
sex = as.factor(sex))
head(covid)
```
## Basic ggplot syntax
There are three basic components of plots: data, aesthetics and geoms. Aesthetics provide the mapping between variables in data and visual properties, and geoms provide the layers describing how to render each observation.
Let's start with the `covid` data and see how these components function:
```{r}
ggplot(data = covid, aes(x = outcome, y = age)) +
geom_boxplot()
```
This is a graph with the most basic components. `outcome` variable of `covid` data is *mapped* to x, and `age` is mapped to y axes and the data is layered as a boxplot. It is also possible to create a similar figure using base R, and some may actually prefer that:
```{r}
boxplot(age ~ outcome, data = covid)
```
The issue with base R is that it is straightforward for basic figures but as you want to create complex figures with many layers and modify its aesthetics, it is very time consuming. Let's modify our boxplot a little bit to add more layers:
```{r}
ggplot(data = covid, aes(x = outcome, y = age)) +
geom_boxplot() +
geom_jitter()
```
Just to treat our eyes better, we can do the following relatively easy. And today we will cover individual aspects of how to do it.
```{r}
ggplot(data = covid, aes( x = outcome, y = age, fill = outcome)) +
geom_boxplot(outlier.shape = NA) +
ggforce::geom_sina(size = 0.5, alpha = 0.3, color = 'gray45') +
ggthemes::scale_fill_pander() +
xlab(NULL) + ylab('Age (in years)') + guides(fill = F) +
theme_bw() +
ggpubr::stat_compare_means(comparisons = list(c('Died','Recovered')),
label = 'p.signif')
```
By the way, just keep in mind that the examples are to show how ggplot works, not to provide the best examples of data visualisation.
Let's see in more detail how to map other variables using other aesthetics such as color, shape and size.
```{r}
ggplot(data = covid, aes(x = longitude, y = latitude, color = age, shape = sex,
size = outcome)) +
geom_point()
```
Here I used size for a discrete variable and it gives a warning as it is better to be used with quantitative variables. Here each variable is encoded with a different channel (x, y axes, shape, color, and size).
If you want to make all points a particular color but not mapped to a variable, that's done outside `aes` function:
```{r}
ggplot(data = covid, aes(x = longitude, y = latitude, shape = sex, size = outcome)) +
geom_point( color = 'darkred')
```
let's see the difference here:
```{r}
ggplot(data = covid, aes(x = longitude, y = latitude, color = 'darkred',
shape = sex, size = outcome)) +
geom_point( )
```
Here we mapped the color to 'darkred' but did not fix its value.
Another way to display categorical data is through faceting. Facets create plots for each category separately. Let's say we want to visualise the first plot outcome vs. age again as a boxplot but we want to create separate graphs for different sexes.
```{r}
ggplot(data = covid, aes(x = outcome, y = age)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(size = 0.3, alpha = 0.3, width = 0.1) +
facet_wrap(~sex)
```
Here the argument `alpha` sets the transparency, size sets the size of the points and width determines the amount of jitter. Just to emphasize again, this is not a good representation of the data but only a handy example.
Lastly, I want to show how to modify axes limits and labels and add a title to the plot:
```{r}
ggplot(data = covid, aes(x = outcome, y = age)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(size = 0.3, alpha = 0.3, width = 0.1) +
facet_wrap(~sex) +
xlab('Patient Outcome') +
ylab('Age (in years)') +
ggtitle('Age distributions stratified by Outcome and Sex') +
ylim(0,125)
```
Let's save this figure as a pdf file, using `ggsave`. And just as you can save other R objects, you can save ggplot objects. It is always useful to save the object instead of just the pdf version as you can further modify it.
```{r}
myplot = ggplot(data = covid, aes(x = outcome, y = age)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(size = 0.3, alpha = 0.3, width = 0.1) +
facet_wrap(~sex) +
xlab('Patient Outcome') +
ylab('Age (in years)') +
ggtitle('Age distributions stratified by Outcome and Sex') +
ylim(0,125)
ggsave('./figures/age_by_sex_and_outcome.pdf', myplot,
units = 'cm', width = 16, height = 10, useDingbats = F)
saveRDS(myplot, 'data/myplot.rds')
```
Let's now load this file again and change it's theme, let's say because we decided to use another theme in our manuscript.
```{r}
myplot_loaded = readRDS('./data/myplot.rds')
myplot_new = myplot_loaded +
theme_bw()
myplot_new
```
Now instead of the default theme, we use a different one. More on themes will come in the future sections. Now we know the basics. Let's have a look at different types of plots and how to combine them to have visually appealing figures.
# Layers
3 purposes of layers:
* Show data
* Show statistical summary of the data (generally on top of the data layer).
* Add metadeta (annotations, references, or background information - like a world map)
## geoms
Geoms are the building blocks of ggplot figures. They are generally named after the type of figure they create - e.g. `geom_area` for area plot, `geom_bar` for bar plot - but they can further be *combined* to create more complex graphics.
To better exemplify the following geoms, we will use `mtcars` data available in R.
```{r}
p = ggplot(mtcars, aes(x = wt, y = mpg))
```
### geom_point
`geom_point` creates a scatterplot.
```{r}
p + geom_point()
```
### geom_text
Let's display the model of cars instead of points:
```{r}
p + geom_text(aes(label = rownames(mtcars)))
```
Another similar function is `geom_label` which draws a rectangle behind the text and could look better when you do not have many labels.
```{r}
p + geom_label(aes(label = rownames(mtcars)))
```
One evident issue in both `geom_text` and `geom_label` is the overlapping texts. To avoid it we can use ggrepel package.
```{r}
library(ggrepel)
p + geom_text_repel(aes(label = rownames(mtcars)))
```
Since the text is 'repelled', we should also plot the points to see where each one is actually located:
```{r}
p + geom_text_repel(aes(label = rownames(mtcars))) +
geom_point()
```
### geom_line
```{r}
p + geom_line()
```
```{r}
p + geom_point() + geom_line()
```
### geom_bar
```{r}
ggplot(covid, aes(x = sex)) +
geom_bar()
```
By default, `geom_bar` can calculate the number of observations in each category. However, let's imagine a case where you do not have the data itself but just the summary including the count data, like the following:
```{r}
sexcount = covid %>%
group_by(sex) %>%
summarise(n = n())
sexcount
```
In this case, we need to map the variable `n` to y-axis. However, we also need to change the `stat` argument in `geom_bar` otherwise it would give an error as it would try to calculate the y axis variable itself.
```{r}
ggplot(sexcount, aes(x = sex, y= n)) +
geom_bar(stat = 'identity')
```
We can also use fill color in `geom_bar`. In order to have a better example, I will modify our covid data to have age groups:
```{r}
covid_agegr = covid %>%
mutate(agegr = cut(age, breaks = seq(0,100,by=10)))
head(covid_agegr)
```
Now we will color by the sex.
```{r}
ggplot(covid_agegr, aes(x = agegr, fill = sex)) +
geom_bar()
```
I used `fill` instead of `color`, because in `geom_bar`, color controls the color of the line around the rectangles.
```{r}
ggplot(covid_agegr, aes(x = agegr, color = sex)) +
geom_bar()
```
Let's go back to using `fill`, but also instead of having the bars for different sexes stacked, I want to have them side by side. For this, we can use `position = 'dodge'`.
```{r}
ggplot(covid_agegr, aes(x = agegr, fill = sex)) +
geom_bar(position = 'dodge')
```
Another value `position` argument can take is `'fill'`. In this case, the sum of each age group will be equal and in a way, the colors will show the proportion of sexes in each age group.
```{r}
ggplot(covid_agegr, aes(x = agegr, fill = sex)) +
geom_bar(position = 'fill')
```
And please don't consider using pie charts much (for details please see [data_viz workshop notes](https://mdonertas.github.io/ScientificFigureDesign/different-types-of-plots.html#pie-chart)) but just to show how flexible ggplot is, we can use `geom_bar(position = 'fill')` with `coord_polar` function (changing the coordinates to polar coordinate system) and have pie charts:
```{r}
ggplot(covid_agegr, aes(fill = sex, x = '')) +
geom_bar(position = 'fill') +
facet_wrap(~agegr) +
coord_polar('y', start = 0) +
theme_void()
```
### geom_histogram
Instead of age groups, if we show the distribution of the continuous variable age with a histogram:
```{r}
ggplot(covid, aes(x = age)) +
geom_histogram(color = 'gray')
```
### geom_boxplot
To have a boxplot, we use `geom_boxplot`. An important point is the variable on the x-axis should not be a continuous variable.
```{r}
ggplot(covid, aes( x = outcome, y = age)) +
geom_boxplot()
```
### geom_violin
Violin plot is similar to a boxplot and a density plot. It looks like a density plot turned horizontally. We can draw lines for the quantiles using `draw_quantiles` argument.
```{r}
ggplot(covid, aes( x = outcome, y = age)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75))
```
### geom_*line
We can use `geom_*line` functions to add horizontal and vertical lines. To examplify use of these functions:
```{r}
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
xlim(0,6) +
ylim(0,35) +
geom_hline(yintercept = 25, color = 'red') +
geom_vline(xintercept = 3, color = 'blue') +
geom_abline(intercept = 0, slope = 5, size = 2,
color = 'gray', linetype = 'dashed')
```
## Custom annotations - `annotate`
When the annotations (text, lines, segments etc.) are not mapped from the data but are custom annotations, it is more convenient to use `annotate` function:
```{r}
ggplot(covid, aes( x = outcome, y = age)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75)) +
annotate(geom = 'text', x = 1, y = 65, label = 'median') +
annotate(geom = 'segment', x = 1, xend = 2, y = 110, yend = 110) +
annotate(geom = 'text', x = 1.5, y = 115, label = 'p<XXX')
```
## Other annotations
When you want to add p-value annotations, it is actually more straightforward to use `stat_compare_means` function in `ggpubr` library:
```{r}
library(ggpubr)
ggplot(covid, aes( x = outcome, y = age)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75)) +
stat_compare_means()
```
If you want it to display the p-value similar to our annotation example, use `comparisons` argument. Also, instead of using wilcoxon, we can use t.test. If we want to show the p value significance levels instead of the pvalues, we can use `label = 'p.signif'`.
```{r}
library(ggpubr)
ggplot(covid, aes( x = outcome, y = age)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75)) +
stat_compare_means(comparisons = list(c('Died','Recovered')),
method = 't.test', label = 'p.signif')
```
When there are multiple groups, but you want the comparison to be against only one of the groups:
```{r}
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot() +
stat_compare_means(ref.group = '4')
```
It is important to note that these are nominal p-values that are not corrected for multiple testing. Lastly, apart from binary comparisons it is possible to calculate the p value for Kruskal-Wallis or ANOVA test when there are multiple groups:
```{r}
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot() +
stat_compare_means()
```
Another visually appealing group of functions for annotations are `geom_mark_*` functions:
```{r}
library(ggforce)
ggplot(mtcars , aes(x = disp, y = mpg)) +
geom_point() +
geom_mark_ellipse(aes(group = cyl, label = cyl))
```
Lastly, when you want to highlight a group of observations while showing all other observations as a background, `gghighlight` function from the package with the same name is useful:
```{r}
library(gghighlight)
ggplot(mtcars , aes(x = disp, y = mpg, color = factor(cyl))) +
geom_point() +
gghighlight() +
facet_wrap(~cyl)
```
There are other use cases as well. I suggest checking the functions in these packages and functions in more detail for nice plots.
# Scales
## Position and axes
`scale_x_*` and `scale_y_*` functions are used to change the scale of the axes.
```{r}
p1 = ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point()
p2 = ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
scale_x_log10()
p3 = ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
scale_x_reverse()
p4 = ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
scale_y_sqrt()
ggarrange(p1,p2,p3,p4, ncol = 2, nrow = 2)
```
You can also use `scale_x_continous` function with the `trans` argument to set your own transformation. Also using these scaling functions you can change the labels on the axes:
```{r}
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
scale_y_continuous(breaks = seq(10,40,by = 3),
labels = seq(10,40,by = 3))
```
Here, we've shown the values with the increments of 3. There is also a package called `scales` where you can find furhter formatting functions such as `pvalue_format()`, `comma()`, `logit_trans()` which I use regularly.
## Color
Let's go back to our previous example:
```{r}
ggplot(covid, aes( x = outcome, y = age, fill = outcome)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75))
```
A straightforward way to change the colors is using `scale_fill_manual` function, which requires you to set the colors. Just as `scale_fill_*`, there are also `scale_color_*` functions to control the colors of the variables mapped with `fill` or `color`.
```{r}
ggplot(covid, aes( x = outcome, y = age, fill = outcome)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75)) +
scale_fill_manual(values = c('gray', 'gold'))
```
You can also use color palettes such as `scale_fill_brewer`:
```{r}
ggplot(covid, aes( x = outcome, y = age, fill = outcome)) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75)) +
scale_fill_brewer(type = 'qual', palette = 1)
```
Here you can set whether your palette type should be qualitative (qual), divergent (div), or sequential (seq) and set which palette you want.
There are even more color schemes in the `ggthemes` package, such as google docs theme (`scale_color_gdocs`)
```{r}
library(ggthemes)
ggplot(covid, aes( x = outcome, y = age, color = sex)) +
geom_sina(alpha = 0.5, size = 0.3) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75), fill = NA) +
scale_color_gdocs()
```
Let's also see how to modify the legend:
```{r}
library(ggthemes)
ggplot(covid, aes( x = outcome, y = age, color = sex)) +
geom_sina(alpha = 0.5, size = 0.3) +
geom_violin(draw_quantiles = c(0.25,0.5,0.75), fill = NA) +
scale_color_gdocs() +
guides(color = guide_legend('Sex',
override.aes = list(alpha = 1, shape = 15,
size = 3, linetype = c(1,0))))
```
Here alpha argument controls the transparency. We changed the shape from a point to a rectangle using `shape = 15`, increased the size, and also we set the linetype to 0 for 'male' so that the legend showing the lines for the violin plot are not drawn in the legend.
# Themes
Let's load the plot we created in the first part and change its theme. I extensively use `theme_pubr()` from `ggpubr` package for my figures:
```{r}
library(ggpubr)
readRDS('./data/myplot.rds') +
theme_pubr()
```
or try another, minimalist theme:
```{r}
readRDS('./data/myplot.rds') +
theme_tufte()
```
Let's try some other themes as well.
```{r, fig.width=10}
p = ggplot(covid_agegr, aes(x = agegr, fill = sex)) +
geom_bar() +
xlab('Age Group') +
guides(fill = guide_legend('Sex')) +
scale_fill_wsj()
p
p + theme_base()
p + theme_wsj()
```
Lastly, it is possible to further modify the theme using many arguments of the `theme` function. For example, let's change the position of the legend and also remove the major gridlines for the y-axis:
```{r}
p + theme(legend.position = 'top',
panel.grid.minor.y = element_blank())
```
# Publication ready figures
So far we just focused on learning different functionalities and didn't care much about data visualization principles or aesthetics. Now using `mtcars` dataset, we will create a figure that is ready to be sent for a publication. If you want you can create a publication ready figure using the covid dataset and your results from the previous session and share them in the slack channel to get feedback or ask your questions afterwards.
Let's have a look at this dataset more closely.
```{r}
str(mtcars)
```
This data is with 32 observations spanning 11 variables.
* [, 1] mpg Miles/(US) gallon
* [, 2] cyl Number of cylinders
* [, 3] disp Displacement (cu.in.)
* [, 4] hp Gross horsepower
* [, 5] drat Rear axle ratio
* [, 6] wt Weight (1000 lbs)
* [, 7] qsec 1/4 mile time
* [, 8] vs Engine (0 = V-shaped, 1 = straight)
* [, 9] am Transmission (0 = automatic, 1 = manual)
* [,10] gear Number of forward gears
* [,11] carb Number of carburetors
All variables are encoded as numeric but actually some of them are categorical, such as number of cylinders (cyl), engine (vs - v-shaped or straight), transmission (am - automatic or manual), and the number of forward gears (gear - 3,4,5).
Without making any changes in the data, let's explore it a little bit. Here I will use `ggpairs` function from `GGally` package, which is an amazing function to explore the trends between different variables easily:
```{r, fig.width=15, fig.height=15}
GGally::ggpairs(mtcars)
```
I will first set my theme. I do this at the beginning of all my projects so that my theme is the same and consistent across plots in the same publication. In this way I won't need to add `+ theme_pubr()` for my figures.
```{r}
theme_set(theme_pubr(base_size = 10, legend = 'bottom'))
```
Here, `base_size` controls the base font size and `legend` sets the default position of the legend.
Another important point that most ggplot users ignore is the text font you set inside `geom_text` or `geom_label` is not the font size you think of. But it is possible to still use it to set the font size in pt. We need to use a coefficient to make this conversion.
```{r}
ptcoef <- 0.352777778
```
Now, I will start with a figure showing the correlation between the weight and mpg (miles per gallon) - but I will also use the number of cylinders.
```{r}
p1 = mtcars %>%
mutate(cyl = as.factor(cyl)) %>%
ggplot(aes( x = wt, y = mpg, color = cyl)) +
geom_point( size = 2 ) +
geom_smooth(method = 'lm', aes(fill = cyl)) +
scale_color_gdocs()+
scale_fill_gdocs()+
xlab('Weight (1000 lbs)')+ ylab ('Miles per gallon')+
stat_cor(aes(color = cyl),method = 'spearman',
cor.coef.name = 'rho',
label.x = 3.5,
label.y=c(31,29,27), show.legend = F,
size = 8*ptcoef) +
guides(color = guide_legend('Number of\nCylinders', override.aes = list(fill = 'white')),
fill = F) +
theme(legend.position = c(0.9,0.8))
p1
```
Here, I used the `ptcoef` variable I created to make sure the font size is 8 pts.
Here we moved the legend to inside of the plot using `legend.position` argument. By playing with the numbers supplied, you can figure out how this argument works.
```{r}
p2 = mtcars %>%
mutate(cyl = as.factor(cyl)) %>%
ggplot(aes(x=cyl,y=qsec,fill=cyl))+
geom_violin()+
geom_boxplot(width = 0.1, fill = 'white') +
scale_fill_gdocs()+
xlab('Number of cylinders')+ ylab('1/4 mile time')+
stat_compare_means(comparisons = list(c('4','6'),c('6','8'),c('4','8')),
method='wilcox.test',label = "p.signif")+ # Add pairwise comparisons p-value
stat_compare_means(label.y = 14.5,method='kruskal.test', size = 8*ptcoef) +
theme(legend.position = c(0.9,0.8)) +
ylim(14,26)
p2
```
Lastly, I will create a bar plot showing the mpgs per model. I will first re-arrange the order of names so that they will be ordered by first the number of cylinders and then the value of mpg. For this I will use `mutate` and `arrange` functions from `tidyverse`.
```{r}
p3 = mtcars %>%
mutate(name = as.factor(rownames(mtcars)),
cyl = as.factor(cyl)) %>%
arrange(cyl,-mpg) %>%
mutate(name = factor(name, levels = unique(name))) %>%
ggplot(aes(x = name, y = mpg, fill = cyl)) +
geom_bar(stat = 'identity') +
scale_fill_gdocs() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
legend.position = c(0.8,0.9),
legend.direction = 'horizontal') +
xlab(NULL) +
ylab('Miles per Gallon')
p3
```
Here we also changed the angle of the x-axis text within `theme` function. Here `vjust = 0.5` aligns the text to the axis ticks (it actually centers the text), and `hjust = 1` right-aligns the text.
Let's now create a figure with multiple panels to combine these. For this we will use `ggarrange` from `ggpubr` package:
```{r,fig.height=6}
ggarrange(p1,p2,p3, labels = 'auto', common.legend = T)
```
Not too bad, but not ideal either.
```{r,fig.height=6}
p = ggarrange(ggarrange(p1,p2, labels = 'auto', common.legend = T, ncol = 2,nrow=1, legend = 'right'),
p3, labels = c(NA,'c'), nrow = 2, ncol =1, legend = 'none')
p
```
Lastly, let's save this image to send for a publication:
```{r}
ggsave('./figures/fig1.pdf', p, useDingbats = F, units = 'cm', width = 16, height = 14)
ggsave('./figures/fig1.png', p, units = 'cm', width = 16, height = 14)
```
When I save figures that will appear in just one column, I use `width = 8` and for the full-width figures I generally use `width = 16` but for most journals this value can be up to `16.8`. If you create a figure using the exact size it will appear on a journal, you can make sure the font sizes will remain as you set them. Please don't forget that even if the journal is available only in a digital format, they'd ask generally for a minimum font size of 6pts.
# Other plots and packages for visualisation
Finally, I want to give a list of packages that you can explore for different types of special cases:
* For networks: `ggnet2` or `ggnetwork`
* Trees: `ggtree`
* Heatmaps: for simple cases `pheatmap` and for more complicated cases `ComplexHeatmap`
* Circular plots, circos plots etc: `circlize`
<file_sep>/README.md
# Workshop2020
RSG Turkey Student Symposium 2020 - Workshop Session
## General info
**Date:** 24-25 October 2020
**Place:** Online
**Organized by:** [RSG-Turkey](https://rsgturkey.com/en/)
**Price:** Free
**Application:** Register from [here](https://forms.gle/mzQLoyoQMMagnsDD6) For questions, please write to <EMAIL>
**Instructors**
- <NAME>, Department of Biological Sciences, METU
- <NAME>, European Molecular Biology Laboratory, EBI
- <NAME>, Department of Biological Sciences, METU
## Before the workshop
We will use the R environment through **RStudio**, so it is important that you have both R and RStudio installed on your personal
computers to follow along the practical examples. [Here](https://www.datacamp.com/community/tutorials/installing-R-windows-mac-ubuntu)
is a comprehensive guide for installing both programs under Windows, macOS or GNU/Linux. Please contact etka at <EMAIL>
for possible problems you encounter during installation process before the first session of the workshop.
## Course material
The slides and/or codes used during the lectures will be made available once edited and structured after the sessions.
## Program
### 24.10.2020
* 13.00 – 14.30 Introduction to R programming (Etka Yapar)
* 14.30 – 15.00 Short Break
* 15.00 – 16.30 Introduction to R programming (cont.) (Etka Yapar)
### 25.10.2020
* 13.00 – 14.00 Machine learning with R programming (Ulaş Işıldak)
* 14.00 – 14.30 Q & A
* 14.15 – 14.30 Short Break
* 14.30 – 15.30 Machine learning with R programming (cont.)(<NAME>)
* 15.30 – 15.45 Short Break
* 15.45 – 17.00 Data visualization with ggplot (<NAME>)
<file_sep>/02-Intro_to_ML/scripts/funs.R
# This script contains functions for visualizing confusion matrices and statistics
# Note that these are custom fuctions that were written for a specific example.
#
# In order to use these functions in the main.R script, you need to either run them
# in the R session, or you need to use 'source()' function as used in main.R
library(tidyverse)
library(reshape2)
plot_cm = function(cm_list){
cm_list %>%
reshape2::melt() %>%
group_by(L1, Reference) %>%
mutate(prop = value/sum(value),
Prediction = factor(Prediction, levels = c("Died","Recovered")),
Reference = factor(Reference, levels = c("Recovered", "Died"))) %>%
ggplot(aes(x=Prediction, y=Reference, fill=prop)) +
geom_tile(color="white") +
facet_grid(.~L1) +
scale_fill_gradient(low = "lightsteelblue1", high = "steelblue4") +
geom_text(aes(label = value), vjust = .5) +
theme_bw() +
theme(legend.position = "none")
}
stat_cm = function(cm_list){
sapply(cm_list, function(x){
data.frame(
"Accuracy" = x$overall["Accuracy"],
"Sensitivity" = x$byClass["Sensitivity"],
"Specificity" = x$byClass["Specificity"],
"Precision" = x$byClass["Precision"],
"MCC" = Matt_Coef(x)
)
})
}
Matt_Coef <- function (conf_matrix)
{
TP <- conf_matrix$table[1,1]
TN <- conf_matrix$table[2,2]
FP <- conf_matrix$table[1,2]
FN <- conf_matrix$table[2,1]
mcc_num <- (TP*TN - FP*FN)
mcc_den <-
as.double((TP+FP))*as.double((TP+FN))*as.double((TN+FP))*as.double((TN+FN))
mcc_final <- mcc_num/sqrt(mcc_den)
return(mcc_final)
}
<file_sep>/02-Intro_to_ML/scripts/main.R
# Load packages
source("/Users/ulas/Drive/Projects/HIBIT20_ML_Workshop/funs.R") # Change the path accordingly
library(caret)
library(rattle)
# Set random seed for reproducibility
set.seed(234)
## Read data
# You can directly get it from GitHub
mydata = read.csv("https://raw.githubusercontent.com/rsgturkey/Workshop2020/master/02-Intro_to_ML/data/processeddata.csv")
# Data overview
dim(mydata)
names(mydata)
View(mydata)
table(mydata$outcome)
## Downsampling for class imbalance
balanced_data = downSample(mydata, mydata$outcome)
table(balanced_data$outcome)
## Split features and response
outcome = balanced_data$outcome # Response
features = balanced_data[, c("age", "sex", "latitude", "longitude")] # Features
## Training/test split
train_idx = createDataPartition(outcome, p=0.8, list=FALSE)
train_x = features[train_idx, ] # Training data features
test_x = features[-train_idx, ] # Testing data features
train_y = outcome[train_idx] # Training data labels
test_y = outcome[-train_idx] # Testing data features
## Set 5-fold cross-validation
ctrl = trainControl(method = "cv", number = 5)
## Logistic regression
logreg = train(x = train_x,
y = train_y,
method = "glm",
family = binomial(),
trControl = ctrl)
cm_logreg = confusionMatrix(data = predict(logreg, newdata = test_x),
reference = test_y)
## Decision tree
dtree = train(x = train_x,
y = train_y,
method = "rpart",
trControl = ctrl)
fancyRpartPlot(dtree$finalModel)
cm_dtree = confusionMatrix(data = predict(dtree, newdata = test_x),
reference = test_y)
## Random forest
rforest = train(x = train_x,
y = train_y,
method = "rf",
trControl = ctrl)
cm_rforest = confusionMatrix(data = predict(rforest, newdata = test_x),
reference = test_y)
# Shows variable importance
varImp(rforest)
## Plot confusion matrices
plot_cm(list(LogRegression = cm_logreg$table,
DecisionTree = cm_dtree$table,
RandForest = cm_rforest$table))
## Compare statistics
stat_cm(list(LogRegression = cm_logreg,
DecisionTree = cm_dtree,
RandForest = cm_rforest))
<file_sep>/02-Intro_to_ML/scripts/preprocess.R
# This script contains code for preprocessing of the raw data
# From Xu. et al, 2020 (https://doi.org/10.1038/s41597-020-0448-0):
# Raw data: https://github.com/beoutbreakprepared/nCoV2019/tree/master/latest_data
library(tidyverse)
rawdata = read_csv("/Users/ulas/Drive/Projects/HIBIT20_ML_Workshop/latestdata.csv")
rawdata %>%
select(outcome, age, sex, latitude, longitude) %>%
drop_na() %>%
mutate(outcome = tolower(outcome)) %>%
filter(outcome %in% c("dead", "death", "deceased", "died", "recovered"),
nchar(age) == 2) %>%
mutate(outcome = ifelse(outcome == "recovered", "Recovered", "Died"),
sex = ifelse(sex == "female", "Female", "Male"),
age = as.numeric(age)) %>%
write_csv("/Users/ulas/Drive/Projects/HIBIT20_ML_Workshop/processeddata.csv", col_names=TRUE)
| aea57155a73e09b00823df799d75e8cc31cc9661 | [
"Markdown",
"R",
"RMarkdown"
] | 5 | RMarkdown | OzgeDemirel91/Workshop2020 | 99b9439eb3f345ef10ed7bc637f6961fe7437064 | a2d255b78c84e02da204d257fae5d84f816eeeea |
refs/heads/master | <file_sep>
function lineComponent() {
let width = 200;
let height = 200;
let xScale = d3.scaleLinear()
.domain([0, 100])
.range([0, 200]);
let yScale = d3.scaleLinear()
.domain([0, 13])
.range([0, 200]);
let axis = d3.axisBottom(xScale);
let svg = null;
function me(selection) {
if (!svg) {
svg = selection
.append("svg")
.attr("width", width)
.attr("height", height);
svg.append('g')
.attr('transform', 'translate(10,180)')
.call(axis);
svg = svg.append('g')
.attr('transform', 'translate(10,10)');
}
let lines = svg.selectAll("line")
.data(selection.datum());
// <line x1='0' y1='0' x2='10' y2='10'/>
lines.enter() // ENTER
.append("line")
.attr("stroke-weight", 1)
.attr("stroke", "black");
// EXIT
lines.exit().remove();
svg.selectAll('line') //UPDATE
.attr("x1", 0)
.attr("x2", function(d, i) {
return xScale(d);
})
.attr("y1", function(d, i) {
return yScale(i);
})
.attr("y2", function(d, i) {
return yScale(i);
});
let texts = svg.selectAll('text')
.data(selection.datum());
texts.enter()
.append('text');
texts.exit().remove();
svg.selectAll('text')
.attr('x', xScale)
.attr('font-size', 10)
.attr('font-family', 'sans-serif')
.attr('y', function(d, i) {
return yScale(i)
})
.attr('dy', 3)
.text(function(d) {
return d
});
}
me.width = function(arg) {
if (!arguments.length)
return width;
width = arg;
xScale.range([0, width - 10 * 2]);
return me;
}
me.height = function(arg) {
if (!arguments.length)
return height;
height = arg;
return me;
}
return me;
}
| 0e61a2f312fe6684a9b63b83e6e541022689a1f6 | [
"JavaScript"
] | 1 | JavaScript | VA602AA-master/lines | 000ac22f7b199151d707563e11cb8ed9e6f2302d | a41072f73357cafab60c4117d3fbb3315fb6f027 |
refs/heads/master | <file_sep># Sparkol-Login-Test
Please be aware that the home page is not 100% secure. This is ok as long as any sensitive data access is done via an api using the jwt and verified.
## Prerequisites
You will need to clone, install and run the auth service specified here (https://github.com/dantame/interview-authentication-service) in order to make this project run.
### Development
```javascript
npm install
npm run start:dev
```
### Production
```javascript
npm install
npm run build
```
<file_sep>import React, { useState } from "react";
import { Redirect } from 'react-router-dom';
import axios from "axios";
import { useAuth } from "../../context/auth";
function Login() {
const [isLoggedIn, setLoggedIn] = useState(false);
const [isError, setIsError] = useState(false);
const [username, setUserName] = useState("");
const [password, setPassword] = useState("");
const { setAuthTokens } = useAuth();
const setHeaderToken = token => token ? axios.defaults.headers.common['Authorization'] = token : delete axios.defaults.headers.common['Authorization'];
async function postLogin() {
await axios.post("http://localhost:3333/login", {
username,
password
}).then(result => {
if (result.status === 200) {
const { token } = result.data;
setHeaderToken(token)
setAuthTokens(token);
setLoggedIn(true);
} else {
setIsError(true);
}
}).catch(e => {
setIsError(true);
});
}
if (isLoggedIn) {
return <Redirect to="/Home" />;
}
return (
<div>
<h1>
Sign in
</h1>
<form>
<label htmlFor="username" />
Username
<input
id="username"
type="text"
onChange={e => {
setUserName(e.target.value);
}}
value={username}
name="username"
/>
<label htmlFor="password" />
Password
<input
id="password"
type="<PASSWORD>"
onChange={e => {
setPassword(e.target.value);
}}
value={password}
name="password"
/>
{ isError &&<p>Invalid Username or Password</p> }
<button type="button" className="submit" onClick={postLogin}>
Login
</button>
</form>
</div>
);
}
export default Login;<file_sep>const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: ['./index.js', './sass/main.scss'],
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: path.join(__dirname, 'public/'),
port: 9000,
publicPath: "http://localhost:9000/dist/",
hotOnly: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(css|sass|scss)$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader',
],
},
],
},
output: {
path: path.join(__dirname, 'dist/'),
publicPath: '/dist/',
filename: 'bundle.js',
},
};<file_sep>import React, { useState } from "react";
import "@babel/polyfill";
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import jwt_decode from "jwt-decode";
import {hot} from "react-hot-loader";
import Home from '../Home/index.jsx';
import Login from '../Login/index.jsx';
import { AuthContext, useAuth } from "../../context/auth";
function PrivateRoute({ component: Component, ...rest }) {
const { authTokens } = useAuth();
return (
<Route
{...rest}
render={props =>
authTokens ? (
<Component {...props} />
) : (
<Redirect to="/" />
)
}
/>
);
}
function App() {
const existingTokens = localStorage.getItem("token");
const [authTokens, setAuthTokens] = useState(existingTokens);
const setTokens = (data) => {
const decodedToken = jwt_decode(data);
localStorage.setItem("token", data);
localStorage.setItem("user_id", decodedToken.user.id);
localStorage.setItem("user_name", decodedToken.user.name);
setAuthTokens(data);
}
return (
<AuthContext.Provider value={{ authTokens, setAuthTokens: setTokens }}>
<Router>
<Switch>
<Route exact path="/" component={Login} />
<PrivateRoute path="/Home" component={Home}/>
</Switch>
</Router>
</AuthContext.Provider>
);
}
export default hot(module)(App);<file_sep>import React from "react";
import { Link } from 'react-router-dom';
import { getUserName } from "../../helpers";
function Home() {
const userName = getUserName();
function logOut() {
localStorage.removeItem("token");
localStorage.removeItem("user_id");
localStorage.removeItem("user_name");
}
return (
<div className="logout-container">
<h1>
Welcome home {userName}!
</h1>
<Link to="/">
<button type="submit" className="logout" onClick={logOut}>
Sign out
</button>
</Link>
</div>
);
}
export default Home; | 7fe42a2f0ca6159989113075c05a5a96c2e87002 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | Muffinman75/sparkol-login-test | b9d02203bef88c363b8ad25c3d48de6053e1f8ed | 54ad2db4cf7922ef023bf823437d996b0f18bdc8 |
refs/heads/master | <file_sep># therohitsharma.github.io
<file_sep>//Directive for the drag and drop system.
angular.module('redditApp').directive('ngDrag', function() {
return {
link: function(scope, element) {
element.draggable({ });
}
}
});
angular.module('redditApp').directive('ngDroppable', function() {
return {
link: function(scope, element) {
element.droppable({
drop: function(event, ui){
scope.subreddits = [];
scope.sr = $(ui.draggable).find('span').text();
scope.populateImages();
$(ui.draggable).draggable('option', 'revert', true);
}
});
}
}
});
<file_sep>//RedditApp Module
var redditApp = angular.module('redditApp', ['ngRoute', 'ngStorage', 'webStorageModule']);
<file_sep>//Directive for the saving the subreddits.
angular.module('redditApp').directive('saveList', ['$localStorage', 'webStorage', function( $localStorage, webStorage ) {
return {
link: function(scope, element) {
element.on('click', function(){
webStorage.local.add('obj', scope.sublist);
});
}
}
}]);
<file_sep>//Directive for deleting all of the subreddits.
angular.module('redditApp').directive('trashList', ['$localStorage', 'webStorage', function( $localStorage, webStorage ) {
return {
link: function(scope, element) {
element.on('click', function(){
scope.sublist = [ ];
$('.subredditcontainer ul').children().fadeOut();
webStorage.local.clear();
});
}
}
}]);
<file_sep>angular.module('redditApp').directive('addSub', function() {
return {
link: function(scope, element) {
element.on('click', function(){
if (scope.sublist.indexOf(scope.sr) == -1) {
scope.sublist.push(scope.sr);
}
});
}
}
});<file_sep>//This directive controls the hover event. The qtip containing the post title shows up on hover.
redditApp.directive('ngHover', function() {
return {
link: function(scope, element) {
element.qtip({
position: {
my: 'bottom center', // Position it where the click was...
at: 'top center',
target: element,
adjust: {
mouse: false
} // ...but don't follow the mouse
},
style: {
classes: 'qtip-youtube'
},
content: {
text: scope.subreddit.title
}
})
element.on('click', function() {
$('.modal-body').empty();
$('#myModal p a').remove();
$('.modal-title').empty();
$('.modal-title').append('<a href="http://reddit.com' + scope.subreddit.permalink + '" target="_blank">' + scope.subreddit.title + '</a>');
$('.modal-body').append('<img id="mimg" src="' + scope.subreddit.url + '">');
$('#myModal').modal('show');
setTimeout(function() {
$('#myModal').data('bs.modal').handleUpdate();
}, 800);
});
}
}
});
| e1a1a200db3f2898d8398364af26dd341f78d453 | [
"Markdown",
"JavaScript"
] | 7 | Markdown | TheRohitSharma/therohitsharma.github.io | e3616ee1018a43eac06b990a6f0322935b180b85 | 6a08f617a8295cf3e4beaaf70c34fbc681c18c45 |
refs/heads/master | <repo_name>j-lopez/WordsForEvilBot<file_sep>/main.py
from trie import Trie
from gameLogic import wordSearch, treasure, runGame
from gameboardGraph import gameboardGraph
from pynput.keyboard import Key, Controller
import random
import numpy as np
def buildTrie():
t = Trie()
with open("words.txt", "r") as f:
for word in f.readlines():
t.insert(word[:-1])
return t
def convertwords():
new = open("words.txt", "w+")
with open("usa2.txt", "r") as f:
for line in f.readlines():
cap = line.upper()
if cap[:-1].isalpha() and len(cap) > 4 and len(cap) < 9:
new.write(cap)
def main():
t = buildTrie()
g = gameboardGraph()
runGame(t, g)
''' This is in case of a character death
while True:
wordShuff = ["R", "G", "T", "O", "I", "L", "Y"]
random.shuffle(wordShuff)
word = ''.join(wordShuff[:7])
if trie.search(word):
print(word)'''
if __name__ == "__main__":
main()
<file_sep>/imageProcessing.py
from PIL import ImageGrab, Image
import pytesseract
game_coords = [56, 315, 426, 655]
def grabImage():
#Grab a screenshot of gameboard
im = ImageGrab.grab(bbox=game_coords)
im.save("gameboard.png")
return im
def imageProcess():
def createLine(row):
# Used to combine a row into a single image, easier for pytessaract to read
def get_concat_h(im1, im2):
dst = Image.new('RGB', (im1.width + im2.width, im1.height))
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
return dst
line = row[0]
for j in range(1, 7):
line = get_concat_h(line, row[j])
return line
im = Image.open("gameboard.png")
# First letter frame is [3, 75, 45, 117]
# Used to store board's letters and colored tile locations
foundLetters = []
for i in range(5):
row = []
for j in range(7):
# Automates creating letters and sends them to createLine
frame = [9 + (53 * j), 81 + (53 * i),
39 + (53 * j), 111 + (53 * i)]
letterI = im.crop(box=frame).resize((60,80))
row.append(letterI)
# Used to save letter images, TODO deprecate soon or create class to toggle necessity
#fileLoc = "images/letter_" + str(i + 1) + "_" + str(j + 1) + ".png"
#letterI.save(fileLoc)
line = createLine(row)
# Pytesseract to create text
foundLetters.append(pytesseract.image_to_string(line))
# Save line for good measure
line.save("images/line" + str(i + 1) + ".png")
# Close all images in row
for image in row:
image.close()
line.close()
l = cleanLetters(foundLetters)
im.close()
return l
def cleanLetters(letters):
n = len(letters)
for i in range(n):
word = letters[i].replace(" ", "")
if len(word) != 7:
if ("Qu" in word) or ("QU" in word):
word = word.replace("QU", "Q")
word = word.replace("Qu", "Q")
letters[i] = word
return letters
def tryClean(rowNum):
n = rowNum + 1
line = Image.open("images/line" + str(n) + ".png").convert("L")
line.resize((line.width * 2, line.height * 2))
line.save("images/line" + str(n) + ".png")
letters = [pytesseract.image_to_string(line)]
return cleanLetters(letters)
line.close()<file_sep>/trie.py
class TrieNode:
def __init__(self):
self.value = None
self.children = [None] * 26
self.endOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def insert(self, word):
n = len(word)
currNode = self.root
for i in range(n):
letter = ord(word[i]) - ord('A')
if not currNode.children[letter]:
currNode.children[letter] = TrieNode()
currNode.children[letter].value = chr(letter + ord('A'))
currNode = currNode.children[letter]
currNode.endOfWord = True
def search(self, word):
if (word != word.upper()):
return False
n = len(word)
currNode = self.root
for i in range(n):
letter = ord(word[i]) - ord('A')
if not currNode.children[letter]:
return False
currNode = currNode.children[letter]
if not currNode.endOfWord:
return False
return True
def getChildren(self, path):
if path != path.upper():
return []
n = len(path)
currNode = self.root
for i in range(n):
letter = ord(path[i]) - ord('A')
if not currNode.children[letter]:
return []
currNode = currNode.children[letter]
if sum([0 if currNode.children[i] else 1 for i in range(26)]) > 0:
return currNode.children
else:
return None
<file_sep>/gameLogic.py
from gameboardGraph import gameboardGraph
from time import sleep
from imageProcessing import grabImage
from pytesseract import image_to_string
from pyautogui import position, press, typewrite, keyUp, keyDown
import random
def wordSearch(t, g):
def recursiveSearch(tile, word, trie):
path = word + tile.value
tile.used = True
foundWords = []
if trie.search(path):
foundWords.append(path)
neighbors = [n for n in tile.neighbors if not n.used]
trieChildren = trie.getChildren(path)
for n in neighbors:
letter = 0
if (n.value == "QU"):
letter = ord("Q") - ord('A')
else:
letter = ord(n.value) - ord('A')
if trieChildren:
if letter < 0 or letter > 25:
return foundWords
if trieChildren[letter]:
foundWords.extend(recursiveSearch(n, path, trie))
tile.used = False
return foundWords
# Graph data structure and all methods
if g.setGameboard():
allWords = []
for line in g.board:
for node in line:
allWords.extend(recursiveSearch(node, '', t))
recommended = sorted(allWords, key=len)
g.words = list(set(recommended[-5:]))
g.words.reverse()
return "Words found"
else:
return "None found"
def treasure(t, board):
letters = []
for i in range(5):
letters.append([board[0][i], board[1][i]])
for i1 in range(2):
for i2 in range(2):
for i3 in range(2):
for i4 in range(2):
for i5 in range(2):
word = letters[0][i1] + letters[1][i2] + letters[2][i3] + letters[3][i4] + letters[4][i5]
if t.search(word):
return word
def runGame(trie, graph):
sleep(2)
while True:
im = grabImage()
foundText = image_to_string(im)
#print(foundText)
# Start of the game, just hit enter
if "Start" in foundText:
press("enter")
# When a fight is about to start
elif "Start the Fight" in foundText:
press("enter")
# A gameboard has been found, run wordsearch
elif "Shuffle" in foundText:
status = wordSearch(trie, graph)
if status == "None found":
print(status + ", shuffling")
keyDown("shift")
keyUp("shift")
sleep(3)
elif status == "Words found":
print("Typing...\n")
for word in graph.words:
typewrite(word.lower(), interval=0.1)
press("enter")
sleep(1)
# End of a battle, hit enter
elif "Gold Earned" in foundText:
press("enter")
# Heroes have found a shrine
elif "<NAME>" in foundText:
i = random.randint(0, 3)
gods = ["s", "a", "w", "l"]
typewrite(gods[i])
sleep(1)
press("enter")
# Loot Chest has been found
elif "Loot Chest" in foundText:
press("enter")
print("Enter the two 5 letter combinations:")
i1 = input("Enter first value: ")
i2 = input("Enter second value: ")
key = treasure(trie, [i1, i2])
sleep(2) # To give you a chance to click back on game
if key != None:
typewrite(key.lower(), interval=0.1)
press("enter")
else:
print("Word not found")
sleep(5)
# Devious Trap has been found
# TODO Think of an algorithm to get rid of all words
elif "Ready\n\na Ka" in foundText:
print("Trap not yet implemented, try to do it yourself in 60 seconds")
sleep(60)
# Potion Shop, bot doesn't need help!
elif "The Potion Shop" in foundText:
typewrite("p")
# Found a fountain, will give 20 seconds to upgrade heroes
elif "The Fountain" in foundText:
typewrite("g")
print("You have 20 seconds to upgrade your heroes")
sleep(10)
print("10 seconds remain")
sleep(5)
print("5 left, finish up")
typewrite("f")
# Blacksmith, will give 30 seconds to buy things
elif "The Blacksmith" in foundText:
typewrite("b")
print("You have 30 seconds to upgrade your heroes\nin the shop")
sleep(25)
print("5 seconds remain, finish up!")
# Medicine man, poor dude can't make a living
elif "edicin" in foundText:
typewrite("o")
elif "Book" in foundText:
typewrite("r")
sleep(5)
typewrite("c")
sleep(1)
typewrite("l")
| 14dbc0bc6d2cbc4047e97275ca4e9759c0e23122 | [
"Python"
] | 4 | Python | j-lopez/WordsForEvilBot | 2f15c4cee2b97c1961a2e266b6c659d59a8f7120 | cdd5e73f6dd172bf4bfb6032f9768ca93515f29d |
refs/heads/master | <repo_name>akhil-06/Basic-change-shape-color-game<file_sep>/README.md
# Basic-change-shape-color-game
# for opening project just OPEN the "changeShape" files.
# others are of no use
<file_sep>/changeShape.js
var current = "square";
var shape = ["square","rectangle","circle", "oval", "triangle-up", "triangle-down", "triangle-topleft", "triangle-bottomleft", "triangle-bottomright", "triangle-right","parallelogram"];
var color = ["red", "orange", "green", "maroon", "pink", "violet","cyan","black","Chartreuse","Gold","GreenYellow","brown"];
var x = document.getElementById("shape")
x.onclick = function(){
var random = shape[Math.floor(Math.random() * shape.length)];
document.getElementById(current).setAttribute("id",random);
current=random;
}
var x1 = document.getElementById("color")
x1.onclick = function(){
var randomcolor = shape[Math.floor(Math.random() * color.length)];
document.getElementById("block").style.background-color = randomcolor;
current=random;
}<file_sep>/togglemode.js
var toggled = false;
var htag = document.getElementsByTagName("h1")[0];
// var htag = document.getElementsById("h12");
var bodytag = document.getElementsByTagName("body")[0];
var circle = document.getElementById("circle");
var x = document.getElementById("toggle");
x.onclick = function () {
if(! toggled){
htag.classList.add("color-white");
bodytag.classList.add("color-black");
circle.style.marginleft = "100px";
toggled = true;
}
else{
htag.classList.remove("color-white");
bodytag.classList.remove("color-black");
circle.style.marginLeft = "1px";
toggled = false;
}
} | 59e8ecdfaa29dfe139659ac5f082abe3862666c3 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | akhil-06/Basic-change-shape-color-game | 66997010420ce90226c1b1f4068439134c51960a | f1ac6623b27206197f3ef2173190b460d3bb9e68 |
refs/heads/master | <repo_name>Moshalov/course-Project<file_sep>/WebApplication1/WebApplication1/DAO/DAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.DAO
{
public class DAO
{
public Type[] getArrayOfTypes()
{
return (new Database().GetTable<Type>().ToArray());
}
public Status[] getArrayOfStatus()
{
return (new Database().GetTable<Status>().ToArray());
}
public AspNetRoles[] getArrayOfRoles()
{
return (new Database().GetTable<AspNetRoles>().ToArray());
}
public School[] getSchoolList()
{
return (new Database().GetTable<School>().ToArray());
}
public AspNetUsers[] getUserList()
{
return (new Database().GetTable<AspNetUsers>().ToArray());
}
public AspNetRoles[] getRoleList()
{
return (new Database().GetTable<AspNetRoles>().ToArray());
}
public IEnumerable<AspUserInSchool> getUserSchoolList(string p)
{
return (new Database().GetTable<AspUserInSchool>().Where(x => x.User_id == p));
}
public IEnumerable<AspNetUserRoles> getUserRoleList(string p)
{
return (new Database().GetTable<AspNetUserRoles>().Where(x => x.UserId == p));
}
}
}<file_sep>/WebApplication1/WebApplication1/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.DAO;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Login()
{
return Redirect("~/Acount/Login");
}
public ActionResult Index()
{
if (User.IsInRole("Administrator"))
{
return Redirect("~/Admin/UserList");
}
if (!User.Identity.IsAuthenticated)
{
return Redirect("~/Account/Login");
}
else
{
return Redirect("~/Report/List");
}
}
[Authorize(Roles = "School_Stuff")]
public ActionResult About()
{
if (!User.Identity.IsAuthenticated)
{
return Redirect("~/Account/Login");
}
else
{
ViewBag.Message = "Your application description page.";
return View();
}
}
public ActionResult Contact()
{
if (!User.Identity.IsAuthenticated)
{
return Redirect("~/Account/Login");
}
else
{
ViewBag.Message = "Your contact page.";
return View();
}
}
public ActionResult stringError(String str)
{
if (!User.Identity.IsAuthenticated)
{
return Redirect("~/Account/Login");
}
else
{
ViewBag.Message = "Your contact page.";
return View();
}
}
public PartialViewResult Menu()
{
if (User.IsInRole("Administrator"))
{
return PartialView("~/Shared/AdminPanel");
}
else
{
if (User.IsInRole("SuperVisor"))
{
return PartialView("~/Shared/AdminPanel");
}
else
{
return PartialView("~/Shared/AdminPanel");
}
}
}
}
}<file_sep>/WebApplication1/WebApplication1/DAO/MEIData.cs
namespace WebApplication1.DAO
{
partial class MEIDataDataContext
{
}
}
<file_sep>/WebApplication1/WebApplication1/Controllers/ReportController.cs
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.DAO;
namespace WebApplication1.Controllers
{
public class ReportController : Controller
{
//
// GET: /Report/
[Authorize(Roles = "School_Stuff")]
public ActionResult Create()
{
// if(DAO.Database())
return View(new Report());
}
[Authorize(Roles = "School_Stuff")]
[HttpPost]
public ActionResult Create(Report rep)
{
DAO.Database db = new DAO.Database();
rep.UserName = User.Identity.Name;
Table<Report> reports = db.GetTable<Report>();
rep.Date = System.DateTime.Now;
rep.Status_id = 2;
String user_id = db.GetTable<AspNetUsers>().Single(x => x.UserName == User.Identity.Name).Id;
Table<AspUserInSchool> tab = db.GetTable<AspUserInSchool>();
AspUserInSchool s = tab.SingleOrDefault(x => x.User_id == user_id);
rep.School = s.School1;
reports.InsertOnSubmit(rep);
db.SubmitChanges();
return RedirectToAction( "List","Report");
}
[Authorize(Roles = "School_Stuff,Supervisor")]
public ActionResult List()
{
DAO.Database db = new DAO.Database();
if (User.IsInRole("Supervisor"))
{
Table<Report> reports = db.GetTable<Report>();
var test = from c in reports
select c;
return View(test.ToList());
}
else
{
Table<Report> reports = db.GetTable<Report>();
var test = from c in reports
where c.UserName == User.Identity.Name
select c;
return View(test.ToList());
}
}
[Authorize(Roles = "School_Stuff")]
public ActionResult Edit(int id)
{
Table<Report> reports = new DAO.Database().GetTable<Report>();
Report rep = reports.SingleOrDefault(item => item.Id == id);
if (rep.UserName == User.Identity.Name)
{
return View(rep);
}
else
{
ViewBag.Message = "Нет доступа";
return RedirectToAction("list");
}
}
[Authorize(Roles = "School_Stuff")]
[HttpPost]
public ActionResult Edit(Report rep)
{
DAO.Database db = new DAO.Database();
Report reps = db.GetTable<Report>().Single(x => x.Id == rep.Id);
reps.Id = rep.Id;
reps.Name = rep.Name;
reps.Text = rep.Text;
reps.School_id = rep.School_id;
reps.Date = rep.Date;
reps.Status_id = 2;
reps.Type_id = rep.Type_id;
reps.UserName = rep.UserName;
db.SubmitChanges();
return RedirectToAction("list", "Report");
}
[Authorize(Roles = "Supervisor")]
public ActionResult Allow(int id)
{
Database db = new Database();
Report rep = db.GetTable<Report>().SingleOrDefault(item => item.Id == id);
return View(rep);
}
[Authorize(Roles = "Supervisor")]
[HttpPost]
public ActionResult Allow(Report rep)
{
DAO.Database db = new DAO.Database();
rep.UserName = User.Identity.Name;
Table<Report> reports = db.GetTable<Report>();
var test = from c in reports
where c.Id == rep.Id
select c;
foreach (Report r in test)
{
r.Status_id = rep.Status_id;
}
db.SubmitChanges();
return RedirectToAction("List","Report");
}
[Authorize(Roles = "School_Stuff, Supervisor")]
public PartialViewResult Comments(int id)
{
DAO.Database db = new Database();
var test = from c in db.GetTable<DAO.Comments>()
where c.Report_id == id
select c;
return PartialView(test.ToArray());
}
[Authorize(Roles = "School_Stuff, Supervisor")]
public ActionResult AddCommentView(int id)
{
Comments com = new Comments();
com.Report_id = id;
com.UserName = User.Identity.Name;
return View(com);
}
[Authorize(Roles = "School_Stuff, Supervisor")]
[HttpPost]
public ActionResult AddCommentView(DAO.Comments com)
{
Database db = new Database();
com.Report_id = com.Id;
com.UserName = User.Identity.Name;
com.Date_time = DateTime.Now;
db.GetTable<Comments>().InsertOnSubmit(com);
db.SubmitChanges();
return RedirectToAction("Details","Report", new { id = com.Report_id});
}
public ActionResult Details(int id)
{
Database db = new Database();
Report rep = db.GetTable<Report>().SingleOrDefault(item => item.Id == id);
return View(rep);
}
public ActionResult Index()
{
return Redirect("~Route/List");
}
}
}
<file_sep>/WebApplication1/WebApplication1/Controllers/AdminController.cs
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.DAO;
namespace WebApplication1.Controllers
{
public class AdminController : Controller
{
[Authorize(Roles = "Administrator")]
public ActionResult CreateUser()
{
return View(new Models.RegisterViewModel());
}
public ActionResult SetRole(String user_id)
{
return View(new AspNetUserRoles() { UserId = user_id });
}
[HttpPost]
public ActionResult SetRole(AspNetUserRoles roles)
{
Database db = new Database();
db.GetTable<AspNetUserRoles>().InsertOnSubmit(roles);
db.SubmitChanges();
return Redirect("~/Admin/UserList");
}
[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult CreateUser(Models.RegisterViewModel acc)
{
AccountController ac = new AccountController();
ac.Register(acc);
Database db = new Database();
string id = db.GetTable<AspNetUsers>().Single(obj => obj.UserName == acc.UserName).Id;
db.GetTable<AspNetUserRoles>().InsertOnSubmit(new AspNetUserRoles() { RoleId = acc.Role_Id.ToString(), UserId = id });
db.SubmitChanges();
if (acc.Role_Id.ToString() == new Database().GetTable<AspNetRoles>().SingleOrDefault(x => x.Name.ToLower() == "School_Stuff".ToLower()).Id)
{
return RedirectToAction("SelectSchoolForUser",id);
}
else
{
return View();
}
}
[Authorize(Roles = "Administrator")]
public PartialViewResult AdminPanel()
{
if (User.IsInRole("Administrator"))
{
return PartialView();
}
else
{
return null;
}
}
[Authorize(Roles = "Administrator")]
public ActionResult Register()
{
return View();
}
[Authorize(Roles = "Administrator")]
public ActionResult CreateSchool()
{
return View(new DAO.School());
}
[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult CreateSchool(DAO.School sc)
{
Database db = new Database();
db.GetTable<School>().InsertOnSubmit(sc);
db.SubmitChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = "Administrator")]
public ActionResult ShcoolList()
{
Database db = new Database();
return View(db.GetTable<School>().ToArray());
}
[Authorize(Roles = "Administrator")]
public ActionResult UserList()
{
return View(new DAO.DAO().getUserList());
}
[Authorize(Roles = "Administrator")]
public ActionResult SelectSchoolForUser(String user_id){
return View(new DAO.AspUserInSchool());
}
[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult SelectSchoolForUser(DAO.AspUserInSchool us)
{
Database db = new DAO.Database();
db.GetTable<AspUserInSchool>().InsertOnSubmit(us);
db.SubmitChanges();
return Redirect("~/Admin/UserList");
}
[Authorize(Roles = "Administrator")]
public ActionResult AddSchool()
{
return View(new School());
}
[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult AddSchool(School sc)
{
Database db = new Database();
db.GetTable<School>().InsertOnSubmit(sc);
db.SubmitChanges();
return RedirectToAction("ShcoolList", "Admin");
}
}
}<file_sep>/WebApplication1/WebApplication1/DAO/Database.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Linq;
using System.Linq;
using System.Web;
namespace WebApplication1.DAO
{
public class Database : DataContext
{
public Database(): base(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString())
{
}
public Database(string name):base(ConfigurationManager.ConnectionStrings[name].ToString())
{
}
public MEIDataDataContext data = new MEIDataDataContext();
public List<Report> getList(){
return(data.GetTable<Report>().ToList());
}
public List<Type> getTypeList()
{
return (data.Type.ToList());
}
public Boolean userInRole(String username, String role)
{
String userid = data.GetTable<AspNetUsers>().SingleOrDefault(item => item.UserName == username).Id;
String roleid = data.GetTable<AspNetRoles>().SingleOrDefault(item => item.Name == role).Id;
AspNetUserRoles asproles = data.GetTable<AspNetUserRoles>().SingleOrDefault(item => item.UserId.ToString() == userid && item.RoleId.ToString() == roleid);
if (asproles != null)
{
return (true);
}
else
{
return (false);
}
}
}
} | fb07e115a4e6a8ee6e369522af13aac403cac055 | [
"C#"
] | 6 | C# | Moshalov/course-Project | 1cae892d82f20a95173cc7076437b620fb5814c8 | 1697ccd309a19c0292e578c64e7bc01c68f8107b |
refs/heads/master | <repo_name>ahaldar/Shakespeare-Character-Model<file_sep>/char-model.py
# Original article at http://nbviewer.jupyter.org/gist/yoavg/d76121dfde2618422139
#
# Python code to implement character level language model
# to generate Shakespeare style text.
from collections import *
def train_char_lm(fname, order=4):
data = file(fname).read()
lm = defaultdict(Counter)
pad = "~" * order
data = pad + data
for i in xrange(len(data)-order):
history, char = data[i:i+order], data[i+order]
lm[history][char]+=1
def normalize(counter):
s = float(sum(counter.values()))
return [(c,cnt/s) for c,cnt in counter.iteritems()]
outlm = {hist:normalize(chars) for hist, chars in lm.iteritems()}
return outlm
from random import random
def generate_letter(lm, history, order):
history = history[-order:]
dist = lm[history]
x = random()
for c,v in dist:
x = x - v
if x <= 0: return c
def generate_text(lm, order, nletters=1000):
history = "~" * order
out = []
for i in xrange(nletters):
c = generate_letter(lm, history, order)
history = history[-order:] + c
out.append(c)
return "".join(out)
print "Training model to write like Shakespeare..."
lm = train_char_lm("shakespeare-input.txt", order=10)
print "Done training."
print "Generated text:"
print generate_text(lm, 10)
"""
Training model to write like Shakespeare...
Done training.
Generated text:
First Citizen:
The king, sir, hath
danced before the Roman?
Lieutenant, is your grace's part; black and blue, that you'll make, advise me like a Fury crown'd with simular proof enough to purchase out abuses:
Therefore I'll watch you for this once. What, hast
smutch'd thy nose?
They say Edgar, his banished son, is with their power i' the eyes, but with my soul delights,
But with him.
PROSPERO:
Come forth.
MECAENAS:
We have strength can give you: live,
And bear his mind, be Edward England's coat one half-penny-worth of bread to
this intolerable.
YORK:
I am thine own so proper as to waste
His borrow'd flaunts, behold
Their infancy again
And knit our powers, with smiling rogues as these
Have moved his highness: my best train
I have from the English beach
Pales in the mask.
The heavens
Reveal the damn'd contriver; and, you know, is haunted
With a reed voice, and that will give us
Some faults to make good time!
Clown:
'O no, no, no.
EROS:
Sir, his wife and doth affliction of her tears;
"""
<file_sep>/README.md
# Shakespeare-Character-Model
Python code to implement maximum likelihood character model to generate Shakespeare style text
| e38304d9b6f916e9b010c4188bacbca566eb9886 | [
"Markdown",
"Python"
] | 2 | Python | ahaldar/Shakespeare-Character-Model | 04f78a645f210ebf4334af9496e6651c0c8d039f | b2b154c0f4be3e3503e824693d18032e3e5063f4 |
refs/heads/master | <repo_name>jaikysh76/python_code<file_sep>/table.py
first_no=2
while(first_no >= 5):
print("table of :",first_no)
second_no=1
while(second_no >= 10):
multiple=first_no*second_no
print(first_no, "x", second_no,"=",multiple)
second_no += 1
print()
first_no += 1
| 195362e64247c94839f423962a0cb06405976f06 | [
"Python"
] | 1 | Python | jaikysh76/python_code | 68403e7171865535db323d35189f516f68fd0063 | 10a365fca6ee85bfbcf945eeea0b9daea9efe4b7 |
refs/heads/master | <file_sep>import React from "react";
import {Nav, Navbar} from "react-bootstrap";
import {Link} from "react-router-dom";
const Topmenu = () => {
return (
<Navbar>
<Navbar.Brand>Spider</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Link to="/" className="nav-link">Home</Link>
<Link to="/search" className="nav-link">Search</Link>
<Link to="/git_repos" className="nav-link">Git Repositories</Link>
<Link to="/search" className="nav-link">Monticello Repositories</Link>
</Nav>
</Navbar.Collapse>
</Navbar>
);
};
export default Topmenu;<file_sep>import React, {useEffect} from "react";
import Prism from "prismjs";
import "prismjs/components/prism-smalltalk.min";
import "prismjs/themes/prism.css";
const MethodSource = ({method}) => {
useEffect(() => {
const src = method ? method.source : "";
const tooLongToFormat = src.length > 2500;
if (!tooLongToFormat) {
Prism.highlightAll();
}
}, [method]);
const source = method ? method.source : "";
return (
<pre><code className="language-smalltalk">{source}</code></pre>
);
}
export default MethodSource;<file_sep>import {useFetch} from "../utils/useFetch";
import React from "react";
const ClassInfo = ({ match }) => {
const {data, loading} = useFetch(`/core/class_names/${match.params.name}`);
if (loading) {
return (
<React.Fragment>
<h3>Class: {match.params.name}</h3>
<p>Loading ...</p>
</React.Fragment>
)
}
return (
<React.Fragment>
<h3>Class: {data.name}</h3>
<p>{JSON.stringify(data)}</p>
</React.Fragment>
);
};
export default ClassInfo;<file_sep>import React, {useState} from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import {Container, Card} from 'react-bootstrap';
import {spiderFetch, useFetch} from "../utils/useFetch";
import RepoBrowser from "./repobrowser";
import Search from "../panels/search/search.js";
import CommitCodeBrowser from "./commitcodebrowser";
import Topmenu from "./topmenu/topmenu";
import PackageInfo from "../panels/packageinfo";
import GitAuthorInfo from "../panels/gitauthorinfo";
import MCAuthorInfo from "../panels/mcauthorinfo";
import GitRepoInfo from "../panels/gitrepoinfo";
import ClassInfo from "../panels/classinfo";
import GitRepos from "../panels/gitrepos";
import SelectorInfo from "../panels/selectorinfo";
function getCommitPackages(repo, commitId, setter) {
spiderFetch(`/git/repos/${repo.domain}/${repo.owner}/${repo.name}/commit/${commitId}`, setter);
}
const Main = () => {
return (
<Router basename="/spider">
<Topmenu/>
<Container>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/index.html" component={Home}/>
<Route path="/browse/:domain/:owner/:name/commit/:commitId" component={BrowseCommit}/>
<Route path="/browse/:domain/:owner/:name/branch/:branch" component={BrowseBranch}/>
<Route path="/browse/:domain/:owner/:name/tag/:tag" component={BrowseTag}/>
<Route path="/search" component={SearchPanel}/>
<Route path="/package_names/:name" component={PackageInfo} />
<Route path="/class_names/:name" component={ClassInfo} />
<Route path="/selectors/:name" component={SelectorInfo} />
<Route path="/mc_authors/:name" component={MCAuthorInfo} />
<Route path="/git_repos/:domain/:owner/:name" component={GitRepoInfo} />
<Route path="/git_repos" component={GitRepos} />
<Route path="/git_authors/:name" component={GitAuthorInfo} />
</Switch>
</Container>
</Router>
);
}
const Home = () => {
const [selectedCommit, setSelectedCommit] = useState(null);
return (
<React.Fragment>
<h1>spider-browser-react</h1>
<RepoBrowser onSelectionChange={(repo, commitId) => getCommitPackages(repo, commitId, setSelectedCommit)}/>
{selectedCommit && (
<CommitCodeBrowser commit={selectedCommit}/>
)}
</React.Fragment>
);
}
const BrowseCommit = ({match}) => {
const {data, loading} = useFetch(`/git/repos/${match.params.domain}/${match.params.owner}/${match.params.name}/commit/${match.params.commitId}`);
return loading ? (<Container fluid>
<Card>
<Card.Body>
<Card.Title>Loading ...</Card.Title>
<p>domain: {match.params.domain}</p>
<p>owner: {match.params.owner}</p>
<p>name: {match.params.name}</p>
<p>commitId: {match.params.commitId}</p>
</Card.Body>
</Card>
</Container>) : (
<Container fluid><CommitCodeBrowser commit={data}/></Container>
)
}
const BrowseBranch = ({match}) => {
const {data, loading} = useFetch(`/git/repos/${match.params.domain}/${match.params.owner}/${match.params.name}/branch/${match.params.branch}`);
return loading ? (<div>
<h1>Loading ...</h1>
<p>domain: {match.params.domain}</p>
<p>owner: {match.params.owner}</p>
<p>name: {match.params.name}</p>
<p>branch: {match.params.branch}</p>
</div>) : (
<Container fluid><CommitCodeBrowser commit={data.commit}/></Container>
)
}
const BrowseTag = ({match}) => {
const {data, loading} = useFetch(`/git/repos/${match.params.domain}/${match.params.owner}/${match.params.name}/tag/${match.params.tag}`);
return loading ? (<div>
<h1>Loading ...</h1>
<p>domain: {match.params.domain}</p>
<p>owner: {match.params.owner}</p>
<p>name: {match.params.name}</p>
<p>tag: {match.params.tag}</p>
</div>) : (
<Container fluid><CommitCodeBrowser commit={data.commit}/></Container>
)
}
const SearchPanel = () => {
return (
<React.Fragment>
<h1>spider-browser-react - Search</h1>
<Search/>
</React.Fragment>
);
}
export default Main;<file_sep>import {useFetch} from "../utils/useFetch";
import {Row,Col,Dropdown} from 'react-bootstrap';
import React, {useState} from "react";
const GitRepoFullname = (match) => {
return match.params.domain + "/" + match.params.owner + "/" + match.params.name;
}
const GitRefSelector = ({ label, list, selected }) => {
return (
<Dropdown>
<Dropdown.Toggle variant="success" id="dropdown-basic">
{label}
</Dropdown.Toggle>
<Dropdown.Menu>
{list.map(item => (
<Dropdown.Item key={item.sha} href="#/action-1">{item.name}</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
);
};
const GitRepoInfo = ({ match }) => {
const {data, loading} = useFetch(`/git/repos/${match.params.domain}/${match.params.owner}/${match.params.name}`);
const [selectedBranch, setSelectedBranch] = useState("");
const [selectedTag, setSelectedTag] = useState({});
if (loading) {
return (
<React.Fragment>
<h3>Git repository: {GitRepoFullname(match)}</h3>
<p>Loading ...</p>
</React.Fragment>
)
}
return (
<React.Fragment>
<h3>Git repository: {GitRepoFullname(match)}</h3>
<Row>
<Col><GitRefSelector label="Branch" list={data.branches} selected={selectedBranch}/></Col>
<Col><GitRefSelector label="Tag" list={data.tags} selected={selectedTag}/></Col>
</Row>
<p>{JSON.stringify(data)}</p>
</React.Fragment>
);
};
export default GitRepoInfo;<file_sep>
<p>
<a href="https://www.cloudctrl.com/git/repos/GitHub/svenvc">
GitHub repositories from owner
</a>
</p>
<p>
<a href="https://www.cloudctrl.com/git/repos/GitHub/svenvc/P3">
GitHub repository details
</a>
</p>
<p>
<a href="https://www.cloudctrl.com/git/repos/GitHub/svenvc/P3/commit/2fe6124985e4<PASSWORD>b28fbe7<PASSWORD>">
GitHub commit details
</a>
</p>
<p>
<a href="https://www.cloudctrl.com/git/diff/GitHub/svenvc/P3/commit/2fe6<PASSWORD>">
A Git diff request with a class comment change
</a>
</p>2542<file_sep>import React from "react";
import {ListGroup} from "react-bootstrap";
function getMethodList(clazz, instanceSide, category) {
if (!clazz) {
return [];
}
var list = instanceSide ? clazz.instanceMethods : clazz.classMethods;
if (category) {
list = list.filter(m => category === m.category);
}
return list;
}
function isActiveMethod(m, selection) {
return selection ? m.id === selection.id : false;
}
const MethodList = ({clazz, instanceSide, category, selection, onSelectionChange}) => {
const methodList = getMethodList(clazz, instanceSide, category);
return (
<ListGroup variant="spider list-group-flush">
{methodList.map(each => (
<ListGroup.Item key={each.id} action active={isActiveMethod(each, selection)} variant="spider"
onClick={() => onSelectionChange(each)}>
{each.selector}
</ListGroup.Item>
))}
</ListGroup>
);
}
export default MethodList;
<file_sep>import React from "react";
import {ListGroup} from "react-bootstrap";
const category_all = "--- all ---";
function getCategoryList(clazz, instanceSide) {
if (!clazz) {
return [];
}
var names = [];
const methods = instanceSide ? clazz.instanceMethods : clazz.classMethods;
methods.forEach((m) => {
if (m.category && !names.includes(m.category)) {
names.push(m.category);
}
});
names.sort();
names.unshift(category_all);
return names;
}
function handleSelection(categoryName, onSelectionChange) {
if (categoryName === category_all) {
onSelectionChange(null);
} else {
onSelectionChange(categoryName);
}
}
function isActiveCategory(name, selection) {
return selection ? name === selection : name === category_all;
}
const MethodCategoryList = ({clazz, instanceSide, selection, onSelectionChange}) => {
const list = getCategoryList(clazz, instanceSide);
return (
<ListGroup variant="spider list-group-flush">
{list.map(each => (
<ListGroup.Item key={each} variant="spider" action active={isActiveCategory(each, selection)}
onClick={() => handleSelection(each, onSelectionChange)}>
{each}
</ListGroup.Item>
))}
</ListGroup>
);
}
export default MethodCategoryList;
<file_sep>import React from "react";
import {Link} from "react-router-dom";
const SearchResultList = ({ name, path, list }) => {
return (
<React.Fragment>
<h3>{name}</h3>
<ul>
{list.map(item => (
<li key={item}><Link to={path + "/" + item }>{item}</Link></li>
))}
</ul>
</React.Fragment>
);
};
export default SearchResultList;<file_sep>import React from "react";
import { formatTimestamp, formatSha } from "../utils/format";
const CodeFooter = ({selectedPackage, selectedClass, selectedMethod}) => {
var gitCommit = null;
var entity = "";
if (selectedMethod != null) {
gitCommit = selectedMethod.gitCommit;
entity = "Method";
} else if (selectedClass != null) {
gitCommit = selectedClass.gitCommit;
entity = "Class";
} else if (selectedPackage != null) {
gitCommit = selectedPackage.gitCommit;
entity = "Package";
}
if (gitCommit == null) {
return "";
}
return (
<div>
{entity} edtion: {formatSha(gitCommit.sha)} {gitCommit.authorName} {formatTimestamp(gitCommit.datetime)} - {gitCommit.messageLine}
</div>
);
}
export default CodeFooter;
<file_sep>import {useState, useEffect} from "react";
const rest_headers = new Headers({
"Content-Type": "application/json"
});
//const baseUrl = "https://www.cloudctrl.com";
const baseUrl = "http://localhost:8080"
function spiderFetch(path, setter) {
fetch(baseUrl + path, {
crossDomain: true,
method: "GET",
rest_headers
})
.then(res => res.json())
.then(data => setter(data));
}
function useFetch(path) {
const url = baseUrl + path;
const [data, setDataState] = useState(null);
const [loading, setLoadingState] = useState(true);
useEffect(
() => {
setLoadingState(true);
fetch(url)
.then(j => j.json())
.then(data => {
setDataState(data);
setLoadingState(false);
});
},
[url]
);
return {data, loading};
}
export { spiderFetch, useFetch }<file_sep>import React from "react";
import {Row, Col} from 'react-bootstrap';
import {spiderFetch, useFetch} from "../utils/useFetch";
import RepoList from "./repolist";
import RepoDetails from "./repodetails";
class RepoBrowser extends React.Component {
constructor(props) {
super(props);
this.state = {
repos: [],
selectedRepo: null,
selectedRepoDetails: null
};
this.handleSelectedRepoChange = this.handleSelectedRepoChange.bind(this);
}
handleSelectedRepoChange(repo) {
this.setState({selectedRepo: repo});
this.getRepoDetails(repo);
}
render() {
return (
<React.Fragment>
<Row>
<Col>
<h2>Repositories</h2>
</Col>
</Row>
<Row style={{"height": "300px"}}>
<Col style={{"height": "100%"}}>
<RepoList
repos={this.state.repos}
onSelectionChange={this.handleSelectedRepoChange}
/>
</Col>
<Col>
<RepoDetails
repo={this.state.selectedRepoDetails}
onSelectionChange={(sha) => this.props.onSelectionChange(this.state.selectedRepo, sha)}
/>
</Col>
</Row>
</React.Fragment>
);
}
componentDidMount() {
spiderFetch("/git/repos", data => {
this.setState({repos: data.list});
});
}
getRepoDetails(repo) {
spiderFetch(`/git/repos/${repo.domain}/${repo.owner}/${repo.name}`, data => {
this.setState({selectedRepoDetails: data});
});
}
}
export default RepoBrowser;
<file_sep>import React from "react";
import {spiderFetch, useFetch} from "../utils/useFetch";
import history from "../utils/history";
import PackageList from "./packagelist";
import ClassList from "./classlist";
import ClassInstSwitch from "./classinstswitch";
import ClassDefinition from "./classdefinition";
import MethodCategoryList from "./methodcategorylist";
import MethodList from "./methodlist";
import MethodSource from "./methodsource";
import CodeFooter from "./codefooter";
class CodeBrowser extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedPackage: null,
selectedClass: null,
instanceSide: true,
selectedMethodCategory: null,
selectedMethod: null,
};
this.handleSelectedPackageChange = this.handleSelectedPackageChange.bind(
this
);
this.handleSelectedClassChange = this.handleSelectedClassChange.bind(this);
this.handleClassInstSwitch = this.handleClassInstSwitch.bind(this);
this.handleSelectedMethodChange = this.handleSelectedMethodChange.bind(
this
);
this.handleSelectedMethodCategoryChange = this.handleSelectedMethodCategoryChange.bind(
this
);
if (this.props.selectedCommitSha != null) {
this.getCommitPackages(this.props.selectedCommitSha);
}
}
// currentPath() {
// let path = this.props.basePath;
// if (this.state.selectedPackage) {
// path = path + "/" + this.state.selectedPackage.name;
// if (this.state.selectedClass) {
// path = path + "/" + this.state.selectedClass.name;
// if (this.state.selectedMethod) {
// path = path + "/" + (this.state.instanceSide ? "instance" : "class") + "/" + this.state.selectedMethod.selector;
// }
// }
// }
// return path;
// }
handleSelectedPackageChange(pack) {
this.handleSelectedClassChange(null);
if (pack === null) {
this.setState({selectedPackage: null});
} else {
this.getPackageDetails(pack.id, this.props.gitRootId);
}
}
handleSelectedClassChange(clazz) {
this.handleSelectedMethodCategoryChange(null);
this.handleSelectedMethodChange(null);
if (clazz === null) {
this.setState({selectedClass: null});
} else {
this.getClassDetails(clazz.id, this.state.selectedPackage.id, this.props.gitRootId);
}
}
handleClassInstSwitch() {
this.setState({instanceSide: !this.state.instanceSide});
}
handleSelectedMethodCategoryChange(name) {
this.setState({selectedMethodCategory: name});
}
handleSelectedMethodChange(method) {
if (method === null) {
this.setState({selectedMethod: null});
} else {
this.getMethodDetails(method.id, this.state.selectedClass.name, !this.state.instanceSide, this.props.gitRootId);
}
}
checkSelectedPackage() {
if (!this.state.selectedPackage) {
return;
}
// Clear the selected package if it is not part of the packages list
if (!this.props.packages.some((p) => p.id === this.state.selectedPackage.id)) {
this.handleSelectedPackageChange(null);
}
}
render() {
this.checkSelectedPackage();
const source = this.state.selectedMethod === null ?
<ClassDefinition clazz={this.state.selectedClass} instanceSide={this.state.instanceSide} /> :
<MethodSource method={this.state.selectedMethod}/>;
return (
<React.Fragment>
<div className="spider-codebrowser">
<div>
<PackageList
packages={this.props.packages}
selection={this.state.selectedPackage}
onSelectionChange={this.handleSelectedPackageChange}
/>
</div>
<div>
<ClassList
pack={this.state.selectedPackage}
selection={this.state.selectedClass}
onSelectionChange={this.handleSelectedClassChange}
/>
</div>
<div>
<MethodCategoryList
clazz={this.state.selectedClass}
instanceSide={this.state.instanceSide}
selection={this.state.selectedMethodCategory}
onSelectionChange={this.handleSelectedMethodCategoryChange}
/>
</div>
<div>
<MethodList
clazz={this.state.selectedClass}
instanceSide={this.state.instanceSide}
category={this.state.selectedMethodCategory}
selection={this.state.selectedMethod}
onSelectionChange={this.handleSelectedMethodChange}
/>
</div>
<div className="controls">
<ClassInstSwitch
instanceSide={this.state.instanceSide}
onSwitch={this.handleClassInstSwitch}
/>
</div>
<div className="source">
{source}
</div>
<div className="footer">
<CodeFooter
selectedPackage={this.state.selectedPackage}
selectedClass={this.state.selectedClass}
selectedMethod={this.state.selectedMethod} />
</div>
</div>
</React.Fragment>
);
}
getPackageDetails(packageId, gitRootId) {
spiderFetch(`/core/packages/${packageId}?gitRootId=${gitRootId}`, data => {
this.setState({selectedPackage: data});
});
}
getClassDetails(classId, packageId, gitRootId) {
spiderFetch(`/core/classes/${classId}?packageId=${packageId}&gitRootId=${gitRootId}`, data => {
this.setState({selectedClass: data});
});
}
getMethodDetails(methodId, className, isMeta, gitRootId) {
spiderFetch(`/core/methods/${methodId}?className=${className}&isMeta=${isMeta}&gitRootId=${gitRootId}`, data => {
this.setState({selectedMethod: data});
});
}
}
export default CodeBrowser;
<file_sep>import React from "react";
import {Link} from "react-router-dom";
const GitRepoLink = ({ repo }) => {
return (
<Link to={"/git_repos/" + repo.domain + "/" + repo.owner + "/" + repo.name}>
{repo.domain} / {repo.owner} / {repo.name}
</Link>
);
};
export default GitRepoLink;
<file_sep>import {useFetch} from "../utils/useFetch";
import React from "react";
const SelectorInfo = ({ match }) => {
const {data, loading} = useFetch(`/core/selectors/${match.params.name}`);
if (loading) {
return (
<React.Fragment>
<h3>Selector: {match.params.name}</h3>
<p>Loading ...</p>
</React.Fragment>
)
}
return (
<React.Fragment>
<h3>Selector: {data.name}</h3>
<p>{JSON.stringify(data)}</p>
</React.Fragment>
);
};
export default SelectorInfo;<file_sep>import React, {useState} from "react";
import { Col } from 'react-bootstrap';
import Form from 'react-bootstrap/Form';
import {spiderFetch} from "../../utils/useFetch";
import SearchResults from "./searchresults";
const Search = () => {
const [term, setTerm] = useState("");
const [result, setResult] = useState({});
const [fetchPackages, setFetchPackages] = useState(true);
const [fetchClasses, setFetchClasses] = useState(true);
const [fetchSelectors, setFetchSelectors] = useState(true);
const doSearch = (seachtString) => {
if (isValidTerm(seachtString)) {
spiderFetch(`/core/search?q=${seachtString}`, data => {
setResult(data);
});
} else {
setResult({});
}
}
const isValidTerm = (input) => {
return input.length > 2;
}
const handleChange = (event) => {
setTerm(event.target.value);
doSearch(event.target.value);
}
return (
<React.Fragment>
<Form>
<Form.Row>
<Col>
<Form.Control autoFocus placeholder="Search" onChange={(event) => handleChange(event)} />
</Col>
</Form.Row>
</Form>
<SearchResults results={result} />
</React.Fragment>
);
};
export default Search;
<file_sep>import React from "react";
const ClassInstSwitch = ({ onSwitch, instanceSide }) => {
if (instanceSide) {
return (
<div>
<strong>Inst. Side</strong>{" "}
<button onClick={() => onSwitch()}>Class Side</button>
</div>
);
} else {
return (
<div>
<button onClick={() => onSwitch()}>Inst. Side</button>{" "}
<strong>Class Side</strong>
</div>
);
}
};
export default ClassInstSwitch;
<file_sep>import React from "react";
import {useFetch} from "../utils/useFetch";
import {formatSha, formatTimestamp} from "../utils/format";
import {Card, ListGroup} from "react-bootstrap";
import {Link} from "react-router-dom";
const CommaIfNotLast = ({ list, index }) => {
//console.log("list.length = " + list.length + " index = " + index)
if (list.length === index+1) {
return null;
}
return (<React.Fragment>, </React.Fragment>);
};
const GitCommitLine = ({ titlePrefix, commit }) => {
return (
<React.Fragment>
<div className="d-flex w-100 justify-content-between">
<h5>{titlePrefix}{formatTimestamp(commit.datetime)} by {commit.authorName}</h5>
<small>{formatSha(commit.sha)}</small>
</div>
<p>{commit.messageLine}</p>
</React.Fragment>
);
};
const MCPackageLine = ({ titlePrefix, mcPackage }) => {
return (
<React.Fragment>
<div className="d-flex w-100 justify-content-between">
<h5>{titlePrefix}{formatTimestamp(mcPackage.datetime)} by {mcPackage.author}</h5>
<small>{formatSha(mcPackage.uuid)}</small>
</div>
<p>{mcPackage.message}</p>
</React.Fragment>
);
};
const GitRepoList = ({ list}) => {
return (
<Card>
<Card.Header><strong>Git Repositories</strong></Card.Header>
<ListGroup>
{list.map(each => (
<ListGroup.Item>{each.domain} / {each.owner} / {each.name}</ListGroup.Item>
))}
</ListGroup>
</Card>
);
};
const MCRepoList = ({ list}) => {
return (
<Card>
<Card.Header><strong>Monticello Repositories</strong></Card.Header>
<ListGroup>
{list.map(each => (
<ListGroup.Item>{each.repoUrl}</ListGroup.Item>
))}
</ListGroup>
</Card>
);
}
const GitAuthorsList = ({ list }) => {
return (
<React.Fragment>
{list.map((each, index) => (
<React.Fragment key={index}>
<Link to={"/git_authors/" + each.author}>{each.author}</Link> ({each.count})
<CommaIfNotLast list={list} index={index} />
</React.Fragment>
))}
</React.Fragment>
);
};
const MCAuthorsList = ({ list }) => {
return (
<React.Fragment>
{list.map((each, index) => (
<React.Fragment key={index}>
<Link to={"/mc_authors/" + each.author}>{each.author}</Link> ({each.count})
<CommaIfNotLast list={list} index={index} />
</React.Fragment>
))}
</React.Fragment>
);
};
const PackageGitInfo = ({ data }) => {
return (
<React.Fragment>
<GitRepoList list={data.gitRepos} />
<Card>
<Card.Header><strong>Git Commits</strong></Card.Header>
<ListGroup>
<ListGroup.Item><GitCommitLine titlePrefix="Oldest Commit: " commit={data.oldestGitCommit} /></ListGroup.Item>
<ListGroup.Item><GitCommitLine titlePrefix="Newest Commit: " commit={data.newestGitCommit}/></ListGroup.Item>
<ListGroup.Item>Authors: <GitAuthorsList list={data.gitAuthors}/></ListGroup.Item>
</ListGroup>
</Card>
</React.Fragment>
);
};
const PackageMCInfo = ({ data }) => {
return (
<React.Fragment>
<MCRepoList list={data.mcRepos} />
<Card>
<Card.Header><strong>Monticello Packages</strong></Card.Header>
<ListGroup>
<ListGroup.Item><MCPackageLine titlePrefix="Oldest: " mcPackage={data.oldestMCPackage} /></ListGroup.Item>
<ListGroup.Item><MCPackageLine titlePrefix="Newest: " mcPackage={data.newestMCPackage}/></ListGroup.Item>
<ListGroup.Item>Author(s): <MCAuthorsList list={data.mcAuthors}/></ListGroup.Item>
</ListGroup>
</Card>
</React.Fragment>
);
};
const PackageInfo = ({ match }) => {
const {data, loading} = useFetch(`/core/package_names/${match.params.name}`);
if (loading) {
return (
<React.Fragment>
<h3>Package: {match.params.name}</h3>
<p>Loading ...</p>
</React.Fragment>
)
}
return (
<React.Fragment>
<h3>Package: {data.name}</h3>
{data.oldestGitCommit &&
<PackageGitInfo data={data} />
}
{data.oldestMCPackage &&
<PackageMCInfo data={data} />
}
</React.Fragment>
);
};
export default PackageInfo;<file_sep>import React from "react";
import {useFetch} from "../utils/useFetch";
function diffPackageName(diff) {
return diff.newPackage ? diff.newPackage.name : diff.oldPackage.name;
}
const CommitDiffBrowser = ({ repo, commitId }) => {
const {diffs, loading} = useFetch(`/git/diff/${repo.domain}/${repo.owner}/${repo.name}/commit/${commitId}`);
if (loading) {
return (<div>Loading ...</div>);
}
return (
<div>
{diffs.map(each => (
<li>package: {diffPackageName(each)}</li>
))}
</div>
)
}
export default CommitDiffBrowser; | c4f0f1b2cdb60416ff1963f04970a904a22dc97c | [
"JavaScript",
"HTML"
] | 19 | JavaScript | jvdsandt/spider-browser-react | ffe3d1add3afdc8fe5647570e7695e3caa8c82c8 | 92e62dc3fee6f6a9145bc380338cecea0b5462b8 |
refs/heads/master | <file_sep>package com.maximcuker.cryptocurrencyinfo.domain.model
import com.maximcuker.cryptocurrencyinfo.data.remote.dto.TeamMember
data class CoinDetail(
val coinId:String,
val name: String,
val description: String,
val symbol: String,
val rank: Int,
val isActive: Boolean,
val tags: List<String>,
val team: List<TeamMember>
)
<file_sep>package com.maximcuker.cryptocurrencyinfo.data.remote.dto
import com.google.gson.annotations.SerializedName
import com.maximcuker.cryptocurrencyinfo.domain.model.Coin
data class CoinDto(
val id: String,
@SerializedName("is_active")
val isActive: Boolean,
@SerializedName("is_new")
val isNew: Boolean,
val name: String,
val rank: Int,
val symbol: String,
val type: String
)
fun CoinDto.toCoin(): Coin {
return Coin(id, isActive, name, rank, symbol)
}<file_sep>package com.maximcuker.cryptocurrencyinfo.data.repository
import com.maximcuker.cryptocurrencyinfo.data.remote.CoinPaprikaApi
import com.maximcuker.cryptocurrencyinfo.data.remote.dto.CoinDetailDto
import com.maximcuker.cryptocurrencyinfo.data.remote.dto.CoinDto
import com.maximcuker.cryptocurrencyinfo.domain.repository.CoinRepository
import javax.inject.Inject
class CoinRepositoryImpl @Inject constructor(
private val api: CoinPaprikaApi
): CoinRepository{
override suspend fun getCoins(): List<CoinDto> {
return api.getCoins()
}
override suspend fun getCoinById(coinId: String): CoinDetailDto {
return api.getCoinById(coinId)
}
}<file_sep>package com.maximcuker.cryptocurrencyinfo.domain.repository
import com.maximcuker.cryptocurrencyinfo.data.remote.dto.CoinDetailDto
import com.maximcuker.cryptocurrencyinfo.data.remote.dto.CoinDto
interface CoinRepository {
suspend fun getCoins(): List<CoinDto>
suspend fun getCoinById(coinId:String): CoinDetailDto
}<file_sep>package com.maximcuker.cryptocurrencyinfo.presentation.coin_detail
import com.maximcuker.cryptocurrencyinfo.domain.model.Coin
import com.maximcuker.cryptocurrencyinfo.domain.model.CoinDetail
data class CoinDetailState(
val isLoading: Boolean = false,
val coin: CoinDetail? = null,
val error: String = ""
)
| 72a23c9c82ad4333bd1187d6e5e1b406c49c96a5 | [
"Kotlin"
] | 5 | Kotlin | maximilian6547s/CryptoCurrencyInfo | 13a298a00adb445c781feeabf210408a91837c2f | 369244093835b5fcd2251f2a3717f70ef389719c |
refs/heads/master | <repo_name>aditya-attawar/Autonomous-Differential-Drive-Robot<file_sep>/final_fuzzy_nbt.ino
#include "fis_header.h"
// Number of inputs to the fuzzy inference system
const int fis_gcI = 1;
// Number of outputs to the fuzzy inference system
const int fis_gcO = 1;
// Number of rules to the fuzzy inference system
const int fis_gcR = 3;
FIS_TYPE g_fisInput[fis_gcI];
FIS_TYPE g_fisOutput[fis_gcO];
const int trig_M = 23;
const int echo_M = 25;
const int trig_L = 28;
const int echo_L = 32;
const int trig_R = 24;
const int echo_R = 22;
const int FL1 = 38;
const int FL2 = 40;
const int EN_FL = 8;
const int FR1 = 31;
const int FR2 = 33;
const int EN_FR = 5;
const int RL1 = 42;
const int RL2 = 44;
const int EN_RL = 10;
const int RR1 = 37;
const int RR2 = 39;
const int EN_RR = 4;
const int hall = 48;
const float r = 3.5;
const float pi = 3.14;
const int led = 52;
const int bluetooth = 50;
int project_done;
long dura;
int dist;
int ultrasonic(int,int);
long pulse;
int check;
void rotations();
int rot_en;
int p_yp;
int p_yn;
int p_xp;
int p_xn;
int a;
int b;
int y_d;
int x_d;
int turn;
int comp;
int state;
float x;
float y;
float x_dest;
float y_dest;
float x_final;
float y_final;
void straight();
void right(int,int);
void left(int,int);
void stop_motors();
void updatea();
void checkxy();
void location();
void opposite_d();
void compensation();
void setup()
{
pinMode(trig_M, OUTPUT);
pinMode(echo_M, INPUT);
pinMode(trig_L, OUTPUT);
pinMode(echo_L, INPUT);
pinMode(trig_R, OUTPUT);
pinMode(echo_R, INPUT);
pinMode(FL1, OUTPUT);
pinMode(FL2, OUTPUT);
pinMode(EN_FL, OUTPUT);
pinMode(RL1, OUTPUT);
pinMode(RL2, OUTPUT);
pinMode(EN_RL, OUTPUT);
pinMode(FR1, OUTPUT);
pinMode(FR2, OUTPUT);
pinMode(EN_FR, OUTPUT);
pinMode(RR1, OUTPUT);
pinMode(RR2, OUTPUT);
pinMode(EN_RR, OUTPUT);
pinMode(hall, INPUT);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
pinMode(bluetooth, INPUT);
digitalWrite(bluetooth, LOW);
Serial.begin(9600);
delay(150);
check=1;
rot_en=1;
a=1;/*Y Axis*/
b=1;/*Positive direction*/
turn=0;
x=0;
y=0;
x_final=0;
y_final=0;
x_dest=60;
y_dest=60;
p_yp=0;
p_yn=0;
p_xp=0;
p_xn=0;
project_done=0;
comp = 0;
state=0;
}
void loop()
{
state=digitalRead(bluetooth);
g_fisInput[0] = ultrasonic(trig_M,echo_M);
g_fisOutput[0] = 0;
fis_evaluate();
if(project_done == 0)
{
digitalWrite(led, LOW);
if(ultrasonic(trig_M,echo_M) >= 2 && ultrasonic(trig_R,echo_R) >= 2 && ultrasonic(trig_L,echo_L) >= 2)
{
checkxy();
location();
if(a==1)
{
if(b==1)
{
if((ultrasonic(trig_M,echo_M)>25 && y_final==0) || ((y_dest - y) < ultrasonic(trig_M,echo_M) && project_done == 0))
{
location();
checkxy();
opposite_d();
straight();
}
else if((ultrasonic(trig_L,echo_L)<=20) && (ultrasonic(trig_R,echo_R)<=20))
{
stop_motors();
}
else if(x == x_dest && y_final == 0)
{
if(ultrasonic(trig_L,echo_L) > ultrasonic(trig_R,echo_R))
{
left(a,b);
}
else
{
right(a,b);
}
}
else if((x_dest>x && (ultrasonic(trig_R,echo_R)>40) && project_done == 0) || (ultrasonic(trig_L,echo_L)<=20 && (project_done==0)) || ((x_dest - x) < ultrasonic(trig_R,echo_R) && project_done == 0))
{
right(a,b);
}
else if((x_dest<x && (ultrasonic(trig_L,echo_L)>40) && project_done == 0) || (ultrasonic(trig_R,echo_R)<=20 && (project_done==0)) || ((x - x_dest) < ultrasonic(trig_L,echo_L) && project_done == 0))
{
left(a,b);
}
else
{
stop_motors();
}
}
if(b==0)
{
if((ultrasonic(trig_M,echo_M)>25 && y_final==0) || ((y - y_dest) < ultrasonic(trig_M,echo_M) && project_done == 0))
{
location();
checkxy();
opposite_d();
straight();
}
else if((ultrasonic(trig_L,echo_L)<=20) && (ultrasonic(trig_R,echo_R)<=20))
{
stop_motors();
}
else if(x == x_dest && y_final == 0)
{
if(ultrasonic(trig_L,echo_L) > ultrasonic(trig_R,echo_R))
{
left(a,b);
}
else
{
right(a,b);
}
}
else if((x_dest>x && (ultrasonic(trig_L,echo_L)>40) && project_done == 0) || (ultrasonic(trig_R,echo_R)<=20 && (project_done==0)) || ((x_dest - x) < ultrasonic(trig_L,echo_L) && project_done == 0))
{
left(a,b);
}
else if((x_dest<x && (ultrasonic(trig_R,echo_R)>40) && project_done == 0) || (ultrasonic(trig_L,echo_L)<=20 && (project_done==0)) || ((x - x_dest) < ultrasonic(trig_R,echo_R) && project_done == 0))
{
right(a,b);
}
else
{
stop_motors();
}
}
}
if(a==0)
{
if(b==1)
{
if((ultrasonic(trig_M,echo_M)>25 && x_final==0) || ((x_dest - x) < ultrasonic(trig_M,echo_M) && project_done == 0))
{
location();
checkxy();
opposite_d();
straight();
}
else if((ultrasonic(trig_L,echo_L)<=20) && (ultrasonic(trig_R,echo_R)<=20))
{
stop_motors();
}
else if(y == y_dest && x_final == 0)
{
if(ultrasonic(trig_L,echo_L) > ultrasonic(trig_R,echo_R))
{
left(a,b);
}
else
{
right(a,b);
}
}
else if((y_dest>y && (ultrasonic(trig_L,echo_L)>40) && project_done == 0) || (ultrasonic(trig_R,echo_R)<=20 && (project_done==0)) || ((y_dest - y) < ultrasonic(trig_L,echo_L) && project_done == 0))
{
left(a,b);
}
else if((y_dest<y && (ultrasonic(trig_R,echo_R)>40) && project_done == 0) || (ultrasonic(trig_L,echo_L)<=20 && (project_done==0)) || ((y - y_dest) < ultrasonic(trig_R,echo_R) && project_done == 0))
{
right(a,b);
}
else
{
stop_motors();
}
}
if(b==0)
{
if((ultrasonic(trig_M,echo_M)>25 && x_final==0) || ((x - x_dest) < ultrasonic(trig_M,echo_M) && project_done == 0))
{
location();
checkxy();
opposite_d();
straight();
}
else if((ultrasonic(trig_L,echo_L)<=20) && (ultrasonic(trig_R,echo_R)<=20) && project_done==0)
{
stop_motors();
}
else if(y == y_dest && x_final == 0)
{
if(ultrasonic(trig_L,echo_L) > ultrasonic(trig_R,echo_R))
{
left(a,b);
}
else
{
right(a,b);
}
}
else if((y_dest>y && ultrasonic(trig_R,echo_R)>40 && project_done==0) || (ultrasonic(trig_L,echo_L)<=20 && project_done==0) || ((y_dest - y) < ultrasonic(trig_R,echo_R) && project_done == 0))
{
right(a,b);
}
else if((y_dest<y && ultrasonic(trig_L,echo_L)>40 && project_done==0) || (ultrasonic(trig_R,echo_R)<=20 && project_done==0) || ((y - y_dest) < ultrasonic(trig_L,echo_L) && project_done == 0))
{
left(a,b);
}
else {
stop_motors();
}
}
}
}
}
else
{
stop_motors();
}
}
void straight()
{
if(g_fisOutput[0] > 100)
{
rot_en=1;
digitalWrite(FL1, LOW);
digitalWrite(FL2, HIGH);
analogWrite(EN_FL , g_fisOutput[0]*0.80);
digitalWrite(FR1, HIGH);
digitalWrite(FR2, LOW);
analogWrite(EN_FR , g_fisOutput[0]*0.80);
digitalWrite(RL1, LOW);
digitalWrite(RL2, HIGH);
analogWrite(EN_RL , g_fisOutput[0]*0.80);
digitalWrite(RR1, HIGH);
digitalWrite(RR2, LOW);
analogWrite(EN_RR , g_fisOutput[0]*0.80);
}
else
{
rot_en=1;
digitalWrite(FL1, LOW);
digitalWrite(FL2, HIGH);
analogWrite(EN_FL , g_fisOutput[0]);
digitalWrite(FR1, HIGH);
digitalWrite(FR2, LOW);
analogWrite(EN_FR , g_fisOutput[0]);
digitalWrite(RL1, LOW);
digitalWrite(RL2, HIGH);
analogWrite(EN_RL , g_fisOutput[0]);
digitalWrite(RR1, HIGH);
digitalWrite(RR2, LOW);
analogWrite(EN_RR , g_fisOutput[0]);
}
}A
void right(int a,int b)
{
rot_en=0;
turn=1;
stop_motors();
digitalWrite(FL1, LOW);
digitalWrite(FL2, HIGH);
analogWrite(EN_FL, 250);
digitalWrite(FR1, LOW);
digitalWrite(FR2, LOW);
digitalWrite(RL1, LOW);
digitalWrite(RL2, HIGH);
analogWrite(EN_RL, 250);
digitalWrite(RR1, LOW);
digitalWrite(RR2, LOW);
delay(1100);
stop_motors();
updatea();
rot_en=1;
}
void left(int a,int b)
{
rot_en=0;
turn=2;
stop_motors();
digitalWrite(FL1, LOW);
digitalWrite(FL2, LOW);
digitalWrite(FR1, HIGH);
digitalWrite(FR2, LOW);
analogWrite(EN_FR, 250);
digitalWrite(RL1, LOW);
digitalWrite(RL2, LOW);
digitalWrite(RR1, HIGH);
digitalWrite(RR2, LOW);
analogWrite(EN_RR, 250);
delay(1100);
stop_motors();
updatea();
rot_en=1;
}
void stop_motors()
{
digitalWrite(FL1, LOW);
digitalWrite(FL2, LOW);
digitalWrite(FR1, LOW);
digitalWrite(FR2, LOW);
digitalWrite(RL1, LOW);
digitalWrite(RL2, LOW);
digitalWrite(RR1, LOW);
digitalWrite(RR2, LOW);
}
void updatea()
{
if(turn==1)
{
if(a==1)
{
a=0;
}
else
{
a=1;
if(b==1)
{
b=0;
}
else
{
b=1;
}
}
}
else
{
if(a==0)
{
a=1;
}
else
{
a=0;
if(b==1)
{
b=0;
}
else
{
b=1;
}
}
}
turn=0;
}
int ultrasonic(int trig,int echo)
{
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
dura = pulseIn(echo, HIGH);
dist = dura*0.034/2;
return(dist);
}
void location()
{
if(rot_en==1)
{
if(a==1)
{
if(b==1)
{
pulse=digitalRead(hall);
if(pulse==0)
{
if(check==1)
{
p_yp = p_yp+1;
check=0;
}
}
else if(pulse==1)
{
if(check==0)
{
p_yp = p_yp+1;
check=1;
}
}
}
else
{
pulse=digitalRead(hall);
if(pulse==0)
{
if(check==1)
{
p_yn = p_yn+1;
check=0;
}
}
else if(pulse==1)
{
if(check==0)
{
p_yn = p_yn+1;
check=1;
}
}
}
}
else
{
if(b==1)
{
pulse=digitalRead(hall);
if(pulse==0)
{
if(check==1)
{
p_xp = p_xp+1;
check=0;
}
}
else if(pulse==1)
{
if(check==0)
{
p_xp = p_xp+1;
check=1;
}
}
}
else
{
pulse=digitalRead(hall);
if(pulse==0)
{
if(check==1)
{
p_xn = p_xn+1;
check=0;
}
}
else if(pulse==1)
{
if(check==0)
{
p_xn = p_xn+1;
check=1;
}
}
}
}
}
y=(p_yp - p_yn)*2*pi*r/6;
x=(p_xp - p_xn)*2*pi*r/6;
Serial.println("Y=");
Serial.println(y);
Serial.println("X=");
Serial.println(x);
}
void checkxy()
{
if(abs(y-y_dest)<=3.66)
{
y_final=1;
stop_motors();
}
else
{
y_final=0;
}
if(abs(x-x_dest)<=3.66)
{
x_final=1;
stop_motors();
}
else
{
x_final=0;
}
if(x_final==1 && y_final==1)
{
project_done=1;
digitalWrite(led, HIGH);
}
}
void opposite_d()
{
if(project_done == 0)
{
if(y_dest-y >=0)
{
y_d=1;
}
else
{
y_d=0;
}
if(x_dest-x>=0)
{
x_d=1;
}
else
{
x_d=0;
}
if(a==1)
{
if(b==1)
{
if (y_d==0)
{
while(project_done == 0)
{
if((x_dest > x && ultrasonic(trig_R,echo_R)>40) || ((x > x_dest) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_L,echo_L) < 40))
{
right(a,b);
break;
}
if((x_dest < x && ultrasonic(trig_L,echo_L)>40) || ((x_dest > x) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_R,echo_R) < 40))
{
left(a,b);
break;
}
straight();
}
}
}
else
{
if(y_d == 1)
{
while(project_done == 0)
{
straight();
if((x_dest > x && ultrasonic(trig_L,echo_L)>40) || ((x > x_dest) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_R,echo_R) < 40))
{
left(a,b);
break;
}
if((x_dest < x && ultrasonic(trig_R,echo_R)>40) || ((x_dest > x) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_L,echo_L) < 40))
{
right(a,b);
break;
}
}
}
}
}
else
{
if(b==1)
{
if(x_d == 0)
{
while(project_done == 0)
{
straight();
if((y_dest > y && ultrasonic(trig_L,echo_L)>40) || ((y > y_dest) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_R,echo_R) < 40))
{
left(a,b);
break;
}
if((y_dest < y && ultrasonic(trig_R,echo_R)>40) || ((y_dest > y) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_L,echo_L) < 40))
{
right(a,b);
break;
}
}
}
}
else
{
if(x_d == 1)
{
while(project_done == 0)
{
straight();
if((y_dest > y && ultrasonic(trig_R,echo_R)>40) || ((y > y_dest) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_L,echo_L) < 40))
{
right(a,b);
break;
}
if((y_dest < y && ultrasonic(trig_L,echo_L)>40) || ((y_dest > y) && ultrasonic(trig_M,echo_M) < 25 && ultrasonic(trig_R,echo_R) < 40))
{
left(a,b);
break;
}
}
}
}
}
}
}
void compensation()
{
if (comp == 1)
{
if(a == 1)
{
if(b == 1)
{
if(turn == 1)
{
x = x + 23;
}
if(turn ==2)
{
x = x - 23;
}
}
else
{
if(turn == 1)
{
x = x - 23;
}
if(turn ==2)
{
x = x + 23;
}
}
}
else
{
if(b ==1)
{
if(turn == 1)
{
y = y - 23;
}
if(turn ==2)
{
y = y + 23;
}
}
else
{
if(turn == 1)
{
y = y + 23;
}
if(turn ==2)
{
y = y - 23;
}
}
}
}
else if(comp == 0)
{
if(a == 1)
{
if(b == 1)
{
if(turn == 1)
{
y = y + 18;
x = x + 23;
}
if(turn ==2)
{
y = y + 18;
x = x - 23;
}
}
else
{
if(turn == 1)
{
y = y - 18;
x = x - 23;
}
if(turn ==2)
{
y = y - 18;
x = x + 23;
}
}
}
else
{
if(b ==1)
{
if(turn == 1)
{
x = x + 18;
y = y - 23;
}
if(turn ==2)
{
x = x +18;
y = y + 23;
}
}
else
{
if(turn == 1)
{
x = x - 18;
y = y + 23;
}
if(turn ==2)
{
x = x - 18;
y = y - 23;
}
}
}
}
comp = 0;
}
//***********************************************************************
// Support functions for Fuzzy Inference System
//***********************************************************************
// Triangular Member Function
FIS_TYPE fis_trimf(FIS_TYPE x, FIS_TYPE* p)
{
FIS_TYPE a = p[0], b = p[1], c = p[2];
FIS_TYPE t1 = (x - a) / (b - a);
FIS_TYPE t2 = (c - x) / (c - b);
if ((a == b) && (b == c)) return (FIS_TYPE) (x == a);
if (a == b) return (FIS_TYPE) (t2*(b <= x)*(x <= c));
if (b == c) return (FIS_TYPE) (t1*(a <= x)*(x <= b));
t1 = min(t1, t2);
return (FIS_TYPE) max(t1, 0);
}
FIS_TYPE fis_min(FIS_TYPE a, FIS_TYPE b)
{
return min(a, b);
}
FIS_TYPE fis_max(FIS_TYPE a, FIS_TYPE b)
{
return max(a, b);
}
FIS_TYPE fis_array_operation(FIS_TYPE *array, int size, _FIS_ARR_OP pfnOp)
{
int i;
FIS_TYPE ret = 0;
if (size == 0) return ret;
if (size == 1) return array[0];
ret = array[0];
for (i = 1; i < size; i++)
{
ret = (*pfnOp)(ret, array[i]);
}
return ret;
}
//***********************************************************************
// Data for Fuzzy Inference System
//***********************************************************************
// Pointers to the implementations of member functions
_FIS_MF fis_gMF[] =
{
fis_trimf
};
// Count of member function for each Input
int fis_gIMFCount[] = { 3 };
// Count of member function for each Output
int fis_gOMFCount[] = { 3 };
// Coefficients for the Input Member Functions
FIS_TYPE fis_gMFI0Coeff1[] = { -9999999, 10, 25 };
FIS_TYPE fis_gMFI0Coeff2[] = { 20, 40, 60 };
FIS_TYPE fis_gMFI0Coeff3[] = { 40, 60, 9999999 };
FIS_TYPE* fis_gMFI0Coeff[] = { fis_gMFI0Coeff1, fis_gMFI0Coeff2, fis_gMFI0Coeff3 };
FIS_TYPE** fis_gMFICoeff[] = { fis_gMFI0Coeff };
// Coefficients for the Output Member Functions
FIS_TYPE fis_gMFO0Coeff1[] = { -104.2, 0, 104.2 };
FIS_TYPE fis_gMFO0Coeff2[] = { 20.83, 135, 250 };
FIS_TYPE fis_gMFO0Coeff3[] = { 250, 250, 354.2 };
FIS_TYPE* fis_gMFO0Coeff[] = { fis_gMFO0Coeff1, fis_gMFO0Coeff2, fis_gMFO0Coeff3 };
FIS_TYPE** fis_gMFOCoeff[] = { fis_gMFO0Coeff };
// Input membership function set
int fis_gMFI0[] = { 0, 0, 0 };
int* fis_gMFI[] = { fis_gMFI0};
// Output membership function set
int fis_gMFO0[] = { 0, 0, 0 };
int* fis_gMFO[] = { fis_gMFO0};
// Rule Weights
FIS_TYPE fis_gRWeight[] = { 1, 1, 1 };
// Rule Type
int fis_gRType[] = { 1, 1, 1 };
// Rule Inputs
int fis_gRI0[] = { 1 };
int fis_gRI1[] = { 2 };
int fis_gRI2[] = { 3 };
int* fis_gRI[] = { fis_gRI0, fis_gRI1, fis_gRI2 };
// Rule Outputs
int fis_gRO0[] = { 1 };
int fis_gRO1[] = { 2 };
int fis_gRO2[] = { 3 };
int* fis_gRO[] = { fis_gRO0, fis_gRO1, fis_gRO2 };
// Input range Min
FIS_TYPE fis_gIMin[] = { 0 };
// Input range Max
FIS_TYPE fis_gIMax[] = { 600 };
// Output range Min
FIS_TYPE fis_gOMin[] = { 0 };
// Output range Max
FIS_TYPE fis_gOMax[] = { 250 };
//***********************************************************************
// Data dependent support functions for Fuzzy Inference System
//***********************************************************************
FIS_TYPE fis_MF_out(FIS_TYPE** fuzzyRuleSet, FIS_TYPE x, int o)
{
FIS_TYPE mfOut;
int r;
for (r = 0; r < fis_gcR; ++r)
{
int index = fis_gRO[r][o];
if (index > 0)
{
index = index - 1;
mfOut = (fis_gMF[fis_gMFO[o][index]])(x, fis_gMFOCoeff[o][index]);
}
else if (index < 0)
{
index = -index - 1;
mfOut = 1 - (fis_gMF[fis_gMFO[o][index]])(x, fis_gMFOCoeff[o][index]);
}
else
{
mfOut = 0;
}
fuzzyRuleSet[0][r] = fis_min(mfOut, fuzzyRuleSet[1][r]);
}
return fis_array_operation(fuzzyRuleSet[0], fis_gcR, fis_max);
}
FIS_TYPE fis_defuzz_centroid(FIS_TYPE** fuzzyRuleSet, int o)
{
FIS_TYPE step = (fis_gOMax[o] - fis_gOMin[o]) / (FIS_RESOLUSION - 1);
FIS_TYPE area = 0;
FIS_TYPE momentum = 0;
FIS_TYPE dist, slice;
int i;
// calculate the area under the curve formed by the MF outputs
for (i = 0; i < FIS_RESOLUSION; ++i){
dist = fis_gOMin[o] + (step * i);
slice = step * fis_MF_out(fuzzyRuleSet, dist, o);
area += slice;
momentum += slice*dist;
}
return ((area == 0) ? ((fis_gOMax[o] + fis_gOMin[o]) / 2) : (momentum / area));
}
//***********************************************************************
// Fuzzy Inference System
//***********************************************************************
void fis_evaluate()
{
FIS_TYPE fuzzyInput0[] = { 0, 0, 0 };
FIS_TYPE* fuzzyInput[fis_gcI] = { fuzzyInput0, };
FIS_TYPE fuzzyOutput0[] = { 0, 0, 0 };
FIS_TYPE* fuzzyOutput[fis_gcO] = { fuzzyOutput0, };
FIS_TYPE fuzzyRules[fis_gcR] = { 0 };
FIS_TYPE fuzzyFires[fis_gcR] = { 0 };
FIS_TYPE* fuzzyRuleSet[] = { fuzzyRules, fuzzyFires };
FIS_TYPE sW = 0;
// Transforming input to fuzzy Input
int i, j, r, o;
for (i = 0; i < fis_gcI; ++i)
{
for (j = 0; j < fis_gIMFCount[i]; ++j)
{
fuzzyInput[i][j] =
(fis_gMF[fis_gMFI[i][j]])(g_fisInput[i], fis_gMFICoeff[i][j]);
}
}
int index = 0;
for (r = 0; r < fis_gcR; ++r)
{
if (fis_gRType[r] == 1)
{
fuzzyFires[r] = FIS_MAX;
for (i = 0; i < fis_gcI; ++i)
{
index = fis_gRI[r][i];
if (index > 0)
fuzzyFires[r] = fis_min(fuzzyFires[r], fuzzyInput[i][index - 1]);
else if (index < 0)
fuzzyFires[r] = fis_min(fuzzyFires[r], 1 - fuzzyInput[i][-index - 1]);
else
fuzzyFires[r] = fis_min(fuzzyFires[r], 1);
}
}
else
{
fuzzyFires[r] = FIS_MIN;
for (i = 0; i < fis_gcI; ++i)
{
index = fis_gRI[r][i];
if (index > 0)
fuzzyFires[r] = fis_max(fuzzyFires[r], fuzzyInput[i][index - 1]);
else if (index < 0)
fuzzyFires[r] = fis_max(fuzzyFires[r], 1 - fuzzyInput[i][-index - 1]);
else
fuzzyFires[r] = fis_max(fuzzyFires[r], 0);
}
}
fuzzyFires[r] = fis_gRWeight[r] * fuzzyFires[r];
sW += fuzzyFires[r];
}
if (sW == 0)
{
for (o = 0; o < fis_gcO; ++o)
{
g_fisOutput[o] = ((fis_gOMax[o] + fis_gOMin[o]) / 2);
}
}
else
{
for (o = 0; o < fis_gcO; ++o)
{
g_fisOutput[o] = fis_defuzz_centroid(fuzzyRuleSet, o);
}
}
}
| 0c155c1a87316580be5b2526d14d5ac1a85e4237 | [
"C++"
] | 1 | C++ | aditya-attawar/Autonomous-Differential-Drive-Robot | 880d044c54db4167d3999117cb1071954a0901b3 | 5e0ab418f00fc4011f3f8a2234e01287a0adcdb0 |
refs/heads/main | <file_sep># BlueD-PyDataIngestor
<file_sep>import pandas as pd
import sqlalchemy as sql
db_in = sql.create_engine('postgresql://pvczseja:X0_soxKtUMurTTbHzxe9ygObOxy9sb4R@<EMAIL>/pvczseja')
db_out= sql.create_engine('postgresql://nysggdyc:K137O8Co9J-pYpysZMo-QhKDuJ1FBVDn@batyr.db.elephantsql.com/nysggdyc')
#create output tables
def corn_table():
query = 'SELECT stock.date as date, market.corn_price as corn_price, stock.corn as corn_stock FROM "public"."grain_stocks" AS stock INNER JOIN (SELECT g.year_month as "date", g.corn as "corn_price" FROM "public"."grain_prices" AS g ) market ON market.date=stock.date ORDER BY "date";'
#ingest data
df=pd.read_sql_query(query,db_in)
#format date
df["date"] = pd.to_datetime(df["date"], format="%Y-%m")
#From bushels to tons
df["corn_price"] = df["corn_price"].apply(lambda x: x*39.368)
#rename colums
df.rename(columns={'corn_price':'price','corn_stock':'stock'}, inplace=True)
#save to output db
df.to_sql('corn_data',db_out,if_exists='replace',index=True, index_label='id')
#add pk
sql.text('ALTER TABLE "public"."corn_data" ADD PRIMARY KEY (id);',db_out)
def soy_table():
query = 'SELECT stock.date as date, market.soy_price as soy_price, stock.soybeans as soy_stock FROM "public"."grain_stocks" AS stock INNER JOIN (SELECT g.year_month as "date", g.soybean as "soy_price" FROM "public"."grain_prices" AS g ) market ON market.date=stock.date ORDER BY "date" ;'
#ingest data
df=pd.read_sql_query(query,db_in)
#format date
df["date"] = pd.to_datetime(df["date"], format="%Y-%m")
#From bushels to tons
df["soy_price"] = df["soy_price"].apply(lambda x: x*36.744)
#rename colums
df.rename(columns={'soy_price':'price','soy_stock':'stock'}, inplace=True)
#save to output db
df.to_sql('soy_data',db_out,if_exists='replace', index=True, index_label='id')
#add pk
sql.text('ALTER TABLE "public"."soy_data" ADD PRIMARY KEY (id);',db_out)
def usdx_table():
query = 'SELECT * FROM "public"."dollar_index";'
#ingest data
df=pd.read_sql_query(query,db_in)
#rename "year_month" column to "date"
df.rename(columns={'year_month':'date'}, inplace=True)
#format date
df["date"] = pd.to_datetime(df["date"], format="%Y-%m")
#save to output db
df.to_sql('usdx_data',db_out,if_exists='replace',index=True, index_label='id')
#add pk
sql.text('ALTER TABLE "public"."usdx_data" ADD PRIMARY KEY (id);',db_out)
print("[+]Processing...")
try:
corn_table()
soy_table()
usdx_table()
print("[+]done")
except:
print("[+]Unable to read/write data on databases. Check credentials and connection")
| 0c09f19edcff193ba8a9a1948688751b78b4b549 | [
"Markdown",
"Python"
] | 2 | Markdown | mpicatto/BlueD-PyDataIngestor | b63b348e7b14a01ad6bbf49feabf0c08d22306af | 28a063606cc0bc1991c5af75bd290620a35800b5 |
refs/heads/master | <repo_name>TBIkapp/loadgeneratorUI<file_sep>/src/main/java/com/mongodb/loadgenerator/BeanOptions.java
package com.mongodb.loadgenerator;
import java.io.Serializable;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.TextField;
public class BeanOptions implements Serializable {
/**
*
*/
private static final long serialVersionUID = -9018929944595965271L;
private TextField textField;
private CheckBox active;
private String opt;
private String longOpt;
private String description;
public BeanOptions(String opt, String longOpt, String description, String value, boolean active) {
this.setTextFieldValue(value);
this.setActive(active);
this.setOpt(opt);
this.setLongOpt(longOpt);
this.setDescription(description);
}
public TextField getTextField() {
return textField;
}
public void setTextFieldValue(String value) {
this.textField = new TextField(value);
this.textField.setValue(value);
}
public CheckBox getActive() {
return active;
}
public void setActive(boolean active) {
this.active = new CheckBox();
this.active.setValue(active);
}
public String getOpt() {
return opt;
}
public void setOpt(String opt) {
this.opt = opt;
}
public String getLongOpt() {
return longOpt;
}
public void setLongOpt(String longOpt) {
this.longOpt = longOpt;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return opt + " " + description + " " + textField.getValue();
}
}
<file_sep>/src/main/java/com/mongodb/loadgenerator/MyUIData.java
package com.mongodb.loadgenerator;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.VerticalLayout;
public class MyUIData extends VerticalLayout {
/**
*
*/
private static final long serialVersionUID = -643961441094143238L;
private Table tblOptions;
private Label lblParameter = new Label("");
private BeanContainer<String, BeanOptions> beans;
private Options cliopt;
private Button btnstartdriver;
private TextArea logArea;
private String lblvalue = "";
private boolean isRunning = false;
private MyUI ui;
private Button btnSetInsertParameters;
private Button btnSetQueryParameters;
private Button btnSetMyParameters;
private Button btnResetMyParameters;
private Options defineOptions() {
cliopt = new Options();
cliopt.addOption("a", "arrays", true, "Shape of any arrays in new sample records x:y so -a 12:60 adds an array of 12 length 60 arrays of integers");
cliopt.addOption("b", "bulksize", true, "Bulk op size (default 512)");
cliopt.addOption("c", "host", true, "Mongodb connection details (default 'mongodb://localhost:27017' )");
cliopt.addOption("d", "duration", true, "Test duration in seconds, default 18,000");
cliopt.addOption("e", "empty", false, "Remove data from collection on startup");
cliopt.addOption("f", "numfields", true, "Number of top level fields in test records (default 10)");
cliopt.addOption("g", "arrayupdates", true, "Ratio of array increment ops requires option 'a' (default 0)");
cliopt.addOption("h", "help", false, "Show Help");
cliopt.addOption("i", "inserts", true, "Ratio of insert operations (default 100)");
cliopt.addOption("j", "workingset", true, "Percentage of database to be the working set (default 100)");
cliopt.addOption("k", "keyqueries", true, "Ratio of key query operations (default 0)");
cliopt.addOption("l", "textfieldsize", true, "Length of text fields in bytes (default 30)");
cliopt.addOption("m", "findandmodify", false, "Use findandmodify instead of update and retireve record (with -u or -v only)");
cliopt.addOption("n", "namespace", true, "Namespace to use , for example myDatabase.myCollection");
cliopt.addOption("o", "logfile", true, "Output stats to <file> ");
cliopt.addOption("p", "print", false, "Print out a sample record according to the other parameters then quit");
cliopt.addOption("q", "opsPerSecond", true, "Try to rate limit the total ops/s to the specified ammount");
cliopt.addOption("r", "rangequeries", true, "Ratio of range query operations (default 0)");
cliopt.addOption("s", "slowthreshold", true, "Slow operation threshold in ms(default 50)");
cliopt.addOption("t", "threads", true, "Number of threads (default 4)");
cliopt.addOption("u", "updates", true, "Ratio of update operations (default 0)");
cliopt.addOption("v", "workflow", true, "Specify a set of ordered operations per thread from [iukp]");
cliopt.addOption("w", "nosharding", false, "Do not shard the collection");
cliopt.addOption("x", "indexes", true, "Number of secondary indexes - does not remove existing (default 0)");
return cliopt;
}
public MyUIData(MyUI ui) {
this.ui = ui;
cliopt = defineOptions();
beans = new BeanContainer<String, BeanOptions>(BeanOptions.class);
beans.setBeanIdProperty("opt");
for (Option opt : cliopt.getOptions()) {
beans.addBean(new BeanOptions(opt.getOpt(), opt.getLongOpt(), opt.getDescription(), "", false));
}
tblOptions = new Table("Load Generator Options", beans);
tblOptions.setHeight("100%");
// tblOptions.addValueChangeListener(valueChangeListenrTable);
tblOptions.setVisibleColumns(new Object[] { "active", "opt", "textField", "longOpt", "description" });
tblOptions.setColumnHeaders(new String[] { "active", "parameter", "value", "short desc", "desc" });
tblOptions.setPageLength(tblOptions.size());
btnSetInsertParameters = new Button("Set Insert Parameters");
btnSetInsertParameters.addClickListener(new ClickListener() {
/**
*
*/
private static final long serialVersionUID = 3431741180099701268L;
@Override
public void buttonClick(ClickEvent event) {
System.out.println("Insert Parameters");
setFillDBParameters();
}
});
btnSetQueryParameters = new Button("Set Query only Parameters");
btnSetQueryParameters.addClickListener(new ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
System.out.println("Query Only Parameters");
setQueryOnlyParameters();
}
});
btnSetMyParameters = new Button("Set My Parameters");
btnSetMyParameters.addClickListener(new ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
System.out.println("My selected Parameters");
setCurrentParameters();
}
});
btnResetMyParameters = new Button("Reset Parameters");
btnResetMyParameters.addClickListener(new ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
System.out.println("Reset Parameters");
resetParameters();
updateParameterLabel();
}
});
btnstartdriver = new Button("Start Driver");
btnstartdriver.addClickListener(new ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
if (!isRunning) {
btnstartdriver.setCaption("Stop Driver");
log("++++ Start the driver ++++");
activateConfigButtons(false);
ui.startThread();
} else {
btnstartdriver.setCaption("Stopping Driver");
log("==== Stop the driver ====");
ui.stopThread();
activateConfigButtons(true);
btnstartdriver.setCaption("Start Driver");
}
isRunning = !isRunning;
}
private void log(String string) {
logArea.setCursorPosition(logArea.getValue().length());
logArea.setValue(logArea.getValue() + "\n" + string);
logArea.setCursorPosition(logArea.getValue().length());
}
private void activateConfigButtons(boolean flag) {
btnResetMyParameters.setEnabled(flag);
btnSetInsertParameters.setEnabled(flag);
btnSetMyParameters.setEnabled(flag);
btnSetQueryParameters.setEnabled(flag);
}
});
HorizontalLayout layoutbuttons = new HorizontalLayout();
layoutbuttons.setMargin(true);
layoutbuttons.setSpacing(true);
layoutbuttons.addComponent(btnResetMyParameters);
layoutbuttons.addComponent(btnSetInsertParameters);
layoutbuttons.addComponent(btnSetQueryParameters);
layoutbuttons.addComponent(btnSetMyParameters);
layoutbuttons.addComponent(btnstartdriver);
HorizontalLayout layoutlbl = new HorizontalLayout();
layoutlbl.addComponent(lblParameter);
setTxtArea(new TextArea());
getTxtArea().setWidth("100%");
Label h1 = new Label("Visual PoC Driver");
h1.addStyleName("h1");
this.addComponent(h1);
this.addComponent(getTxtArea());
this.addComponent(layoutbuttons);
this.addComponent(layoutlbl);
this.addComponent(tblOptions);
// POCDriver pocdriver = new POCDriver();
// pocdriver.main(new String[]{"A", "B"});
this.setMargin(true);
this.setSpacing(true);
}
void setFillDBParameters() {
// -r 20 -k 20 -g 30 -a 5:10 -f 7 -i 40 -u 30 -c mongodb://tim:test@127.0.0.1:27000/test
unsetParameters();
setBeanParameters("r", "20", true);
setBeanParameters("k", "20", true);
setBeanParameters("g", "30", true);
setBeanParameters("a", "5:10", true);
setBeanParameters("f", "7", true);
setBeanParameters("i", "40", true);
setBeanParameters("u", "30", true);
setBeanParameters("c", "'mongodb://127.0.0.1:27000/test'", true);
updateParameterLabel();
beans.sort(new Object[] { "opt", "active" }, new boolean[] { true });
}
void updateParameterLabel() {
String lblprefixvalue = "java -jar POCDriver.jar ";
setLblvalue("");
for (String id : beans.getItemIds()) {
BeanOptions bean = beans.getItem(id).getBean();
if (!bean.getTextField().getValue().isEmpty() && bean.getActive().getValue()) {
setLblvalue(getLblvalue() + " -" + bean.getOpt() + " " + bean.getTextField().getValue());
}
}
lblParameter.setValue(lblprefixvalue + getLblvalue());
}
void setQueryOnlyParameters() {
// -r 20 -k 20 -g 30 -a 5:10 -u 20 -i 0 -s 20 -c mongodb://tim:test@127.0.0.1:27000/test
unsetParameters();
setBeanParameters("r", "20", true);
setBeanParameters("k", "20", true);
setBeanParameters("g", "30", true);
setBeanParameters("a", "5:10", true);
setBeanParameters("u", "30", true);
setBeanParameters("i", "40", true);
setBeanParameters("s", "20", true);
setBeanParameters("c", "'mongodb://127.0.0.1:27000/test'", true);
updateParameterLabel();
beans.sort(new Object[] { "opt", "active" }, new boolean[] { true });
}
void setBeanParameters(String id, String value, boolean active) {
BeanOptions bean = beans.getItem(id).getBean();
beans.removeItem(id);
bean.setActive(active);
bean.setTextFieldValue(value);
beans.addItem(id, bean);
}
void setCurrentParameters() {
updateParameterLabel();
}
void unsetParameters() {
for (String id : beans.getItemIds()) {
BeanOptions b = beans.getItem(id).getBean();
b.setActive(false);
b.setTextFieldValue("");
}
}
void resetParameters() {
beans.removeAllItems();
for (Option opt : cliopt.getOptions()) {
beans.addBean(new BeanOptions(opt.getOpt(), opt.getLongOpt(), opt.getDescription(), "", false));
}
}
public String getLblvalue() {
return lblvalue;
}
public void setLblvalue(String lblvalue) {
this.lblvalue = lblvalue;
}
public TextArea getTxtArea() {
return logArea;
}
public void setTxtArea(TextArea txtArea) {
this.logArea = txtArea;
}
}
| 43cb58d9de499f22c796fa39312d6ba7bd92a811 | [
"Java"
] | 2 | Java | TBIkapp/loadgeneratorUI | f9eaf71993770cf7ca06ac2292dad7779da77d2c | 801246f68c5c3cc4259bb9d0a5b893a3b2165934 |
refs/heads/master | <repo_name>TeamDoAnUIT/DoAnLapTrinhTrucQuan<file_sep>/SQLQuery/Tao_bang_user.sql
create database do_an
use do_an
create table users(
id int primary key,
userName varchar(16),
password varchar(16)
)<file_sep>/SQLQuery/Tao_acc_truy_cap_csdl.sql
create login test with password ='<PASSWORD>'
create user test for login test | 8ef1a96ee68540c260da056e7a14942a78a36688 | [
"SQL"
] | 2 | SQL | TeamDoAnUIT/DoAnLapTrinhTrucQuan | 8b47d2b539ed4f01288ec67119440362a7dccfae | d518d7da06928a3f8f70bb0c4cba8c446533110c |
refs/heads/master | <file_sep># ~~Heroku ICU Buildpack~~
# May 27th 2021: no longer used by any apps
A buildpack for including the ICU library into a Heroku dyno. This is required
as a dependency for several tools.
## How it works
This buildpack makes ICU4C available in the `/app/icu` directory for both
compilation and runtime uses. The primary purpose of this is to allow [Charlock Holmes](https://github.com/brianmario/charlock_holmes)
(a Ruby gem for encoding heuristics) to run on Heroku.
In order to achieve this, the following happens:
1. ICU is downloaded and compiled from source
2. The compiled library is cached for future builds
3. The compiled result is copied into `/app/icu` and `$1/icu` (the build
directory) to make it available in a seemingly consistent location during
both compilation and runtime
4. A Bundler config option is exported to the rest of the compilation process to
ensure Charlock Holmes looks for ICU in the correct place.
<file_sep>#!/bin/bash
ICU_VERSION="57.1"
compile="/app/icu"
build="$1/icu"
cache_container="$2/icu"
cache="$cache_container/$ICU_VERSION"
buildpack=`cd $(dirname $0); cd ..; pwd`
icu_url="http://download.icu-project.org/files/icu4c/${ICU_VERSION}/icu4c-${ICU_VERSION//./_}-src.tgz"
if [[ -d "$cache" ]]; then
echo "Using cached build of ICU"
cp -R $cache $build
cp -R $cache $compile
else
echo "Downloading ICU $ICU_VERSION"
curl -L $icu_url | tar xz
echo "Building ICU $ICU_VERSION"
pushd icu/source
./runConfigureICU Linux --prefix=$compile
make
make install
popd
echo "Caching build"
mkdir -p $cache_container
rm -rf "$cache_container/*"
cp -R $compile $cache
cp -R $compile $build
fi
# Tell Charlock Holmes where to find ICU.
export BUNDLE_BUILD__CHARLOCK_HOLMES="--with-icu-dir=$compile"
# Make sure we export the relevant environment variables for later buildpacks
export | grep -E -e '(BUNDLE_BUILD__CHARLOCK_HOLMES)=' > "$buildpack/export"
<file_sep>#!/bin/bash
echo "heroku-icu-buildpack" && exit 0
<file_sep>#!/bin/bash
# No default addons or procfile
echo "--- {}"
| 617b50b0c4f7ff849cddbe608e8ef0f3a8085f18 | [
"Markdown",
"Shell"
] | 4 | Markdown | generalassembly/heroku-icu-buildpack | 5b27da84ac04ccd8ebcc28b98b87ccea44810968 | 93d7bac8b754daa87d4053fc63026ba49dad4957 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package life;
import java.util.*;
/**
*
* @author dsizzle
*/
public class EvolveTask extends TimerTask {
/**The frame that the task controls*/
private ColonyFrame frame;
/**The colony that the task controls*/
private Colony colony;
/**The delay between evolutions*/
private int delay;
/**The timer used by this task*/
private Timer timer;
/**The number of updates before the timer will end*/
private int numUpdates;
/**Constructor for task
*
* @param cf - the colony's frame
* @param nu - the number of updates needed
* @param t - the timer for the task
*/
public EvolveTask(ColonyFrame cf, Colony c, int nu, Timer t) {
frame = cf;
timer = t;
numUpdates = nu;
colony = c;
}
/**Runs the timer and tells it when to stop*/
@Override
public void run() {
colony.evolve();
frame.repaint();
numUpdates--;
if (numUpdates == 0) {
timer.cancel();
}
}
/**Starts the timer and completes the number of updates
*
* @param frame - the colony's frame
* @param nu - the number of updates needed
* @param d - the delay between updates
* @return - the task of timing the evolutions
*/
public static EvolveTask start(ColonyFrame frame, Colony c, int nu, int d) {
Timer timer = new Timer();
EvolveTask task = new EvolveTask(frame, c, nu, timer);
timer.schedule(task, d, d);
return task;
}
}
| 99fc51b1639e22ca8802704edf4ab611d2c02a39 | [
"Java"
] | 1 | Java | DanielShaar/Java-Conway-Life | 636198ec8ccc53a7f9501bea2a9cfaf9ab1b2523 | 8195d5d34a5bcad95b8f596208c4e386d9841731 |
refs/heads/main | <repo_name>pantelis-kan/Project_2020_HW2<file_sep>/README.md
# Project_2020_HW2
https://docs.google.com/document/d/1<KEY>/edit?usp=sharing
<file_sep>/fully_connected.py
import sys
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import keras
from keras.optimizers import Adam,RMSprop
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import UpSampling2D,Conv2D, MaxPooling2D, BatchNormalization
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
def read_labels(filename, num_images):
f = open(filename, "rb")
f.read(4)
num_images = int.from_bytes(f.read(4), 'big')
print("Total images in labels file: ", num_images)
buf = f.read(1 * num_images)
labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
return labels
def read_input(filename, num_images):
f = open(filename, "rb")
image_size = 28
#ignore header
f.read(4)
num_images = int.from_bytes(f.read(4), 'big')
# print("Total images in file: ", num_images)
f.read(8)
buf = f.read(image_size * image_size * num_images)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32) / 255
data = data.reshape(num_images, image_size, image_size,1)
return data
def show_image(img):
image = np.asarray(img).squeeze()
plt.imshow(image, cmap='gray')
#plt.imshow(image)
plt.show()
global activation_method
# Create a fully connected layer
def fully_connected(enco,drop_param):
flat = Flatten()(enco)
# After experimentation, 2 dropout layers are better than one
drop1 = Dropout(drop_param)(flat)
den = Dense(128, activation='relu')(drop1)
drop2 = Dropout(drop_param)(den)
# Choose activation method
activation_option = input("Choose an activation method (1 for softmax, 2 for linear, 3 for sigmoid): ")
if int(activation_option) == 1 :
activation_method = "softmax"
elif int(activation_option) == 2:
activation_method = "linear"
else:
activation_method = "sigmoid"
# Since we have 10 classes, output a filter with size 10
out = Dense(10, activation=activation_method)(drop2)
return out
# Handle command line arguments
if len(sys.argv) < 10:
exit("Please give ALL the necessairy arguments. Exiting...")
args = 0
if "-d" in sys.argv:
input_filename = sys.argv[sys.argv.index("-d") + 1]
args += 1
if "-t" in sys.argv:
test_filename = sys.argv[sys.argv.index("-t") + 1]
args += 1
if "-dl" in sys.argv:
input_label_filename = sys.argv[sys.argv.index("-dl") + 1]
args += 1
if "-tl" in sys.argv:
test_label_filename = sys.argv[sys.argv.index("-tl") + 1]
args += 1
if "-model" in sys.argv:
modelfile = sys.argv[sys.argv.index("-model") + 1]
args += 1
print(args)
if args != 5:
exit("Please give ALL the necessairy arguments. Exiting...")
print(input_filename)
print(input_label_filename)
print(test_filename)
print(test_label_filename)
input_num_images = 0
test_num_images = 0
train_data = read_input(input_filename,input_num_images)
test_data = read_input(test_filename,test_num_images)
train_labels = read_labels(input_label_filename,input_num_images)
test_labels = read_labels(test_label_filename, test_num_images)
#print("Original image:\n")
#show_image(train_data[1])
print(train_data.shape)
print(train_data.dtype)
# Convert labels from categorical representation to one-hot encoding
train_Y_one_hot = to_categorical(train_labels)
test_Y_one_hot = to_categorical(test_labels)
#print(train_Y_one_hot[0])
# Normalize data in the 0-1 scale
train_data = train_data / np.max(train_data)
test_data = test_data / np.max(test_data)
#modelfile = "/content/drive/My Drive/ML/data/results/layers6_epochs50_batch128.h5"
# Load an autoencoder h5 model
load_model = keras.models.load_model(modelfile)
total_layers = (len(load_model.layers) / 2) + 1
print(total_layers)
layer_names=[layer.name for layer in load_model.layers]
# Ask the user to choose the hyperparameters for each experiment
repeat = True
while (repeat == True):
percent = -1
while percent > 100 or percent < 0:
percent = input("Choose test data % (0-100): ")
percent = int(percent)
train_X,valid_X,train_label,valid_label = train_test_split(train_data,train_Y_one_hot,test_size=int(percent)/100,random_state=13)
drop_param = input("Choose dropout parameter: ")
optimizer_option = input("Choose optimizer (1 for Adam, everything else for RMSPprop)")
drop_param = float(drop_param)
optimizer_option = int(optimizer_option)
# Get the encoder layers only from the loaded autoencoder model
outputs = [layer.output for layer in load_model.layers]
encoded_output = outputs[int(total_layers)-1]
input_img = keras.Input(shape=(28,28,1))
# Use the encoder layers(including the input layer = outputs[0]), to construct a fully connected layer
full_model = keras.Model(outputs[0],fully_connected(encoded_output,drop_param))
# Use the weights from the encoder part of the autoencoder to create the new model
for l1,l2 in zip(full_model.layers[:int(total_layers)],load_model.layers[0:int(total_layers)]):
l1.set_weights(l2.get_weights())
# Do NOT train the encoder part again. It was already done in autoencoder.py
for layer in full_model.layers[0:int(total_layers)]:
layer.trainable = False
if optimizer_option == 1:
optimizer_method = "Adam"
# Compile the new model with cross entropy since we want classification
full_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy'])
else:
optimizer_method = "RMSprop"
# Compile the new model with cross entropy since we want classification
full_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.RMSprop(),metrics=['accuracy'])
#full_model.summary()
fc_epochs = input("Choose epochs: ")
fc_batch_size = input("Choose batch size: ")
fc_epochs = int(fc_epochs)
fc_batch_size = int(fc_batch_size)
classify_train = full_model.fit(train_X, train_label, batch_size=fc_batch_size,epochs=fc_epochs,verbose=1,validation_data=(valid_X, valid_label))
full_model_name = "testSplit_"+str(percent)+"_2dropout_FullyConnected_epochs"+str(fc_epochs)+"_batch"+str(fc_batch_size)+"_dropout"+str(drop_param) +optimizer_method+".h5"
#full_model.save('/content/drive/My Drive/ML/data/fully_connected_results/'+full_model_name)
full_model.save(full_model_name)
# Plot the accuracy and loss plots
accuracy = classify_train.history['accuracy']
val_accuracy = classify_train.history['val_accuracy']
loss = classify_train.history['loss']
val_loss = classify_train.history['val_loss']
epochs = range(len(accuracy))
plt.plot(epochs, accuracy, 'bo', label='Training accuracy')
plt.plot(epochs, val_accuracy, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
#plt.savefig('/content/drive/My Drive/ML/data/fully_connected_diagrams/' + full_model_name + '.png')
plt.savefig(full_model_name + '.png')
plt.show()
test_eval = full_model.evaluate(test_data, test_Y_one_hot, verbose=0)
print('Test loss:', test_eval[0])
print('Test accuracy:', test_eval[1])
user_option = input("If you want to repeat the experiment press 1. Any other option will terminate: ")
if (int(user_option) == 1):
repeat = True
else:
repeat = False
#fully_connected_modelfile = "/content/drive/My Drive/ML/data/fully_connected_results/new_2dropout_FullyConnected_epochs70_batch512_dropout0.58Adam.h5"
fully_connected_modelfile = full_model_name
full_model_load = keras.models.load_model(fully_connected_modelfile)
predicted_classes = full_model_load.predict(test_data)
# Round the predicted values to the closest integer
predicted_classes = np.argmax(np.round(predicted_classes),axis=1)
correct = np.where(predicted_classes==test_labels)[0]
print("Found %d correct labels" % len(correct) )
# Print the number of correctly predicted images
# Print 9 correct images as a sample (it would be time consuming to print all the correct images)
for i, correct in enumerate(correct[:9]):
plt.subplot(3,3,i+1)
plt.imshow(test_data[correct].reshape(28,28), cmap='gray', interpolation='none')
plt.title("Predicted {}, Class {}".format(predicted_classes[correct], test_labels[correct]))
plt.tight_layout()
incorrect = np.where(predicted_classes!=test_labels)[0]
print("Found %d incorrect labels" % len(incorrect))
for i, incorrect in enumerate(incorrect[:9]):
plt.subplot(3,3,i+1)
plt.imshow(test_data[incorrect].reshape(28,28), cmap='gray', interpolation='none')
plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], test_labels[incorrect]))
plt.tight_layout()
# Create a classification report
from sklearn.metrics import classification_report
target_names = ["Class {}".format(i) for i in range(10)]
print(classification_report(test_labels, predicted_classes, target_names=target_names)) | 8118a2aff924d5bd70188d9d887cd54a0be2d89d | [
"Markdown",
"Python"
] | 2 | Markdown | pantelis-kan/Project_2020_HW2 | 5adc3c04e274a70d073c467ac20b801ed7ad261b | e9716e10aebf52c141cdbd253ed2c06f7fd51a6e |
refs/heads/master | <file_sep>cmake_minimum_required(VERSION 3.15)
project(Chip8)
set(CMAKE_CXX_STANDARD 14)
# Include sub-projects.
if(NOT WIN32)
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake_modules")
find_package(SFML COMPONENTS system graphics window audio REQUIRED)
include_directories(${SFML_INCLUDE_DIR})
add_executable(Chip8 chip8.cpp CPU.h CPU.cpp)
target_link_libraries(Chip8 sfml-graphics sfml-window sfml-system sfml-audio)
else(WIN32)
set(SFML_STATIC_LIBRARIES TRUE)
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/SFML-2.5.1")
set(SFML_DIR ${CMAKE_CURRENT_SOURCE_DIR}/SFML-2.5.1/lib/cmake/SFML)
find_package(SFML COMPONENTS system graphics window audio REQUIRED)
add_executable(Chip8 chip8.cpp CPU.h CPU.cpp)
target_link_libraries(Chip8 sfml-graphics sfml-window sfml-system sfml-audio)
endif()<file_sep>#include <iostream>
#include "CPU.h"
#include <SFML/Window.hpp>
#include <fstream>
#include <thread>
//#include <ncurses.h>
#include <chrono>
#include <array>
#include <include/SFML/Graphics.hpp>
using namespace std;
void keyboard_check(uint8_t inp[]) {
sf::Keyboard::Key keymap[16] = {sf::Keyboard::Num1, sf::Keyboard::Num2, sf::Keyboard::Num3, sf::Keyboard::Num4,
sf::Keyboard::Q, sf::Keyboard::W, sf::Keyboard::E, sf::Keyboard::R,
sf::Keyboard::A, sf::Keyboard::S, sf::Keyboard::D, sf::Keyboard::F,
sf::Keyboard::Z, sf::Keyboard::X, sf::Keyboard::C, sf::Keyboard::V};
while (1) {
for(auto i = 0; i < 16; i++ ) {
if (sf::Keyboard::isKeyPressed(keymap[i])) {
inp[i] = i;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(25));
/*
char pressed_key = getch();
for(uint8_t i = 0; i < 16; i++)
{
if (keymap[i] == pressed_key)
{
inp[i] = i;
cout << "It worked" << endl;
}
}
*/
}
}
int main()
{
//TODO make keymap and graphics array
CPU cpu;
cpu.initCPU();
size_t ret = cpu.loadROM("Pong.ch8");
if (ret == 0) cout << "Did not load ROM" << endl;
thread t(keyboard_check, cpu.key);
sf::RenderWindow window(sf::VideoMode(640, 320), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
cpu.cycle();
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// clear the window with black color
if (cpu.drawFlag == true) {
auto ypoint = 0;
auto ycounter = 0;
for (int i = 0; i < sizeof(cpu.screen); i++) {
auto xpoint = (i % 64);
if (cpu.screen[i] == 1) {
sf::RectangleShape sprite(sf::Vector2f(10, 10));
sprite.setPosition(xpoint * 10, ypoint * 10);
sprite.setFillColor(sf::Color::White);
window.draw(sprite);
}
else {
sf::RectangleShape sprite(sf::Vector2f(10, 10));
sprite.setPosition(xpoint * 10, ypoint * 10);
sprite.setFillColor(sf::Color::Black);
window.draw(sprite);
}
ycounter++;
if (ycounter == 64) {
ypoint += 1;
ycounter = 0;
}
}
cpu.drawFlag = false;
std::this_thread::sleep_for(std::chrono::microseconds(1200));
}
// draw everything here...
// window.draw(...);
// end the current frame
window.display();
}
return 0;
}<file_sep>//
// Created by <NAME> on 1/13/20.
//
#include "CPU.h"
#include <vector>
void CPU::CLS(uint16_t op)
{
cout << "clear display" << op << endl;
}
void CPU::RET(uint16_t op)
{
pc = s.top();
sp--;
}
void CPU::JP(uint16_t op)
{
pc = op & 0x0FFF;
}
void CPU::CALL(uint16_t op)
{ sp++;
s.push(pc);
pc = op & 0x0FFF;
}
void CPU::SEVX(uint16_t op)
{
if (V[(op & 0x0F00) >> 8] == (op & 0x00FF))
{
pc += 4;
} else{
pc += 2;
}
}
void CPU::SNEVX(uint16_t op)
{
if (V[(op & 0x0F00) >> 8] != (op & 0x00FF))
{
pc += 4;
} else{
pc += 2;
}
}
void CPU::SE(uint16_t op)
{
if (V[(op & 0x0F00) >> 8] == V[(op & 0x00F0 >> 4)])
{
pc += 4;
} else{
pc += 2;
}
}
void CPU::LDVX(uint16_t op)
{
V[(op & 0x0F00) >> 8] = op & 0x00FF;
pc += 2;
}
void CPU::ADDVX(uint16_t op)
{
V[(op & 0x0F00) >> 8] = V[(op & 0x0F00) >> 8] + (op & 0x00FF);
pc += 2;
}
void CPU::SNE(uint16_t op)
{
if (V[(op & 0x0F00) >> 8] != (op & 0x00F0) >> 4 )
{
pc += 4;
} else{
pc += 2;
}
}
void CPU::LD(uint16_t op)
{
V[(op & 0x0F00) >> 8] = V[(op & 0x00F0) >> 4];
pc += 2;
}
void CPU::OR(uint16_t op)
{
V[(op & 0x0F00) >> 8]= (V[(op & 0x0F00) >> 8] | V[(op & 0x00F0) >> 4]);
pc += 2;
}
void CPU::AND(uint16_t op)
{
V[(op & 0x0F00) >> 8]= (V[(op & 0x0F00) >> 8] & V[(op & 0x00F0) >> 4]);
pc += 2;
}
void CPU::XOR(uint16_t op)
{
V[(op & 0x0F00) >> 8]= (V[(op & 0x0F00) >> 8] ^ V[(op & 0x00F0) >> 4]);
pc += 2;
}
void CPU::ADD(uint16_t op)
{
uint16_t sum = V[(op & 0x0F00) >> 8] + V[(op & 0x00F0) >> 4];
if (sum > 0xFF)
{
V[0xF] = 0x1;
V[(op & 0x0F00) >> 8] = sum & 0x00FF;
}
else
{
V[0xF] = 0;
V[(op & 0x0F00) >> 8] = sum;
}
pc += 2;
}
void CPU::SUB(uint16_t op)
{
if(V[(op & 0x0F00) >> 8] > V[(op & 0x00F0) >> 4])
V[0xF] = 0x1;
else{
V[0xF] = 0x0;
}
V[(op & 0x0F00) >> 8] = V[(op & 0x0F00) >> 8] - V[(op & 0x00F0) >> 4];
pc += 2;
}
void CPU::SHR(uint16_t op)
{
if ((V[(op & 0x0F00) >> 8] & 0x1) == 1)
V[0xF] = 0x1;
else
V[0xF] = 0x0;
V[(op & 0x0F00) >> 8] = V[(op & 0x0F00) >> 8] >> 1;
pc += 2;
}
void CPU::SUBN(uint16_t op)
{
if(V[(op & 0x0F00) >> 8] < V[(op & 0x00F0) >> 4])
V[0xF] = 0x1;
else
V[0xF] = 0x0;
V[(op & 0x0F00) >> 8] = V[(op & 0x00F0) >> 4] - V[(op & 0x0F00) >> 8];
pc += 2;
}
void CPU::SHL(uint16_t op)
{
if(((V[(op & 0x0F00) >> 8]) >> 7) == 1)
V[0xF] = 0x1;
else V[0xF] = 0x0;
V[(op & 0x0F00) >> 8] = V[(op & 0x0F00) >> 8] << 1;
pc += 2;
}
void CPU::LDI(uint16_t op)
{
I = op & 0x0FFF;
pc += 2;
}
void CPU::JPV0(uint16_t op)
{
pc = op & 0x0FFF + V[0];
}
void CPU::RND(uint16_t op)
{
uint8_t randNumber = (rand() % 255) + 1;
V[(op & 0x0F00) >> 8] = (randNumber & (op & 0x00FF));
pc += 2;
}
void CPU::DRW(uint16_t op)
{
uint8_t x = V[(op & 0x0F00) >> 8];
uint8_t y = V[(op & 0x00F0) >> 4];
uint8_t height = op & 0x000F;
uint16_t pixel;
V[0xF] = 0;
for (int yline = 0; yline < height; yline++)
{
pixel = memory[I + yline];
for (int xline = 0; xline < 8; xline++)
{
if ((pixel & (0x80 >> xline)) != 0)
{
if (screen[(x + xline + ((y + yline) * 64)) % 0x800] == 1)
V[0xF] = 1;
screen[x + xline + ((y + yline) * 64) % 0x800] ^= 1;
}
}
}
drawFlag = true;
pc += 2;
}
void CPU::SKP(uint16_t op)
{
if (key[V[(op & 0x0F00) >> 8]] != 0)
{
pc += 4;
memset(key, 0, sizeof(key));
}
else
{
pc += 2;
}
}
void CPU::SKNP(uint16_t op)
{
if (key[V[(op & 0x0F00) >> 8]] == 0)
{
pc += 4;
memset(key, 0, sizeof(key));
}
else
{
pc += 2;
}
}
void CPU::LDVXDT(uint16_t op)
{
V[(op & 0x0F00) >> 8] = delay_timer;
pc += 2;
}
void CPU::LDKEY(uint16_t op)
{
bool key_pressed = false;
while(key_pressed == false)
{
uint8_t key_val = *max_element(begin(key), end(key));
if (key_val != 0)
{
V[(op & 0x0F00) >> 8] = key_val;
bool key_pressed = true;
}
}
memset(key, 0, sizeof(key));
pc += 2;
}
void CPU::LDDTVX(uint16_t op)
{
delay_timer = V[(op & 0x0F00) >> 8];
pc += 2;
}
void CPU::LDSTVX(uint16_t op)
{
sound_timer = V[(op & 0x0F00) >> 8];
pc += 2;
}
void CPU::ADDI(uint16_t op)
{
I = V[(op & 0x0F00) >> 8] + I;
pc += 2;
}
void CPU::LDHEXFT(uint16_t op)
{
I = ((op & 0x0F00) >> 8) * 0x5;
pc += 2;
}
void CPU::LDB(uint16_t op)
{
memory[I] = V[(op & 0x0F00) >> 8] / 100;
memory[I + 1] = (V[(op & 0x0F00) >> 8] / 10) % 10;
memory[I + 2] = (V[(op & 0x0F00) >> 8]) % 10;
pc += 2;
}
void CPU::LDVALL(uint16_t op)
{
for (int i = 0; i <= ((op & 0x0F00) >> 8); i++)
memory[I + i] = V[i];
pc += 2;
}
void CPU::LDIALL(uint16_t op)
{
for (int i = 0; i <= ((op & 0x0F00) >> 8); i++)
V[i] = memory[I + i] ;
pc += 2;
}
void CPU::initCPU()
{
memset(screen, 0, sizeof(screen));
memset(V, 0, sizeof(V));
memset(memory, 0, sizeof(memory));
memset(key, 0, sizeof(key));
memcpy(memory, hexSprites, (sizeof(hexSprites[0]) * 0x50 ));
drawFlag = false;
s=stack<uint16_t>();
I = 0;
pc = 0x200;
sp = 0;
delay_timer, sound_timer = 0;
fnmap[0xE0] = &CPU::CLS;
fnmap[0xEE] = &CPU::RET;
fnmap[0x1] = &CPU::JP;
fnmap[0x2] = &CPU::CALL;
fnmap[0x3] = &CPU::SEVX;
fnmap[0x4] = &CPU::SNEVX;
fnmap[0x5] = &CPU::SE;
fnmap[0x6] = &CPU::LDVX;
fnmap[0x7] = &CPU::ADDVX;
fnmap[0x8000] = &CPU::LD;
fnmap[0x8001] = &CPU::OR;
fnmap[0x8002] = &CPU::AND;
fnmap[0x8003] = &CPU::XOR;
fnmap[0x8004] = &CPU::ADD;
fnmap[0x8005] = &CPU::SUB;
fnmap[0x8006] = &CPU::SHR;
fnmap[0x8007] = &CPU::SUBN;
fnmap[0x800E] = &CPU::SHL;
fnmap[0x9] = &CPU::SNE;
fnmap[0xA] = &CPU::LDI;
fnmap[0xB] = &CPU::JPV0;
fnmap[0xC] = &CPU::RND;
fnmap[0xD] = &CPU::DRW;
fnmap[0xE00E] = &CPU::SKP;
fnmap[0xE001] = &CPU::SKNP;
fnmap[0xF007] = &CPU::LDVXDT;
fnmap[0xF00A] = &CPU::LDKEY;
fnmap[0xF015] = &CPU::LDDTVX;
fnmap[0xF018] = &CPU::LDSTVX;
fnmap[0xF01E] = &CPU::ADDI;
fnmap[0xF029] = &CPU::LDHEXFT;
fnmap[0xF033] = &CPU::LDB;
fnmap[0xF055] = &CPU::LDIALL;
fnmap[0xF065] = &CPU::LDVALL;
}
size_t CPU::loadROM(const char* filepath)
{
int i = 0;
ifstream rom(filepath, ios::ate | ios::binary);
size_t rom_size = rom.tellg();
if ((bool)rom == false)
return 0;
rom.seekg(0, ios::beg);
while (!rom.eof()) {
rom.read(reinterpret_cast<char*> (&memory[i + 0x200]), sizeof(uint8_t));
i++;
}
return rom.tellg();
}
void CPU::cycle()
{
uint16_t opcode = memory[pc] << 8 | memory[pc + 1];
auto a = (opcode)-(opcode & 0x0FF0);
if (((opcode & 0xF000) >> 12) == 0) {
(this->*fnmap[opcode])(opcode);
}
else if (((opcode & 0xF000) >> 12) == (0x8 | 0xE))
{
(this->*fnmap[(opcode)-(opcode & 0x0FF0)])(opcode);
}
else if (((opcode & 0xF000) >> 12) == 0xF)
{
(this->*fnmap[(opcode)-(opcode & 0x0F00)])(opcode);
}
else {
(this->*fnmap[(opcode & 0xF000) >> 12])(opcode);
}
}
<file_sep>//
// Created by <NAME> on 1/13/20.
//
#ifndef CHIP8_CPU_H
#define CHIP8_CPU_H
/*
* CPU.h
*
* Created on: Dec 29, 2019
* Author: root
*/
#include <iostream>
#include <cstdint>
#include <string>
#include <stack>
#include <array>
#include <fstream>
#include <map>
#include <algorithm>
using namespace std;
class CPU {
public:
void initCPU();
size_t loadROM(const char* filepath);
void cycle();
uint8_t key[0xF];
uint16_t screen[64 * 32];
bool drawFlag;
private:
unsigned char hexSprites[0x50] =
{
0xF0, 0x90, 0x90, 0x90, 0xF0, //0
0x20, 0x60, 0x20, 0x20, 0x70, //1
0xF0, 0x10, 0xF0, 0x80, 0xF0, //2
0xF0, 0x10, 0xF0, 0x10, 0xF0, //3
0x90, 0x90, 0xF0, 0x10, 0x10, //4
0xF0, 0x80, 0xF0, 0x10, 0xF0, //5
0xF0, 0x80, 0xF0, 0x90, 0xF0, //6
0xF0, 0x10, 0x20, 0x40, 0x40, //7
0xF0, 0x90, 0xF0, 0x90, 0xF0, //8
0xF0, 0x90, 0xF0, 0x10, 0xF0, //9
0xF0, 0x90, 0xF0, 0x90, 0x90, //A
0xE0, 0x90, 0xE0, 0x90, 0xE0, //B
0xF0, 0x80, 0x80, 0x80, 0xF0, //C
0xE0, 0x90, 0x90, 0x90, 0xE0, //D
0xF0, 0x80, 0xF0, 0x80, 0xF0, //E
0xF0, 0x80, 0xF0, 0x80, 0x80 //F
};
uint8_t V[0x10];
uint16_t I = 0;
uint16_t pc = 0;
uint8_t sp = 0;
stack <uint16_t> s;
uint8_t delay_timer = 0;
uint8_t sound_timer = 0;
//MEMORY
uint8_t memory[0x1000];
void CLS(uint16_t op);
void RET(uint16_t op);
void JP(uint16_t op);
void CALL(uint16_t op);
void SEVX(uint16_t op);
void SNEVX(uint16_t op);
void SE(uint16_t op);
void LDVX(uint16_t op);
void ADDVX(uint16_t op);
void SNE(uint16_t op);
void LD(uint16_t op);
void OR(uint16_t op);
void AND(uint16_t op);
void XOR(uint16_t op);
void ADD(uint16_t op);
void SUB(uint16_t op);
void SHR(uint16_t op);
void SUBN(uint16_t op);
void SHL(uint16_t op);
void LDI(uint16_t op);
void JPV0(uint16_t op);
void RND(uint16_t op);
void DRW(uint16_t op);
void SKP(uint16_t op);
void SKNP(uint16_t op);
void LDVXDT(uint16_t op);
void LDKEY(uint16_t op);
void LDDTVX(uint16_t op);
void LDSTVX(uint16_t op);
void ADDI(uint16_t op);
void LDHEXFT(uint16_t op);
void LDB(uint16_t op);
void LDVALL(uint16_t op);
void LDIALL(uint16_t op);
typedef void (CPU::*fn)(uint16_t);
map<uint16_t , fn> fnmap;
// void (CPU::*fn[0x16])(uint16_t);
};
#endif //CHIP8_CPU_H
| 0498a389911b8ea2b70fcfa6f8a91994b23bec7e | [
"CMake",
"C++"
] | 4 | CMake | JamesAnthonyDellaMorte/Chip8 | 51fccedb9cb012a13c2f60a925fdf8261d425be1 | 78ac414c68708426f3a7c05d7466758687af193d |
refs/heads/master | <repo_name>kevb34ns/pinyinify<file_sep>/pinyinify.js
/**
* @file Converts pinyin tone numbers to tone marks.
* @author <NAME> <<EMAIL>>
* @copyright <NAME> 2017. Licensed under the MIT License.
*/
/**
* An object holding arrays of Unicode tone marks for each vowel.
* Each tone mark can be accessed very intuitively. For example,
* to access the tone marked version of a2, you would call
* toneMarks["a"][2].
*
* @type {Object}
*/
var toneMarks = {
a: ["a", "\u0101", "\u00e1", "\u01ce", "\u00e0", "a"],
e: ["e", "\u0113", "\u00e9", "\u011b", "\u00e8", "e"],
i: ["i", "\u012b", "\u00ed", "\u01d0", "\u00ec", "i"],
o: ["o", "\u014d", "\u00f3", "\u01d2", "\u00f2", "o"],
u: ["u", "\u016b", "\u00fa", "\u01d4", "\u00f9", "u"],
v: ["\u00fc", "\u01d6", "\u01d8", "\u01da", "\u01dc", "\u00fc"]
};
/**
* @return {Boolean} whether this string is a single alphabetical letter.
*/
String.prototype.isAlpha = function() {
return /^[A-Za-z]$/.test(this);
}
/**
* @return {Boolean} is this string a valid pinyin vowel
*/
String.prototype.isPinyinVowel = function() {
return /^[aeiouv\u00fc]$/.test(this);
}
/**
* Finds the last occurrence of a regular expression
* pattern match in this String.
*
* @param {RegExp} the pattern to match
* @return {Number} the last match in this string
*/
String.prototype.lastIndexOfRegex = function(regExp) {
var lastIndex = -1;
for (var i = 0; i < this.length; i++) {
if (regExp.test(this.charAt(i))) {
lastIndex = i;
}
}
return lastIndex;
}
/**
* @param {Number} index The index of the character to replace
* @param {String} replacement The string to insert at the index
* @return {String} this String, with the specified replacement
*/
String.prototype.replaceAt = function(index, replacement) {
if (index >= 0 && index < this.length && typeof replacement === "string") {
return this.substring(0, index) + replacement
+ this.substring(index + 1);
} else {
return this;
}
}
/**
* Converts this String, which must be a single pinyin word followed by a
* tone number, to the equivalent pinyin word with tone marks.
*
* @return {String} this String, with the tone number removed
* and tone mark inserted.
*/
String.prototype.convertPinyin = function() {
// convert to lowercase
var str = this.toLocaleLowerCase();
// get index of the tone number
var toneNumIndex = str.search(/[1-5]/);
// get index of the first pinyin vowel
var firstVowelIndex = str.search(/[aeiouv\u00fc]/);
if (str.length > 7 || toneNumIndex < 1 ||
toneNumIndex !== str.length - 1 ||
firstVowelIndex < 0) {
// this string is either too long to be pinyin, does not contain a \
// correctly placed tone number, or has no pinyin vowels
console.log("String.prototype.convertPinyin:" + this +
" is not a valid pinyin word.")
return this;
}
/** @type {Number} from 1 to 5 */
var toneNum = parseInt(str[toneNumIndex]);
if (/[ae]/.test(str)) {
// str contains an 'a' or an 'e', both of which take precedence
var index = str.search(/[ae]/);
str = str.replaceAt(index, toneMarks[str.charAt(index)][toneNum]);
} else if (/ou/.test(str)) {
// str contains 'ou'. The tone always goes on the 'o'
var index = str.search(/ou/);
str = str.replaceAt(index, toneMarks[str.charAt(index)][toneNum]);
} else {
// place the tone on the last vowel
var index = str.lastIndexOfRegex(/[aeiouv\u00fc]/);
var vowel = str.charAt(index);
if (vowel == "\u00fc") {
vowel = "v";
}
str = str.replaceAt(index, toneMarks[vowel][toneNum]);
}
// strip the tone number
str = str.substring(0, str.length - 1);
return str;
}
/**
* @param {String} the string to convert
* @return {String} the converted string
*/
var pinyinify = function(str) {
if (typeof str !== 'string') {
return str;
}
var res = "";
var i = 0;
// parse str character by character
while (str.length > 0) {
var char = str.charAt(i);
if (char.isAlpha()) {
// a letter has been found
if (i !== 0) {
// remove non-letters found up to now, add to res
res += str.substring(0, i);
str = str.substring(i);
i = 0;
}
// get index of next tone number, if it exists
var toneNumIndex = str.search(/[1-5]/);
// get index of next whitespace, if it exists
var whitespaceIndex = str.search(/\s/);
if (toneNumIndex > 0 && toneNumIndex < 7 &&
(whitespaceIndex < 0 || whitespaceIndex > toneNumIndex)) {
// there is a tone number within 6 characters from now, and no \
// whitespaces between this character and the tone number
res += str.substring(0, toneNumIndex + 1).convertPinyin();
str = str.substring(toneNumIndex + 1);
} else if (whitespaceIndex < 0) {
// no valid tone numbers nor whitespace, add rest of string to res
res += str.substring(0);
str = "";
} else {
// whitespace found, remove everything up to and including the \
// whitespace, and add to res
res += str.substring(0, whitespaceIndex + 1);
str = str.substring(whitespaceIndex + 1);
}
} else if (i >= str.length) {
// no more characters to parse
res += str.substring(0);
str = "";
}
else {
// increment index
i++;
}
}
return res;
}
<file_sep>/README.md
# pinyinify
A simple JavaScript function for converting pinyin containing tone numbers (`pin4yin1`) to pinyin using standard Unicode tone marks (<code>pìnyīn</code>). A list of Unicode tone marks for HTML can be found [here](http://pinyin.info/unicode/unicode_test.html).
## Usage
The function `pinyinify()` takes a string parameter, which can be one of the following:
+ A single character, which must be one of: `a`, `e`, `i`, `o`, `u`, or <code>ü</code>, followed by a tone mark. `v` is an acceptable substitute for <code>ü</code>.
+ A pinyin word or phrase using tone numbers. Examples: `mao1`, `chi1fan4`, `wo3 men5`. For simplicity's sake, the function will process most words with tone numbers, including ones that may not be valid pinyin.
+ A string containing both pinyin words and non-pinyin words, characters, or symbols. Pinyin must be separated from non-pinyin words by whitespace, but pinyin can have symbols/punctuation adjacent to it. Example: `My Chinese name is yang2kai3wen2.` **Be careful:** any word that resembles the structure of pinyin (has a number at the end of it, for example) may be given tone marks. Therefore, it is recommended that you avoid this option if possible.
If you pass a string that meets one of the requirements above, the function will return a string with the tone numbers converted to tone marks. Otherwise, it will return an unchanged string.
## Limitations
These are some current limitations, which may be addressed in the future should the need arise.
+ **Lowercase Pinyin Only:** since some typefaces have trouble displaying uppercase pinyin symbols, any pinyin words will be converted to lowercase. Non-pinyin words are not affected.
+ **Incomplete Validation:** Right now, `pinyinify()` does not ensure that words are valid pinyin words before conversion. It performs several checks to eliminate obviously incorrect cases:
- Words that are longer than 6 characters (without the tone number) are ignored, since no pinyin words are longer than that.
- There must be a tone number from 1-5 at the end.
- There must be at least one pinyin vowel in the word. The placement of tone marks is correct for any valid pinyin word.
## Test Page
The included HTML test page allows you to test the function without writing any of your code. Simply open `test.html`, located in the `test/` directory, in your browser, and type some text into the text box to see the result.
## Bugs
Feel free to report bugs on the issue tracker. I will do my best to get around to them in a timely manner. If you want to contribute improvements to the code, let me know by [sending me an email](mailto:<EMAIL>) or opening an issue.
## License
This code is licensed under the MIT License. This means you are free to use and change this code however you want, as long as you include the proper copyright notice and attribution. View the full terms [here](https://github.com/kevinkyang/pinyinify/blob/master/LICENSE). | c9ed6b828746acb1b7bc3f0619693e54e7e9571a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kevb34ns/pinyinify | acf9e8c0091be1c58bb908870807488f83273c32 | c6d4fef528ddeba48bbe1b4d850982eccfea5ba2 |
refs/heads/main | <file_sep>package keyauth
import (
"os"
"strings"
"github.com/gofiber/fiber/v2"
)
func getKeysInEnv() []string {
var keys []string
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
key := pair[0]
value := pair[1]
if strings.HasPrefix(key, "API_KEY_") {
keys = append(keys, value)
}
}
return keys
}
func keyInKeys(key string, keys []string) bool {
for _, k := range keys {
if key == k {
return true
}
}
return false
}
func keyAuth(c *fiber.Ctx) error {
key := c.Get("x-api-key")
if key == "" {
return fiber.NewError(fiber.StatusUnauthorized, "no api key")
}
keys := getKeysInEnv()
if keyInKeys(key, keys) {
return c.Next()
}
return fiber.NewError(fiber.StatusUnauthorized, "invalid api key")
}
// New exports a keyauth middleware handler
func New() fiber.Handler {
return keyAuth
}
<file_sep><br />
<p align="center">
<h3 align="center">fiber-key-auth</h3>
<p align="center">
Secure your fiber endpoints using API keys.
<br />
<a href="https://github.com/iwpnd/fiber-key-auth/issues">Report Bug</a>
·
<a href="https://github.com/iwpnd/fiber-key-auth/issues">Request Feature</a>
</p>
</p>
<!-- TABLE OF CONTENTS -->
<details open="open">
<summary><h2 style="display: inline-block">Table of Contents</h2></summary>
<ol>
<li>
<a href="#about-the-project">About The Project</a>
<ul>
<li><a href="#built-with">Built With</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
</ol>
</details>
<!-- ABOUT THE PROJECT -->
## About The Project
On deployment inject API keys authorized to use your service. Every call to a private
endpoint of your service has to include a `header['x-api-key']` attribute that is
validated against the API keys (starting with: `API_KEY_`) in your environment.
If it is present, a request is authorized. If it is not fiber returns `401 Unauthorized`.
Use this either as a middleware the usage.
### Built With
- [fiber](https://github.com/gofiber/fiber/v2)
<!-- GETTING STARTED -->
## Getting Started
### Installation
```sh
go get github.com/iwpnd/fiber-key-auth
```
## Usage
As Middleware:
```go
package main
import (
"os"
"github.com/iwpnd/fiber-key-auth"
"github.com/gofiber/fiber/v2"
)
os.Setenv("API_KEY_TEST", "valid")
func main() {
app := fiber.New()
app.Use(keyauth.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World 👋!")
})
app.Listen(":3000")
}
```
Now try to access your `/` route.
```bash
curl localhost:3000
>> "no api key"
curl localhost:3000 -H "x-api-key: invalid"
>> "invalid api key"
curl localhost:3000 -H "x-api-key: valid"
>> Hello, World 👋!
```
## License
Distributed under the MIT License. See `LICENSE` for more information.
<!-- CONTACT -->
## Contact
<NAME> - [@imwithpanda](https://twitter.com/imwithpanda) - <EMAIL>
Project Link: [https://github.com/iwpnd/fiber-key-auth](https://github.com/iwpnd/fiber-key-auth)
<file_sep>package keyauth
import (
"net/http/httptest"
"os"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/assert"
)
func TestRoute(t *testing.T) {
os.Setenv("API_KEY_TEST", "valid")
tests := []struct {
description string
route string
expectedCode int
apiKey string
}{
{
description: "get HTTP status 403 when invalid key",
route: "/",
expectedCode: 401,
apiKey: "invalid",
},
{
description: "get HTTP status 403 when no key",
route: "/",
expectedCode: 401,
},
{
description: "get HTTP status 200 when authorized",
route: "/",
expectedCode: 200,
apiKey: "valid",
},
}
app := fiber.New()
app.Use(New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Ahoi!")
})
for _, test := range tests {
req := httptest.NewRequest("GET", test.route, nil)
if test.apiKey != "" {
req.Header.Set("x-api-key", test.apiKey)
}
resp, _ := app.Test(req, 1)
assert.Equalf(t, test.expectedCode, resp.StatusCode, test.description)
}
}
<file_sep>module github.com/iwpnd/fiber-key-auth
go 1.17
require (
github.com/gofiber/fiber/v2 v2.19.0
github.com/stretchr/testify v1.7.0
)
require (
github.com/andybalholm/brotli v1.0.2 // indirect
github.com/davecgh/go-spew v1.1.0 // indirect
github.com/klauspost/compress v1.13.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.29.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 // indirect
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
)
| ad21d09cf04e2104bc2df7bc41e30cedf3d3861a | [
"Markdown",
"Go Module",
"Go"
] | 4 | Go | Amenacliff/fiber-key-auth | 2470b8d3e0e6bfc3e88c3b9c6f91820a522770ef | 88994052335e08bc0b3cbe6871efa47062285ce6 |
refs/heads/master | <repo_name>ymfact/GposMakes<file_sep>/Geometry Train/Assets/BlockSelect.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BlockSelect : MonoBehaviour {
Vector3 cursor;
Vector3 block, center;
List<Vector3> list;
public int top, left, width, height, mapSize = 4;
float cycleDir;
bool finish = false;
public bool cw;
int OuterProduct(Vector3 before, Vector3 after)
{
if (before.x * after.y - before.y * after.x > 0)
return 1;
else if (before.x * after.y - before.y * after.x < 0)
return -1;
else return 0;
}
// Use this for initialization
void Start () {
list = new List<Vector3>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
cursor = Input.mousePosition;
if (mapSize == 4)
{
block.x = (int)((cursor.x + 17) / 75);
if (block.x < 0)
block.x = 0;
else if (block.x > mapSize - 1)
block.x = mapSize - 1;
block.y = (int)((331 - cursor.y) / 74);
if (block.y < 0)
block.y = 0;
else if (block.y > mapSize - 1)
block.y = mapSize - 1;
}
/*
입력받은 영역에 따라 block 리턴 (1,1)블록 이런 식으로*/
if (list.Count == 0)
list.Add(block);
else if (list[list.Count - 1] != block)
{
list.Add(block);//새로운 블럭으로 넘어가면 리스트에 블록 넣음.
if (block == list[0])
finish = true;//처음꺼로 돌아오면 바로 연산하러 감.
}
}
else if (!Input.GetMouseButton(0) && finish == false && list.Count != 0)
{
list.Clear();//마우스 버튼을 놓았지만 원위치로 돌아가지 않음
Debug.Log("Draw again");
}
if (finish==true)
{
top = mapSize;
left = mapSize;
height = 0;
width = 0;
cycleDir = 0;
for(int i=0; i<list.Count; i++)
{
if (list[i].x < left)
left = (int)list[i].x;//제일 왼쪽 점
if (list[i].y < top)
top = (int)list[i].y;//제일 위쪽 점
}
for(int i=0; i<list.Count; i++)
{
if (height < list[i].y - top)
height = (int)list[i].y - top;//시작 블럭을 포함한 세로축 사각형 개수
if (width < list[i].x - left)
width = (int)list[i].x - left;//시작 블럭을 포함한 가로축 사각형 개수
}
height += 1;
width += 1;
center.x = left + (float)width / 2;
center.y = top + (float)height / 2;
for (int i = 0; i < list.Count - 1; i++)
{
cycleDir += Vector3.Distance(list[i], list[i + 1]) * OuterProduct(list[i] - center, list[i + 1] - center);
}
if (cycleDir > 0)
cw = false;//반시계방향
else
cw = true;//시계방향
//리턴하는 자료는 top, left, height, width, cw
Debug.Log("top: " + top + ", left: " + left + ", width: " + width + ", height: " + height + ",cw: " + cw);
GameObject.Find("InGameScript").GetComponent<InGameScript>().Turn(top, left, width, height, cw);
list.Clear();
finish = false;
}
}
}
<file_sep>/Geometry Train/Assets/MainScript.cs
using UnityEngine;
using System.Collections;
public class MainScript : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {/*
while (true)
{
int random, random2, random3, random4;
yield return new WaitForSeconds(0.5f);
random = Random.Range(0, 3);
random2 = Random.Range(2, 5 - random);
random3 = Random.Range(0, 3);
random4 = Random.Range(2, 5 - random3);
GameObject.Find("InGameScript").GetComponent<InGameScript>().Turn(random, random3, random2, random4, Random.Range(0, 2) == 1 ? true : false);
}*/
yield return null;
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Geometry Train/Assets/train.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class train : MonoBehaviour
{
List<Vector3> list;
Vector3 input, center;
public Vector3 vertext;
float maxX, maxY, minX, minY;
public float Xlength, Ylength;
float incline, minIncline, maxIncline;
int maxPoint, minPoint, num;
public float cycleDir=0;//1 is CCW, -1 is CW
// Use this for initialization
float GetAbs(float num)
{
if (num > 0)
return num;
else
return (-1)*num;
}
int OuterProduct(Vector3 before, Vector3 after)
{
if (before.x * after.y - before.y * after.x > 0)
return 1;
else if (before.x * after.y - before.y * after.x < 0)
return -1;
else return 0;
}
void Start()
{
list = new List<Vector3>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
input = Input.mousePosition;
list.Add(input);
}
else if (!Input.GetMouseButton(0) && list.Count != 0)//입력을 끝낸 상태
{
cycleDir = 0;
maxX = 0;
minX = 10000;
maxY = 0;
minY = 10000;
for(int i=0; i<list.Count; i++)
{
if (list[i].x < minX)
minX = list[i].x;
if (list[i].x > maxX)
maxX = list[i].x;
if (list[i].y < minY)
minY = list[i].y;
if (list[i].y > maxY)
maxY = list[i].y;
}
Xlength = maxX - minX;
Ylength = maxY - minY;
maxIncline = 0;
minIncline = 100;
for(int i=0; i<list.Count-1; i++)
{
incline = (list[i].x - list[i + 1].x) / (list[i].y - list[i + 1].y);
if (GetAbs(incline) < GetAbs(minIncline))
{
minIncline = incline;
minPoint = i;
}
if (GetAbs(incline) > GetAbs(maxIncline))
{
maxIncline = incline;
maxPoint = i;
}
}
vertext.x = list[minPoint].x;
vertext.y = list[maxPoint].y;
num = 0;
for (int i=0; i<list.Count; i++)
if (vertext.x > list[i].x)
num++;
if (num > 2 * list.Count / 3)
vertext.x -= Xlength;
num = 0;
for (int i = 0; i < list.Count; i++)
if (vertext.y < list[i].y)
num++;
if (num > 2 * list.Count / 3)
vertext.y += Ylength;
center.x = vertext.x + Xlength / 2;
center.y = vertext.y + Ylength / 2;
for (int i = 0; i < list.Count-1; i++)
{
cycleDir += Vector3.Distance(list[i], list[i+1]) *OuterProduct(list[i] - center, list[i + 1] - center);
}
cycleDir /= GetAbs(cycleDir);
list.Clear();
/*
vertext와 Xength, Ylength, cycleDir을 리턴하면 된다함.
*/
//GameObject.Find("InGameScript").GetComponent<InGameScript>().InputRect(vertext, Xlength, Ylength, cycleDir);
}
}
}
<file_sep>/Geometry Train/Assets/TextReader.cs
using UnityEngine;
using System.Collections;
public class TextReader : MonoBehaviour {
string[] block;
int[][] blockNum;
// Use this for initialization
void Start () {
TextAsset asset = Resources.Load<TextAsset>("a");
block = asset.text.Split(null);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
GetComponent<InGameScript>().map[i][j] = int.Parse(block[4 * i + j]);
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Geometry Train/Assets/Block.cs
using UnityEngine;
using System.Collections;
public class Block : MonoBehaviour {
public Vector3 goalPosition;
public int prop;
// Use this for initialization
void Start () {
goalPosition = transform.position;
}
// Update is called once per frame
void Update () {
transform.Translate((goalPosition - transform.position) / 10f);
}
}
<file_sep>/Geometry Train/Assets/InGameScript.cs
using UnityEngine;
using System.Collections;
public class InGameScript : MonoBehaviour {
public int[][] map;
public GameObject[][] map2;
public GameObject block;
public int row, col;
private Camera camera;
public void InputRect(Vector3 point, float width, float height, float cw)
{
Vector3 point2 = point + new Vector3(width, height, 0);
point = camera.ScreenToWorldPoint(point);
point2 = camera.ScreenToWorldPoint(point2);
width = (point2 - point).x;
height = (point2 - point).y;
//Debug.Log("" + point + " " + width + " " + height);
int w;
int h;
int x;
int y;
x = Mathf.RoundToInt((point.x + 3) / 2);
y = Mathf.RoundToInt(-(point.y - 3) / 2);
w = Mathf.RoundToInt(width / 2 + 1);
h = Mathf.RoundToInt(height / 2 + 1);
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x > col - 2) x = col - 2;
if (y > row - 2) y = row - 2;
if (w <= 1) w = 2;
if (h <= 1) h = 2;
if (x + w > col) w = col - x;
if (h + y > row) h = row - y;
//Debug.Log("" + x + " " + y + " " + w + " " + h);
Turn(x, y, w, h, cw < 0 ? true : false);
}
public void Turn(int left, int top, int width, int height, bool cw)
{
int temp;
Vector3 temp2;
GameObject temp3;
Vector3 temp4;
Vector3 temp5;
width--;
height--;
if (cw == false)
{
temp = map[top][left];
temp3 = map2[top][left];
temp4 = map2[top][left].GetComponent<Block>().goalPosition;
for (int i = left; i < left + width; i++)
{
map[top][i] = map[top][i + 1];
temp5 = map2[top][i + 1].GetComponent<Block>().goalPosition;
map2[top][i + 1].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[top][i] = map2[top][i + 1];
}
for (int i = top; i < top + height; i++)
{
map[i][left + width] = map[i + 1][left + width];
temp5 = map2[i+1][left + width].GetComponent<Block>().goalPosition;
map2[i+1][left + width].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[i][left + width] = map2[i + 1][left + width];
}
for (int i = left + width; i > left; i--)
{
map[top + height][i] = map[top + height][i - 1];
temp5 = map2[top + height][i-1].GetComponent<Block>().goalPosition;
map2[top + height][i-1].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[top + height][i] = map2[top + height][i - 1];
}
for (int i = top + height; i > top + 1; i--)
{
map[i][left] = map[i - 1][left];
temp5 = map2[i - 1][left].GetComponent<Block>().goalPosition;
map2[i - 1][left].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[i][left] = map2[i - 1][left];
}
map[top + 1][left] = temp;
temp3.GetComponent<Block>().goalPosition = temp4;
map2[top + 1][left] = temp3;
}
else
{
temp = map[top][left];
temp3 = map2[top][left];
temp4 = map2[top][left].GetComponent<Block>().goalPosition;
for (int i = top; i < top + height; i++)
{
map[i][left] = map[i + 1][left];
temp5 = map2[i + 1][left].GetComponent<Block>().goalPosition;
map2[i + 1][left].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[i][left] = map2[i + 1][left];
}
for (int i = left; i < left + width; i++)
{
map[top + height][i] = map[top + height][i + 1];
temp5 = map2[top + height][i + 1].GetComponent<Block>().goalPosition;
map2[top + height][i + 1].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[top + height][i] = map2[top + height][i + 1];
}
for (int i = top + height; i > top; i--)
{
map[i][left + width] = map[i - 1][left + width];
temp5 = map2[i - 1][left + width].GetComponent<Block>().goalPosition;
map2[i - 1][left + width].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[i][left + width] = map2[i - 1][left + width];
}
for (int i = left + width; i > left+1; i--)
{
map[top][i] = map[top][i - 1];
temp5 = map2[top][i - 1].GetComponent<Block>().goalPosition;
map2[top][i - 1].GetComponent<Block>().goalPosition = temp4;
temp4 = temp5;
map2[top][i] = map2[top][i - 1];
}
map[top][left + 1] = temp;
temp3.GetComponent<Block>().goalPosition = temp4;
map2[top][left+1] = temp3;
}
/*
string str = "";
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
str += map[i][j] + " ";
}
str += "\n";
}
Debug.Log(str);*/
}
// Use this for initialization
void Start()
{
camera = GameObject.Find("Main Camera").GetComponent<Camera>();
row = 4;
col = 4;
map = new int[row][];
map2 = new GameObject[row][];
for (int i = 0; i < 4; i++)
{
map[i] = new int[col];
map2[i] = new GameObject[col];
for (int j = 0; j < 4; j++)
{
map[i][j] = i * 4 + j;
map2[i][j] = (GameObject)Instantiate(block, new Vector3(j*2-3, -i*2+3, 0), Quaternion.identity);
map2[i][j].GetComponent<SpriteRenderer>().color = new Color((i*4+j)/16f, 1, 1, 1);
}
}
}
// Update is called once per frame
void Update()
{
}
}
| be42af72ac9607a870cc974e0abd2ea34799362f | [
"C#"
] | 6 | C# | ymfact/GposMakes | e3289384f52931a3a34314cf571ef60c2be6aec1 | f94db476b5f0cc1b686ddabf90aef6c7db0228a8 |
refs/heads/master | <file_sep># Stats-BayesNetwork
<file_sep>
# coding: utf-8
# # Project 1
# ### Import data
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal, norm
import math
import numpy as np # importing this way allows us to refer to numpy as np
df = pd.read_excel('DataSet/university data.xlsx', encoding = 'utf8').drop([49])
# In[2]:
# In[3]:
def to_precision(x,p):
"""
Code credit for this function: http://randlet.com/blog/python-significant-figures-format/
returns a string representation of x formatted with a precision of p
Based on the webkit javascript implementation taken from here:
https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp
"""
x = float(x)
if x == 0.:
return "0." + "0"*(p-1)
out = []
if x < 0:
out.append("-")
x = -x
e = int(math.log10(x))
tens = math.pow(10, e - p + 1)
n = math.floor(x/tens)
if n < math.pow(10, p - 1):
e = e -1
tens = math.pow(10, e - p+1)
n = math.floor(x / tens)
if abs((n + 1.) * tens - x) <= abs(n * tens -x):
n = n + 1
if n >= math.pow(10,p):
n = n / 10.
e = e + 1
m = "%.*g" % (p, n)
if e < -2 or e >= p:
out.append(m[0])
if p > 1:
out.append(".")
out.extend(m[1:p])
out.append('e')
if e > 0:
out.append("+")
out.append(str(e))
elif e == (p -1):
out.append(m)
elif e >= 0:
out.append(m[:e+1])
if e+1 < len(m):
out.append(".")
out.extend(m[e+1:])
else:
out.append("0.")
out.extend(["0"]*-(e+1))
out.append(m)
return "".join(out)
# #Q1 Compute for each variable ((CS Score, Research Overhead, Admin Base Pay, Tuition)) its sample mean, variance and standard deviation. Related variables: mu1, mu2, mu3, mu4, var1, var2, var3, var4, sigma1, sigma2, sigma3, sigma4
# In[4]:
def sampleMean(stat):
n = 0
total = 0
for i in range (0,len(df.index)):
n += 1
total += df.at[i,stat]
sampleMean = total / n
return sampleMean
def sampleMeanNumpy(stat): ##CHECK FORMULA IS CORRECT
return np.mean(df[stat])
def variance(stat):
n = 1
sumSqs = 0
mean = sampleMean(stat)
for i in range (0,len(df.index)):
n += 1
sumSqs += (df.at[i,stat] - mean) ** 2
variance = sumSqs / (n - 1)
return variance
def varianceNumpy(stat): ##CHECK FORMULA IS CORRECT
return np.var(df[stat])
def standardDeviation(stat):
var = variance(stat)
stddev = var ** (1/2.0)
return stddev
def standardDeviationNumpy(stat): ##CHECK FORMULA IS CORRECT
return np.std(df[stat])
# In[5]:
mu1 = sampleMean('CS Score (USNews)')
#mu1np = sampleMeanNumpy('CS Score (USNews)') ##CHECK FORMULA IS CORRECT
mu2 = sampleMean('Research Overhead %')
mu3 = sampleMean('Admin Base Pay$')
mu4 = sampleMean('Tuition(out-state)$')
var1 = variance('CS Score (USNews)')
#var1np = varianceNumpy('CS Score (USNews)') ##CHECK FORMULA IS CORRECT
var2 = variance('Research Overhead %')
var3 = variance('Admin Base Pay$')
var4 = variance('Tuition(out-state)$')
sigma1 = standardDeviation('CS Score (USNews)')
#sigma1np = standardDeviationNumpy('CS Score (USNews)') ##CHECK FORMULA IS CORRECT
sigma2 = standardDeviation('Research Overhead %')
sigma3 = standardDeviation('Admin Base Pay$')
sigma4 = standardDeviation('Tuition(out-state)$')
# In[6]:
print"mu1 =",to_precision(mu1,3)
#print"mu1np =",mu1np
print"mu2 =",to_precision(mu2,3)
print"mu3 =",to_precision(mu3,3)
print"mu4 =",to_precision(mu4,3)
print"var1 =",to_precision(var1,3)
#print"var1np =",var1np
print"var2 =",to_precision(var2,3)
print"var3 =",to_precision(var3,3)
print"var4 =",to_precision(var4,3)
print"sigma1 =",to_precision(sigma1,3)
#print"sigma1np =",sigma1np
print"sigma2 =",to_precision(sigma2,3)
print"sigma3 =",to_precision(sigma3,3)
print"sigma4 =",to_precision(sigma4,3)
# #Q2 Compute for each pair of variables their covariance and correlation.
#
# Show the results in the form of covariance and correlation matrices.
#
# Also make a plot of the pairwise data showing the label associated with each data point.
#
# Which are the most correlated and least correlated variable pair?
#
# Related variables: covarianceMat, correlationMat
# In[7]:
covarianceMat = np.cov([df['CS Score (USNews)'],df['Research Overhead %'],df['Admin Base Pay$'],df['Tuition(out-state)$']])
correlationMat = np.corrcoef([df['CS Score (USNews)'],df['Research Overhead %'],df['Admin Base Pay$'],df['Tuition(out-state)$']])
def covarXMat(features):
cov = df[features].cov().as_matrix()
return cov
def corrXMat(features):
corr = df[features].corr().as_matrix()
return corr
# In[8]:
np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
print "covarianceMat =",covarianceMat
print "correlationMat =",correlationMat
# Also make a plot of the pairwise data showing the label associated with each data point.
# In[9]:
def scatterplot(feature1, feature2):
fig = plt.figure()
ax = fig.add_subplot(111)
x = df[feature1].as_matrix()
y = df[feature2].as_matrix()
ax.scatter(x, y)
fit = np.polyfit(x, y, deg=1)
ax.plot(x, fit[0] * x + fit[1], color='red')
ax.set_xlabel(feature1)
ax.set_ylabel(feature2)
plt.tight_layout()
plt.show()
name = feature1 + feature2 + "1.png"
fig.savefig(name)
# In[10]:
scatterplot('CS Score (USNews)', 'Admin Base Pay$')
scatterplot('CS Score (USNews)', 'Research Overhead %')
scatterplot('CS Score (USNews)', 'Tuition(out-state)$')
scatterplot('Research Overhead %', 'Admin Base Pay$')
scatterplot('Research Overhead %', 'Tuition(out-state)$')
scatterplot('Admin Base Pay$', 'Tuition(out-state)$')
# #Q3 Assuming that each variable is normally distributed and that they are independent of each other, determine the log-likelihood of the data
#
# (Use the means and variances computed earlier to determine the likelihood of each data value.)
#
# Related variables: logLikelihood
# In[ ]:
# Calculate the log likelihood for a single variable value (along one dimension)
# In[11]:
def pOfX(x,feature):
sigma = standardDeviation(feature)
mean = sampleMean(feature)
prob = 1 / (sigma*(2 * math.pi) ** (1/2.0)) * math.e ** (-1 / 2.0 * ((x - mean)/sigma) ** 2.0)
return prob
# In[12]:
#CALCULATE P(x) FOR A PARTICULAR FEATURE WITH norm.pdf
def pOfXpdf(x,feature):
sigma = standardDeviation(feature)
mean = sampleMean(feature)
prob = norm.pdf(x, loc=mean, scale=sigma)
return prob
# In[13]:
#ICALCULATE P(x1,x2,...,xn) WITH multivariate_normal.pdf
def pOfXMultivariatePDF(row,features):
dpoint = np.zeros((len(features)))
meanArr = np.zeros((len(features)))
i = 0
for f in features:
dpoint[i] = df.loc[row,f]
meanArr[i] = sampleMean(f)
i = i + 1
covr = covarXMat(features)
return multivariate_normal.pdf(dpoint,mean=meanArr, cov=covr, allow_singular=True)
# Note that by independence, Pn(x)=P(x0)* P(x1) * P(x2)...P(xn)
#
# To calculate the log likelihood for a single value along all dimensions
# In[14]:
def logLikelihoodMultivariatePDF(features):
sumlh = 0
for i in range (0,len(df.index)):
prob = pOfXMultivariatePDF(i,features)
sumlh += math.log(prob)
return sumlh
def logLikelihoodIndependentPDF(features):
sumlh = 0
for i in range (0,len(df.index)):
rowprob = 1
for f in features:
x = df.loc[i,f]
prob = pOfX(x,f)
rowprob = rowprob*prob
sumlh += math.log(rowprob)
return sumlh
# Sum over all data points to get log likelihood of the data
# In[20]:
logLikelihood = logLikelihoodMultivariatePDF(['CS Score (USNews)','Research Overhead %','Admin Base Pay$','Tuition(out-state)$']) #PRINT LOG LIKELIHOOD
logLikelihood2 = logLikelihoodIndependentPDF(['CS Score (USNews)','Research Overhead %','Admin Base Pay$','Tuition(out-state)$'])
print"logLikelihood with Multivariate PDF = ",logLikelihood
print"logLikelihood with independent PDFs = ",logLikelihood2
# #Q4 Using the correlation values construct a Bayesian network which results in a higher log-likelihood than in 3.
#
# Related variables: BNgraph, BNlogLikelihood
# Loop over bnStructure, figure out what each variable is conditioned on
# e.g.
# [[0 1 0 0]
# [0 0 0 1]
# [1 0 0 1]
# [0 0 0 0]]
# P(v1,v2,v3,v4) = P(v4|v2,v3)P(v2|v1)P(v1|v3)P(v3)
# In[16]:
#Creates a list of tuples, tuple contains conditioned item and what it is conditioned on, based on bnStructure
vDict = {0:'CS Score (USNews)', 1:'Research Overhead %', 2:'Admin Base Pay$', 3:'Tuition(out-state)$'}
def calcCondDist (bnStruc):
condDist = []
i = 0
while i<4:
condOn = []
j = 0
#print("Checking Child " + vDict[i])
while j<4:
#print("Checking Parent " + vDict[j])
#print("i,j is :")
#print(bnStruc[i,j])
if bnStruc[i,j] == 1:
#print(vDict[j])
condOn.append(vDict[j])
j=j+1
term = (vDict[i],condOn)
condDist.append(term)
i=i+1
return condDist
# In[17]:
def logLikelihoodLinearAlgSolution(data, bnStructure):
#print(bnStructure)
condDists = calcCondDist(bnStructure)
#print(condDists)
totalLogLike = 0
for dist in condDists:
(var1, conditionedvars) = dist
n = len(data.index)
numVars = len(conditionedvars)
#termslhs = np.zeros((numVars+1,numVars+1))#create matrix of summation terms
#termsrhs = np.zeros((numVars+1,1))
dfSubset = np.ones((numVars+1,n))
i = 1
for f in conditionedvars:
dfSubset[i] = np.transpose(data[f])
i = i+1
termslhs = np.dot(dfSubset,np.transpose(dfSubset))
termsrhs = np.dot(dfSubset,data[var1])
params = np.linalg.solve(termslhs, termsrhs)
#print(params)
sigmaSquared = np.sum(((np.dot(params,dfSubset) - data[var1])**2))/n
#print(-1/2*n*math.log(2*math.pi*sigmaSquared))
loglikelihood = -1*n*math.log(2*math.pi*sigmaSquared)/2 - np.sum(((np.dot(params,dfSubset) - data[var1])**2)/(2*sigmaSquared))
#print("loglikelihood ",dist,"is",to_precision(loglikelihood,3))
totalLogLike = totalLogLike + loglikelihood
return totalLogLike
# In[18]:
bnStructure1 = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])
bnStructure2 = np.array([[0,1,0,0],[0,0,0,1],[1,0,0,1],[0,0,0,0]])
bnStructure3 = np.array([[0,0,0,1],[1,0,0,0],[0,0,0,0],[0,0,1,0]])
bnStructure4 = np.array([[0,0,0,1],[1,0,1,0],[0,0,0,1],[0,0,0,0]])
bnStructure5 = np.array([[0,0,0,1],[1,0,0,1],[0,0,0,1],[0,0,0,0]])
bnStructure6 = np.array([[0,0,0,1],[1,0,0,1],[0,0,0,0],[0,0,1,0]])
bnStructure7 = np.array([[0,0,0,1],[1,0,1,1],[0,0,0,1],[0,0,0,0]])
print "BNgraph ="
print bnStructure7
print "BNlogLikelihood =",logLikelihoodLinearAlgSolution(df, bnStructure7)
# In[ ]:
# In[ ]:
| f37973c0b6e9a1f21b245624709945426319dfa7 | [
"Markdown",
"Python"
] | 2 | Markdown | ebellingham/Stats-BayesNetwork | 95a2e91a33b7eb205d6211eab60f739feb5b30d5 | 37b3f0148f745420ce2345614c98f89df189918c |
refs/heads/master | <repo_name>cesarenaldi/react-router-lifecycle<file_sep>/src/initializeRoutes.js
import { matchRoutes } from 'react-router-config'
import updateRoutes from './updateRoutes'
export default function (routes, path) {
const matches = matchRoutes(routes, path)
if (matches.length === 0) {
return Promise.resolve([])
}
return Promise
.all(
matches.map(({ route, match }) => {
if (typeof route.onEnter === 'function') {
return route.onEnter(match).then(Component => {
routes = updateRoutes(routes, route, { __component: Component })
})
}
return Promise.resolve()
})
)
.then((values) => routes)
}
<file_sep>/src/__tests__/initializeRoutes.spec.js
import React from 'react'
import initializeRoutes from '../initializeRoutes'
const Component = props => <h1>My component</h1>
const Loading = props => <p>loading...</p>
const routes = [
{
path: '/foo',
onEnter: jest.fn(match => Promise.resolve(Component)),
onUpdate: jest.fn(),
onLeave: jest.fn(),
routes: [
{
path: '/foo/:id',
onEnter: jest.fn(match => Promise.resolve(Component)),
onUpdate: jest.fn(),
onLeave: jest.fn()
}
]
}
]
describe('Given the initializeRoutes function', () => {
describe('when initializing a list of nested routes', () => {
it('should invoke the onEnter handler of every matching route ' +
'and store the resolved component in the route.__component property', () => {
return initializeRoutes(routes, '/foo/42').then(newRoutes => {
expect(newRoutes[0].onEnter).toHaveBeenCalled();
expect(newRoutes[0]).toHaveProperty('__component', Component);
expect(newRoutes[0].routes[0].onEnter).toHaveBeenCalled();
expect(newRoutes[0].routes[0]).toHaveProperty('__component', Component);
})
})
})
})
<file_sep>/src/RoutesProvider.js
import React from 'react'
import PropTypes from 'prop-types'
import updateRoutes from './updateRoutes'
export default class RoutesProvider extends React.Component {
static propTypes = {
children: PropTypes.func.isRequired,
routes: PropTypes.array.isRequired
}
static childContextTypes = {
updateRoute: React.PropTypes.func.isRequired
}
state = {
routes: this.props.routes
}
getChildContext() {
return {
updateRoute: (route, update) => {
this.setState({
routes: updateRoutes(this.state.routes, route, update)
})
}
}
}
render() {
return this.props.children(this.state.routes)
}
}
<file_sep>/src/__tests__/integration.spec.js
import React from 'react'
import { MemoryRouter, Router } from 'react-router'
import createHistory from 'history/createMemoryHistory'
import { renderRoutes } from 'react-router-config'
import { mount } from 'enzyme'
import { RoutesProvider, initializeRoutes, handleLifecycle } from '../index';
const MyParentComponent = ({ route }) => (
<div>
{ renderRoutes(route.routes) }
</div>
)
const MyComponent = () => <p>ready!</p>
const Loading = () => <p>loading...</p>
const routes = [
{
path: '/foo/',
component: MyParentComponent,
routes: [
{
path: '/foo/:id',
// simulates () => import('./path/to/MyComponent').then(extractDefault)
onEnter: jest.fn(() => Promise.resolve(MyComponent)),
onUpdate: jest.fn(),
onLeave: jest.fn(),
component: handleLifecycle(Loading)
}
]
},
{
path: '/bar',
component: () => <p>bar</p>
}
]
const App = ({ history, routes }) => (
<Router history={ history }>
<RoutesProvider routes={ routes }>
{
routes => (
<div>
{ renderRoutes(routes) }
</div>
)
}
</RoutesProvider>
</Router>
)
var history;
describe('Given an app that make use of React Router', () => {
describe('and the rendering tree includes RoutesProvider component', () => {
describe('and the matching route uses an handleLifecycle HoC as route.component', () => {
beforeAll(function () {
history = createHistory({
initialEntries: [ '/foo/42' ],
initialIndex: 0
})
})
describe('when rendering the app', () => {
it('should render the placeholder component, then resolve and render the lazy loaded component', done => {
const wrapper = mount(<App history={ history } routes={ routes } />)
expect(wrapper.find(Loading)).toHaveLength(1)
process.nextTick(() => {
expect(wrapper.find(MyComponent)).toHaveLength(1)
done()
})
})
})
describe('when rendering the app with initialized routes', () => {
it('should render the resolved route component straightaway', () => {
return initializeRoutes(routes, '/foo/42')
.then(routes => {
const wrapper = mount(<App history={ history } routes={ routes } />)
expect(wrapper.find(MyComponent)).toHaveLength(1)
})
})
})
describe('when the location changes', () => {
var wrapper;
beforeAll(function () {
wrapper = mount(<App history={ history } routes={ routes } />)
})
beforeEach(function () {
routes[0].routes[0].onUpdate.mockClear()
})
describe('but the router resolves the new location with the same route', () => {
it('should invoke the route onUpdate callback with the new `match` object', () => {
history.push('/foo/83')
const onUpdateMock = routes[0].routes[0].onUpdate;
expect(onUpdateMock).toBeCalledWith(
expect.objectContaining({
url: '/foo/83',
params: {
id: '83'
}
})
)
})
})
describe('and the router resolves the new location a different route', () => {
it('should invoke the route onLeave callback and NOT invoke the route onLeave callback', () => {
history.push('/bar')
const { onLeave: onLeaveMock, onUpdate: onUpdateMock } = routes[0].routes[0];
expect(onLeaveMock).toHaveBeenCalled()
expect(onUpdateMock).not.toHaveBeenCalled()
})
})
})
})
})
})
<file_sep>/examples/code-splitting-ssr/webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
app: './src/client.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
'react',
[ 'es2015', { loose: true, modules: false } ],
'stage-1'
],
plugins: [
'syntax-async-functions',
'syntax-dynamic-import'
]
}
}
]
}
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'public/'),
publicPath: '/',
chunkFilename: 'part-[id].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
};
<file_sep>/src/updateRoutes.js
import update from 'immutability-helper'
function createUpdateInstructions(routes, routeToUpdate, updates) {
return routes.reduce((instructions, route, idx) => {
if (route.path === routeToUpdate.path) {
instructions[idx] = { $merge: updates }
} else if (Array.isArray(route.routes)) {
instructions[idx] = {
...(
Array.isArray(route.routes) ?
{ routes: createUpdateInstructions(route.routes, routeToUpdate, updates) } :
{}
)
}
}
return instructions
}, {})
}
export default function (routes, route, updates) {
const instructions = createUpdateInstructions(routes, route, updates)
return update(routes, instructions)
}
<file_sep>/examples/code-splitting-ssr/src/App.js
import React from 'react'
import { Link } from 'react-router-dom'
import { renderRoutes } from 'react-router-config'
import PropTypes from 'prop-types'
import { RoutesProvider } from '../../../src/index'
import routes from './routes'
export default function App({ routes }) {
return (
<div>
<Link to='/'>Home</Link> | <Link to='/about-us'>About Us</Link>
<RoutesProvider routes={ routes }>
{
routes => renderRoutes(routes)
}
</RoutesProvider>
</div>
)
}
App.propTypes = {
routes: PropTypes.array.isRequired
}
<file_sep>/src/__tests__/updateRoutes.spec.js
import updateRoutes from '../updateRoutes';
const noop = () => null;
const routes = [
{
path: '/foo',
onEnter: noop,
onUpdate: noop,
onLeave: noop,
routes: [
{
path: '/foo/:id',
onEnter: noop,
onUpdate: noop,
onLeave: noop
}
]
}
]
describe('Given the updateRoutes function', () => {
describe('when updating a route', () => {
it('should return a new list with the updated route', () => {
const routeToUpdate = routes[0].routes[0]
const updates = {
foo: 42
}
const newRoutes = updateRoutes(routes, routeToUpdate, updates);
expect(newRoutes[0].routes[0].foo).toEqual(42)
expect(routeToUpdate !== newRoutes[0].routes[0]).toBeTruthy()
})
})
})
<file_sep>/examples/code-splitting-ssr/src/components/Homepage.js
import React from 'react'
export default function Homepage({ match }) {
return (
<div>
<h1>Home</h1>
<pre>
{ JSON.stringify(match, null, 2) }
</pre>
</div>
)
}
<file_sep>/src/handleLifecycle.js
import React from 'react'
import PropTypes from 'prop-types'
export default function (Placeholder) {
return class HandleLifecycle extends React.Component {
static contextTypes = {
updateRoute: PropTypes.func.isRequired
}
static propTypes = {
match: PropTypes.object.isRequired,
route: PropTypes.object.isRequired
}
state = {
Component: this.props.route.__component || null
}
componentDidMount() {
const { route, match } = this.props;
if (typeof route.onEnter === 'function') {
route.onEnter(match)
.then(Component => {
this.context.updateRoute(route, { __component: Component })
})
}
}
componentWillReceiveProps(nextProps) {
const { route: nextRoute, match: nextMatch } = nextProps;
const { route, match } = this.props;
if (nextMatch.url !== match.url) {
if (typeof nextRoute.onUpdate === 'function') {
nextRoute.onUpdate(nextMatch)
}
}
if (nextRoute !== route) {
if (nextRoute.__component) {
this.setState({
Component: nextRoute.__component
})
}
}
}
componentWillUnmount() {
if (typeof this.props.route.onLeave === 'function') {
this.props.route.onLeave()
}
}
render() {
const { Component } = this.state
return (
Component ?
<Component { ...this.props } /> :
<Placeholder { ...this.props } />
)
}
}
}
| a694e31d4c4336c9d7847711ae51424ba2a32e69 | [
"JavaScript"
] | 10 | JavaScript | cesarenaldi/react-router-lifecycle | 1d26ed7b2df1655bcaa212cfb9b1d19ac855c506 | 74ab7e2038b0c8f81e0e945ab671185d2614e178 |
refs/heads/master | <repo_name>shajedul-islam/exploring-java-memory<file_sep>/src/ExploringMemoryApplication.java
public class ExploringMemoryApplication {
public static void calculate(int calcValue) {
calcValue = calcValue * 100;
}
public static void renameCustomer(Customer customer2) {
customer2.setName("Ron");
}
public static void main(String[] a) {
int localValue = 5;
calculate(localValue);
// passes a copy of the value, therefore, pass by value
// pass by reference not possible
System.out.println("local value: " + localValue); // prints 5
Customer customer1 = new Customer();
customer1.setName("John");
renameCustomer(customer1);
System.out.println("customer name: " + customer1.getName());
final Customer finalCustomer = new Customer();
finalCustomer.setName("<NAME>");
renameCustomer(finalCustomer);
System.out.println("Final customer name: " + finalCustomer.getName());
}
}
| 246db36941b9343b1bf2dcf1e1122483318fe457 | [
"Java"
] | 1 | Java | shajedul-islam/exploring-java-memory | fa3e5ec5663bcc5bc08dc86843b02c5f9f833b45 | 83e082baf150f4fac6939e6f55cc9c16c3fd9dbf |
refs/heads/master | <file_sep>#include <stdio.h>
#include <ctime>
#include "Neuron.h"
int main()
{
srand((unsigned)time(NULL));
Neuron* nr = new Neuron(2, 0.1);
//샘플 데이터
double sampleInput[4][2] = { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } };
double sampleOutput[4] = { 0, 1, 1, 0 };
for (int i = 0; i < 5000; i++)
{
for (int j = 0; j < 4; j++)
nr->learn(sampleInput[j], sampleOutput[j]);
nr->fix();
//결과를 출력
if ((i + 1) % 500 == 0)
{
printf("-학습 %d 번-\n", i + 1);
for (int j = 0; j < 4; j++)
printf("%.0lf %.0lf : %lf\n", sampleInput[j][0], sampleInput[j][1], nr->work(sampleInput[j]));
}
}
delete nr;
/*
Neuron nr[2][2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
nr[i][j].init(2, 0.1f);
}
}*/
return 0;
}<file_sep>#pragma once
#include <cstdlib>
#include <cmath>
#define sigmoid(x) (1.0 / (1.0 + exp(-(x))))
class Neuron
{
public:
Neuron();
Neuron(int numOfInput, double alpha);
virtual ~Neuron();
void init(int numOfInput, double alpha);
double work(double input[]);
void learn(double input[], double target);
void fix();
private:
int _numInput; //시냅스의 갯수
double* _inputWeight; //입력의 가중치
double* _weightError; //가중치의 에러를 누적 저장함
double _learnAlpha; //민감도(배우는 정도)
};
<file_sep>#include "Neuron.h"
Neuron::Neuron()
{
}
Neuron::Neuron(int numOfInput, double alpha)
{
_numInput = numOfInput;
_learnAlpha = alpha;
_inputWeight = new double[_numInput + 1]; //마지막은 상수 가중치 이다.
_weightError = new double[_numInput + 1];
for (int i = 0; i < _numInput + 1; i++)
{
_inputWeight[i] = ((double)rand() / RAND_MAX) * 2 - 1;
_weightError[i] = 0.0;
}
}
Neuron::~Neuron()
{
delete[] _inputWeight;
delete[] _weightError;
}
void Neuron::init(int numOfInput, double alpha)
{
_numInput = numOfInput;
_learnAlpha = alpha;
_inputWeight = new double[_numInput + 1]; //마지막은 상수 가중치 이다.
_weightError = new double[_numInput + 1];
for (int i = 0; i < _numInput + 1; i++)
{
_inputWeight[i] = ((double)rand() / RAND_MAX) * 2 - 1;
_weightError[i] = 0.0;
}
}
double Neuron::work(double input[])
{
double sum = 0;
for (int i = 0; i < _numInput; i++)
sum += _inputWeight[i] * input[i];
sum += _inputWeight[_numInput] * 1.0; //상수 가중치를 계산한다.
return sigmoid(sum);
}
void Neuron::learn(double input[], double target)
{
double output = work(input); //일단 계산해본다.
double output_error = output - target; //정답과의 오차를 계산
for (int i = 0; i < _numInput; i++) //오차를 누적한다.
_weightError[i] += output_error * input[i] * output * (1 - output);
_weightError[_numInput] += output_error * 1.0 * output * (1 - output);
}
void Neuron::fix()
{
for (int i = 0; i < _numInput + 1; i++) //누적한 오차에 alpha를 곱해 학습한다.
{
_inputWeight[i] -= _learnAlpha * _weightError[i];
_weightError[i] = 0.0;
}
} | 066b93679a7dad6ebded238fc956997d82945b5b | [
"C++"
] | 3 | C++ | MikaAriel/BasicNeuron | 0204bb9c7f2bea27624aa43c6aed5eee5b23442e | d13e9548d1bdb3e0381e544fa544a4fdf3dbfad0 |
refs/heads/main | <file_sep>#include <gtest/gtest.h>
#include "fibonacci_generator.hpp"
using namespace module1;
class FibonacciGeneratorTest : public ::testing::Test
{
protected:
// You can remove any or all of the following functions if their bodies would
// be empty.
FibonacciGeneratorTest()
{
// You can do set-up work for each test here.
}
~FibonacciGeneratorTest() override
{
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override
{
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override
{
// Code here will be called immediately after each test (right
// before the destructor).
}
FibonacciGenerator mGenerator;
};
// Tests that the FibonacciGenerator::next() method does Abc.
TEST_F(FibonacciGeneratorTest, test_next)
{
const long long expected[] = {
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,
987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025,
121393, 196418, 317811, 514229, 832040};
int size = sizeof(expected) / sizeof(expected[0]);
for (int i = 0; i < size; i++)
{
std::pair<int, long long> result = mGenerator.next();
EXPECT_EQ(i, result.first);
EXPECT_EQ(expected[i], result.second);
}
}<file_sep>cd ..
mkdir -p build bin coverage
cd build && cmake .. && make && ../bin/app_test
echo "Done."<file_sep># DOCKER CPP PROJECT
cpp project configured with docker.<file_sep>docker run --rm -it -v $PWD:/workspace museop/googletest:1.0 /bin/sh \
-c "cd /workspace && rm -r build bin coverage"<file_sep>set( BINARY "app" )
set( EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin )
file( GLOB APP_SOURCES
"src/*.cc"
)
add_executable( ${BINARY}
${APP_SOURCES}
${COMMON_SOURCES}
)
target_include_directories( ${BINARY} PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
)<file_sep>#ifndef _FIBONACCI_H_
#define _FIBONACCI_H_
#ifdef __cplusplus
extern "C" {
#endif
long long int fibonacci(int n);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>docker run --rm -it -v $PWD:/workspace museop/googletest:1.0 /bin/sh \
-c "cd /workspace/scripts && ./build.sh"<file_sep>#include "fibonacci.h"
long long fibonacci(int n)
{
if (n == 0 || n == 1)
{
return n;
}
long long fn2 = 0;
long long fn1 = 1;
long long fn;
for (int i = 2; i <= n; ++i)
{
fn = fn1 + fn2;
fn2 = fn1;
fn1 = fn;
}
return fn;
}<file_sep>#include "fibonacci_generator.hpp"
namespace module1
{
std::pair<int, long long> FibonacciGenerator::next()
{
std::pair<int, long long> ret = {count, fn};
long long tmp = fn + fn1;
fn = fn1;
fn1 = tmp;
count++;
return ret;
}
}; // namespace module1<file_sep>cmake_minimum_required( VERSION 3.8.0 )
project( a_cpp_project )
find_package(GTest REQUIRED)
set( CMAKE_CXX_STANDARD 17 )
# common include directories
include_directories(
"module1/include"
"module2/include"
)
# common sources
file(GLOB COMMON_SOURCES
"module1/src/*.cc"
"module2/src/*.c"
)
# common library
# link_libraries( m stdc++fs )
# sub directories
add_subdirectory( application )
add_subdirectory( tests )
<file_sep>#include <iostream>
#include "fibonacci_generator.hpp"
#include "fibonacci.h"
int main(int argc, char *argv[])
{
// module1
module1::FibonacciGenerator generator;
for (int i = 0; i < 20; i++) {
std::pair<int, long long> result = generator.next();
std::cout << result.first << "th fibonacci number is " << result.second << " (from FibonacciGenerator class)\n";
}
std::cout << "\n";
// module2
for (int i = 0; i < 20; i++) {
std::cout << i << "th fibonacci number is " << fibonacci(i) << " (from fibonacci function)\n";
}
return 0;
}<file_sep>set( BINARY "app_test" )
set( EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin )
set( TEST_SOURCES
"test_main.cc"
"test_module1.cc"
"test_module2.cc"
)
add_executable( ${BINARY}
${TEST_SOURCES}
${COMMON_SOURCES}
)
target_link_libraries( ${BINARY}
gtest
)<file_sep>#include <gtest/gtest.h>
#include "fibonacci.h"
TEST(test_module2, test_fibonacci)
{
const long long expected[] = {
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,
987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025,
121393, 196418, 317811, 514229, 832040};
int size = sizeof(expected) / sizeof(expected[0]);
for (int i = 0; i < size; i++)
{
EXPECT_EQ(expected[i], fibonacci(i));
}
}<file_sep>#pragma once
#include <string>
namespace module1 {
class FibonacciGenerator
{
public:
FibonacciGenerator() : count(0), fn(0), fn1(1) {}
virtual ~FibonacciGenerator() {}
std::pair<int, long long> next();
private:
int count;
long long fn;
long long fn1;
};
}; // namespace module1
<file_sep>docker run --rm -it -v $PWD:/workspace museop/googletest:1.0 /bin/sh \
-c "cd /workspace/bin && ./app" | e0a73c9f974deef885e695ee86ccd4d740fe7eea | [
"CMake",
"Markdown",
"C",
"C++",
"Shell"
] | 15 | C++ | museop/docker-cpp-project | 2519d1cd6476847243b064c44127ce3cd15b447d | f0abd48b1281ae3c0f41915a851ceb471dd1583f |
refs/heads/master | <repo_name>pushkars16/reactPoc<file_sep>/src/components/details/Details.js
import React, {Component} from 'react';
import './Details.css';
import ToggleDisplay from 'react-toggle-display';
import {withRouter} from 'react-router-dom';
import MaterialIcon from 'material-icons-react';
class Details extends Component {
constructor(props){
super(props);
this.state = {
customerDetails : this.props.UserInfo,
pageName : this.props.PageName,
show: false
};
}
editFields() {
this.setState({
show: true
})
}
confirmDetails(event) {
if (this.state.pageName === "Home") {
this.props.history.push("/reviewAndConfirm", [this.state.customerDetails]);
}
else {
this.props.history.push("/travelInsurance");
}
}
render() {
const {customerDetails,pageName, show} = this.state;
const isReviewAndConfirm = pageName==="ReviewAndConfirm";
return (
<div className="container">
<div className="vl d"><span id="details">Contact Details</span>
<ToggleDisplay if={pageName === "ReviewAndConfirm"}>
<span onClick={(e) => this.editFields(e)}>
<MaterialIcon icon="create" color="black" size="tiny"/><span id="editText">Edit</span>
</span>
</ToggleDisplay>
<br/>
<span className="tiny">*Marked Fields must be completed, and can be completed in English.</span>
</div>
<form onSubmit = {(e) => this.confirmDetails(e)}>
<label>Given Names</label>
<ToggleDisplay if={show && isReviewAndConfirm}>
<input type="text" placeholder={customerDetails.fName} /> <br/>
</ToggleDisplay>
<ToggleDisplay if={!show}>
<b>{customerDetails.fName}</b> <br/>
</ToggleDisplay>
<label>Family Name</label>
<ToggleDisplay if={show && isReviewAndConfirm}>
<input type="text" placeholder={customerDetails.lName} /> <br/>
</ToggleDisplay>
<ToggleDisplay if={!show}>
<b>{customerDetails.lName}</b> <br/>
</ToggleDisplay>
<input type="submit" value={!isReviewAndConfirm ? "Confirm" : "Buy Now"}/>
</form>
</div>
);
}
}
export default withRouter(Details);
<file_sep>/src/components/home/Home.js
import React, {Component} from 'react';
import Details from '../details/Details';
class Home extends Component {
constructor(props){
super(props);
this.state = {
customerDetails : {},
error: null,
isLoaded: false,
};
}
componentDidMount() {
fetch('data.json')
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded : true,
customerDetails : result
});
},
(error) => {
this.setState({
isLoaded:true,
error
});
}
)
}
render() {
const {isLoaded, error, customerDetails} = this.state;
if(error) {
return <div>Error : {error.message}</div>
}
else if (!isLoaded) {
return <div>Loading...</div>
}
else {
return (
<div>
<Details UserInfo={customerDetails} PageName="Home"/>
</div>
);
}
}
}
export default Home;
<file_sep>/src/components/travelinsurance/TravelInsurance.js
import React, {Component} from 'react';
import MaterialIcon from 'material-icons-react';
import './TravelInsurance.css';
export default class TravelInsurance extends Component {
nextPage(){
this.props.history.push("/");
}
render(){
return(
<div>
<h1>Your Travel Insurance</h1>
<ul id="menu">
<li>1. PERSONAL DETAILS</li>
<li>2. REVIEW</li>
<li>3. ACKNOWLEDGEMENT</li>
</ul>
<div className="div2">
<h3><MaterialIcon icon="check_circle_outline" color="white"/>Congratulations!</h3>
<p>Your insurance purchased is confirmed on Thursday 08 march, 2018.</p>
<p>A confirmation mail is on its way.</p>
</div>
<button onClick={(e) => this.nextPage(e)}>Buy New Policy</button>
</div>
);
}
}
<file_sep>/src/components/reviewandconfirm/ReviewAndConfirm.js
import React, {Component} from 'react';
import Details from '../details/Details';
class ReviewAndConfirm extends Component {
constructor(props){
super(props);
this.state = {
customerDetails : this.props.location.state[0]
};
}
render() {
return (
<div>
<Details UserInfo={this.state.customerDetails} PageName="ReviewAndConfirm"/>
</div>
);
}
}
export default ReviewAndConfirm;
<file_sep>/src/routes/routes.js
import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Home from '../components/home/Home';
import ReviewAndConfirm from '../components/reviewandconfirm/ReviewAndConfirm';
import TravelInsurance from '../components/travelinsurance/TravelInsurance';
export default () => (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/reviewAndConfirm" exact component={ReviewAndConfirm}/>
<Route path="/travelInsurance" exact component={TravelInsurance}/>
</Switch>
</BrowserRouter>
)
| f6dcb7a693d5a275be1d2004dd7ad86b1428b5ca | [
"JavaScript"
] | 5 | JavaScript | pushkars16/reactPoc | 8a092c58381b765e9fa20f67679b65527ac5ad8d | f52e27e9a7d1cf24b50cec90e489702369dcddc6 |
refs/heads/master | <repo_name>caseydailey/pickle-notes<file_sep>/picklenotes.py
#see docs: https://docs.python.org/3/library/pickle.html
import pickle
class Notes:
'''
defines properties and methods for a CLI to record user input,
serialize it, write it to a file, and retrieve it.
properties:
all_notes-- (list) containing previous user input (notes)
methods:
list_notes(self)
prompt(self)
serialize(self)
deserialize(self)
'''
#if there are notes,
#get them them, deserialize them (see deserialize() method below)
#and assign them to the empty set up for them.
#if none exist, pass. (notes will be written to the list when entered by user)
def __init__(self):
self.all_notes = []
try:
self.all_notes = self.deserialize()
except FileNotFoundError:
pass
#invoke when input = 'ls'
#iterates through all_notes list, returning and 'enumerate object', which is printed like this
#0: first note
#1: second note
def list_notes(self):
for key,note in enumerate(self.all_notes):
print(str(key) + ": " + note)
#handles user input
def prompt(self):
'''responds conditionaly to user input
arg: self (instance of app)
returns: 1 of 4 actions based on user input
'''
#prompt user for input
note = input("Enter quick note > ")
#if user inputs 'ls' list_notes
if note == "ls":
self.list_notes()
# 'rm' will list notes, ask which to delete,
# and pass that to delete, converted to integer represent a key
# in all_notes dictionary
elif note == "rm":
self.list_notes()
deleted = input("Which one? > ")
del(self.all_notes[int(deleted)])
#else if user input is not 'quit',
#it must be a note
#in this case append input (note) to the notes list and serialize
elif note != "quit":
self.all_notes.append(note)
self.serialize()
#bring back the prompt as long as they haven't typed 'quit'
if note != "quit": self.prompt()
#open notes and write, in 'binary' by passing all_notes list to
#pickle's dump method https://docs.python.org/3/library/pickle.html
def serialize(self):
with open(notes.txt, wb+) as f:
pickle.dump(self.all_notes, f)
#try to open notes.txt, read the binary using pickle's load method
#assign the resulting value to all_notes (a list)
def deserialize(self):
try:
with open(notes.txt, rb+) as f:
self.all_notes = pickle.load(f)
#https://docs.python.org/3.6/library/exceptions.html
#EOFError means the file was read, but there was nothing in it.
except EOFError:
pass
#return a list of the notes
return self.all_notes
| 09a971c9227b58d8416c02b56d9b0a1417fa8251 | [
"Python"
] | 1 | Python | caseydailey/pickle-notes | 7cfc5c31654537a673c6da262ec0e357aae9a930 | ff7324a13819be1abdf2a82c51c5f7bb0cc9d92c |
refs/heads/master | <repo_name>jexia-inc/matches<file_sep>/Gruntfile.js
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
less: {
options: {
compress: false
},
dev: {
files: {
'app/css/main.css': 'app/css/main.less'
},
options: {
compress: false,
sourceMap: true,
outputSourceFiles: true,
sourceMapFilename: 'app/css/main.css.map',
sourceMapURL: '/css/main.css.map',
sourceMapRootpath: '/'
}
},
prod: {
files: {
'app/css/main.css': 'app/css/main.less'
},
options: {
compress: false,
sourceMap: true,
outputSourceFiles: true,
sourceMapFilename: 'app/css/main.css.map',
sourceMapURL: '/css/main.css.map',
sourceMapRootpath: '/'
}
}
},
useminPrepare: {
html: 'app/index.html',
options: {
dest: 'dist'
}
},
//concat: {
// options: {
// sourceMap: true
// }
//},
//
//uglify: {
// options: {
// sourceMap: true,
// sourceMapIncludeSources: true
// }
//},
usemin: {
html: ['dist/*.html']
},
copy: {
dist: {
files: [
{
expand: true,
dot: true,
src: 'app/*.html',
flatten: true,
dest: 'dist/'
},
{
expand: true,
flatten: true,
src: ['app/css/main.css', 'app/css/main.css.map'],
dest: 'dist/css/'
},
{
expand: true,
dot: true,
cwd: 'app/fonts/',
dest: 'dist/fonts/',
src: ['**/*']
},
{
expand: true,
dot: true,
cwd: 'app/templates/',
dest: 'dist/templates/',
src: ['*']
},
{
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/fonts/',
dest: 'dist/fonts/',
src: ['*']
},
{
expand: true,
dot: true,
cwd: 'bower_components/font-awesome/fonts/',
dest: 'dist/fonts/',
src: ['*']
},
{
expand: true,
dot: true,
cwd: 'app/images/',
dest: 'dist/images/',
src: ['**/*']
}
]
}
},
replace: {
css: {
src: ['dist/css/*.css'], // source files array (supports minimatch)
overwrite: true,
replacements: [{
from: '../../bower_components/bootstrap/', // string replacement
to: '../'
},
{
from: '../../bower_components/font-awesome/', // string replacement
to: '../'
}]
}
},
autoprefixer: {
options: {
browsers: ['last 2 versions', 'ie 8', 'ie 9', 'ie 10']
},
'main': {
src: 'app/css/main.css',
dest: 'app/css/main.css',
options: {
map: {
prev: 'app/css/',
inline: false
}
}
}
},
watch: {
options: {
nospawn: true
},
less: {
files: ['app/css/**/*.less'],
tasks: ['compile']
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-usemin');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-text-replace');
//alias for watch
grunt.registerTask('dev', ['watch']);
//build for the first time
grunt.registerTask('compile', ['less:dev', 'autoprefixer:main']);
// simple build task
grunt.registerTask('build', [
'less:prod',
'autoprefixer:main',
'copy:dist',
'useminPrepare',
'concat',
'uglify',
//'cssmin',
'usemin',
'replace'
]);
};<file_sep>/README.md
# matches
Simple matches example based on Jexia
| 4066f03c23192238eacd3928d1ce03974cf1fb1f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | jexia-inc/matches | b4ded4b2d091ef94551e7d81fb34c0a8c61fc50c | 098b6903fb54be0ca938aeced6cffbb57c7cc3fc |
refs/heads/master | <repo_name>mohnish/twentyeight<file_sep>/README.md
## TwentyEight
Mask your messages. Mix your messages inbetween news articles.
### Usage
- Type "facebook" without the quotes in the search field on the top and hit the "Contact Us" link beside it.
- This will take you directly to the secret messaging app that is embedded inside the camouflage app.
- Once you're done sending the messages, just click on any link on the navigation bar and BOOM. You're messages are hidden again.
- It's that simple ;-)
<file_sep>/config/database.example.js
/*
* RENAME THIS FILE TO database.js and fill-in your details
*/
// Contains all the information about your database
var mysql = require('mysql');
// Database configuration
var user = '';
var password = '';
var database = '';
var host = '';
// Class to encapsulate the mysql object and
// to create a mysql client
var MysqlConfig = function(mysql) {
this.mysql = mysql;
this.client = mysql.createClient({
user: user,
password: <PASSWORD>,
database: database,
host: host
});
}
exports.database = new MysqlConfig(mysql);
// Sample Usage:
// var database = require('../config/database').database;
// var mysql = database.mysql;
// var client = database.client;<file_sep>/public/javascripts/scripts.js
var socket = io.connect();
helpMe = function() {
$('#contact').attr('href', '#');
$('#latest').hide();
$('#enter-chat').hide();
$('#search').val('Enter Search');
}
scrollDown = function() {
$("#latest").scrollTop($("#latest")[0].scrollHeight);
}
$(document).ready(function() {
// ON
socket.on('broadcast', function(data) {
$('#latest').append('<p>' + data.message +'</p>');
scrollDown();
console.log(data.message);
});
socket.on('welcome', function(data) {
var i; // initialize
for(i = 0; i < data.messages.length; i++) {
$('#latest').append('<p>' + data.messages[i] +'</p>');
}
scrollDown();
console.log(data.messages);
});
$('#enter-chat').keydown(function(e) {
if (e.keyCode == '13') {
socket.emit('message', {message: $('#enter-chat').val().trim() });
$(this).val('');
}
});
// This is to clear the placeholder text
$('#search').click(function() {
$(this).val('');
});
$('#contact').click(function() {
if($('#search').val() === 'facebook') {
// Open up the hidden chat box
$('#contact').attr('href', '#latest');
$('#latest').show();
$('#enter-chat').show();
scrollDown();
$('#search').val('');
} else {
helpMe();
}
});
$('.rescue').click(function() {
helpMe();
});
$('.modal-footer a').click(function() {
$('#learn-more-modal').modal('hide');
});
});<file_sep>/routes/index.js
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Twenty8 stories to kick start your day' })
}; <file_sep>/config/password.example.js
// Rename the file to password.js
var password = '<PASSWORD>';
exports.password = function() {
return password;
} | 200ef314d69e35b101730fd751e97e84743ae5fa | [
"Markdown",
"JavaScript"
] | 5 | Markdown | mohnish/twentyeight | 79948848e8eebdb2040d4b29fb62e297de93b4d0 | 1f52d7402c78b53cb998221986b4a390e3b407b7 |
refs/heads/main | <repo_name>sngooglee/Computer-Vision-AI-Human-Pose-Estimation<file_sep>/model/model_deploy.js
let video;
let poseNet;
let pose;
let skeleton;
let numOutputs = 4;
let brain;
let label = "";
function setup() {
var canvas = createCanvas(800, 600);
canvas.position(375, 50);
video = createCapture(VIDEO);
video.hide();
video.size(800, 600);
poseNet = ml5.poseNet(video, modelLoaded);
poseNet.on('pose', gotPoses);
let options = {
inputs: 14,
outputs: numOutputs,
task: 'classification',
debug: true
}
brain = ml5.neuralNetwork(options);
const modelInfo = {
model: 'model/model.json',
metadata: 'model/model_meta.json',
weights: 'model/model.weights.bin',
};
brain.load(modelInfo, brainLoaded);
}
function brainLoaded() {
console.log('pose classification model ready');
// if model is ready, then you can begin classification
classifyPose();
}
function calculate_angle(P1,P2,P3) {
var angle = (
Math.atan2(
P2.position.y - P1.position.y,
P2.position.x - P1.position.x
)
- Math.atan2(
P3.position.y - P1.position.y,
P3.position.x - P1.position.x
)
) * (180 / Math.PI);
if (angle > 90) {
angle = 450 - angle;
} else {
angle = 90 - angle;
}
return angle;
}
function classifyPose(){
// only classify if there is a pose detected from posenet
if(pose){
let inputs = [];
// angle is denoted by angle(P1,P2,P3) where P1 is the 'origin'
let lKnee_lAnkle_lHip = calculate_angle(pose.keypoints[13], pose.keypoints[15], pose.keypoints[11]);
let rKnee_rAnkle_rHip = calculate_angle(pose.keypoints[14], pose.keypoints[16], pose.keypoints[12]);
inputs.push(lKnee_lAnkle_lHip);
inputs.push(rKnee_rAnkle_rHip);
let lHip_lKnee_lShoulder = calculate_angle(pose.keypoints[11], pose.keypoints[13], pose.keypoints[5]);
let rHip_rKnee_rShoulder = calculate_angle(pose.keypoints[12], pose.keypoints[14], pose.keypoints[6]);
inputs.push(lHip_lKnee_lShoulder);
inputs.push(rHip_rKnee_rShoulder);
let lShoulder_lHip_lElbow = calculate_angle(pose.keypoints[5], pose.keypoints[11], pose.keypoints[7]);
let rShoulder_rHip_rElbow = calculate_angle(pose.keypoints[6], pose.keypoints[12], pose.keypoints[8]);
inputs.push(lShoulder_lHip_lElbow);
inputs.push(rShoulder_rHip_rElbow);
let lElbow_lShoulder_lWrist = calculate_angle(pose.keypoints[7], pose.keypoints[5], pose.keypoints[9]);
let rElbow_rShoulder_rWrist = calculate_angle(pose.keypoints[8], pose.keypoints[6], pose.keypoints[10]);
inputs.push(lElbow_lShoulder_lWrist);
inputs.push(rElbow_rShoulder_rWrist);
let lShoulder_lAnkle_lWrist = calculate_angle(pose.keypoints[5], pose.keypoints[15], pose.keypoints[9]);
let rShoulder_rAnkle_rWrist = calculate_angle(pose.keypoints[6], pose.keypoints[16], pose.keypoints[10]);
inputs.push(lShoulder_lAnkle_lWrist);
inputs.push(rShoulder_rAnkle_rWrist);
let lShoulder_lKnee_lWrist = calculate_angle(pose.keypoints[5], pose.keypoints[13], pose.keypoints[9]);
let rShoulder_rKnee_rWrist = calculate_angle(pose.keypoints[6], pose.keypoints[14], pose.keypoints[10]);
inputs.push(lShoulder_lKnee_lWrist);
inputs.push(rShoulder_rKnee_rWrist);
let lShoulder_lHip_lWrist = calculate_angle(pose.keypoints[5], pose.keypoints[11], pose.keypoints[9]);
let rShoulder_rHip_rWrist = calculate_angle(pose.keypoints[6], pose.keypoints[12], pose.keypoints[10]);
inputs.push(lShoulder_lHip_lWrist);
inputs.push(rShoulder_rHip_rWrist);
brain.classify(inputs, gotResult);
}
else{
// delay if it wasnt able to detect the initial pose
setTimeout(classifyPose, 100);
}
}
function gotResult(error, results){
if(results[0].confidence > 0.75){
label = results[0].label;
console.log(label);
}
// after first classification, you want to keep classifying for new poses
classifyPose();
}
function gotPoses(poses) {
console.log(poses);
if (poses.length > 0) {
pose = poses[0].pose;
skeleton = poses[0].skeleton;
}
}
function modelLoaded () {
console.log('poseNet ready');
}
function draw() {
push();
translate(video.width,0);
scale(-1,1);
image(video, 0, 0, video.width, video.height);
if (pose) {
for (let i = 0; i < pose.keypoints.length; i++){
let x = pose.keypoints[i].position.x;
let y = pose.keypoints[i].position.y;
fill (100, 99, 82);
ellipse(x, y, 16, 16);
}
for (let i = 0; i < skeleton.length; i++){
let a = skeleton[i][0]; //skeleton is a 2D array, the second dimension holds the 2 locations that are connected on the keypoint
let b = skeleton[i][1];
strokeWeight(2);
stroke(255);
line(a.position.x, a.position.y, b.position.x, b.position.y);
}
}
pop();
fill(0, 76, 154);
textSize(100);
textAlign(CENTER,TOP);
text(label, 0, 12, width);
}
<file_sep>/README.md
# Computer-Vision-AI-Human-Pose-Estimation
Link to website: <a href="https://vatsalshreekant.github.io/Computer-Vision-AI-Human-Pose-Estimation/index.html" target="_blank" title="AA06">AA06</a>
## Objective:
The objective was to apply computer vision techniques based on Artificial Intelligence for human pose detection that gives real-time feedback. The system assesses a yoga pose being performed and gives real time feedback in the form of error indicators along with a score to measure the accuracy of the pose being performed.
## Motivation:
Recent advancements in Deep Learning has added a huge boost to the already rapidly developing field of computer vision. Pose estimation is a subset of computer vision that refers to computer vision techniques that detect human figures in images and video, so that one could determine, for example, where someone’s ankle shows up in an image. The motivation behind this project was to detect movement and posture errors in performing yoga poses. The idea was to build an effective yoga programme for each user to help them improve their posture and health.
## Approach:
Building a human pose detection system with the PoseNet model entailed dividing the process into 3 steps: Data Collection, Model Training and Model Testing.
<kbd>

</kbd>
<kbd>

</kbd>
<ins>Data Collection</ins>: Using PoseNet, when a pose would be detected, the 14-(x,y) inputs and target data would be fed into the neural network defined object. A setTimeout() function was used to record the poses for 5 seconds.
<ins>Model Training</ins>: The existing data would be loaded into the JavaScript environment. Once the downloaded json file was attached to the model training file, the neural network was then trained across 50 epochs.
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117877283-5f4f9900-b272-11eb-8116-76804aac5d36.PNG">
</kbd>
</p>
<ins>Model Testing</ins>: The model was trained by determining a better way to collect the angles based on specified points as well as a scoring system. For the scoring system, two comparisons were run. Firstly, the model compared the user’s chosen pose with the pose being performed on camera. The second comparison was dependant upon the first. The model then compared each incoming angle against some target angle determined as the average of all individual angles computed for each pose.
## Performance Results:
The performance of the model is quite promising. For poses such as ‘Mountain’ and ‘Warrior 2’, the results, when performed correctly, classifies the current pose.
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117877564-b6ee0480-b272-11eb-93fd-8fb7f19078b1.PNG">
</kbd>
</p>
Upon evaluation of the model, the model is able to classify the poses with an accuracy of 82.9%. Incorrect poses can be detected immediately, and outputs real-time feedback to the user with error indicators.
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117877733-e7ce3980-b272-11eb-98da-895b47221104.PNG">
</kbd>
</p>
The performance of the model drops when the detection of keypoints fails. The scenarios include dark background or environment, as well as multiple users being in the frame of recording. The pose estimation uses a single-pose estimation model to perform data points collection, before being fed to the model classifier.
Attempt of performing ‘Tree’ pose with some computed angles falling below a threshold of 10° and 20° error:
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117879304-cd955b00-b274-11eb-8648-b99d2364f4d3.PNG">
</kbd>
</p>
Attempt of performing ‘Goddess’ pose with some computed angles falling below margin of 20° error:
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117879399-ef8edd80-b274-11eb-9302-92032ace12a7.PNG">
</kbd>
</p>
Attempt of performing ‘Goddess’ pose with some computed angles falling below a threshold of 10° and 20° error:
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117879448-02091700-b275-11eb-9225-76db4fe4fe99.PNG">
</kbd>
</p>
Attempt of performing ‘Warrior 2’ pose with some computed angles falling below a threshold of 10° and 20° error:
<p align="center">
<kbd>
<img src="https://user-images.githubusercontent.com/32462270/117879514-15b47d80-b275-11eb-8f1c-aaa991801432.PNG">
</kbd>
</p>
| e7facd8081f04c2a32a7d8db691c2fe05a7f57eb | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | sngooglee/Computer-Vision-AI-Human-Pose-Estimation | dde8dd091e6877f36c8ef8d3379911fa2f86a617 | 544728619499fc4b3dad27acc7d9317546b715d7 |
refs/heads/master | <repo_name>jroller03/UniversityRegistrar<file_sep>/UniversityRegistrar.Test/ModelTests/StudentTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System;
using UniversityRegistrar.Models;
using UniversityRegistrar;
using MySql.Data.MySqlClient;
namespace UniversityRegistrar.Tests
{
[TestClass]
public class StudentTests : IDisposable
{
public StudentTests()
{
DBConfiguration.ConnectionString = "server=localhost;user id=root;password=<PASSWORD>;port=8889;database=university_registrar;";
}
public void Dispose()
{
Student.DeleteAll();
Course.DeleteAll();
}
[TestMethod]
public void Save_SavesStudentToDatabase_StudentList()
{
Student testStudent = new Student("John", "2018-08-22");
testStudent.Save();
List<Student> testResult = Student.GetAllStudents();
List<Student> allStudents = new List<Student> {testStudent};
CollectionAssert.AreEqual(testResult, allStudents);
}
[TestMethod]
public void Save_DatabaseAssignsIdToObject_Id()
{
//Arrange
Student testStudent = new Student("John", "2018-08-22");
testStudent.Save();
//Act
Student savedStudent = Student.GetAllStudents()[0];
int result = savedStudent.GetId();
int testId = testStudent.GetId();
//Assert
Assert.AreEqual(testId, result);
}
[TestMethod]
public void Equals_OverrideTrueForSameName_Student()
{
//Arrange, Act
Student firstStudent = new Student("John", "2018-08-22");
Student secondStudent = new Student("John", "2018-08-22");
//Assert
Assert.AreEqual(firstStudent, secondStudent);
}
[TestMethod]
public void Find_FindsStudentInDatabase_Student()
{
//Arrange
Student testStudent = new Student("John", "2018-08-22");
testStudent.Save();
//Act
Student foundStudent = Student.Find(testStudent.GetId());
//Assert
Assert.AreEqual(testStudent, foundStudent);
}
[TestMethod]
public void GetCourses_ReturnsAllStudentCourses_CourseList()
{
//Arrange
Student testStudent = new Student("John", "2018-08-22");
testStudent.Save();
Course testCourse1 = new Course("Mathamatics", 8911);
testCourse1.Save();
Course testCourse2 = new Course("Chemistry", 7911);
testCourse2.Save();
//Act
testStudent.AddCourse(testCourse1);
testStudent.AddCourse(testCourse2);
List<Course> result = testStudent.GetCourses();
List<Course> testList = new List<Course> {testCourse1, testCourse2};
//Assert
CollectionAssert.AreEqual(testList, result);
}
}
}
<file_sep>/UniversityRegistrar/Models/Course.cs
using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using UniversityRegistrar.Models;
namespace UniversityRegistrar
{
public class Course
{
private string _courseName;
private int _courseNo;
private int _id;
public Course(string CourseName, int CourseNumber, int id = 0)
{
_courseName = CourseName;
_courseNo = CourseNumber;
_id = id;
}
public int GetId()
{
return _id;
}
public string GetCourseName()
{
return _courseName;
}
public int GetCourseNo()
{
return _courseNo;
}
public override bool Equals(System.Object otherCourse)
{
if (!(otherCourse is Course))
{
return false;
}
else
{
Course newCourse = (Course) otherCourse;
bool idEquality = this.GetId() == newCourse.GetId();
bool courseNameEquality = this.GetCourseName() == newCourse.GetCourseName();
bool courseNoEquality = this.GetCourseNo() == newCourse.GetCourseNo();
return (idEquality && courseNameEquality && courseNoEquality);
}
}
public override int GetHashCode()
{
return this.GetCourseName().GetHashCode();
}
public void Save()
{
MySqlConnection conn = DB.Connection();
conn.Open();
MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"INSERT INTO courses (course_name, course_number) VALUES (@thisCourseName, @thisCourseNo);";
cmd.Parameters.Add(new MySqlParameter("@thisCourseName", this._courseName));
cmd.Parameters.Add(new MySqlParameter("@thisCourseNo", this._courseNo));
cmd.ExecuteNonQuery();
_id = (int) cmd.LastInsertedId;
conn.Close();
if (conn != null)
{
conn.Dispose();
}
}
public static List<Course> GetAllCourses()
{
List<Course> allCourses = new List<Course> {};
MySqlConnection conn = DB.Connection();
conn.Open();
MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT * FROM courses;";
MySqlDataReader rdr = cmd.ExecuteReader() as MySqlDataReader;
while(rdr.Read())
{
int id = rdr.GetInt32(0);
string courseName = rdr.GetString(1);
int courseNo = rdr.GetInt32(2);
Course newCourse = new Course(courseName, courseNo, id);
allCourses.Add(newCourse);
}
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return allCourses;
}
public static Course Find (int id)
{
MySqlConnection conn = DB.Connection();
conn.Open();
MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT * FROM courses WHERE id = (@searchId);";
cmd.Parameters.Add(new MySqlParameter("@searchId", id));
var rdr = cmd.ExecuteReader() as MySqlDataReader;
int courseId = 0;
string courseName = "";
int courseNo = 0;
while(rdr.Read())
{
courseId = rdr.GetInt32(0);
courseName = rdr.GetString(1);
courseNo = rdr.GetInt32(2);
}
Course newCourse = new Course(courseName, courseNo, courseId);
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return newCourse;
}
public static void DeleteAll()
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"DELETE FROM courses;";
cmd.ExecuteNonQuery();
conn.Close();
if (conn != null)
{
conn.Dispose();
}
}
public void Delete()
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"DELETE FROM courses WHERE id = @thisId; DELETE FROM courses_students WHERE course_id = @thisId;";
MySqlParameter idParameter = new MySqlParameter();
idParameter.ParameterName = "@thisId";
idParameter.Value = this.GetId();
cmd.Parameters.Add(idParameter);
cmd.ExecuteNonQuery();
if (conn != null)
{
conn.Close();
}
}
public void AddStudent(Student newStudent)
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"INSERT INTO course (student_id, course_id) VALUES (@studentId, @CourseId);";
MySqlParameter student_id = new MySqlParameter();
student_id.ParameterName = "@StudentId";
student_id.Value = newStudent.GetId();
cmd.Parameters.Add(student_id);
MySqlParameter _id = new MySqlParameter();
_id.ParameterName = "@CourseId";
_id.Value = _id;
cmd.Parameters.Add(_id);
cmd.ExecuteNonQuery();
conn.Close();
if (conn != null)
{
conn.Dispose();
}
}
public List<Student> GetStudents()
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT students.* FROM courses
JOIN course_students ON (courses.course_id = course_students.course_id)
JOIN students ON (course_students.student_id = students.student_id)
WHERE courses.course_id = @CourseId;";
MySqlParameter idParameter = new MySqlParameter();
idParameter.ParameterName = "@CourseId";
idParameter.Value = _id;
cmd.Parameters.Add(idParameter);
var rdr = cmd.ExecuteReader() as MySqlDataReader;
List<int> studentIds = new List<int> {};
while(rdr.Read())
{
int studentId = rdr.GetInt32(0);
studentIds.Add(studentId);
}
rdr.Dispose();
List<Student> students = new List<Student> {};
foreach (int studentId in studentIds)
{
var studentQuery = conn.CreateCommand() as MySqlCommand;
studentQuery.CommandText = @"SELECT * FROM students WHERE student_id = @StudentId;";
MySqlParameter studentIdParameter = new MySqlParameter();
studentIdParameter.ParameterName = "@StudentId";
studentIdParameter.Value = studentId;
studentQuery.Parameters.Add(studentIdParameter);
var studentQueryRdr = studentQuery.ExecuteReader() as MySqlDataReader;
while(studentQueryRdr.Read())
{
int StudentId = studentQueryRdr.GetInt32(0);
string studentName = studentQueryRdr.GetString(1);
string studentDate = studentQueryRdr.GetString(2);
Student foundStudent = new Student(studentName, studentDate, studentId);
students.Add(foundStudent);
}
studentQueryRdr.Dispose();
}
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return students;
}
public void UpdateCourse(string newCourse)
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"UPDATE courses SET course_name = @courseName WHERE id = @searchId";
cmd.Parameters.Add(new MySqlParameter("@searchId", _id));
cmd.Parameters.Add(new MySqlParameter("@courseName", newCourse));
cmd.ExecuteNonQuery();
_courseName = newCourse;
conn.Close();
if (conn !=null)
{
conn.Dispose();
}
}
}
}
<file_sep>/UniversityRegistrar/Controllers/CourseController.cs
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using UniversityRegistrar.Models;
using System;
namespace UniversityRegistrar.Controllers
{
public class CourseController : Controller
{
[HttpGet("/courses/index")]
public ActionResult Index()
{
List<Course> allCourses = Course.GetAllCourses();
return View(allCourses);
}
[HttpGet("/courses/new")]
public ActionResult CreateForm()
{
return View();
}
[HttpPost("/courses")]
public ActionResult Create()
{
Course newCourse = new Course(Request.Form["courseName"], Int32.Parse(Request.Form["courseNo"]));
newCourse.Save();
return RedirectToAction("Success", "Home");
}
[HttpGet("/courses/{id}")]
public ActionResult Details(int id)
{
Dictionary<string, object> model = new Dictionary<string, object>();
Course selectedCourse = Course.Find(id);
List<Student> courseStudents = selectedCourse.GetStudents();
List<Student> allStudents = Student.GetAll();
model.Add("selectedCourse", selectedCourse);
model.Add("courseStudents", courseStudents);
model.Add("allStudents", allStudents);
return View(model);
}
[HttpPost("/courses/{courseId}/students/new")]
public ActionResult AddStudent(int courseId)
{
Course course = Course.Find(courseId);
Student student = Student.Find(Int32.Parse(Request.Form["id"]));
course.AddStudent(student);
return RedirectToAction("Details", new { id = courseId });
}
[HttpGet("/courses/{courseId}/delete")]
public ActionResult DeleteCourse(int courseId)
{
Course course = Course.Find(courseId);
course.Delete();
List<Course> allCourses = Course.GetAllCourses();
return View("Index", allCourses);
}
[HttpGet("/courses/deleteall")]
public ActionResult DeleteAll()
{
Course.DeleteAll();
List<Course> allCourses = Course.GetAllCourses();
return View("Index", allCourses);
}
[HttpGet("/update-course/{id}")]
public ActionResult UpdateCourse(int id)
{
Course updateCourse = Course.Find(id);
return View(updateCourse);
}
[HttpPost("/course-updated/{id}")]
public ActionResult UpdatedCourse(int id)
{
string newCourseName = Request.Form["courseName"];
Course newCourse = new Course(newCourseName, id);
newCourse.UpdateCourse(newCourseName);
return RedirectToAction("AddCourse");
}
}
}
<file_sep>/UniversityRegistrar/Controllers/StudentController.cs
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using UniversityRegistrar.Models;
using System;
namespace UniversityRegistrar.Controllers
{
public class StudentController : Controller
{
[HttpGet("/students/index")]
public ActionResult Index()
{
List<Student> allStudents = Student.GetAll();
return View(allStudents);
}
[HttpGet("/students/new")]
public ActionResult CreateForm()
{
return View();
}
[HttpPost("/students")]
public ActionResult Create()
{
Student newStudent = new Student(Request.Form["name"], Request.Form["date"]);
newStudent.Save();
return RedirectToAction("Success", "Home");
}
[HttpGet("/students/{id}")]
public ActionResult Details(int id)
{
Dictionary<string, object> model = new Dictionary<string, object>();
Student selectedStudent = Student.Find(id);
List<Course> studentCourses = selectedStudent.GetCourses();
List<Course> allCourses = Course.GetAllCourses();
model.Add("selectedStudent", selectedStudent);
model.Add("studentCourses", studentCourses);
model.Add("allCourses", allCourses);
return View(model);
}
[HttpPost("/students/{studentId}/courses/new")]
public ActionResult AddCourse(int studentId)
{
Student student = Student.Find(studentId);
Course course = Course.Find(Int32.Parse(Request.Form["id"]));
student.AddCourse(course);
return RedirectToAction("Details", new { id = studentId });
}
[HttpGet("/students/{studentId}/delete")]
public ActionResult DeleteStudent(int studentId)
{
Student student = Student.Find(studentId);
student.Delete();
List<Student> allStudents = Student.GetAll();
return View("Index", allStudents);
}
[HttpGet("/students/deleteall")]
public ActionResult DeleteAll()
{
Student.DeleteAll();
List<Student> allStudents = Student.GetAll();
return View("Index", allStudents);
}
[HttpGet("/update-student/{id}")]
public ActionResult Updatestudent(int id)
{
Student updateStudent = Student.Find(id);
return View(updateStudent);
}
[HttpPost("/student-updated/{id}")]
public ActionResult UpdatedStudent(int id)
{
string newStudentName = Request.Form["name"];
Student newStudent = new Student(newStudentName, id);
newStudent.UpdateStudent(newStudentName);
return RedirectToAction("AddStudent");
}
}
}
<file_sep>/UniversityRegistrar/Models/Student.cs
using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using UniversityRegistrar.Models;
namespace UniversityRegistrar
{
public class Student
{
private int _id;
private string _name;
private string _date;
public Student(string Name, string DateOfEnrollment, int id = 0)
{
_name = Name;
_date = DateOfEnrollment;
_id = id;
}
public string GetName()
{
return _name;
}
public int GetId()
{
return _id;
}
public string GetDate()
{
return _date;
}
public override bool Equals(System.Object otherStudent)
{
if (!(otherStudent is Student))
{
return false;
}
else
{
Student newStudent = (Student) otherStudent;
bool idEquality = this.GetId() == newStudent.GetId();
bool nameEquality = this.GetName() == newStudent.GetName();
bool dateEquality = this.GetDate() == newStudent.GetDate();
return (idEquality && nameEquality && dateEquality);
}
}
public override int GetHashCode()
{
return this.GetName().GetHashCode();
}
public static List<Student> GetAllStudents()
{
List<Student> allStudents = new List<Student>{};
MySqlConnection conn = DB.Connection();
conn.Open();
MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText= @"SELECT * FROM students;";
var rdr = cmd.ExecuteReader() as MySqlDataReader;
while (rdr.Read())
{
int id = rdr.GetInt32(0);
string name = rdr.GetString(1);
string date = rdr.GetString(2);
Student newStudent = new Student(name, date, id);
allStudents.Add(newStudent);
}
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return allStudents;
}
public void Save()
{
MySqlConnection conn = DB.Connection();
conn.Open();
MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"INSERT INTO students (name, date_of_enrollment) VALUES (@thisName, @thisDate);";
cmd.Parameters.Add(new MySqlParameter("@thisName", _name));
cmd.Parameters.Add(new MySqlParameter("@thisDate", _date));
cmd.ExecuteNonQuery();
_id = (int) cmd.LastInsertedId;
conn.Close();
if (conn != null)
{
conn.Dispose();
}
}
public static Student Find (int id)
{
MySqlConnection conn = DB.Connection();
conn.Open();
MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText= @"SELECT * FROM students WHERE id = (@searchId);";
MySqlParameter searchId = new MySqlParameter();
searchId.ParameterName = "@searchId";
searchId.Value = id;
cmd.Parameters.Add(searchId);
var rdr = cmd.ExecuteReader() as MySqlDataReader;
int studentId = 0;
string name = "";
string date = "";
while(rdr.Read())
{
studentId = rdr.GetInt32(0);
name = rdr.GetString(1);
date = rdr.GetString(2);
}
Student newStudent = new Student(name, date, studentId);
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return newStudent;
}
public void AddCourse(Course newCourse)
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"INSERT INTO courses_students (course_id, student_id ) VALUES (@CourseId, @StudentId);";
MySqlParameter course_id = new MySqlParameter();
course_id.ParameterName = "@CourseId";
course_id.Value = newCourse.GetId();
cmd.Parameters.Add(course_id);
MySqlParameter student_id = new MySqlParameter();
student_id.ParameterName = "@StudentId";
student_id.Value = _id;
cmd.Parameters.Add(student_id);
cmd.ExecuteNonQuery();
conn.Close();
if (conn != null)
{
conn.Dispose();
}
}
public List<Course> GetCourses()
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT courses.* FROM students
JOIN courses_students ON (student_id = courses_students.student_id)
JOIN courses ON (courses_students.course_id=courses.id)
WHERE student_id = @StudentId;";
MySqlParameter studentIdParameter = new MySqlParameter();
studentIdParameter.ParameterName = "@StudentId";
studentIdParameter.Value = _id;
cmd.Parameters.Add(studentIdParameter);
var rdr = cmd.ExecuteReader() as MySqlDataReader;
List<Course> courses = new List<Course> {};
while(rdr.Read())
{
int courseId = rdr.GetInt32(0);
string courseName = rdr.GetString(1);
int courseNumber = rdr.GetInt32(2);
Course newCourse = new Course(courseName, courseNumber, courseId);
courses.Add(newCourse);
}
rdr.Dispose();
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return courses;
}
public static void DeleteAll()
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"DELETE FROM students;";
cmd.ExecuteNonQuery();
conn.Close();
if (conn != null)
{
conn.Dispose();
}
}
public static List<Student> GetAll()
{
List<Student> allStudents = new List<Student> {};
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT * FROM students;";
var rdr = cmd.ExecuteReader() as MySqlDataReader;
while(rdr.Read())
{
int studentId = rdr.GetInt32(0);
string studentName = rdr.GetString(1);
string studentDate = rdr.GetString(2);
Student newStudent = new Student(studentName, studentDate, studentId);
allStudents.Add(newStudent);
}
conn.Close();
if (conn != null)
{
conn.Dispose();
}
return allStudents;
}
public void Delete()
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"DELETE FROM students WHERE id = @thisId; DELETE FROM courses_students WHERE course_id = @thisId;";
MySqlParameter idParameter = new MySqlParameter();
idParameter.ParameterName = "@thisId";
idParameter.Value = this.GetId();
cmd.Parameters.Add(idParameter);
cmd.ExecuteNonQuery();
if (conn != null)
{
conn.Close();
}
}
public void UpdateStudent(string newStudent)
{
MySqlConnection conn = DB.Connection();
conn.Open();
var cmd = conn.CreateCommand() as MySqlCommand;
cmd.CommandText = @"UPDATE students SET name = @name WHERE id = @searchId";
cmd.Parameters.Add(new MySqlParameter("@searchId", _id));
cmd.Parameters.Add(new MySqlParameter("@name", newStudent));
cmd.ExecuteNonQuery();
_name = newStudent;
conn.Close();
if (conn !=null)
{
conn.Dispose();
}
}
}
}
<file_sep>/UniversityRegistrar.Test/ModelTests/CourseTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System;
using UniversityRegistrar.Models;
using UniversityRegistrar;
using MySql.Data.MySqlClient;
namespace UniversityRegistrar.Tests
{
[TestClass]
public class CourseTests : IDisposable
{
public CourseTests()
{
DBConfiguration.ConnectionString = "server=localhost;user id=root;password=<PASSWORD>;port=8889;database=university_registrar;";
}
public void Dispose()
{
Course.DeleteAll();
Student.DeleteAll();
}
[TestMethod]
public void Save_SavesCourseToDatabase_CourseList()
{
Course testCourse = new Course("Physics", 11212);
testCourse.Save();
List<Course> testResult = Course.GetAllCourses();
List<Course> allCities = new List<Course> {testCourse};
CollectionAssert.AreEqual(testResult, allCities);
}
[TestMethod]
public void Save_DatabaseAssignsIdToObject_Id()
{
//Arrange
Course testCourse = new Course("Maths", 89892);
testCourse.Save();
//Act
Course savedCourse = Course.GetAllCourses()[0];
int result = savedCourse.GetId();
int testId = testCourse.GetId();
//Assert
Assert.AreEqual(testId, result);
}
[TestMethod]
public void Equals_OverrideTrueForSameName_Course()
{
//Arrange, Act
Course firstCourse = new Course("Maths", 89892);
Course secondCourse = new Course("Maths", 89892);
//Assert
Assert.AreEqual(firstCourse, secondCourse);
}
[TestMethod]
public void Find_FindsCourseInDatabase_Course()
{
//Arrange
Course testCourse = new Course("Data Structure", 71232);
testCourse.Save();
//Act
Course foundCourse = Course.Find(testCourse.GetId());
//Assert
Assert.AreEqual(testCourse, foundCourse);
}
}
}
<file_sep>/university_registrar.sql
-- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: May 09, 2018 at 01:39 AM
-- Server version: 5.6.35
-- PHP Version: 7.0.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `university_registrar`
--
CREATE DATABASE IF NOT EXISTS `university_registrar` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `university_registrar`;
-- --------------------------------------------------------
--
-- Table structure for table `courses`
--
CREATE TABLE `courses` (
`id` int(11) NOT NULL,
`course_name` varchar(255) NOT NULL,
`course_number` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `courses`
--
INSERT INTO `courses` (`id`, `course_name`, `course_number`) VALUES
(19, 'Math', 7911);
-- --------------------------------------------------------
--
-- Table structure for table `courses_students`
--
CREATE TABLE `courses_students` (
`id` int(11) NOT NULL,
`course_id` int(11) NOT NULL,
`student_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `courses_students`
--
INSERT INTO `courses_students` (`id`, `course_id`, `student_id`) VALUES
(1, 1, 11),
(2, 2, 11),
(3, 12, 15),
(4, 13, 15),
(5, 17, 19),
(6, 18, 19);
-- --------------------------------------------------------
--
-- Table structure for table `students`
--
CREATE TABLE `students` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`date_of_enrollment` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `students`
--
INSERT INTO `students` (`id`, `name`, `date_of_enrollment`) VALUES
(20, 'John', '2018-09-30'),
(22, 'billy', '2018-3-23');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `courses`
--
ALTER TABLE `courses`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `courses_students`
--
ALTER TABLE `courses_students`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `students`
--
ALTER TABLE `students`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `courses`
--
ALTER TABLE `courses`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT for table `courses_students`
--
ALTER TABLE `courses_students`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `students`
--
ALTER TABLE `students`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 24b2b0cb758acfce2b069cf1dcc10b9cacc9bb6b | [
"C#",
"SQL"
] | 7 | C# | jroller03/UniversityRegistrar | 34c926d04c6c82a114f16fd4833126a507b7efa7 | 631338ddfc3048949ac2ec1f2844f17ef94403a4 |
refs/heads/master | <file_sep>/**
* @class ReportChart
* @extends Graphics
* @param {App.Collection} model
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.ReportChart = function ReportChart(model,width,height,pixelRatio)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
eventListenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,width,height);
this._model = model;
this._eventsRegistered = false;
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._segmentTween = new App.TweenProxy(1,App.Easing.outExpo,0,eventListenerPool);
this._highlightTween = new App.TweenProxy(1,App.Easing.outExpo,0,eventListenerPool);
this._segmentPool = new App.ObjectPool(App.ReportChartSegment,5);
this._segments = null;
this._showSegments = void 0;
this._hideSegments = void 0;
this._highlightSegment = void 0;
this._center = new PIXI.Point(Math.round(width/2),Math.round(height/2));
this._thickness = Math.round(width * 0.07 * pixelRatio);
this._chartSize = width - Math.round(5 * pixelRatio * 2);// 5px margin on sides for highlight line
this._highlight = this.addChild(new App.ReportChartHighlight(this._center,width,height,Math.round(3 * pixelRatio)));
};
App.ReportChart.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Update
*/
App.ReportChart.prototype.update = function update()
{
var i = 0,
l = this._model.length(),
j = 0,
k = 0,
totalBalance = 0.0,
previousBalance = 0.0,
deletedState = App.LifeCycleState.DELETED,
segmentArray = null,
segment = null,
account = null,
category = null,
categories = null;
// Reset segments and highlight
this._showSegments = null;
this._hideSegments = null;
this._highlight.change(null);
this._highlight.update(1);
// Release segments back to pool
if (this._segments)
{
for (var prop in this._segments)
{
segmentArray = this._segments[prop];
while (segmentArray.length)
{
segment = segmentArray.pop();
this.removeChild(segment);
this._segmentPool.release(segment);
}
}
}
else
{
this._segments = Object.create(null);
}
// Populate segments again
for (i=0;i<l;)
{
account = this._model.getItemAt(i++);
totalBalance = account.balance;
if (account.lifeCycleState !== deletedState && !isNaN(totalBalance) && totalBalance !== 0.0)
{
if (!this._segments[account.id]) this._segments[account.id] = [];
segmentArray = this._segments[account.id];
previousBalance = 0.0;
category = null;
categories = account.categories;
for (j=0,k=categories.length;j<k;)
{
if (category) previousBalance += category.balance;
category = categories[j++];
segment = this._segmentPool.allocate();
segment.setModel(category,totalBalance,previousBalance);
segmentArray.push(segment);
this.addChild(segment);
}
}
}
};
/**
* Show segments associated with account passed in
* @param {App.Account} account
*/
App.ReportChart.prototype.showSegments = function showSegments(account)
{
if (this._showSegments)
{
if (this._showSegments === this._segments[account.id]) return;
this._hideSegments = this._showSegments;
}
else
{
this._hideSegments = null;
}
this._showSegments = this._segments[account.id];
for (var i=0,l=this._showSegments.length;i<l;) this._showSegments[i++].fullyRendered = false;
this._registerEventListeners();
this._segmentTween.restart();
};
/**
* Highlight segment
* @param {App.Category} category
*/
App.ReportChart.prototype.highlightSegment = function highlightSegment(category)
{
//TODO add icon of highlighted category in the middle of chart
if (this._showSegments)
{
var segment = this._getSegmentByCategory(category);
if (segment === this._highlightSegment) return;
this._highlightSegment = segment;
this._highlight.change(segment);
this._registerEventListeners();
this._highlightTween.restart();
}
};
/**
* Find and return segment by category passed in
* @param {App.Category} category
* @returns {App.ReportChartSegment}
* @private
*/
App.ReportChart.prototype._getSegmentByCategory = function _getSegmentByCategory(category)
{
var i = 0,
l = this._showSegments.length;
for (;i<l;i++)
{
if (this._showSegments[i].rendersModel(category)) return this._showSegments[i];
}
return null;
};
/**
* Register event listeners
* @private
*/
App.ReportChart.prototype._registerEventListeners = function _registerEventListeners()
{
if (!this._eventsRegistered)
{
this._eventsRegistered = true;
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._segmentTween.addEventListener(App.EventType.COMPLETE,this,this._onSegmentTweenComplete);
this._highlightTween.addEventListener(App.EventType.COMPLETE,this,this._onHighlightTweenComplete);
}
};
/**
* UnRegister event listeners
* @private
*/
App.ReportChart.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._segmentTween.removeEventListener(App.EventType.COMPLETE,this,this._onSegmentTweenComplete);
this._highlightTween.removeEventListener(App.EventType.COMPLETE,this,this._onHighlightTweenComplete);
this._eventsRegistered = false;
};
/**
* RAF tick handler
* @private
*/
App.ReportChart.prototype._onTick = function _onTick()
{
if (this._segmentTween.isRunning()) this._updateSegmentTween();
if (this._highlightTween.isRunning()) this._highlight.update(this._highlightTween.progress);
};
/**
* Update show hide tween
* @private
*/
App.ReportChart.prototype._updateSegmentTween = function _updateSegmentTween()
{
var GraphicUtils = App.GraphicUtils,
progress = this._segmentTween.progress,
progressAngle = progress * 360,
size = this._chartSize,
i = 0,
l = this._showSegments.length,
end = 0,
segment = null;
if (this._showSegments)
{
for (;i<l;i++)
{
segment = this._showSegments[i];
if (progressAngle >= segment.startAngle && !segment.fullyRendered)
{
end = progressAngle;
if (end >= segment.endAngle)
{
end = segment.endAngle;
segment.fullyRendered = true;
}
GraphicUtils.drawArc(segment,this._center,size,size,this._thickness,segment.startAngle,end,segment.steps,0,0,0,"0x"+segment.color,1);
}
}
}
if (this._hideSegments)
{
progress = 1 - progress;
size = this._chartSize * progress;
for (i=0,l=this._hideSegments.length;i<l;i++)
{
segment = this._hideSegments[i];
GraphicUtils.drawArc(segment,this._center,size,size,this._thickness,segment.startAngle,segment.endAngle,20,0,0,0,"0x"+segment.color,progress);
}
}
};
/**
* On segment tweenc omplete
* @private
*/
App.ReportChart.prototype._onSegmentTweenComplete = function _onSegmentTweenComplete()
{
if (!this._segmentTween.isRunning() && !this._highlightTween.isRunning()) this._unRegisterEventListeners();
this._updateSegmentTween();
};
/**
* On Highlight tween complete
* @private
*/
App.ReportChart.prototype._onHighlightTweenComplete = function _onHighlightTweenComplete()
{
if (!this._segmentTween.isRunning() && !this._highlightTween.isRunning()) this._unRegisterEventListeners();
this._highlight.update(1);
};
<file_sep>/**
* @class EventListener
* @param {number} index
* @constructor
*/
App.EventListener = function EventListener(index)
{
this.allocated = false;
this.poolIndex = index;
this.type = null;
this.scope = null;
this.handler = null;
};
/**
* @method reset Reset item returning to pool
*/
App.EventListener.prototype.reset = function reset()
{
this.allocated = false;
this.type = null;
this.scope = null;
this.handler = null;
};
<file_sep>/**
* @class TweenProxy
* @param {number} duration
* @param {Function} ease
* @param {number} defaultProgress
* @param {ObjectPool} eventListenerPool
* @extends {EventDispatcher}
* @constructor
*/
App.TweenProxy = function TweenProxy(duration,ease,defaultProgress,eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
this.progress = defaultProgress || 0.0;
this._interval = -1;
this._running = false;
this._reversed = false;
this._start = -1.0;
this._end = -1.0;
this._reversedEnd = -1.0;
this._now = -1.0;
this._duration = duration * 1000 || 1000;
this._ease = ease || App.Easing.linear;
this._timeStamp = window.performance && window.performance.now ? window.performance : Date;
this._intervalReference = this._tweenInterval.bind(this);
};
App.TweenProxy.prototype = Object.create(App.EventDispatcher.prototype);
/**
* Set easing function
* @method setEase
* @param {Function} value
*/
App.TweenProxy.prototype.setEase = function setEase(value)
{
this._ease = value;
};
/**
* Start
* @method start
* @param {boolean} [reverseIfRunning=false] - reverse the tween if the tween is currently running
* @param {Function} [ease=null] - set new ease
*/
App.TweenProxy.prototype.start = function start(reverseIfRunning,ease)
{
if (ease) this.setEase(ease);
if (!this._running)
{
this._running = true;
this._reversed = false;
this._tween();
}
else
{
if (reverseIfRunning)
{
if (this._reversed)
{
this._reversed = false;
}
else
{
this._reversed = true;
this._reversedEnd = this._start + (this._now - this._start) * 2;
}
}
}
};
/**
* Stop
* @method stop
*/
App.TweenProxy.prototype.stop = function stop()
{
this._running = false;
clearInterval(this._interval);
this._interval = -1;
};
/**
* Restart
* @method restart
*/
App.TweenProxy.prototype.restart = function restart()
{
if (this._running) this.stop();
this.start();
};
/**
* Is tween running?
* @method isRunning
* @returns {boolean}
*/
App.TweenProxy.prototype.isRunning = function isRunning()
{
return this._running;
};
/**
* Tween
* @method _tween
* @private
*/
App.TweenProxy.prototype._tween = function _tween()
{
if (this._interval > 0)
{
clearInterval(this._interval);
this._interval = -1.0;
}
this.progress = 0.0;
this._start = this._timeStamp.now();
this._end = this._start + this._duration;
this._interval = setInterval(this._intervalReference,1000/120);
};
/**
* Tween interval function
* @method _tweenInterval
* @private
*/
App.TweenProxy.prototype._tweenInterval = function _tweenInterval()
{
this._now = this._timeStamp.now();
var end = this._reversed ? this._reversedEnd : this._end;
var progress = (this._duration - (end - this._now)) / this._duration;
if (progress < 0) progress = 0.0;
else if (progress > 1) progress = 1.0;
this.progress = this._ease(progress);
if(this._now >= end)
{
this.progress = 1.0;
this.stop();
this.dispatchEvent(App.EventType.COMPLETE);
}
};
/**
* Destroy
*/
App.TweenProxy.prototype.destroy = function destroy()
{
App.EventDispatcher.prototype.destroy.call(this);
this.stop();
this._intervalReference = null;
this._timeStamp = null;
this._ease = null;
};<file_sep>/**
* @class ChangeCategory
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeCategory = function ChangeCategory(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool || App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
};
App.ChangeCategory.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {Object} data
* @param {string} data.type
* @param {App.Category} data.category
* @param {string} data.name
* @param {string} data.color
* @param {string} data.icon
* @param {string} data.budget
* @param {App.Account} data.account
* @param {Command} data.nextCommand
* @param {Object} data.nextCommandData
*/
App.ChangeCategory.prototype.execute = function execute(data)
{
var EventType = App.EventType,
category = data.category,
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
category = new App.Category();
category.account = data.account.id;
this._nextCommandData.updateData = category;
}
else if (type === EventType.CHANGE)
{
category.name = data.name || category.name;
category.icon = data.icon || category.icon;
category.color = data.color || category.color;
category.budget = data.budget || category.budget;
this._registerSubCategories(category);
}
else if (type === EventType.CONFIRM)
{
category.name = data.name;
category.icon = data.icon;
category.color = data.color;
category.budget = data.budget;
this._registerCategory(category);
this._registerSubCategories(category);
}
else if (type === EventType.CANCEL)
{
this._cancelChanges(category);
}
else if (type === EventType.DELETE)
{
this._deleteCategory(category);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
/**
* Add category to collection
* @param category
* @private
*/
App.ChangeCategory.prototype._registerCategory = function _registerCategory(category)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
categories = ModelLocator.getProxy(ModelName.CATEGORIES);
if (categories.indexOf(category) === -1)
{
categories.addItem(category);
ModelLocator.getProxy(ModelName.ACCOUNTS).find("id",category.account).addCategory(category);
var StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE);
Storage.setData(StorageKey.ACCOUNTS,ModelLocator.getProxy(ModelName.ACCOUNTS).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.CATEGORIES,categories.serialize());//TODO do I need to serialize every time?
}
};
/**
* Add subCategories to collection
* @param category
* @private
*/
App.ChangeCategory.prototype._registerSubCategories = function _registerSubCategories(category)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE),
StorageKey = App.StorageKey,
subCategoryCollection = ModelLocator.getProxy(ModelName.SUB_CATEGORIES),
subCategories = category.subCategories,
subCategory = null,
i = 0,
l = subCategories.length;
for (;i<l;)
{
subCategory = subCategories[i++];
if (subCategoryCollection.indexOf(subCategory) === -1) subCategoryCollection.addItem(subCategory);
}
Storage.setData(StorageKey.CATEGORIES,ModelLocator.getProxy(ModelName.CATEGORIES).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.SUB_CATEGORIES,subCategoryCollection.serialize());//TODO do I need to serialize every time?
};
/**
* Cancel changes made to the category since last saved state
* @param {App.Category} category
* @private
*/
App.ChangeCategory.prototype._cancelChanges = function _cancelChanges(category)
{
var ModelName = App.ModelName,
ModelLocator = App.ModelLocator,
StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE),
subCategoryCollection = ModelLocator.getProxy(ModelName.SUB_CATEGORIES),
allSubCategories = category.subCategories,
i = 0,
l = allSubCategories.length;
category.revokeState();
var revokedSubCategories = category.subCategories;
for (;i<l;i++)
{
if (revokedSubCategories.indexOf(allSubCategories[i]) === -1 && subCategoryCollection.indexOf(allSubCategories[i]) > -1)
{
subCategoryCollection.removeItem(allSubCategories[i]);
}
}
i = 0;
l = revokedSubCategories.length;
for (;i<l;) revokedSubCategories[i++].revokeState();
//TODO destroy category if it was newly created and eventually cancelled?
Storage.setData(StorageKey.CATEGORIES,ModelLocator.getProxy(ModelName.CATEGORIES).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.SUB_CATEGORIES,subCategoryCollection.serialize());//TODO do I need to serialize every time?
};
/**
* Delete category
* @param {App.Category} category
* @private
*/
App.ChangeCategory.prototype._deleteCategory = function _deleteCategory(category)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE),
accounts = ModelLocator.getProxy(ModelName.ACCOUNTS);
accounts.find("id",category.account).removeCategory(category);
Storage.setData(StorageKey.ACCOUNTS,accounts.serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.CATEGORIES,ModelLocator.getProxy(ModelName.CATEGORIES).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.SUB_CATEGORIES,ModelLocator.getProxy(ModelName.SUB_CATEGORIES).serialize());//TODO do I need to serialize every time?
category.destroy();
};
<file_sep>/**
* @class CurrencyButton
* @extends DisplayObjectContainer
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {PIXI.Texture} options.skin
* @param {{font:string,fill:string}} options.symbolLabelStyle
* @constructor
*/
App.CurrencyButton = function CurrencyButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new PIXI.Rectangle(0,0,options.width,options.height);
this._model = null;
this._pixelRatio = options.pixelRatio;
this._skin = this.addChild(new PIXI.Sprite(options.skin));
this._symbolLabel = this.addChild(new PIXI.Text("",options.symbolLabelStyle));
this._renderAll = true;
this._render();
};
App.CurrencyButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* @method render
* @private
*/
App.CurrencyButton.prototype._render = function _render()
{
if (this._renderAll)
{
this._renderAll = false;
this._symbolLabel.x = Math.round(20 * this._pixelRatio);
this._symbolLabel.y = Math.round((this.boundingBox.height - this._symbolLabel.height) / 2);
}
};
/**
* Set model
* @param {App.CurrencySymbol} model
*/
App.CurrencyButton.prototype.setModel = function getModel(model)
{
this._model = model;
this._symbolLabel.setText(this._model.symbol);
};
/**
* Click handler
*/
App.CurrencyButton.prototype.onClick = function onClick()
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(EventType.CHANGE_TRANSACTION,{
type:EventType.CHANGE,
currencyQuote:this._model.symbol,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
};
<file_sep>/**
* LayoutUtils
* @type {{update: Function}}
*/
App.LayoutUtils = {
/**
* Update layout
* @param {Array.<{x:number,y:number,boundingBox:Rectangle}>} items
* @param {string} direction
* @param {number} originalPosition
*/
update:function update(items,direction,originalPosition)
{
var i = 0,
l = items.length,
item = null,
position = originalPosition || 0,
Direction = App.Direction;
if (direction === Direction.X)
{
for (;i<l;)
{
item = items[i++];
item.x = position;
position = Math.round(position + item.boundingBox.width);
}
}
else if (direction === Direction.Y)
{
for (;i<l;)
{
item = items[i++];
item.y = position;
position = Math.round(position + item.boundingBox.height);
}
}
}
};
<file_sep>/**
* @class ApplicationView
* @extends DisplayObjectContainer
* @param {Stage} stage
* @param {CanvasRenderer} renderer
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.ApplicationView = function ApplicationView(stage,renderer,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
ViewLocator = App.ViewLocator,
ViewName = App.ViewName,
listenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
this._renderer = renderer;
this._stage = stage;
this._layout = {
originalWidth:width,
originalHeight:height,
width:Math.round(width * pixelRatio),
height:Math.round(height * pixelRatio),
headerHeight:Math.round(50 * pixelRatio),
contentHeight:Math.round((height - 50) * pixelRatio),
pixelRatio:pixelRatio
};
//TODO do I need event dispatcher here?
this._eventDispatcher = new App.EventDispatcher(listenerPool);
this._background = new PIXI.Graphics();
this._backgroundPattern = new PIXI.TilingSprite(App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_PATTERN,this._layout.width,this._layout.height);
//TODO use ScreenFactory for the screens?
//TODO deffer initiation and/or rendering of most of the screens?
this._screenStack = ViewLocator.addViewSegment(ViewName.SCREEN_STACK,new App.ViewStack([
new App.AccountScreen(this._layout),
new App.CategoryScreen(this._layout),
new App.SelectTimeScreen(this._layout),
new App.EditCategoryScreen(this._layout),
new App.TransactionScreen(this._layout),
new App.ReportScreen(this._layout),
new App.AddTransactionScreen(this._layout),
new App.EditScreen(this._layout),
new App.CurrencyPairScreen(this._layout),
new App.EditCurrencyPairScreen(this._layout),
new App.CurrencyScreen(this._layout),
new App.SettingScreen(this._layout),
new App.Menu(this._layout)
],false,listenerPool));
this._header = ViewLocator.addViewSegment(ViewName.HEADER,new App.Header(this._layout));
this._init();
this.addChild(this._background);
this.addChild(this._backgroundPattern);
this.addChild(this._screenStack);
this.addChild(this._header);
};
App.ApplicationView.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Init
* @private
*/
App.ApplicationView.prototype._init = function _init()
{
App.GraphicUtils.drawRect(this._background,App.ColorTheme.GREY,1,0,0,this._layout.width,this._layout.height);
this._backgroundPattern.alpha = 0.4;
this.scrollTo(0);
this._registerEventListeners();
this._screenStack.y = this._layout.headerHeight;
};
/**
* Register event listeners
*
* @method _registerEventListeners
* @private
*/
App.ApplicationView.prototype._registerEventListeners = function _registerEventListeners()
{
var EventType = App.EventType;
this._screenStack.addEventListener(EventType.CHANGE,this,this._onScreenChange);
App.ModelLocator.getProxy(App.ModelName.TICKER).addEventListener(EventType.TICK,this,this._onTick);
};
/**
* On screen change
* @private
*/
App.ApplicationView.prototype._onScreenChange = function _onScreenChange()
{
this._screenStack.show();
this._screenStack.hide();
};
/**
* Scroll to value passed in
* @param {number} value
*/
App.ApplicationView.prototype.scrollTo = function scrollTo(value)
{
if (document.documentElement && document.documentElement.scrollTop) document.documentElement.scrollTop = value;
else document.body.scrollTop = value;
};
/**
* On Ticker's Tick event
*
* @method _onTick
* @private
*/
App.ApplicationView.prototype._onTick = function _onTick()
{
//TODO do not render if nothing happens (prop 'dirty'?) - drains battery
this._renderer.render(this._stage);
};
/**
* On resize
* @private
*/
App.ApplicationView.prototype._onResize = function _onResize()
{
//this.scrollTo(0);
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ApplicationView.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ApplicationView.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
<file_sep>/**
* Storage
* @param {string} workerUrl
* @constructor
*/
App.Storage = function Storage(workerUrl)
{
this._workerUrl = workerUrl;
this._worker = null;
this._initialized = false;
};
/**
* Init
* @private
*/
App.Storage.prototype._init = function _init()
{
if (!this._initialized)
{
this._initialized = true;
if (window.Worker)
{
this._worker = new Worker(this._workerUrl);
this._registerEventListeners();
this._worker.postMessage("init|"+JSON.stringify(App.StorageKey));
}
}
};
/**
* Register event listeners
* @private
*/
App.Storage.prototype._registerEventListeners = function _registerEventListeners()
{
this._worker.addEventListener("message",this._onWorkerMessage);
};
/**
* On worker message
* @param {Event} e
* @private
*/
App.Storage.prototype._onWorkerMessage = function _onWorkerMessage(e)
{
var components = e.data.split("|");
localStorage.setItem(components[0],components[1]);//TODO compress
};
/**
* Send data to worker to save under key passed in
* @param {string} key
* @param {Object} data
*/
App.Storage.prototype.setData = function setData(key,data/*,context? (CONFIRM|DELETE|...)*/)
{
if (!this._initialized) this._init();
this._worker.postMessage(key+"|"+JSON.stringify(data));
};
/**
* Query worker for data by key passed in
* @param {string} key
*/
App.Storage.prototype.getData = function getData(key)
{
if (!this._initialized) this._init();
var data = localStorage.getItem(key),
serialized = data;
if (data)
{
data = JSON.parse(data);
}
else
{
data = App.DefaultData[key];
serialized = JSON.stringify(data);
localStorage.setItem(key,serialized);//TODO save via worker ... and compress
}
this._worker.postMessage("save|"+key+"|"+serialized);
return data;
};
<file_sep>/**
* ScreenMode
* @type {{DEFAULT: number, ADD: number, EDIT: number, SELECT: number}}
*/
App.ScreenMode = {
DEFAULT:1,
ADD:2,
EDIT:3,
SELECT:4
};
<file_sep>/**
* @class Menu
* @param {Object} layout
* @constructor
*/
App.Menu = function Menu(layout)
{
App.Screen.call(this,layout);
var MenuItem = App.MenuItem,
ScreenName = App.ScreenName,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width,
itemLabelStyle = FontStyle.get(20,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
itemOptions = {
width:w,
height:Math.round(40 * r),
pixelRatio:r,
style:itemLabelStyle
};
this._addTransactionItem = new MenuItem("Add Transaction","transactions",ScreenName.ADD_TRANSACTION,{width:w,height:Math.round(50*r),pixelRatio:r,style:itemLabelStyle});
this._transactionsItem = new MenuItem("Transactions","transactions",ScreenName.TRANSACTIONS,itemOptions);
this._reportItem = new MenuItem("Report","chart",ScreenName.REPORT,itemOptions);
this._accountsItem = new MenuItem("Accounts","account",ScreenName.ACCOUNT,itemOptions);
this._budgetItem = new MenuItem("Budgets","budget",-1,itemOptions);
this._currenciesItem = new MenuItem("Currency rates","currencies",ScreenName.CURRENCY_PAIRS,itemOptions);
this._settignsItem = new MenuItem("Settings","settings-app",ScreenName.SETTINGS,itemOptions);
this._container = new PIXI.Graphics();
this._pane = new App.Pane(App.ScrollPolicy.OFF,App.ScrollPolicy.AUTO,w,layout.contentHeight,r,false);
this._background = new PIXI.Graphics();
this._items = [];
this._render();
this.addChild(this._background);
this._items.push(this._container.addChild(this._addTransactionItem));
this._items.push(this._container.addChild(this._transactionsItem));
this._items.push(this._container.addChild(this._reportItem));
this._items.push(this._container.addChild(this._accountsItem));
this._items.push(this._container.addChild(this._budgetItem));
this._items.push(this._container.addChild(this._currenciesItem));
this._items.push(this._container.addChild(this._settignsItem));
this._pane.setContent(this._container);
this.addChild(this._pane);
};
App.Menu.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.Menu.prototype._render = function _render()
{
var r = this._layout.pixelRatio,
smallGap = Math.round(2 * r),
bigGap = Math.round(25 * r),
GraphicUtils = App.GraphicUtils,
bgColor = App.ColorTheme.BLUE_DARK;
this._transactionsItem.y = this._addTransactionItem.boundingBox.height + bigGap;
this._reportItem.y = this._transactionsItem.y + this._transactionsItem.boundingBox.height + smallGap;
this._accountsItem.y = this._reportItem.y + this._reportItem.boundingBox.height + smallGap;
this._budgetItem.y = this._accountsItem.y + this._accountsItem.boundingBox.height + smallGap;
this._currenciesItem.y = this._budgetItem.y + this._budgetItem.boundingBox.height + bigGap;
this._settignsItem.y = this._currenciesItem.y + this._currenciesItem.boundingBox.height + smallGap;
GraphicUtils.drawRect(this._container,bgColor,1,0,0,this._layout.width,this._settignsItem.y+this._settignsItem.boundingBox.height);
GraphicUtils.drawRect(this._background,bgColor,1,0,0,this._layout.width,this._layout.contentHeight);
};
/**
* Enable
*/
App.Menu.prototype.enable = function enable()
{
if (!this._enabled)
{
this._registerEventListeners(App.EventLevel.LEVEL_1);
this._registerEventListeners(App.EventLevel.LEVEL_2);
this._pane.resetScroll();
this._pane.enable();
this._enabled = true;
}
};
/**
* Disable
*/
App.Menu.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
};
/**
* Click handler
* @private
*/
App.Menu.prototype._onClick = function _onClick()
{
this._pane.cancelScroll();
var ScreenName = App.ScreenName,
ScreenTitle = App.ScreenTitle,
HeaderAction = App.HeaderAction,
item = this._getItemByPosition(this.stage.getTouchData().getLocalPosition(this._container).y),
screenName = item ? item.getScreenName() : ScreenName.BACK,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(screenName,0,null,HeaderAction.MENU,HeaderAction.ADD_TRANSACTION);
switch (screenName)
{
case ScreenName.ADD_TRANSACTION:
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
break;
case ScreenName.TRANSACTIONS:
changeScreenData.headerName = ScreenTitle.TRANSACTIONS;
changeScreenData.updateData = App.ModelLocator.getProxy(App.ModelName.TRANSACTIONS).copySource().reverse();
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.REPORT:
changeScreenData.headerName = ScreenTitle.REPORT;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.ACCOUNT:
changeScreenData.screenMode = App.ScreenMode.EDIT;
changeScreenData.headerName = ScreenTitle.ACCOUNTS;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.CURRENCY_PAIRS:
changeScreenData.screenMode = App.ScreenMode.EDIT;
changeScreenData.headerName = ScreenTitle.CURRENCY_RATES;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.SETTINGS:
changeScreenData.headerName = ScreenTitle.SETTINGS;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
}
};
/**
* Return item by position passed in
* @param {number} position
* @return {MenuItem}
* @private
*/
App.Menu.prototype._getItemByPosition = function _getItemByPosition(position)
{
var i = 0,
l = this._items.length,
item = null;
for (;i<l;)
{
item = this._items[i++];
if (position >= item.y && position < item.y + item.boundingBox.height) return item;
}
return null;
};
<file_sep>/**
* @class CategoryButtonEdit
* @extends SwipeButton
* @param {number} poolIndex
* @param {{width:number,height:number,pixelRatio:number,nameLabelStyle:{font:string,fill:string},editLabelStyle:{font:string,fill:string}}} options
* @constructor
*/
App.CategoryButtonEdit = function CategoryButtonEdit(poolIndex,options)
{
App.SwipeButton.call(this,options.width,Math.round(80*options.pixelRatio));
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._mode = null;
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._editLabel = this.addChild(new PIXI.Text("Edit",options.editLabelStyle));
this._swipeSurface = this.addChild(new App.CategoryButtonSurface(options));
this._renderAll = true;
};
App.CategoryButtonEdit.prototype = Object.create(App.SwipeButton.prototype);
/**
* Render
* @private
*/
App.CategoryButtonEdit.prototype._render = function _render()
{
var w = this.boundingBox.width,
h = this.boundingBox.height;
this._swipeSurface.render(this._model.name,this._model.icon,this._model.color);
if (this._renderAll)
{
this._renderAll = false;
App.GraphicUtils.drawRect(this._background,App.ColorTheme.RED,1,0,0,w,h);
this._editLabel.x = Math.round(w - 50 * this._pixelRatio);
this._editLabel.y = Math.round(18 * this._pixelRatio);
}
};
/**
* Disable
*/
App.CategoryButtonEdit.prototype.disable = function disable()
{
App.SwipeButton.prototype.disable.call(this);
};
/**
* Update
* @param {App.Category} model
* @param {string} mode
*/
App.CategoryButtonEdit.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._render();
this.close(true);
};
/**
* Click handler
* @param {InteractionData} data
*/
App.CategoryButtonEdit.prototype.onClick = function onClick(data)
{
if (this._isOpen && data.getLocalPosition(this).x >= this._width - this._openOffset)
{
this._model.saveState();
App.Controller.dispatchEvent(
App.EventType.CHANGE_SCREEN,
App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT_CATEGORY,
App.ScreenMode.EDIT,
this._model,
0,
0,
App.ScreenTitle.EDIT_CATEGORY
)
);
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.CategoryButtonEdit.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.CategoryButtonEdit.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
<file_sep>/**
* @class ChangeSubCategory
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeSubCategory = function ChangeSubCategory(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool);//App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL)
};
App.ChangeSubCategory.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {{subCategory:App.SubCategory,name:string,category:App.Category,nextCommand:Command,nextCommandData:App.ChangeScreenData}} data
*/
App.ChangeSubCategory.prototype.execute = function execute(data)
{
var EventType = App.EventType,
subCategory = data.subCategory,
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
subCategory = new App.SubCategory();
// subCategory.category = data.category.id;
this._nextCommandData.updateData = {subCategory:subCategory,category:data.category};
}
else if (type === EventType.CHANGE)
{
subCategory.name = data.name;
data.category.addSubCategory(subCategory);
}
else if (type === EventType.DELETE)
{
data.category.removeSubCategory(subCategory);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
<file_sep>App.StorageKey = Object.create(null,{
SETTINGS:{value:"settings",writable:false,configurable:false,enumerable:true},
CURRENCY_PAIRS:{value:"currencyPairs",writable:false,configurable:false,enumerable:true},
SUB_CATEGORIES:{value:"subCategories",writable:false,configurable:false,enumerable:true},
CATEGORIES:{value:"categories",writable:false,configurable:false,enumerable:true},
ACCOUNTS:{value:"accounts",writable:false,configurable:false,enumerable:true},
TRANSACTIONS_META:{value:"transactionsMeta",writable:false,configurable:false,enumerable:true},
TRANSACTIONS:{value:"transactions",writable:false,configurable:false,enumerable:true}
});
<file_sep>/**
* ScreenTitle
* @type {{
* MENU: string,
* ACCOUNTS:string,
* EDIT_ACCOUNT:string,
* ADD_ACCOUNT:string,
* CATEGORIES:string,
* SELECT_ACCOUNT: string,
* SELECT_CATEGORY: string,
* ADD_CATEGORY: string,
* EDIT_CATEGORY: string,
* EDIT_SUB_CATEGORY:string,
* ADD_SUB_CATEGORY:string,
* SELECT_TIME: string,
* TRANSACTIONS:string,
* ADD_TRANSACTION: string,
* EDIT_TRANSACTION: string,
* REPORT:string,
* CURRENCY_RATES:string,
* SELECT_CURRENCY:string,
* EDIT_CURRENCY_RATE:string,
* SETTINGS:string
* }}
*/
App.ScreenTitle = {
MENU:"Menu",
ACCOUNTS:"Accounts",
EDIT_ACCOUNT:"Edit Account",
ADD_ACCOUNT:"Add Account",
SELECT_ACCOUNT:"Select Account",
CATEGORIES:"Categories",
SELECT_CATEGORY:"Select Category",
ADD_CATEGORY:"Add Category",
EDIT_CATEGORY:"Edit Category",
EDIT_SUB_CATEGORY:"Edit SubCategory",
ADD_SUB_CATEGORY:"Add SubCategory",
SELECT_TIME:"Select Time & Date",
TRANSACTIONS:"Transactions",
ADD_TRANSACTION:"Add Transaction",
EDIT_TRANSACTION:"Edit Transaction",
REPORT:"Report",
CURRENCY_RATES:"Currency Rates",
SELECT_CURRENCY:"Select Currency",
EDIT_CURRENCY_RATE:"Edit Currency Rate",
SETTINGS:"Settings"
};
<file_sep>/**
* @class TilePane
* @extends Pane
* @param {string} xScrollPolicy
* @param {string} yScrollPolicy
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {boolean} useMask
* @constructor
*/
App.TilePane = function TilePane(xScrollPolicy,yScrollPolicy,width,height,pixelRatio,useMask)
{
App.Pane.call(this,xScrollPolicy,yScrollPolicy,width,height,pixelRatio,useMask);
};
App.TilePane.prototype = Object.create(App.Pane.prototype);
/**
* Set content of the pane
*
* @method setContent
* @param {TileList} content
*/
App.TilePane.prototype.setContent = function setContent(content)
{
this.removeContent();
this._content = content;
this._contentHeight = Math.round(this._content.boundingBox.height);
this._contentWidth = Math.round(this._content.boundingBox.width);
this._contentBoundingBox.width = this._contentWidth;
this._contentBoundingBox.height = this._contentHeight;
this.addChildAt(this._content,0);
this._updateScrollers();
if (this._useMask) this._updateMask();
};
/**
* Resize
*
* @param {number} width
* @param {number} height
*/
App.TilePane.prototype.resize = function resize(width,height)
{
this.boundingBox.width = width || this.boundingBox.width;
this.boundingBox.height = height || this.boundingBox.height;
if (this._content)
{
this._contentHeight = Math.round(this._content.boundingBox.height);
this._contentWidth = Math.round(this._content.boundingBox.width);
this._contentBoundingBox.width = this._contentWidth;
this._contentBoundingBox.height = this._contentHeight;
this._checkPosition();
this._updateScrollers();
if (this._useMask) this._updateMask();
}
};
/**
* Update content's x position
* @param {number} position
* @private
*/
App.TilePane.prototype._updateX = function _updateX(position)
{
this._content.updateX(position);
};
/**
* Update content's y position
* @param {number} position
* @private
*/
App.TilePane.prototype._updateY = function _updateY(position)
{
this._content.updateY(position);
};
<file_sep>/**
* @class Stack
* @constructor
*/
App.Stack = function Stack()
{
this._source = [];
this._top = 0;
};
/**
* Push item into stack
* @param {*} item
*/
App.Stack.prototype.push = function push(item)
{
this._source[this._top++] = item;
};
/**
* Remove item from top of the stack
* @returns {*}
*/
App.Stack.prototype.pop = function pop()
{
var item = this._source[this._top-1];
if (item) this._source[--this._top] = null;
return item;
};
/**
* Peek what on top of the stack
* @returns {*}
*/
App.Stack.prototype.peek = function peek(index)
{
if (!index) index = 1;
return this._source[this._top-index];
};
/**
* Return size of the stack
* @returns {number}
*/
App.Stack.prototype.length = function length()
{
return this._top;
};
/**
* Clear stack
*/
App.Stack.prototype.clear = function clear()
{
this._top = 0;
};
<file_sep>/** @type {{
* rgbToHex:Function,
* hexToRgb:Function,
* rgbToHsl:Function,
* hslToRgb:Function,
* rgbToHsv:Function,
* hsvToRgb:Function
* }} */
App.MathUtils = {
/**
* Convert RGB values to HEX value
* @param {number} red
* @param {number} green
* @param {number} blue
* @returns {string}
*/
rgbToHex:function rgbToHex(red,green,blue)
{
return ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
},
/**
* Convert HEX value to r, g, and b color component values
* @param {string} hex
* @param {Object|null} container
* @returns {{r:number,g:number,b:number}|null}
*/
hexToRgb:function hexToRgb(hex,container)
{
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (result)
{
if (container)
{
container.r = parseInt(result[1],16);
container.g = parseInt(result[2],16);
container.b = parseInt(result[3],16);
return container;
}
else
{
return {r:parseInt(result[1],16),g:parseInt(result[2],16),b:parseInt(result[3],16)};
}
}
return null;
},
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @param {Object|null} container
* @return {{h:number,s:number,l:number}} The HSL representation
*/
rgbToHsl:function rgbToHsl(r,g,b,container)
{
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r,g,b),
min = Math.min(r,g,b),
h,
s,
l = (max + min) / 2;
if(max == min)
{
h = s = 0; // achromatic
}
else
{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max)
{
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
if (container)
{
container.h = h;
container.s = s;
container.l = l;
return container;
}
return {h:h,s:s,l:l};
},
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} l The lightness
* @param {Object|null} container
* @return {{r:number,g:number,b:number}} The RGB representation
*/
hslToRgb:function hslToRgb(h,s,l,container)
{
var r = l,
g = l,
b = l;
if (s !== 0)
{
var q = l < 0.5 ? l * (1 + s) : l + s - l * s,
p = 2 * l - q;
r = this._hueToRgb(p,q,h+1/3);
g = this._hueToRgb(p,q,h);
b = this._hueToRgb(p,q,h-1/3);
}
if (container)
{
container.r = r * 255;
container.g = g * 255;
container.b = b * 255;
return container;
}
return {r:r*255,g:g*255,b:b*255};
},
/**
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and v in the set [0, 1].
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @param {Object|null} container
* @return {{h:number,s:number,v:number}} The HSV representation
*/
rgbToHsv:function rgbToHsv(r,g,b,container)
{
r = r / 255;
g = g / 255;
b = b / 255;
var max = Math.max(r,g,b),
min = Math.min(r,g,b),
d = max - min,
s = max === 0 ? 0 : d / max,
h = 0;
if(max !== min)
{
switch(max)
{
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
if (container)
{
container.h = h;
container.s = s;
container.v = max;
return container;
}
return {h:h,s:s,v:max};
},
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and v are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} v The value
* @param {Object|null} container
* @return {{r:number,g:number,b:number}} The RGB representation
*/
hsvToRgb:function hsvToRgb(h,s,v,container)
{
var i = Math.floor(h * 6),
f = h * 6 - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
r = 0,
g = 0,
b = 0;
switch(i % 6)
{
case 0:
r = v, g = t, b = p;
break;
case 1:
r = q, g = v, b = p;
break;
case 2:
r = p, g = v, b = t;
break;
case 3:
r = p, g = q, b = v;
break;
case 4:
r = t, g = p, b = v;
break;
case 5:
r = v, g = p, b = q;
break;
}
if (container)
{
container.r = r * 255;
container.g = g * 255;
container.b = b * 255;
return container;
}
return {r:r*255,g:g*255,b:b*255};
},
/**
* Converts Hue to RGB
* @param {number} p
* @param {number} q
* @param {number} t
* @return {number}
*/
_hueToRgb:function _hueToRgb(p,q,t)
{
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
};
<file_sep>/**
* @class TileList
* @extends List
* @param {string} direction
* @param {number} windowSize
* @constructor
*/
App.TileList = function TileList(direction,windowSize)
{
App.List.call(this,direction);
this._windowSize = windowSize;
};
App.TileList.prototype = Object.create(App.List.prototype);
/**
* Update X position
* @param {number} position
*/
App.TileList.prototype.updateX = function updateX(position)
{
this.x = Math.round(position);
var i = 0,
l = this._items.length,
width = 0,
childX = 0,
child = null;
for (;i<l;)
{
child = this._items[i++];
width = child.boundingBox.width;
childX = this.x + child.x;
child.visible = childX + width > 0 && childX < this._windowSize;
}
};
/**
* Update Y position
* @param {number} position
*/
App.TileList.prototype.updateY = function updateY(position)
{
this.y = Math.round(position);
var i = 0,
l = this._items.length,
height = 0,
childY = 0,
child = null;
for (;i<l;)
{
child = this._items[i++];
height = child.boundingBox.height;
childY = this.y + child.y;
child.visible = childY + height > 0 && childY < this._windowSize;
}
};
/**
* Update layout
* @param {boolean} [updatePosition=false]
*/
App.TileList.prototype.updateLayout = function updateLayout(updatePosition)
{
App.List.prototype.updateLayout.call(this);
if (updatePosition)
{
if (this._direction === App.Direction.X) this.updateX(this.x);
else if (this._direction === App.Direction.Y) this.updateY(this.y);
}
};
<file_sep>/**
* @class PaymentMethod
* @param {string} name
* @param {Collection} collection
* @param {*} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.PaymentMethod = function PaymentMethod(name,collection,parent,eventListenerPool)
{
this.id = App.PaymentMethod._ID++;
this.name = name;
};
App.PaymentMethod._ID = 1;
App.PaymentMethod.CASH = "Cash";
App.PaymentMethod.CREDIT_CARD = "Credit-Card";
//TODO add vouchers (or let user add his own method)
<file_sep>/**
* Transition state
* @enum {string}
* @return {{SHOWING:string,SHOWN:string,HIDING:string,HIDDEN:string,OPEN:string,OPENING:string,CLOSED:string,CLOSING:string}}
*/
App.TransitionState = {
SHOWING:"SHOWING",
SHOWN:"SHOWN",
HIDING:"HIDING",
HIDDEN:"HIDDEN",
OPEN:"OPEN",
OPENING:"OPENING",
CLOSED:"CLOSED",
CLOSING:"CLOSING"
};
<file_sep>/**
* GraphicUtils
* @type {{drawRect: Function,drawRects:Function}}
*/
App.GraphicUtils = {
/**
* Draw rectangle into graphics passed in
* @param {PIXI.Graphics} graphics
* @param {number} color
* @param {number} alpha
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
*/
drawRect:function drawRect(graphics,color,alpha,x,y,width,height)
{
graphics.clear();
graphics.beginFill(color,alpha);
graphics.drawRect(x,y,width,height);
graphics.endFill();
},
/**
* Draw multiple rectangles
* @param {PIXI.Graphics} graphics
* @param {number} color
* @param {number} alpha
* @param {Array.<number>} data
* @param {boolean} clear
* @param {boolean} end
*/
drawRects:function drawRects(graphics,color,alpha,data,clear,end)
{
if (clear) graphics.clear();
graphics.beginFill(color,alpha);
var i = 0,
l = data.length;
for (;i<l;) graphics.drawRect(data[i++],data[i++],data[i++],data[i++]);
if (end) graphics.endFill();
},
/**
* Draw rounded rectangle into graphics passed in
* @param {PIXI.Graphics} graphics
* @param {number} color
* @param {number} alpha
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {number} radius
*/
drawRoundedRect:function drawRoundedRect(graphics,color,alpha,x,y,width,height,radius)
{
graphics.clear();
graphics.beginFill(color,alpha);
graphics.drawRoundedRect(x,y,width,height,radius);
graphics.endFill();
},
/**
* Draw arc
* @param {PIXI.Graphics} graphics
* @param {PIXI.Point} center
* @param {number} width
* @param {number} height
* @param {number} thickness
* @param {number} startAngle
* @param {number} endAngle
* @param {number} smoothSteps
* @param {number} lineColor
* @param {number} lineAlpha
* @param {number} lineThickness
* @param {number} fillColor
* @param {number} fillAlpha
*/
drawArc:function drawArc(graphics,center,width,height,thickness,startAngle,endAngle,smoothSteps,lineColor,lineAlpha,lineThickness,fillColor,fillAlpha)
{
startAngle -= 90;
endAngle -= 90;
var angle = startAngle,
angleStep = (endAngle - startAngle) / smoothSteps,
degToRad = Math.PI / 180,
radians = angle * degToRad,
radiusX = width / 2,
radiusY = height / 2,
centerX = center.x,
centerY = center.y,
i = 0;
graphics.clear();
graphics.lineStyle(lineThickness,lineColor,lineAlpha);
graphics.beginFill(fillColor,fillAlpha);
graphics.moveTo(centerX+Math.cos(radians)*radiusX,centerY+Math.sin(radians)*radiusY);
for (;i<smoothSteps;)
{
angle = startAngle + angleStep * i++;
radians = angle * degToRad;
graphics.lineTo(centerX+Math.cos(radians)*radiusX,centerY+Math.sin(radians)*radiusY);
}
radians = endAngle * degToRad;
graphics.lineTo(centerX+Math.cos(radians)*radiusX,centerY+Math.sin(radians)*radiusY);
for (i=smoothSteps;i>=0;)
{
angle = startAngle + angleStep * i--;
radians = angle * degToRad;
graphics.lineTo(centerX+Math.cos(radians)*(radiusX-thickness),centerY+Math.sin(radians)*(radiusY-thickness));
}
graphics.endFill();
}
};
<file_sep>/**
* @class SubCategoryList
* @extends Graphics
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {boolean} options.displayHeader
* @param {{font:string,fill:string}} options.nameLabelStyle
* @param {{font:string,fill:string}} options.deleteLabelStyle
* @param {{font:string,fill:string}} options.addLabelStyle
* @param {number} options.openOffset
* @constructor
*/
App.SubCategoryList = function SubCategoryList(options)
{
PIXI.DisplayObjectContainer.call(this);
var FontStyle = App.FontStyle,
r = options.pixelRatio,
w = options.width,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:w,
height:Math.round(40 * r),
pixelRatio:r,
whiteSkin:skin.WHITE_40,
greySkin:skin.GREY_40,
nameLabelStyle:FontStyle.get(14,FontStyle.BLUE),
editLabelStyle:FontStyle.get(16,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
openOffset:Math.round(80 * r)
};
this.boundingBox = new App.Rectangle(0,0,w,0);
this._model = null;
this._mode = null;
this._width = w;
this._pixelRatio = r;
this._buttonPool = new App.ObjectPool(App.SubCategoryButton,5,buttonOptions);
this._interactiveButton = null;
if (options.displayHeader) this._header = this.addChild(new App.ListHeader("Sub-Categories",this._width,this._pixelRatio));
this._buttonList = this.addChild(new App.List(App.Direction.Y));
this._addNewButton = new App.AddNewButton("ADD SUB-CATEGORY",options.addLabelStyle,options.addButtonSkin,this._pixelRatio);
};
App.SubCategoryList.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Update layout
* @private
*/
App.SubCategoryList.prototype._render = function _render()
{
if (this._header) this._buttonList.y = this._header.height;
this.boundingBox.height = this._buttonList.y + this._buttonList.boundingBox.height;
};
/**
* @method update
* @param {App.Category} model
* @param {string} mode
*/
App.SubCategoryList.prototype.update = function update(model,mode)
{
this._model = model;
this._buttonList.remove(this._addNewButton);
var subCategories = model.subCategories,
i = 0,
l = this._buttonList.length,
button = null;
for (;i<l;i++) this._buttonPool.release(this._buttonList.removeItemAt(0));
i = 0;
l = subCategories.length;
for (;i<l;)
{
button = this._buttonPool.allocate();
button.update(subCategories[i++],mode);
this._buttonList.add(button,false);
}
this._buttonList.add(this._addNewButton);
this._buttonList.updateLayout();
this._render();
this._mode = mode;
};
/**
* Called when swipe starts
* @param {string} direction
* @private
*/
App.SubCategoryList.prototype.swipeStart = function swipeStart(direction)
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button && !(button instanceof App.AddNewButton))
{
this._interactiveButton = button;
this._interactiveButton.swipeStart(direction);
this.closeButtons(false);
}
};
/**
* Called when swipe ends
* @private
*/
App.SubCategoryList.prototype.swipeEnd = function swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.SubCategoryList.prototype.closeButtons = function closeButtons(immediate)
{
var i = 0,
l = this._buttonList.length - 1,// last button is 'AddNewButton'
button = null;
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
};
/**
* Find and return item under point passed in
* @param {InteractionData} data PointerData to get the position from
*/
App.SubCategoryList.prototype.getItemUnderPoint = function getItemUnderPoint(data)
{
return this._buttonList.getItemUnderPoint(data);
};
/**
* Test if position passed in falls within this list boundaries
* @param {number} position
* @returns {boolean}
*/
App.SubCategoryList.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* @property length
* @type number
*/
Object.defineProperty(App.SubCategoryList.prototype,'length',{
get:function()
{
// Subtract one; last button is 'Add' button
return this._buttonList.length - 1;
}
});<file_sep>/**
* @class Transaction
* @param {Array} [data=null]
* @param {Collection} [collection=null]
* @param {*} [parent=null]
* @param {ObjectPool} [eventListenerPool=null]
* @constructor
*/
App.Transaction = function Transaction(data,collection,parent,eventListenerPool)
{
if (data)
{
this._data = data;
this.id = data[0];
this.amount = data[1];
this.type = data[2];
this.pending = data[3] === 1;
this.repeat = data[4] === 1;
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
this._currencyBase = null;
this._currencyQuote = null;
// this._currencyRate = 1.0;
this.note = data[9] ? decodeURIComponent(data[9]) : "";
}
else
{
this._data = null;
this.id = null;
this.amount = "";
this.type = App.TransactionType.EXPENSE;
this.pending = false;
this.repeat = false;
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
this._currencyBase = null;
this._currencyQuote = null;
// this._currencyRate = 1.0;
this.note = "";
}
};
/**
* Destroy
*/
App.Transaction.prototype.destroy = function destroy()
{
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
};
/**
* Check if the transaction is saved, i.e. has data
* @returns {Array|null}
*/
App.Transaction.prototype.isSaved = function isSaved()
{
return this._data;
};
/**
* Save
*/
App.Transaction.prototype.save = function save()
{
this._data = this.serialize();
};
/**
* Revoke all changes to the last saved ones
*/
App.Transaction.prototype.revokeState = function revokeState()
{
if (this._data)
{
this.id = this._data[0];
this.amount = this._data[1];
this.type = this._data[2];
this.pending = this._data[3] === 1;
this.repeat = this._data[4] === 1;
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
this._currencyBase = null;
this._currencyQuote = null;
// this._currencyRate = 1.0;
this.note = this._data[9] ? decodeURIComponent(this._data[9]) : "";
}
};
/**
* Serialize
* @returns {Array}
*/
App.Transaction.prototype.serialize = function serialize()
{
// If base and quote currency are same, I don't need to save whole 'base/quote@rate' format - it's redundant; save just one quote.
var base = this.currencyBase,
quote = this.currencyQuote,
currency = base === quote ? quote : base + "/" + quote + "@" + App.ModelLocator.getProxy(App.ModelName.CURRENCY_PAIRS).findRate(base,quote),
data = [
this.id,
parseFloat(this.amount),
this.type,
this.pending ? 1 : 0,
this.repeat ? 1 : 0,
this.account.id + "." + this.category.id + "." + this.subCategory.id,
this.method.id,
this.date.getTime(),
currency
];
if (this.note && this.note.length) data.push(App.StringUtils.encode(this.note));
return data;
};
/**
* Return serialized data
* @param {boolean} serialize If set to true, return result of 'serialize' call
* @returns {Array}
*/
App.Transaction.prototype.getData = function getData(serialize)
{
return serialize ? this.serialize() : this._data;
};
/**
* Create and return copy of itself
* @returns {App.Transaction}
*/
App.Transaction.prototype.copy = function copy()
{
var copy = new App.Transaction();
copy.amount = this.amount;
copy.type = this.type;
copy.pending = this.pending;
copy.repeat = this.repeat;
copy.account = this.account;
copy.category = this.category;
copy.subCategory = this.subCategory;
copy.method = this.method;
copy.date = this.date;
copy.currencyBase = this.currencyBase;
copy.currencyQuote = this.currencyQuote;
copy.note = this.note;
return copy;
};
/**
* @property savedAmount
* @type number
*/
Object.defineProperty(App.Transaction.prototype,'savedAmount',{
get:function()
{
if (this._data) return this._data[1];
else return 0.0;
}
});
/**
* @property savedType
* @type number
*/
Object.defineProperty(App.Transaction.prototype,'savedType',{
get:function()
{
if (this._data) return this._data[2];
else return 1;
}
});
/**
* @property savedPending
* @type boolean
*/
Object.defineProperty(App.Transaction.prototype,'savedPending',{
get:function()
{
if (this._data) return this._data[3] === 1;
else return false;
}
});
/**
* @property savedSubCategory
* @type App.SubCategory
*/
Object.defineProperty(App.Transaction.prototype,'savedSubCategory',{
get:function()
{
return App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).find("id",this._data[5].split(".")[2]);
}
});
/**
* @property savedCurrencyBase
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'savedCurrencyBase',{
get:function()
{
if (this._data[8].indexOf("@") === -1) return this._data[8];
else return this._data[8].split("@")[0].split("/")[0];
}
});
/**
* @property savedCurrencyQuote
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'savedCurrencyQuote',{
get:function()
{
if (this._data[8].indexOf("@") === -1) return this._data[8];
else return this._data[8].split("@")[0].split("/")[1];
}
});
/**
* @property savedCurrencyRate
* @type number
*/
Object.defineProperty(App.Transaction.prototype,'savedCurrencyRate',{
get:function()
{
if (this._data[8].indexOf("@") === -1) return null;
else return parseFloat(this._data[8].split("@")[1]);
}
});
/**
* @property account
* @type Account
*/
Object.defineProperty(App.Transaction.prototype,'account',{
get:function()
{
if (!this._account)
{
if (this._data) this._account = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).find("id",this._data[5].split(".")[0]);
else this._account = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultAccount;
}
return this._account;
},
set:function(value)
{
this._account = value;
}
});
/**
* @property category
* @type Category
*/
Object.defineProperty(App.Transaction.prototype,'category',{
get:function()
{
if (!this._category)
{
if (this._data)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
ids = this._data[5].split(".");
this._category = ModelLocator.getProxy(ModelName.CATEGORIES).find("id",ids[1]);
this._subCategory = ModelLocator.getProxy(ModelName.SUB_CATEGORIES).find("id",ids[2]);
}
else
{
this._category = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultCategory;
this._subCategory = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultSubCategory;
}
}
return this._category;
},
set:function(value)
{
this._category = value;
}
});
/**
* @property subCategory
* @type SubCategory
*/
Object.defineProperty(App.Transaction.prototype,'subCategory',{
get:function()
{
if (!this._subCategory)
{
if (this._data) this._subCategory = this.savedSubCategory;
else this._subCategory = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultSubCategory;
}
return this._subCategory;
},
set:function(value)
{
this._subCategory = value;
}
});
/**
* @property method
* @type PaymentMethod
*/
Object.defineProperty(App.Transaction.prototype,'method',{
get:function()
{
if (!this._method)
{
if (this._data) this._method = App.ModelLocator.getProxy(App.ModelName.PAYMENT_METHODS).find("id",this._data[6]);
else this._method = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultPaymentMethod;
}
return this._method;
},
set:function(value)
{
this._method = value;
}
});
/**
* @property date
* @type Date
*/
Object.defineProperty(App.Transaction.prototype,'date',{
get:function()
{
if (!this._date)
{
if (this._data) this._date = new Date(this._data[7]);
else this._date = new Date();
}
return this._date;
},
set:function(value)
{
this._date = value;
}
});
/**
* @property currency
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'currencyBase',{
get:function()
{
if (!this._currencyBase)
{
if (this._data) this._currencyBase = this.savedCurrencyBase;
else this._currencyBase = App.ModelLocator.getProxy(App.ModelName.SETTINGS).baseCurrency;
}
return this._currencyBase;
},
set:function(value)
{
this._currencyBase = value;
}
});
/**
* @property currency
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'currencyQuote',{
get:function()
{
if (!this._currencyQuote)
{
if (this._data) this._currencyQuote = this.savedCurrencyQuote;
else this._currencyQuote = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultCurrencyQuote;
}
return this._currencyQuote;
},
set:function(value)
{
this._currencyQuote = value;
}
});
<file_sep>/**
* @class CurrencyPairCollection
* @param {Array} source
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.CurrencyPairCollection = function CurrencyPairCollection(source,eventListenerPool)
{
App.Collection.call(this,source,App.CurrencyPair,null,eventListenerPool);
};
App.CurrencyPairCollection.prototype = Object.create(App.Collection.prototype);
/**
* Find and return rate between base and symbol(spent) currency symbols passed in
* In case there is no direct rate, EUR is used as cross since all currency have EUR-pair
* @param {string} base
* @param {string} symbol
* @private
*/
App.CurrencyPairCollection.prototype.findRate = function findRate(base,symbol)
{
var pair = null,
basePair = null,
symbolPair = null,
i = 0,
l = this._items.length;
// First, check if both base and spent currency are in one pair ...
for (;i<l;)
{
pair = this._items[i++];
if ((base === pair.base && symbol === pair.symbol) || (base === pair.symbol && symbol === pair.base))
{
if (base === pair.base && symbol === pair.symbol) return pair.rate;
else if (base === pair.symbol && symbol === pair.base) return 1 / pair.rate;
}
}
// .. if not, use EUR pair as cross
for (i=0;i<l;)
{
pair = this._items[i++];
if (pair.base === "EUR")
{
if (pair.symbol === base) basePair = pair;
if (pair.symbol === symbol) symbolPair = pair;
}
}
if (basePair && symbolPair) return symbolPair.rate / basePair.rate;
return 1.0;
};
<file_sep>/**
* @class Button
* @extend Graphics
* @param {string} label
* @param {{width:number,height:number,pixelRatio:number,style:Object,backgroundColor:number}} options
* @constructor
*/
App.Button = function Button(label,options)
{
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._pixelRatio = options.pixelRatio;
this._label = label;
this._style = options.style;
this._backgroundColor = options.backgroundColor;
this._labelField = new PIXI.Text(label,this._style);
this._render();
this.addChild(this._labelField);
};
App.Button.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Button.prototype._render = function _render()
{
var w = this.boundingBox.width,
h = this.boundingBox.height;
App.GraphicUtils.drawRoundedRect(this,this._backgroundColor,1,0,0,w,h,Math.round(5 * this._pixelRatio));
this._labelField.x = Math.round((w - this._labelField.width) / 2);
this._labelField.y = Math.round((h - this._labelField.height) / 2);
};
/**
* Resize
* @param {number} width
* @param {number} height
*/
App.Button.prototype.resize = function resize(width,height)
{
this.boundingBox.width = width || this.boundingBox.width;
this.boundingBox.height = height || this.boundingBox.height;
this._render();
};
/**
* Test if position passed in falls within this button bounds
* @param {Point} position
* @returns {boolean}
*/
App.Button.prototype.hitTest = function hitTest(position)
{
return position.x >= this.x && position.x < this.x + this.boundingBox.width && position.y >= this.y && position.y < this.y + this.boundingBox.height;
};
<file_sep>/**
* @class CategoryButtonSurface
* @extends DisplayObjectContainer
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {{font:string,fill:string}} options.nameLabelStyle
* @constructor
*/
App.CategoryButtonSurface = function CategoryButtonSurface(options)
{
PIXI.DisplayObjectContainer.call(this);
this._width = options.width;
this._height = options.height;
this._pixelRatio = options.pixelRatio;
this._skin = this.addChild(new PIXI.Sprite(options.skin));
this._colorStripe = this.addChild(new PIXI.Graphics());
this._icon = null;
this._nameLabel = this.addChild(new PIXI.Text("",options.nameLabelStyle));
this._renderAll = true;
};
App.CategoryButtonSurface.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @param {string} label
* @param {string} iconName
* @param {string} color
*/
App.CategoryButtonSurface.prototype.render = function render(label,iconName,color)
{
this._nameLabel.setText(label);
if (this._icon) this._icon.setTexture(PIXI.TextureCache[iconName]);
App.GraphicUtils.drawRect(this._colorStripe,"0x"+color,1,0,0,Math.round(4 * this._pixelRatio),this._height);
if (this._renderAll)
{
this._renderAll = false;
this._icon = PIXI.Sprite.fromFrame(iconName);
this.addChild(this._icon);
this._icon.width = Math.round(20 * this._pixelRatio);
this._icon.height = Math.round(20 * this._pixelRatio);
this._icon.x = Math.round(25 * this._pixelRatio);
this._icon.y = Math.round((this._height - this._icon.height) / 2);
this._nameLabel.x = Math.round(64 * this._pixelRatio);
this._nameLabel.y = Math.round(18 * this._pixelRatio);
}
this._icon.tint = parseInt(color,16);
};
<file_sep>/**
* @class Collection
* @param {Array} source
* @param {Function} itemConstructor
* @param {Object} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Collection = function Collection(source,itemConstructor,parent,eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
if (source)
{
var i = 0, l = source.length;
this._items = new Array(l);
for (;i<l;i++) this._items[i] = new itemConstructor(source[i],this,parent,eventListenerPool);
}
if (!this._items) this._items = [];
this._currentItem = null;
this._currentIndex = -1;
};
App.Collection.prototype = Object.create(App.EventDispatcher.prototype);
/**
* @method addItem Add item into collection
* @param {*} item
*/
App.Collection.prototype.addItem = function addItem(item)
{
this._items[this._items.length] = item;
this.dispatchEvent(App.EventType.ADDED,item);
};
/**
* @method setCurrent Set current item of collection
* @param {*} value item to set as current
* @param {?boolean} [force=null] force to execute the method, even if the value is same as current item
*/
App.Collection.prototype.setCurrent = function setCurrent(value,force)
{
if (value === this._currentItem && !force) return;
//var data = {oldItem:this._currentItem};
this._currentItem = value;
this._updateCurrentIndex();
//data.currentItem = this._currentItem;
this.dispatchEvent(App.EventType.CHANGE/*,data*/);
};
/**
* @method getCurrent Returns current item
* @returns {null|*}
*/
App.Collection.prototype.getCurrent = function getCurrent()
{
return this._currentItem;
};
/**
* @method getItemAt Return item at index passed in
* @param {number} index
* @return {*} item
*/
App.Collection.prototype.getItemAt = function getItemAt(index)
{
return this._items[index];
};
/**
* Return copy of underlying array
* @returns {Array}
*/
App.Collection.prototype.copySource = function copySource()
{
return this._items.concat();
};
/**
* Serialize collection data
* @returns {Array}
*/
App.Collection.prototype.serialize = function serialize()
{
var data = [],
i = 0,
l = this._items.length;
for (;i<l;) data.push(this._items[i++].serialize());
return data;
};
/**
* Filter collection against value passed in
* @param {string|Array} value
* @param {string} [property=null]
* @returns {Array}
*/
App.Collection.prototype.filter = function filter(value,property)
{
if (value)
{
var i = 0,
l = this._items.length,
result = [];
if (property)
{
for (;i<l;i++)
{
if (value.indexOf(this._items[i][property]) > -1) result.push(this._items[i]);
}
}
else
{
for (;i<l;i++)
{
if (value.indexOf(this._items[i]) > -1) result.push(this._items[i]);
}
}
return result;
}
return this._items;
};
/**
* Find and return item by key and value passed in
* @param {string} key
* @param {*} value
*/
App.Collection.prototype.find = function find(key,value)
{
var i = 0,
l = this._items.length;
for (;i<l;i++)
{
if (this._items[i][key] === value) return this._items[i];
}
return null;
};
/**
* @method previous Return previous item
* @returns {*}
*/
App.Collection.prototype.previous = function previous()
{
var index = this._currentIndex;
if (index === -1) index = 0;
if (index <= 0) index = this._items.length - 1;
else index -= 1;
return this._items[index];
};
/**
* @method next Return next item
* @returns {*}
*/
App.Collection.prototype.next = function next()
{
var index = this._currentIndex;
if (index === -1 || index >= this._items.length-1) index = 0;
else index += 1;
return this._items[index];
};
/**
* @method other Go to either prev or next item, based on delta passed in
* @param {number} delta
*/
App.Collection.prototype.other = function other(delta)
{
var l = this._items.length;
return this._items[this._currentIndex + l + delta] % l;
};
/**
* @method hasItem Check if the item is already in collection
* @param {*} item
* @return {boolean}
*/
App.Collection.prototype.hasItem = function hasItem(item)
{
return this.indexOf(item) > -1;
};
/**
* @method removeItem Remove item passed in
* @param {*} item
* @return {*} item
*/
App.Collection.prototype.removeItem = function removeItem(item)
{
return this.removeItemAt(this.indexOf(item));
};
/**
* @method removeItemAt Remove item at index passed in
* @return {*} item
*/
App.Collection.prototype.removeItemAt = function removeItemAt(index)
{
var item = this._items.splice(index,1)[0];
this._updateCurrentIndex();
if (this._currentIndex === -1) this._currentItem = null;
this.dispatchEvent(App.EventType.REMOVED,item);
return item;
};
/**
* @method updateCurrentIndex Return currentItem's index
* @private
*/
App.Collection.prototype._updateCurrentIndex = function _updateCurrentIndex()
{
this._currentIndex = this.indexOf(this._currentItem);
};
/**
* @method indexOf Return currentItem's index
* @param {Object} item
* @return {number}
*/
App.Collection.prototype.indexOf = function indexOf(item)
{
var multiplier = 8, i = 0, l = Math.floor(this._items.length / multiplier) * multiplier;
for (;i<l;)
{
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
}
l = this._items.length;
for (;i<l;)
{
if (this._items[i++] === item) return i-1;
}
return -1;
};
/**
* Return current item's index
* @method index
* @returns {number}
*/
App.Collection.prototype.index = function index()
{
return this._currentIndex;
};
/**
* @method length Return length of the collection
* @return {number}
*/
App.Collection.prototype.length = function length()
{
return this._items.length;
};
<file_sep>/**
* @class ModelLocator
* @type {{_proxies:Object,addProxy:Function,hasProxy:Function,getProxy:Function}}
*/
App.ModelLocator = {
_proxies:{},
/**
* Initialize with array of proxies passed in
* @param {Array.<>} proxies
*/
init:function init(proxies)
{
var i = 0,
l = proxies.length;
for (;i<l;) this._proxies[proxies[i++]] = proxies[i++];
},
/**
* @method addPoxy Add proxy to the locator
* @param {string} proxyName
* @param {*} proxy
*/
addProxy:function addProxy(proxyName,proxy)
{
if (this._proxies[proxyName]) throw Error("Proxy "+proxyName+" already exist");
this._proxies[proxyName] = proxy;
},
/**
* @method hasProxy Check if proxy already exist
* @param {string} proxyName
* @return {boolean}
*/
hasProxy:function hasProxy(proxyName)
{
return this._proxies[proxyName];
},
/**
* @method getProxy Returns proxy by name passed in
* @param {string} proxyName
* @return {*}
*/
getProxy:function getProxy(proxyName)
{
return this._proxies[proxyName];
}
};<file_sep>/**
* The Command
* @class Command
* @extends {EventDispatcher}
* @param allowMultipleInstances {boolean}
* @param eventListenerPool {ObjectPool}
*/
App.Command = function Command(allowMultipleInstances,eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
this.allowMultipleInstances = allowMultipleInstances;
};
App.Command.prototype = Object.create(App.EventDispatcher.prototype);
/**
* Execute a command
* @param {*=} data Defaults to null
*/
App.Command.prototype.execute = function execute(data) {};
/**
* Destroy current instance
*
* @method destroy
*/
App.Command.prototype.destroy = function destroy()
{
App.EventDispatcher.prototype.destroy.call(this);
};
<file_sep>/**
* @class FontStyle
* @type {{init: Function, get: Function, WHITE: string, BLUE: string, BLUE_LIGHT: string, BLUE_DARK: string, GREY: string, GREY_DARK: string, GREY_DARKER: string,BLACK_LIGHT:string, RED_DARK: string}}
*/
App.FontStyle = {
/**
* @private
*/
_pixelRatio:1,
_styles:[],
/**
* Init
* @param {number} pixelRatio
*/
init:function init(pixelRatio)
{
this._pixelRatio = pixelRatio;
return this;
},
/**
* Construct and return font style object
* @param {number} fontSize
* @param {string} color
* @param {string} [align=null]
* @param {string} [font=null]
* @returns {{font: string, fill: string}}
*/
get:function get(fontSize,color,align,font)
{
var i = 0,
l = this._styles.length,
style = null;
font = font || this.CONDENSED;
for (;i<l;)
{
style = this._styles[i++];
if (style.fontSize === fontSize && style.fill === color && style.fontName === font)
{
if (align)
{
if (style.align === align)
{
return style;
}
}
else
{
return style;
}
}
}
style = {fontSize:fontSize,font:Math.round(fontSize * this._pixelRatio)+"px "+font,fill:color,align:align ? align : "left",fontName:font};
this._styles.push(style);
return style;
},
CONDENSED:"HelveticaNeueCond",
LIGHT_CONDENSED:"HelveticaNeueLightCond",
WHITE:"#ffffff",
BLUE:"#394264",
BLUE_LIGHT:"#50597B",
BLUE_DARK:"#252B44",
GREY:"#efefef",
GREY_DARK:"#cccccc",
GREY_DARKER:"#999999",
BLACK_LIGHT:"#333333",
RED_DARK:"#990000"
};
<file_sep>/**
* ChangeScreenData
* @param {number} index
* @constructor
*/
App.ChangeScreenData = function ChangeScreenData(index)
{
this.allocated = false;
this.poolIndex = index;
this.screenName = App.ScreenName.ADD_TRANSACTION;
this.screenMode = App.ScreenMode.ADD;
this.updateData = null;
this.headerLeftAction = App.HeaderAction.CANCEL;
this.headerRightAction = App.HeaderAction.CONFIRM;
this.headerName = App.ScreenTitle.ADD_TRANSACTION;
this.backSteps = 1;
this.updateBackScreen = false;
};
/**
* Update
* @param {number} screenName
* @param {number} screenMode
* @param {Object} updateData
* @param {number} headerLeftAction
* @param {number} headerRightAction
* @param {string} headerName
* @param {number} [backSteps=1]
* @param {boolean} [updateBackScreen=false]
* @returns {App.ChangeScreenData}
*/
App.ChangeScreenData.prototype.update = function update(screenName,screenMode,updateData,headerLeftAction,headerRightAction,headerName,backSteps,updateBackScreen)
{
this.screenName = isNaN(screenName) ? App.ScreenName.ADD_TRANSACTION : screenName;
this.screenMode = screenMode || App.ScreenMode.ADD;
this.updateData = updateData;
this.headerLeftAction = headerLeftAction || App.HeaderAction.CANCEL;
this.headerRightAction = headerRightAction || App.HeaderAction.CONFIRM;
this.headerName = headerName || App.ScreenTitle.ADD_TRANSACTION;
this.backSteps = backSteps || 1;
this.updateBackScreen = updateBackScreen;
return this;
};
<file_sep>/**
* Abstract Screen
*
* @class Screen
* @extends DisplayObjectContainer
* @param {Object} layout
* @param {number} tweenDuration
* @constructor
*/
App.Screen = function Screen(layout,tweenDuration)
{
PIXI.DisplayObjectContainer.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
pixelRatio = layout.pixelRatio;
this._model = null;
this._layout = layout;
this._enabled = false;
this._eventsRegistered = App.EventLevel.NONE;
this._transitionState = App.TransitionState.HIDDEN;
this._interactiveState = null;
this._mouseDownPosition = null;
this._mouseX = 0.0;
this._mouseY = 0.0;
this._leftSwipeThreshold = 15 * pixelRatio;
this._rightSwipeThreshold = 5 * pixelRatio;
this._clickThreshold = 5 * pixelRatio;
this._swipeEnabled = false;
this._preferScroll = true;
this._mode = App.ScreenMode.DEFAULT;
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._eventDispatcher = new App.EventDispatcher(ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL));
this._showHideTween = new App.TweenProxy(tweenDuration,App.Easing.outExpo,0,ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL));
this.alpha = 0.0;
};
App.Screen.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Show
*/
App.Screen.prototype.show = function show()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.HIDDEN || this._transitionState === TransitionState.HIDING)
{
this.enable();
this._transitionState = TransitionState.SHOWING;
this._showHideTween.restart();
this.visible = true;
}
};
/**
* Hide
*/
App.Screen.prototype.hide = function hide()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWN || this._transitionState === TransitionState.SHOWING)
{
this.disable();
this._transitionState = TransitionState.HIDING;
this._showHideTween.start(true);
}
};
/**
* Enable
*/
App.Screen.prototype.enable = function enable()
{
if (!this._enabled)
{
this._registerEventListeners(App.EventLevel.LEVEL_1);
this._enabled = true;
}
};
/**
* Disable
*/
App.Screen.prototype.disable = function disable()
{
this._unRegisterEventListeners(App.EventLevel.LEVEL_2);
this._enabled = false;
this._interactiveState = null;
};
/**
* Update
*/
App.Screen.prototype.update = function update(data,mode)
{
this._mode = mode;
//TODO mark layout/UI as 'dirty' and update/render on Tick event
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Screen.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Screen.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* Register event listeners
* @param {number} level
* @private
*/
App.Screen.prototype._registerEventListeners = function _registerEventListeners(level)
{
var EventLevel = App.EventLevel;
if (level === EventLevel.LEVEL_1 && this._eventsRegistered !== EventLevel.LEVEL_1)
{
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._showHideTween.addEventListener(App.EventType.COMPLETE,this,this._onTweenComplete);
}
if (level === EventLevel.LEVEL_2 && this._eventsRegistered !== EventLevel.LEVEL_2)
{
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = this._onPointerDown;
this.touchend = this._onPointerUp;
this.touchendoutside = this._onPointerUp;
}
else
{
this.mousedown = this._onPointerDown;
this.mouseup = this._onPointerUp;
this.mouseupoutside = this._onPointerUp;
}
App.ViewLocator.getViewSegment(App.ViewName.HEADER).addEventListener(App.EventType.CLICK,this,this._onHeaderClick);
this.interactive = true;
}
this._eventsRegistered = level;
};
/**
* UnRegister event listeners
* @param {number} level
* @private
*/
App.Screen.prototype._unRegisterEventListeners = function _unRegisterEventListeners(level)
{
var EventLevel = App.EventLevel;
if (level === EventLevel.LEVEL_1)
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._showHideTween.removeEventListener(App.EventType.COMPLETE,this,this._onTweenComplete);
this._eventsRegistered = EventLevel.NONE;
}
if (level === EventLevel.LEVEL_2)
{
this.interactive = false;
App.ViewLocator.getViewSegment(App.ViewName.HEADER).removeEventListener(App.EventType.CLICK,this,this._onHeaderClick);
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = null;
this.touchend = null;
this.touchendoutside = null;
}
else
{
this.mousedown = null;
this.mouseup = null;
this.mouseupoutside = null;
}
this._eventsRegistered = EventLevel.LEVEL_1;
}
};
/**
* On tick
* @private
*/
App.Screen.prototype._onTick = function _onTick()
{
if (this._showHideTween.isRunning())
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWING) this.alpha = this._showHideTween.progress;
else if (this._transitionState === TransitionState.HIDING) this.alpha = 1.0 - this._showHideTween.progress;
}
if (this._swipeEnabled && this._interactiveState === App.InteractiveState.DRAGGING) this._drag();
};
/**
* On tween complete
* @private
*/
App.Screen.prototype._onTweenComplete = function _onTweenComplete()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWING)
{
this._transitionState = TransitionState.SHOWN;
this.alpha = 1.0;
this._registerEventListeners(App.EventLevel.LEVEL_2);
}
else if (this._transitionState === TransitionState.HIDING)
{
this._transitionState = TransitionState.HIDDEN;
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
this.alpha = 0.0;
this.visible = false;
this._eventDispatcher.dispatchEvent(App.EventType.COMPLETE,{target:this,state:this._transitionState});
}
};
/**
* On pointer down
*
* @param {Object} data
* @private
*/
App.Screen.prototype._onPointerDown = function _onPointerDown(data)
{
if (this.stage)
{
this._mouseDownPosition = data.getLocalPosition(this.stage);
this._mouseX = this._mouseDownPosition.x;
this._mouseY = this._mouseDownPosition.y;
}
if (this._swipeEnabled) this._interactiveState = App.InteractiveState.DRAGGING;
};
/**
* On pointer up
* @param {Object} data
* @private
*/
App.Screen.prototype._onPointerUp = function _onPointerUp(data)
{
if (this._swipeEnabled)
{
if (this._interactiveState === App.InteractiveState.SWIPING) this._swipeEnd();
this._interactiveState = null;
}
if (this.stage && this._mouseDownPosition && this._enabled)
{
var oldX = this._mouseDownPosition.x,
oldY = this._mouseDownPosition.y;
this._mouseDownPosition = data.getLocalPosition(this.stage,this._mouseDownPosition);
var dx = oldX - this._mouseDownPosition.x,
dy = oldY - this._mouseDownPosition.y,
dist = dx * dx - dy * dy,
TransitionState = App.TransitionState;
if (Math.abs(dist) < this._clickThreshold && (this._transitionState === TransitionState.SHOWING || this._transitionState === TransitionState.SHOWN)) this._onClick();
this._mouseDownPosition = null;
}
};
/**
* Drag
* @private
*/
App.Screen.prototype._drag = function _drag()
{
var InteractiveState = App.InteractiveState;
if (this._interactiveState === InteractiveState.DRAGGING)
{
if (this.stage && this._mouseX)
{
var position = this.stage.getTouchPosition(),
newX = position.x,
newY = position.y;
if (this._mouseX - newX > this._leftSwipeThreshold)
{
this._interactiveState = InteractiveState.SWIPING;
this._swipeStart(Math.abs(this._mouseY-newY) > Math.abs(this._mouseX-newX) && this._preferScroll,App.Direction.LEFT);
}
else if (newX - this._mouseX > this._rightSwipeThreshold)
{
this._interactiveState = InteractiveState.SWIPING;
this._swipeStart(Math.abs(this._mouseY-newY) > Math.abs(this._mouseX-newX) && this._preferScroll,App.Direction.RIGHT);
}
this._mouseX = newX;
this._mouseY = newY;
}
}
};
/**
* Click handler
* @private
*/
App.Screen.prototype._onClick = function _onClick()
{
this._eventDispatcher.dispatchEvent(App.EventType.CLICK);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.Screen.prototype._onHeaderClick = function _onHeaderClick(action)
{
// Abstract
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @private
*/
App.Screen.prototype._swipeStart = function _swipeStart(preferScroll)
{
// Abstract
};
/**
* Called when swipe ends
* @param {string} direction
* @private
*/
App.Screen.prototype._swipeEnd = function _swipeEnd(direction)
{
// Abstract
};
<file_sep>/**
* @class ChangeAccount
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeAccount = function ChangeAccount(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool);
};
App.ChangeAccount.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {{account:App.Account,name:string,nextCommand:Command,nextCommandData:App.ChangeScreenData}} data
*/
App.ChangeAccount.prototype.execute = function execute(data)
{
var EventType = App.EventType,
account = data.account,
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
account = new App.Account();
this._nextCommandData.updateData = account;
}
else if (type === EventType.CHANGE)
{
account.name = data.name;
if (account.lifeCycleState === App.LifeCycleState.CREATED)
{
var collection = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS);
if (collection.indexOf(account) === -1) collection.addItem(account);
account.lifeCycleState = App.LifeCycleState.ACTIVE;
// Save
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.ACCOUNTS,
App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).serialize()
);
}
}
else if (type === EventType.DELETE)
{
account.lifeCycleState = App.LifeCycleState.DELETED;
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.ACCOUNTS,
App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).serialize()
);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
<file_sep>/**
* @class Category
* @param {Array} data
* @param {Collection} collection
* @param {*} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Category = function Category(data,collection,parent,eventListenerPool)
{
if (data)
{
this._data = data;
if (parseInt(data[0],10) >= App.Category._UID) App.Category._UID = parseInt(data[0],10);
this.id = data[0];
this.name = decodeURIComponent(data[1]);
this.color = data[2];
this.icon = data[3];
this.account = data[4];
this.budget = data[6];
this._subCategories = null;
}
else
{
this._data = null;
this.id = String(++App.Category._UID);
this.name = "Category" + this.id;
this.color = null;
this.icon = null;
this.account = null;
this.budget = null;
this._subCategories = null;
}
this.balance = 0.0;
this._states = null;
};
App.Category._UID = 0;
/**
* Destroy
* Don't erase strings, since they can still be used in TransactionButton
*/
App.Category.prototype.destroy = function destroy()
{
var i = 0,
l = this._subCategories.length;
for (;i<l;) this._subCategories[i++] = null;
this._subCategories.length = 0;
this._subCategories = null;
if (this._states && this._states.length)
{
for (i=0,l=this._states.length;i<l;) this._states[i++] = null;
this._states.length = 0;
this._states = null;
}
this._data = null;
};
/**
* Calculate balance
* @returns {number}
*/
App.Category.prototype.calculateBalance = function calculateBalance()
{
var collection = this.subCategories, // Inflate subCategories
i = 0,
l = this._subCategories.length;
this.balance = 0.0;
for (;i<l;) this.balance += this._subCategories[i++].balance;
return this.balance;
};
/**
* Add subCategory
* @param {App.SubCategory} subCategory
*/
App.Category.prototype.addSubCategory = function addSubCategory(subCategory)
{
if (this._subCategories)
{
var i = 0,
l = this._subCategories.length;
for (;i<l;)
{
if (this._subCategories[i++] === subCategory) return;
}
this._subCategories.push(subCategory);
}
else
{
this._subCategories = [subCategory];
}
};
/**
* Remove subCategory
* @param {App.SubCategory} subCategory
*/
App.Category.prototype.removeSubCategory = function removeSubCategory(subCategory)
{
var i = 0,
l = this._subCategories.length;
for (;i<l;i++)
{
if (this._subCategories[i] === subCategory)
{
this._subCategories.splice(i,1);
break;
}
}
};
/**
* Serialize
* @returns {Array}
*/
App.Category.prototype.serialize = function serialize()
{
var collection = this.subCategories,
data = [this.id,App.StringUtils.encode(this.name),this.color,this.icon,this.account],
subCategoryIds = "",
i = 0,
l = this._subCategories.length;
for (;i<l;) subCategoryIds += this._subCategories[i++].id + ",";
subCategoryIds = subCategoryIds.substring(0,subCategoryIds.length-1);
data.push(subCategoryIds);
if (this.budget) data.push(this.budget);
return data;
};
/**
* Save current state
*/
App.Category.prototype.saveState = function saveState()
{
if (!this._states) this._states = [];
this._states[this._states.length] = this.serialize();
};
/**
* Revoke last state
*/
App.Category.prototype.revokeState = function revokeState()
{
if (this._states && this._states.length)
{
var state = this._states.pop();
this.name = decodeURIComponent(state[1]);
this.color = state[2];
this.icon = state[3];
this.account = state[4];
this.budget = state[6];
this._inflateSubCategories(state[5]);
}
};
/**
* Clear saved states
*/
App.Category.prototype.clearSavedStates = function clearSavedStates()
{
if (this._states) this._states.length = 0;
var i = 0,
l = this._subCategories.length;
for (;i<l;) this._subCategories[i++].clearSavedState();
};
/**
* Populate array of SubCategory object from their respective IDs
* @param {string} ids
* @private
*/
App.Category.prototype._inflateSubCategories = function _inflateSubCategories(ids)
{
this._subCategories = App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).filter(ids.split(","),"id");
};
/**
* @property subCategories
* @type Array.<App.SubCategory>
*/
Object.defineProperty(App.Category.prototype,'subCategories',{
get:function()
{
if (!this._subCategories)
{
if (this._data)
{
this._inflateSubCategories(this._data[5]);
}
else
{
var subCategory = new App.SubCategory();
subCategory.category = this.id;
this._subCategories = [subCategory];
}
}
return this._subCategories;
}
});
<file_sep>/**
* @class CurrencyPairButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {PIXI.Texture} options.skin
* @param {{font:string,fill:string}} options.editLabelStyle
* @param {{font:string,fill:string}} options.pairLabelStyle
* @param {{font:string,fill:string}} options.rateLabelStyle
* @param {number} options.openOffset
* @constructor
*/
App.CurrencyPairButton = function CurrencyPairButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new PIXI.Rectangle(0,0,options.width,options.height);
this._model = null;
//TODO add arrow to the right indicating Edit option
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._editLabel = this.addChild(new PIXI.Text("Edit",options.editLabelStyle));
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._skin = this._swipeSurface.addChild(new PIXI.Sprite(options.skin));
this._pairLabel = this._swipeSurface.addChild(new PIXI.Text("EUR/USD",options.pairLabelStyle));
this._rateLabel = this._swipeSurface.addChild(new PIXI.Text("@ 1.0",options.rateLabelStyle));
this._renderAll = true;
this._render();
};
App.CurrencyPairButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* @method render
* @private
*/
App.CurrencyPairButton.prototype._render = function _render()
{
var w = this.boundingBox.width,
h = this.boundingBox.height,
r = this._pixelRatio,
offset = Math.round(15 * r);
App.GraphicUtils.drawRect(this._background,App.ColorTheme.RED,1,0,0,w,h);
this._editLabel.x = Math.round(w - 50 * this._pixelRatio);
this._editLabel.y = Math.round((h - this._editLabel.height) / 2);
this._pairLabel.x = offset;
this._pairLabel.y = Math.round((h - this._pairLabel.height) / 2);
this._rateLabel.x = Math.round(offset + this._pairLabel.width + 5 * r);
this._rateLabel.y = Math.round((h - this._rateLabel.height) / 2);
};
/**
* Set model
* @param {App.CurrencyPair} model
*/
App.CurrencyPairButton.prototype.setModel = function setModel(model)
{
this._model = model;
this._pairLabel.setText(model.base+"/"+model.symbol);
this._rateLabel.setText("@ "+model.rate);
};
/**
* Click handler
* @param {InteractionData} interactionData
*/
App.CurrencyPairButton.prototype.onClick = function onClick(interactionData)
{
if (this._isOpen && interactionData.getLocalPosition(this).x >= this._width - this._openOffset)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT_CURRENCY_RATE,
App.ScreenMode.EDIT,
this._model,
0,
0,
App.ScreenTitle.EDIT_CURRENCY_RATE
));
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.CurrencyPairButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.CurrencyPairButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
<file_sep>/**
* @class Calendar
* @extend Graphic
* @param {number} width
* @param {number} pixelRatio
* @constructor
*/
App.Calendar = function Calendar(width,pixelRatio)
{
PIXI.Graphics.call(this);
var dayLabelStyle = {font:"bold " + Math.round(12 * pixelRatio)+"px Arial",fill:"#999999"},
CalendarWeekRow = App.CalendarWeekRow,
Text = PIXI.Text,
DateUtils = App.DateUtils,
FontStyle = App.FontStyle,
startOfWeek = App.ModelLocator.getProxy(App.ModelName.SETTINGS).startOfWeek,
weekTextStyle = FontStyle.get(14,FontStyle.GREY_DARK),
weekSelectedStyle = FontStyle.get(14,FontStyle.WHITE),
dayLabels = DateUtils.getDayLabels(startOfWeek),
daysInWeek = dayLabels.length,
weeksInMonth = 6,
i = 0;
this.boundingBox = new App.Rectangle(0,0,width);
this._date = null;
this._selectedDate = null;
this._width = width;
this._pixelRatio = pixelRatio;
this._weekRowPosition = Math.round(81 * pixelRatio);
this._monthField = new PIXI.Text("",FontStyle.get(18,FontStyle.BLUE));
this._prevButton = PIXI.Sprite.fromFrame("arrow-app");
this._nextButton = PIXI.Sprite.fromFrame("arrow-app");
this._dayLabelFields = new Array(daysInWeek);
this._weekRows = new Array(weeksInMonth);
this._separatorContainer = new PIXI.Graphics();
for (;i<daysInWeek;i++) this._dayLabelFields[i] = new Text(dayLabels[i],dayLabelStyle);
for (i = 0;i<weeksInMonth;i++) this._weekRows[i] = new CalendarWeekRow(weekTextStyle,weekSelectedStyle,width,pixelRatio);
this._render();
this.addChild(this._monthField);
this.addChild(this._prevButton);
this.addChild(this._nextButton);
for (i = 0;i<daysInWeek;) this.addChild(this._dayLabelFields[i++]);
for (i = 0;i<weeksInMonth;) this.addChild(this._weekRows[i++]);
this.addChild(this._separatorContainer);
};
App.Calendar.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
*
* @private
*/
App.Calendar.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._pixelRatio,
w = this._width,
arrowResizeRatio = Math.round(12 * r) / this._prevButton.height,
separatorPadding = Math.round(15 * r),
separatorWidth = w - separatorPadding * 2,
dayLabel = null,
dayLabelWidth = Math.round(w / this._dayLabelFields.length),
dayLabelOffset = Math.round(40 * r),
weekRow = this._weekRows[0],
weekRowHeight = weekRow.boundingBox.height,
l = this._dayLabelFields.length,
i = 0;
this._monthField.y = Math.round((dayLabelOffset - this._monthField.height) / 2);
this._prevButton.scale.x = arrowResizeRatio;
this._prevButton.scale.y = arrowResizeRatio;
this._prevButton.x = Math.round(20 * r + this._prevButton.width);
this._prevButton.y = Math.round((dayLabelOffset - this._prevButton.height) / 2 + this._prevButton.height);
this._prevButton.rotation = Math.PI;
this._prevButton.tint = ColorTheme.BLUE;
this._nextButton.scale.x = arrowResizeRatio;
this._nextButton.scale.y = arrowResizeRatio;
this._nextButton.x = Math.round(w - 20 * r - this._nextButton.width);
this._nextButton.y = Math.round((dayLabelOffset - this._prevButton.height) / 2);
this._nextButton.tint = ColorTheme.BLUE;
for (;i<l;i++)
{
dayLabel = this._dayLabelFields[i];
dayLabel.x = Math.round((i * dayLabelWidth) + (dayLabelWidth - dayLabel.width) / 2);
dayLabel.y = Math.round(dayLabelOffset + r + (dayLabelOffset - dayLabel.height) / 2);
}
i = 0;
l = this._weekRows.length;
this._separatorContainer.clear();
this._separatorContainer.beginFill(ColorTheme.GREY,1.0);
for (;i<l;i++)
{
weekRow = this._weekRows[i];
weekRow.y = this._weekRowPosition + i * weekRowHeight;
this._separatorContainer.drawRect(0,weekRow.y + weekRowHeight,w,1);
}
this._separatorContainer.endFill();
this.boundingBox.height = weekRow.y + weekRowHeight;
//TODO I dont need this (can use screen's bg) ... and can extend from DOContainer instead
GraphicUtils.drawRects(this,ColorTheme.GREY,1,[0,0,w,this.boundingBox.height],true,false);
GraphicUtils.drawRects(this,ColorTheme.GREY_DARK,1,[0,Math.round(80 * r),w,1,separatorPadding,dayLabelOffset,separatorWidth,1],false,false);
GraphicUtils.drawRects(this,ColorTheme.GREY_LIGHT,1,[separatorPadding,dayLabelOffset+1,separatorWidth,1],false,true);
};
/**
* Update
* @param {Date} date
*/
App.Calendar.prototype.update = function update(date)
{
this._date = date;
if (this._selectedDate) this._selectedDate.setTime(this._date.valueOf());
else this._selectedDate = new Date(this._date.valueOf());
var month = App.DateUtils.getMonth(this._date,App.ModelLocator.getProxy(App.ModelName.SETTINGS).startOfWeek),
selectedDate = this._selectedDate.getDate(),
weeksInMonth = month.length,
i = 0;
for (i = 0;i<weeksInMonth;i++) this._weekRows[i].change(month[i],selectedDate);
this._updateMonthLabel();
};
/**
* Return selected date
* @returns {Date}
*/
App.Calendar.prototype.getSelectedDate = function getSelectedDate()
{
return this._selectedDate;
};
/**
* Update month label
* @private
*/
App.Calendar.prototype._updateMonthLabel = function _updateMonthLabel()
{
this._monthField.setText(App.DateUtils.getMonthLabel(this._date.getMonth()) + " " + this._date.getFullYear());
this._monthField.x = Math.round((this._width - this._monthField.width) / 2);
};
/**
* On click
*/
App.Calendar.prototype.onClick = function onClick()
{
var position = this.stage.getTouchData().getLocalPosition(this),
x = position.x,
y = position.y;
// Click into the actual calendar
if (y >= this._weekRowPosition)
{
this._selectDay(x,y);
}
// Click at one of the prev-, next-buttons
else
{
var prevDX = this._prevButton.x - this._prevButton.width / 2 - x,
nextDX = this._nextButton.x + this._nextButton.width / 2 - x,
dy = this._nextButton.y + this._nextButton.height / 2 - y,
prevDist = prevDX * prevDX - dy * dy,
nextDist = nextDX * nextDX - dy * dy,
threshold = 20 * this._pixelRatio;
if (Math.sqrt(Math.abs(prevDist)) < threshold) this._changeDate(App.Direction.LEFT,-1);
else if (Math.sqrt(Math.abs(nextDist)) < threshold) this._changeDate(App.Direction.RIGHT,-1);
}
};
/**
* Find and return week row by position passed in
* @param {number} position
* @private
*/
App.Calendar.prototype._getWeekByPosition = function _getWeekByPosition(position)
{
var weekRowHeight = this._weekRows[0].boundingBox.height,
weekRow = null,
l = this._weekRows.length,
i = 0;
for (;i<l;)
{
weekRow = this._weekRows[i++];
if (weekRow.y <= position && weekRow.y + weekRowHeight > position)
{
return weekRow;
}
}
return null;
};
/**
* Select day by position passed in
* @param {number} x
* @param {number} y
* @private
*/
App.Calendar.prototype._selectDay = function _selectDay(x,y)
{
var week = this._getWeekByPosition(y),
day = week.getDayByPosition(x),
date = day.day,
l = this._weekRows.length,
i = 0;
if (day.otherMonth)
{
if (date > 20) this._changeDate(App.Direction.LEFT,date);
else this._changeDate(App.Direction.RIGHT,date);
}
else
{
for (;i<l;)this._weekRows[i++].updateSelection(date);
this._selectedDate.setFullYear(this._date.getFullYear(),this._date.getMonth(),date);
}
};
/**
* Change date
* @param {string} direction
* @param {number} selectDate
* @private
*/
App.Calendar.prototype._changeDate = function _changeDate(direction,selectDate)
{
var currentMonth = this._date.getMonth(),
currentYear = this._date.getFullYear(),
newMonth = currentMonth < 11 ? currentMonth + 1 : 0,
newYear = newMonth ? currentYear : currentYear + 1;
if (direction === App.Direction.LEFT)
{
newMonth = currentMonth ? currentMonth - 1 : 11;
newYear = currentMonth ? currentYear : currentYear - 1;
}
this._date.setFullYear(newYear,newMonth);
if (selectDate > -1) this._selectedDate.setFullYear(newYear,newMonth,selectDate);
this._updateMonthLabel();
var month = App.DateUtils.getMonth(this._date,App.ModelLocator.getProxy(App.ModelName.SETTINGS).startOfWeek),
weeksInMonth = month.length,
selectedMonth = this._selectedDate.getFullYear() === newYear && this._selectedDate.getMonth() === newMonth,
selectedDate = selectedMonth ? this._selectedDate.getDate() : -1,
i = 0;
for (i = 0;i<weeksInMonth;i++) this._weekRows[i].change(month[i],selectedDate);
};
<file_sep>'use strict';
var port = process.argv[2] && parseInt(process.argv[2],10) || 80,
server,
dir;
/**
* Init
*/
function init()
{
dir = __dirname + "/public";
server = require('http').createServer();
server.on('request',onServerRequest);
server.listen(port,onServerListens);
}
/**
* Server listens handler
*/
function onServerListens()
{
console.log(getAddresses());
}
/**
* On server request
* @param request
* @param response
*/
function onServerRequest(request,response)
{
//console.log(__dirname);
//console.log(request.url);
require('fs').readFile(request.url === "/" ? dir+"/index.html" : dir+request.url,function(error,content)
{
if (error)
{
response.writeHead('500');
response.end(error.toString());
}
response.writeHead('200');
response.end(content);
});
}
/**
* Find and return local addresses
* @returns {Array}
*/
function getAddresses()
{
var os = require('os'),
interfaces = os.networkInterfaces(),
addresses = [],
address = null;
for (var k in interfaces)
{
for (var k2 in interfaces[k])
{
address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal)
{
addresses.push(address.address);
}
}
}
return addresses;
}
init();
<file_sep>/**
* @class LoadData
* @extends {Command}
* @param {ObjectPool} pool
* @param {Storage} storage
* @constructor
*/
App.LoadData = function LoadData(pool,storage)
{
App.Command.call(this,false,pool);
this._storage = storage;
this._jsonLoader = null;
this._fontLoadingInterval = -1;
this._fontInfoElement = null;
this._icons = null;
};
App.LoadData.prototype = Object.create(App.Command.prototype);
/**
* Execute the command
*
* @method execute
*/
App.LoadData.prototype.execute = function execute()
{
this._loadAssets();
};
/**
* Load image assets
*
* @method _loadAssets
* @private
*/
App.LoadData.prototype._loadAssets = function _loadAssets()
{
this._jsonLoader = new PIXI.JsonLoader("./data/icons-big.json");
this._jsonLoader.on("loaded",function()
{
this._icons = this._jsonLoader.json.frames;
this._jsonLoader.removeAllListeners("loaded");
this._jsonLoader = null;
this._loadFont();
}.bind(this));
this._jsonLoader.load();
};
/**
* Set app font and check if it is loaded
*
* @method _loadFont
* @private
*/
App.LoadData.prototype._loadFont = function _loadFont()
{
this._fontInfoElement = document.getElementById("fontInfo");
var FontStyle = App.FontStyle,
fontInfoWidth = this._fontInfoElement.offsetWidth,
fontName = "QW@HhsXJ",
fontsLoaded = 0;
this._fontLoadingInterval = setInterval(function()
{
if (this._fontInfoElement.offsetWidth !== fontInfoWidth && this._fontInfoElement.style.fontFamily === fontName)
{
fontsLoaded++;
if (fontsLoaded === 1)
{
fontInfoWidth = this._fontInfoElement.offsetWidth;
fontName = FontStyle.CONDENSED;
this._fontInfoElement.style.fontFamily = FontStyle.CONDENSED;
}
else if (fontsLoaded >= 2)
{
clearInterval(this._fontLoadingInterval);
document.body.removeChild(this._fontInfoElement);
this._loadData();
}
}
}.bind(this),100);
fontName = FontStyle.LIGHT_CONDENSED;
this._fontInfoElement.style.fontFamily = FontStyle.LIGHT_CONDENSED;
};
/**
* Load locally stored app data
*
* @method _loadData
* @private
*/
App.LoadData.prototype._loadData = function _loadData()
{
var StorageKey = App.StorageKey,
userData = Object.create(null),
timeStamp = window.performance && window.performance.now ? window.performance : Date,
start = timeStamp.now(),
transactions = Object.create(null),
transactionIds = null,
transactionKey = null,
i = 0,
l = 0;
// localStorage.clear();
userData[StorageKey.SETTINGS] = this._storage.getData(StorageKey.SETTINGS);
userData[StorageKey.CURRENCY_PAIRS] = this._storage.getData(StorageKey.CURRENCY_PAIRS);
userData[StorageKey.SUB_CATEGORIES] = this._storage.getData(StorageKey.SUB_CATEGORIES);
userData[StorageKey.CATEGORIES] = this._storage.getData(StorageKey.CATEGORIES);
userData[StorageKey.ACCOUNTS] = this._storage.getData(StorageKey.ACCOUNTS);
transactions[StorageKey.TRANSACTIONS_META] = this._storage.getData(StorageKey.TRANSACTIONS_META);
// Find and load two last segments of transactions
transactionIds = this._getMetaIds(transactions[StorageKey.TRANSACTIONS_META],2);
for (l=transactionIds.length;i<l;)
{
transactionKey = StorageKey.TRANSACTIONS+transactionIds[i++];
transactions[transactionKey] = this._storage.getData(transactionKey);
}
transactions.ids = transactionIds;
userData[StorageKey.TRANSACTIONS] = transactions;
// console.log("userData: ",timeStamp.now()-start,userData);
this.dispatchEvent(App.EventType.COMPLETE,{userData:userData,icons:this._icons});
};
/**
* Find and return IDs of transaction segments to load
* @param {Array.<Array>} metas
* @param {number} lookBack
* @private
*/
App.LoadData.prototype._getMetaIds = function _getMetaIds(metas,lookBack)
{
var i = metas.length > lookBack ? lookBack : metas.length - 1,
meta = null,
ids = [];
for (;i>-1;)
{
meta = metas[i--];
// Only return IDs of meta, that have more than zero transactions
if (meta[1]) ids.push(meta[0]);
}
return ids;
};
/**
* Destroy the command
*
* @method destroy
*/
App.LoadData.prototype.destroy = function destroy()
{
App.Command.prototype.destroy.call(this);
this._jsonLoader = null;
clearInterval(this._fontLoadingInterval);
this._storage = null;
this._fontInfoElement = null;
this._icons = null;
};
<file_sep>/**
* @class SubCategoryButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {number} options.openOffset
* @param {Texture} options.whiteSkin
* @param {Texture} options.greySkin
* @param {{font:string,fill:string}} options.nameLabelStyle
* @param {{font:string,fill:string}} options.editLabelStyle
* @constructor
*/
App.SubCategoryButton = function SubCategoryButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._mode = null;
this._options = options;
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._deleteLabel = this.addChild(new PIXI.Text("Edit",options.editLabelStyle));
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._skin = this._swipeSurface.addChild(new PIXI.Sprite(options.whiteSkin));
this._icon = PIXI.Sprite.fromFrame("subcategory-app");
this._nameLabel = this._swipeSurface.addChild(new PIXI.Text("",options.nameLabelStyle));
this._renderAll = true;
};
App.SubCategoryButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* Render
* @private
*/
App.SubCategoryButton.prototype._render = function _render()
{
this._nameLabel.setText(this._model.name);
if (this._renderAll)
{
this._renderAll = false;
var ColorTheme = App.ColorTheme,
r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
offset = Math.round(25 * r),
iconResizeRatio = Math.round(20 * r) / this._icon.height;
App.GraphicUtils.drawRect(this._background,ColorTheme.RED,1,0,0,w,h);
this._deleteLabel.x = Math.round(w - 50 * r);
this._deleteLabel.y = Math.round((h - this._deleteLabel.height) / 2);
this._icon.scale.x = iconResizeRatio;
this._icon.scale.y = iconResizeRatio;
this._icon.x = offset;
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = ColorTheme.GREY;
this._nameLabel.y = Math.round((h - this._nameLabel.height) / 2);
}
if (this._mode === App.ScreenMode.SELECT)
{
this._skin.setTexture(this._options.whiteSkin);
this._nameLabel.x = Math.round(64 * this._pixelRatio);
if (!this._swipeSurface.contains(this._icon)) this._swipeSurface.addChild(this._icon);
}
else if (this._mode === App.ScreenMode.EDIT)
{
this._skin.setTexture(this._options.greySkin);
this._nameLabel.x = this._icon.x;
if (this._swipeSurface.contains(this._icon)) this._swipeSurface.removeChild(this._icon);
}
};
/**
* Disable
*/
App.SubCategoryButton.prototype.disable = function disable()
{
App.SwipeButton.prototype.disable.call(this);
};
/**
* Update
* @param {App.SubCategory} model
* @param {string} mode
*/
App.SubCategoryButton.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._render();
this.close(true);
};
/**
* Return model
* @returns {App.SubCategory}
*/
App.SubCategoryButton.prototype.getModel = function getModel()
{
return this._model;
};
/**
* Click handler
* @param {InteractionData} interactionData
* @param {App.Category} category
* @param {number} screenMode
*/
App.SubCategoryButton.prototype.onClick = function onClick(interactionData,category,screenMode)
{
if (this._mode === App.ScreenMode.EDIT)
{
if (this._isOpen && interactionData.getLocalPosition(this).x >= this._width - this._openOffset)
{
this._model.saveState();
App.Controller.dispatchEvent(
App.EventType.CHANGE_SCREEN,
App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT,
screenMode,
{subCategory:this._model,category:category},
0,
0,
App.ScreenTitle.EDIT_SUB_CATEGORY
)
);
}
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.SubCategoryButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.SubCategoryButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
<file_sep>/**
* Model Proxy name
* @enum {number}
* @return {{
* TICKER:number,
* EVENT_LISTENER_POOL:number,
* PAYMENT_METHODS:number,
* CURRENCY_PAIRS:number,
* CURRENCY_SYMBOLS:number,
* SUB_CATEGORIES:number,
* CATEGORIES:number,
* ACCOUNTS:number,
* TRANSACTIONS:number,
* SETTINGS:number,
* ICONS:number,
* CHANGE_SCREEN_DATA_POOL:number,
* SCREEN_HISTORY:number
* }}
*/
App.ModelName = {
TICKER:0,
EVENT_LISTENER_POOL:1,
PAYMENT_METHODS:2,
CURRENCY_PAIRS:3,
CURRENCY_SYMBOLS:4,
SUB_CATEGORIES:5,
CATEGORIES:6,
ACCOUNTS:7,
TRANSACTIONS:8,
SETTINGS:9,
ICONS:10,
CHANGE_SCREEN_DATA_POOL:11,
SCREEN_HISTORY:12
};
<file_sep>/**
* TransactionType
* @type {{EXPENSE: number, INCOME: number, toString: Function}}
*/
App.TransactionType = {
EXPENSE:1,
INCOME:2,
toString:function toString(type)
{
return type === App.TransactionType.INCOME ? "Income" : "Expense";
}
};
<file_sep>/**
* @class ColorSample
* @extends Graphics
* @param {number} modelIndex
* @param {number} color
* @param {number} pixelRatio
* @constructor
*/
App.ColorSample = function ColorSample(modelIndex,color,pixelRatio)
{
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,Math.round(40*pixelRatio),Math.round(50*pixelRatio));
this._modelIndex = modelIndex;
this._pixelRatio = pixelRatio;
this._color = color.toString();
this._selected = false;
this._render();
};
App.ColorSample.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.ColorSample.prototype._render = function _render()
{
var xPadding = Math.round((this._selected ? 0 : 5) * this._pixelRatio),
yPadding = Math.round((this._selected ? 5 : 10) * this._pixelRatio),
w = this.boundingBox.width,
h = this.boundingBox.height;
this.clear();
this.beginFill("0x"+this._color);
this.drawRoundedRect(xPadding,yPadding,w-xPadding*2,h-yPadding*2,Math.round(5*this._pixelRatio));
this.endFill();
};
/**
* Set color
* @param {number} index
* @param {number} color
* @param {number} selectedIndex
*/
App.ColorSample.prototype.setModel = function setModel(index,color,selectedIndex)
{
this._modelIndex = index;
this._color = color;
this._selected = selectedIndex === this._modelIndex;
this._render();
};
/**
* Return model index
* @return {number}
*/
App.ColorSample.prototype.getModelIndex = function getModelIndex()
{
return this._modelIndex;
};
/**
* Return value
* @returns {string}
*/
App.ColorSample.prototype.getValue = function getValue()
{
return this._color;
};
/**
* Select
* @param {number} selectedIndex Index of selected item in the collection
*/
App.ColorSample.prototype.select = function select(selectedIndex)
{
var selected = this._modelIndex === selectedIndex;
if (this._selected === selected) return;
this._selected = selected;
this._render();
};
<file_sep>/**
* @class ScrollIndicator
* @extends Graphics
* @param {string} direction
* @param {number} pixelRatio
* @constructor
*/
App.ScrollIndicator = function ScrollIndicator(direction,pixelRatio)
{
PIXI.Graphics.call(this);
this.visible = false;
this.boundingBox = new PIXI.Rectangle(0,0,0,0);
this._direction = direction;
this._pixelRatio = pixelRatio;
this._minIndicatorSize = Math.round(50 * pixelRatio);
this._padding = Math.round(4 * pixelRatio);
this._size = 0;
this._indicatorSize = 0;
this._indicatorThickness = 0;
this._contentPosition = 0;
this._positionStep = 0;
this._showHideTween = new App.TweenProxy(0.2,App.Easing.linear,0,App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
this._state = App.TransitionState.HIDDEN;
};
App.ScrollIndicator.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Show
*/
App.ScrollIndicator.prototype.show = function show()
{
var TransitionState = App.TransitionState;
if (this._state === TransitionState.HIDING || this._state === TransitionState.HIDDEN)
{
this._state = TransitionState.SHOWING;
this.visible = true;
this._showHideTween.start(true);
}
};
/**
* Hide
*
* @param {boolean} [immediate=false]
*/
App.ScrollIndicator.prototype.hide = function hide(immediate)
{
var TransitionState = App.TransitionState;
if (immediate)
{
this._state = TransitionState.HIDDEN;
this.alpha = 0.0;
this.visible = false;
}
else
{
if (this._state === TransitionState.SHOWING || this._state === TransitionState.SHOWN)
{
this._state = TransitionState.HIDING;
this._showHideTween.start(true);
}
}
};
/**
* Update indicator according to position passed in
* @param {number} contentPosition
*/
App.ScrollIndicator.prototype.update = function update(contentPosition)
{
this._contentPosition = contentPosition;
var TransitionState = App.TransitionState;
if (this._state === TransitionState.SHOWING || this._state === TransitionState.HIDING)
{
this._updateVisibility(TransitionState);
}
this._render();
};
/**
* Update visibility
* @param {App.TransitionState} TransitionState
* @private
*/
App.ScrollIndicator.prototype._updateVisibility = function _updateVisibility(TransitionState)
{
var progress = this._showHideTween.progress;
if (this._state === TransitionState.SHOWING)
{
this.alpha = progress;
if (progress === 1.0) this._state = TransitionState.SHOWN;
}
else if (this._state === TransitionState.HIDING)
{
this.alpha = 1.0 - progress;
if (progress === 1.0)
{
this._state = TransitionState.HIDDEN;
this.visible = false;
}
}
};
/**
* Resize
* @param {number} size
* @param {number} contentSize
*/
App.ScrollIndicator.prototype.resize = function resize(size,contentSize)
{
this._size = size;
if (this._direction === App.Direction.X)
{
this.boundingBox.width = this._size;
this.boundingBox.height = Math.round(7 * this._pixelRatio);
this._indicatorThickness = this.boundingBox.height - this._padding;
this._indicatorSize = Math.round(this._size * (this._size / contentSize));
if (this._indicatorSize < this._minIndicatorSize) this._indicatorSize = this._minIndicatorSize;
this._positionStep = (this._size - this._indicatorSize) / (contentSize - this._size);
}
else if (this._direction === App.Direction.Y)
{
this.boundingBox.width = Math.round(7 * this._pixelRatio);
this.boundingBox.height = this._size;
this._indicatorThickness = this.boundingBox.width - this._padding;
this._indicatorSize = Math.round(this._size * (this._size / contentSize));
if (this._indicatorSize < this._minIndicatorSize) this._indicatorSize = this._minIndicatorSize;
this._positionStep = (this._size - this._indicatorSize) / (contentSize - this._size);
}
this._render();
};
/**
* Render indicator
* @private
*/
App.ScrollIndicator.prototype._render = function _render()
{
var indicatorSize = this._indicatorSize,
position = -Math.round(this._contentPosition * this._positionStep);
if (position + indicatorSize > this._size)
{
indicatorSize = this._size - position;
}
else if (position < 0)
{
indicatorSize = indicatorSize + position;
position = 0;
}
this.clear();
this.beginFill(0x000000,0.3);
if (this._direction === App.Direction.X)
{
this.drawRoundedRect(
position + this._padding,
Math.round(this._padding * 0.5),
indicatorSize - this._padding * 2,
this._indicatorThickness,
this._indicatorThickness * 0.5
);
}
else if (this._direction === App.Direction.Y)
{
this.drawRoundedRect(
Math.round(this._padding * 0.5),
position + this._padding,
this._indicatorThickness,
indicatorSize - this._padding * 2,
this._indicatorThickness * 0.5
);
}
this.endFill();
};
/**
* Destroy
*/
App.ScrollIndicator.prototype.destroy = function destroy()
{
//TODO also destroy PIXI's Graphics object!
this._showHideTween.destroy();
this._showHideTween = null;
this.boundingBox = null;
this._direction = null;
this._state = null;
this.clear();
};
<file_sep>/**
* @class HeaderSegment
* @extends DisplayObjectContainer
* @param {number} value
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.HeaderSegment = function HeaderSegment(value,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
this._action = value;
this._width = width;
this._height = height;
this._pixelRatio = pixelRatio;
this._frontElement = null;
this._backElement = null;
this._middlePosition = Math.round(15 * pixelRatio);
this._needsUpdate = true;
this._mask = new PIXI.Graphics();
this.mask = this._mask;
this.addChild(this._mask);
};
App.HeaderSegment.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.HeaderSegment.prototype._render = function _render()
{
var padding = Math.round(10 * this._pixelRatio);
App.GraphicUtils.drawRect(this._mask,0xff0000,0.5,0,0,this._width,this._height-padding*2);
this._mask.y = padding;
};
/**
* Change
* @param {number} action
*/
App.HeaderSegment.prototype.change = function change(action)
{
if (this._action === action)
{
this._needsUpdate = false;
}
else
{
var tempIcon = this._frontElement;
this._frontElement = this._backElement;
this._backElement = tempIcon;
this._needsUpdate = true;
}
this._action = action;
};
/**
* Update
* @param {number} progress
*/
App.HeaderSegment.prototype.update = function update(progress)
{
if (this._needsUpdate)
{
this._frontElement.y = Math.round((this._middlePosition + this._frontElement.height) * progress - this._frontElement.height);
this._backElement.y = Math.round(this._middlePosition + (this._height - this._middlePosition) * progress);
}
};
/**
* Return action
* @returns {number}
*/
App.HeaderSegment.prototype.getAction = function getAction()
{
return this._action;
};
<file_sep>/**
* @class SwipeButton
* @extends DisplayObjectContainer
* @param {number} width
* @param {number} openOffset
* @constructor
*/
App.SwipeButton = function SwipeButton(width,openOffset)
{
PIXI.DisplayObjectContainer.call(this);
this._width = width;
this._interactionEnabled = false;
this._interactiveState = null;
this._dragFriction = 0.5;
this._snapForce = 0.5;
this._openOffset = openOffset;
this._isOpen = false;
this._ticker = App.ModelLocator.getProxy(App.ModelName.TICKER);
};
App.SwipeButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Disable
*/
App.SwipeButton.prototype.disable = function disable()
{
this._disableInteraction();
this.close(true);
};
/**
* Enable interaction
* @private
*/
App.SwipeButton.prototype._enableInteraction = function _enableInteraction()
{
if (!this._interactionEnabled)
{
this._interactionEnabled = true;
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this.interactive = true;
}
};
/**
* Disable interaction
* @private
*/
App.SwipeButton.prototype._disableInteraction = function _disableInteraction()
{
this.interactive = false;
this._interactiveState = null;
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._interactionEnabled = false;
};
/**
* Tick handler
* @private
*/
App.SwipeButton.prototype._onTick = function _onTick()
{
var InteractiveState = App.InteractiveState;
if (this._interactiveState === InteractiveState.SWIPING) this._swipe();
else if (this._interactiveState === InteractiveState.SNAPPING) this._snap();
};
/**
* @method swipeStart
* @param {string} direction
*/
App.SwipeButton.prototype.swipeStart = function swipeStart(direction)
{
var Direction = App.Direction,
InteractiveState = App.InteractiveState;
if (!this._interactiveState)
{
if (!this._isOpen && direction === Direction.LEFT)
{
this._interactiveState = InteractiveState.SWIPING;
this._enableInteraction();
}
else if (this._isOpen && direction === Direction.RIGHT)
{
this._interactiveState = InteractiveState.SNAPPING;
this._enableInteraction();
}
}
};
/**
* @method swipeEnd
*/
App.SwipeButton.prototype.swipeEnd = function swipeEnd()
{
if (this._interactiveState === App.InteractiveState.SWIPING) this._interactiveState = App.InteractiveState.SNAPPING;
};
/**
* @method _swipe
* @private
*/
App.SwipeButton.prototype._swipe = function _swipe()
{
if (this.stage && !this._isOpen)
{
var x = this.stage.getTouchPosition().x;
if (x <= -10000) return;
this._updateSwipePosition(-Math.round(this._width * (1 - (x / this._width)) * this._dragFriction));
}
};
/**
* @method _snap
* @private
*/
App.SwipeButton.prototype._snap = function _snap()
{
var swipePosition = this._getSwipePosition(),
result = Math.round(swipePosition * this._snapForce);
// Snap to open
if (swipePosition < -this._openOffset)
{
if (result >= -this._openOffset)
{
this._isOpen = true;
this._disableInteraction();
this._updateSwipePosition(-this._openOffset);
}
else
{
this._updateSwipePosition(result);
}
}
// Snap to close
else
{
if (result >= -1)
{
this._isOpen = false;
this._disableInteraction();
this._updateSwipePosition(0);
}
else
{
this._updateSwipePosition(result);
}
}
};
/**
* Close Edit button
* @param {boolean} [immediate=false]
*/
App.SwipeButton.prototype.close = function close(immediate)
{
if (this._isOpen)
{
if (immediate)
{
this._updateSwipePosition(0);
this._isOpen = false;
}
else
{
this._interactiveState = App.InteractiveState.SNAPPING;
this._enableInteraction();
}
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.SwipeButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
// Abstract
};
/**
* Return swipe position
* @private
*/
App.SwipeButton.prototype._getSwipePosition = function _getSwipePosition()
{
// Abstract
};
<file_sep>/**
* Direction
* @enum {string}
* @return {{X:string,Y:string,LEFT:string,RIGHT:string}}
*/
App.Direction = {
X:"x",
Y:"y",
LEFT:"LEFT",
RIGHT:"RIGHT"
};
<file_sep>/**
* @class TransactionButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {{width:number,height:number,pixelRatio:number:labelStyles:Object}} options
* @constructor
*/
App.TransactionButton = function TransactionButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
var Text = PIXI.Text,
Graphics = PIXI.Graphics,
editStyle = options.labelStyles.edit;
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._pixelRatio = options.pixelRatio;
this._labelStyles = options.labelStyles;
this._isPending = void 0;
this._background = this.addChild(new Graphics());
this._copyLabel = this.addChild(new Text("Copy",editStyle));
this._editLabel = this.addChild(new Text("Edit",editStyle));
this._icon = null;
this._iconResizeRatio = -1;
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._redSkin = this._swipeSurface.addChild(new PIXI.Sprite(options.redSkin));
this._greySkin = this._swipeSurface.addChild(new PIXI.Sprite(options.greySkin));
this._colorStripe = this._swipeSurface.addChild(new Graphics());
this._accountField = this._swipeSurface.addChild(new Text("",editStyle));
this._categoryField = this._swipeSurface.addChild(new Text("",editStyle));
this._amountField = this._swipeSurface.addChild(new Text("",editStyle));
this._currencyField = this._swipeSurface.addChild(new Text("",editStyle));
this._dateField = this._swipeSurface.addChild(new Text("",editStyle));
this._pendingFlag = this._swipeSurface.addChild(new Graphics());
this._pendingLabel = this._pendingFlag.addChild(new Text("PENDING",this._labelStyles.pending));
};
App.TransactionButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* Update
* @param {boolean} [updateAll=false]
* @private
*/
App.TransactionButton.prototype._update = function _update(updateAll)
{
var pending = this._model.pending,
date = this._model.date,
dateText = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
this._accountField.setText(this._model.account.name);
this._amountField.setText(this._model.amount);
this._currencyField.setText(" " + this._model.currencyQuote);
this._categoryField.setText(this._model.subCategory.name+" / "+this._model.category.name);
this._dateField.setText(pending ? "Due by\n"+dateText : dateText);
if (this._icon) this._icon.setTexture(PIXI.TextureCache[this._model.category.icon]);
else this._icon = this._swipeSurface.addChild(PIXI.Sprite.fromFrame(this._model.category.icon));
if (pending !== this._isPending)
{
if (pending)
{
this._accountField.setStyle(this._labelStyles.accountPending);
this._amountField.setStyle(this._labelStyles.amountPending);
this._currencyField.setStyle(this._labelStyles.currencyPending);
this._categoryField.setStyle(this._labelStyles.accountPending);
this._dateField.setStyle(this._labelStyles.datePending);
}
else
{
this._accountField.setStyle(this._labelStyles.accountIncome);
this._amountField.setStyle(this._labelStyles.amountIncome);
this._currencyField.setStyle(this._labelStyles.currencyIncome);
this._categoryField.setStyle(this._labelStyles.accountIncome);
this._dateField.setStyle(this._labelStyles.date);
}
}
this._render(updateAll,pending);
this._updateLayout(updateAll,pending);
this.close(true);
this._isPending = pending;
};
/**
* Render
* @param {boolean} [renderAll=false]
* @param {boolean} pending
* @private
*/
App.TransactionButton.prototype._render = function _render(renderAll,pending)
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
swipeOptionWidth = Math.round(this._openOffset / 2);
if (renderAll)
{
GraphicUtils.drawRects(this._background,ColorTheme.GREEN,1,[0,0,w-swipeOptionWidth,h],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.RED,1,[w-swipeOptionWidth,0,swipeOptionWidth,h],false,true);
GraphicUtils.drawRect(this._pendingFlag,0x000000,1,0,0,Math.round(this._pendingLabel.width+10*r),Math.round(this._pendingLabel.height+6*r));
}
GraphicUtils.drawRect(this._colorStripe,"0x"+this._model.category.color,1,0,0,Math.round(4 * r),h);
if (pending !== this._isPending)
{
if (pending)
{
this._greySkin.visible = false;
this._redSkin.visible = true;
this._pendingFlag.visible = true;
}
else
{
this._greySkin.visible = true;
this._redSkin.visible = false;
this._pendingFlag.visible = false;
}
}
this._icon.tint = pending ? ColorTheme.RED_DARK : parseInt(this._model.category.color,16);
};
/**
* Update layout
* @param {boolean} [updateAll=false]
* @param {boolean} pending
* @private
*/
App.TransactionButton.prototype._updateLayout = function _updateLayout(updateAll,pending)
{
var r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
swipeOptionWidth = Math.round(60 * r),
padding = Math.round(10 * r);
if (updateAll)
{
this._copyLabel.x = w - swipeOptionWidth * 2 + Math.round((swipeOptionWidth - this._copyLabel.width) / 2);
this._copyLabel.y = Math.round((h - this._copyLabel.height) / 2);
this._editLabel.x = w - swipeOptionWidth + Math.round((swipeOptionWidth - this._editLabel.width) / 2);
this._editLabel.y = Math.round((h - this._editLabel.height) / 2);
if (this._iconResizeRatio === -1) this._iconResizeRatio = Math.round(32 * this._pixelRatio) / this._icon.height;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round(20 * r);
this._icon.y = Math.round((h - this._icon.height) / 2);
this._accountField.x = Math.round(70 * r);
this._accountField.y = Math.round(7 * r);
this._amountField.x = Math.round(70 * r);
this._amountField.y = Math.round(26 * r);
this._currencyField.y = Math.round(33 * r);
this._categoryField.x = Math.round(70 * r);
this._categoryField.y = Math.round(52 * r);
this._pendingLabel.x = Math.round(5 * r);
this._pendingLabel.y = Math.round(4 * r);
this._pendingFlag.x = Math.round(w - padding - this._pendingFlag.width);
this._pendingFlag.y = Math.round(7 * r);
}
this._currencyField.x = Math.round(this._amountField.x + this._amountField.width);
this._dateField.x = Math.round(w - padding - this._dateField.width);
this._dateField.y = pending ? Math.round(38 * r) : Math.round(52 * r);
};
/**
* Set model
* @param {App.Transaction} model
*/
App.TransactionButton.prototype.setModel = function setModel(model)
{
this._model = model;
this._update(this._icon === null);
};
/**
* Click handler
* @param {PIXI.InteractionData} data
*/
App.TransactionButton.prototype.onClick = function onClick(data)
{
var position = data.getLocalPosition(this).x;
if (this._isOpen && position >= this._width - this._openOffset)
{
var changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update();
// Edit
if (position >= this._width - this._openOffset / 2)
{
App.ModelLocator.getProxy(App.ModelName.TRANSACTIONS).setCurrent(this._model);
changeScreenData.screenMode = App.ScreenMode.EDIT;
changeScreenData.updateData = this._model;
changeScreenData.headerName = App.ScreenTitle.EDIT_TRANSACTION;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
// Copy
else
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.COPY,
transaction:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.TransactionButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.TransactionButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
<file_sep>/**
* @class Account
* @param {Array} data
* @param {Collection} collection
* @param {Object} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Account = function Account(data,collection,parent,eventListenerPool)
{
if (data)
{
this._data = data;
if (parseInt(data[0],10) >= App.Account._UID) App.Account._UID = parseInt(data[0],10);
this.id = this._data[0];
this.name = decodeURIComponent(this._data[1]);
this.lifeCycleState = parseInt(this._data[2],10) ? App.LifeCycleState.ACTIVE : App.LifeCycleState.DELETED;
this._categories = null;
}
else
{
this._data = null;
this.id = String(++App.Account._UID);
this.name = "Account" + this.id;
this.lifeCycleState = App.LifeCycleState.CREATED;
this._categories = null;
}
this.balance = 0.0;
};
App.Account._UID = 0;
/**
* Serialize
* @return {Array}
*/
App.Account.prototype.serialize = function serialize()
{
var categoryCollection = this.categories,
encodedName = App.StringUtils.encode(this.name),
lifeCycle = this.lifeCycleState === App.LifeCycleState.DELETED ? 0 : 1;
if (categoryCollection.length)
{
var i = 0,
l = categoryCollection.length,
ids = [];
for (;i<l;) ids.push(categoryCollection[i++].id);
return [this.id,encodedName,lifeCycle,ids.join(",")];
}
else
{
return [this.id,encodedName,lifeCycle];
}
};
/**
* Add category
* @param {App.Category} category
* @private
*/
App.Account.prototype.addCategory = function addCategory(category)
{
if (this._categories) this._categories.push(category);
else this._categories = [category];
};
/**
* Remove category
* @param {App.Category} category
* @private
*/
App.Account.prototype.removeCategory = function removeCategory(category)
{
var i = 0,
l = this._categories.length;
for (;i<l;i++)
{
if (this._categories[i] === category)
{
this._categories.splice(i,1);
break;
}
}
};
/**
* Calculate balance
* @returns {number}
*/
App.Account.prototype.calculateBalance = function calculateBalance()
{
var collection = this.categories, // Inflate categories
i = 0,
l = this._categories.length;
this.balance = 0.0;
for (;i<l;) this.balance += this._categories[i++].calculateBalance();
return this.balance;
};
/**
* @property categories
* @type Array.<Category>
*/
Object.defineProperty(App.Account.prototype,'categories',{
get:function()
{
if (!this._categories)
{
if (this._data && this._data[3]) this._categories = App.ModelLocator.getProxy(App.ModelName.CATEGORIES).filter(this._data[3].split(","),"id");
else this._categories = [];
}
return this._categories;
}
});
<file_sep>/**
* @class TransactionScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.TransactionScreen = function TransactionScreen(layout)
{
App.Screen.call(this,layout,0.4);
//TODO display message/tutorial in case of empty screen
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width,
h = layout.contentHeight,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
labelStyles:{
edit:FontStyle.get(18,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
accountIncome:FontStyle.get(14,FontStyle.BLUE_LIGHT,null,FontStyle.LIGHT_CONDENSED),
amountIncome:FontStyle.get(26,FontStyle.BLUE),
currencyIncome:FontStyle.get(16,FontStyle.BLUE_DARK,null,FontStyle.LIGHT_CONDENSED),
date:FontStyle.get(14,FontStyle.GREY_DARK),
pending:FontStyle.get(12,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
accountPending:FontStyle.get(14,FontStyle.RED_DARK),
amountPending:FontStyle.get(26,FontStyle.WHITE),
currencyPending:FontStyle.get(16,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
datePending:FontStyle.get(14,FontStyle.WHITE,"right",FontStyle.LIGHT_CONDENSED)
},
greySkin:skin.GREY_70,
redSkin:skin.RED_70,
width:w,
height:Math.round(70 * r),
pixelRatio:r,
openOffset:Math.round(120 * r)
};
this._interactiveButton = null;
this._buttonPool = new App.ObjectPool(App.TransactionButton,4,buttonOptions);
this._buttonList = new App.VirtualList(this._buttonPool,App.Direction.Y,w,h,r);
this._pane = this.addChild(new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,w,h,r,false));
this._pane.setContent(this._buttonList);
};
App.TransactionScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.TransactionScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.enable();
this._swipeEnabled = true;
};
/**
* Disable
*/
App.TransactionScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
this._swipeEnabled = false;
};
/**
* Update
*/
App.TransactionScreen.prototype.update = function update(model)
{
this._model = model;
this._buttonList.update(model);
this._pane.resize();
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.TransactionScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
this._interactiveButton = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (this._interactiveButton) this._interactiveButton.swipeStart(direction);
this._closeButtons(false);
};
/**
* Called when swipe ends
* @private
*/
App.TransactionScreen.prototype._swipeEnd = function _swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.TransactionScreen.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._buttonList.children.length,
button = null;
for (;i<l;)
{
button = this._buttonList.getChildAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
};
/**
* Click handler
* @private
*/
App.TransactionScreen.prototype._onClick = function _onClick()
{
var data = this.stage.getTouchData(),
button = this._buttonList.getItemUnderPoint(data);
if (button) button.onClick(data);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.TransactionScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate();
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
changeScreenData.update(App.ScreenName.MENU,0,null,HeaderAction.NONE,HeaderAction.CANCEL,App.ScreenTitle.MENU);
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
};
<file_sep>/** @type {{
* _daysInMonth:Array.<number>,
* _monthLabels:Array.<string>,
* _dayLabels:Array.<string>,
* getMonthLabel:Function,
* getDayLabels:Function,
* getMonth:Function,
* getDaysInMonth:Function
* }} */
App.DateUtils = {
_daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],
_monthLabels:["January","February","March","April","May","June","July","August","September","October","November","December"],
_dayLabels:["S","M","T","W","T","F","S"],
/**
* Return month label according to month index passed in
* @param {number} month
* @returns {string}
*/
getMonthLabel:function getMonthLabel(month)
{
return this._monthLabels[month];
},
/**
* Return array of day labels in order from start of week passed in
* @param {number} startOfWeek
* @return {Array.<string>}
*/
getDayLabels:function getDayLabels(startOfWeek)
{
var i = startOfWeek;
while (i)
{
this._dayLabels.push(this._dayLabels.shift());
i--;
}
return this._dayLabels;
},
/**
* Calculate and generate all days in a month, based on starting day of a week passed in
* Returns 2-dimensional array, where rows are weeks, and columns particular days in a week
* @param {Date} date
* @param {number} startOfWeek 0 = Sunday, 1 = Monday, ... , 6 = Saturday
* @return {Array.<Array.<number>>} Days in Week array is twice as long, as the second offsetting number indicate if the day belongs to other month(1) or not(0)
*/
getMonth:function getMonth(date,startOfWeek)
{
//TODO allocate arrays from pool?
var year = date.getFullYear(),
currentMonth = date.getMonth(),
previousMonth = currentMonth ? currentMonth - 1 : 11,
daysInCurrentMonth = this.getDaysInMonth(year,currentMonth),
daysInPreviousMonth = this.getDaysInMonth(year,previousMonth),
firstDayOfMonth = new Date(year,currentMonth,1).getDay(),
dayOffset = firstDayOfMonth >= startOfWeek ? firstDayOfMonth - startOfWeek : 7 + firstDayOfMonth - startOfWeek,
firstDateOfWeek = 7 + 1 - dayOffset,
weeks = [],
days = null,
otherMonth = 0,
l = 6 * 7,// 6 weeks of 7 days
i = 0,
j = 0;
if (firstDateOfWeek !== 1)
{
firstDateOfWeek = daysInPreviousMonth + 1 - dayOffset;
otherMonth = 1;
}
for (;i<l;i++)
{
if (firstDateOfWeek > daysInPreviousMonth && otherMonth === 1)
{
firstDateOfWeek = 1;
otherMonth = 0;
}
if (firstDateOfWeek > daysInCurrentMonth && otherMonth === 0)
{
firstDateOfWeek = 1;
otherMonth = 1;
}
if (i % 7 === 0)
{
days = new Array(7*2);
weeks[weeks.length] = days;
j = 0;
}
days[j++] = firstDateOfWeek++;
days[j++] = otherMonth;
}
return weeks;
},
/**
* Return number of days in particular month passed in
* Also check for Leap year
* @param {number} year
* @param {number} month zero-based
* @return {number}
*/
getDaysInMonth:function getDaysInMonth(year,month)
{
return (month === 1 && (year % 400 === 0 || year % 4 === 0)) ? 29 : this._daysInMonth[month];
},
/**
* Format and return military time
* @param {Date} time
* @returns {string}
*/
getMilitaryTime:function getMilitaryTime(time)
{
var padFunction = App.StringUtils.pad;
return padFunction(time.getHours()) + ":" + padFunction(time.getMinutes());
}
};
<file_sep>/**
* @class Controller
* @type {{_eventListenerPool:ObjectPool,_eventCommandMap: {}, _commands: Array, _init: Function, _onCommandComplete: Function, _destroyCommand: Function, dispatchEvent: Function}}
*/
App.Controller = {
_eventListenerPool:null,
_eventCommandMap:{},
/** @type {Array.<Command>} */
_commands:[],
/**
* Init
* @param {ObjectPool} eventListenerPool
* @param {Array.<>} eventMap
*/
init:function init(eventListenerPool,eventMap)
{
this._eventListenerPool = eventListenerPool;
var i = 0,
l = eventMap.length;
for (;i<l;) this._eventCommandMap[eventMap[i++]] = {constructor:eventMap[i++]};
},
/**
* On command complete
* @param {*} data
* @private
*/
_onCommandComplete:function _onCommandComplete(data)
{
this._destroyCommand(data);
},
/**
* Destroy command
* @param {Command} command
* @private
*/
_destroyCommand:function _destroyCommand(command)
{
var i = 0, l = this._commands.length, cmd = null;
for (;i<l;)
{
cmd = this._commands[i++];
if (cmd === command)
{
cmd.removeEventListener(App.EventType.COMPLETE,this,this._onCommandComplete);
cmd.destroy();
this._commands.splice(i,1);
break;
}
}
},
/**
* Dispatch event passed in
* @param {string} eventType
* @param {*} [data=null] Defaults to null
* @param {boolean} [checkRunningInstances=false] Defaults to false
*/
dispatchEvent:function dispatchEvent(eventType,data,checkRunningInstances)
{
/** @type {Function} */var commandConstructor = this._eventCommandMap[eventType].constructor;
if (commandConstructor)
{
/** @type {Command} */var cmd = null;
// First check, if multiple instances of this Command are allowed
// If not, destroy running instances, before executing new one
if (checkRunningInstances)
{
var i = 0, l = this._commands.length;
for (;i<l;)
{
cmd = this._commands[i++];
if (cmd instanceof commandConstructor && !cmd.allowMultipleInstances)
{
this._destroyCommand(cmd);
}
}
}
// Execute command
cmd = /** @type {Command} */new commandConstructor(this._eventListenerPool);
this._commands.push(cmd);
cmd.addEventListener(App.EventType.COMPLETE,this,this._onCommandComplete);
cmd.execute(data);
}
}
};
<file_sep>/**
* @class List
* @extends DisplayObjectContainer
* @param {string} direction
* @constructor
*/
App.List = function List(direction)
{
PIXI.DisplayObjectContainer.call(this);
this.boundingBox = new App.Rectangle();
this._direction = direction;
this._items = [];
};
App.List.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Add item
* @param {DisplayObject} item
* @param {boolean} [updateLayout=false]
* @returns {DisplayObject} returns item added
*/
App.List.prototype.add = function add(item,updateLayout)
{
this._items[this._items.length] = item;
this.addChild(item);
if (updateLayout) this.updateLayout();
return item;
};
/**
* Remove item passed in
* @param {DisplayObject} item
*/
App.List.prototype.remove = function remove(item)
{
this.removeItemAt(this._items.indexOf(item));
};
/**
* Remove item at index passed in
* @param {number} index
*/
App.List.prototype.removeItemAt = function removeItemAt(index)
{
var item = this._items.splice(index,1)[0];
this.removeChild(item);
return item;
};
/**
* Return
* @param {number} index
*/
App.List.prototype.getItemAt = function getItemAt(index)
{
return this._items[index];
};
/**
* Update layout
*/
App.List.prototype.updateLayout = function updateLayout()
{
var i = 0,
l = this._items.length,
item = null,
position = 0,
Direction = App.Direction;
if (this._direction === Direction.X)
{
for (;i<l;)
{
item = this._items[i++];
item.x = position;
position = Math.round(position + item.boundingBox.width);
}
this.boundingBox.width = position;
this.boundingBox.height = item.boundingBox.height;
}
else if (this._direction === Direction.Y)
{
for (;i<l;)
{
item = this._items[i++];
item.y = position;
position = Math.round(position + item.boundingBox.height);
}
this.boundingBox.height = position;
this.boundingBox.width = item.boundingBox.width;
}
};
/**
* Find and return item under point passed in
* @param {InteractionData} data PointerData to get the position from
*/
App.List.prototype.getItemUnderPoint = function getItemUnderPoint(data)
{
var position = data.getLocalPosition(this).x,
boundsProperty = "width",
itemPosition = 0,
itemProperty = "x",
item = null,
i = 0,
l = this._items.length;
if (this._direction === App.Direction.Y)
{
position = data.getLocalPosition(this).y;
itemProperty = "y";
boundsProperty = "height";
}
for (;i<l;)
{
item = this._items[i++];
itemPosition = item[itemProperty];
if (itemPosition <= position && itemPosition + item.boundingBox[boundsProperty] >= position)
{
return item;
}
}
return null;
};
/**
* Test if position passed in falls within this list boundaries
* @param {number} position
* @returns {boolean}
*/
App.List.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* @property length
* @type number
*/
Object.defineProperty(App.List.prototype,'length',{
get:function()
{
return this._items.length;
}
});
<file_sep>/**
* LifeCycle state
* @enum {number}
* @return {{CREATED:number,ACTIVE:number,DELETED:number}}
*/
App.LifeCycleState = {
CREATED:1,
ACTIVE:2,
DELETED:3
};
<file_sep>/**
* @class CategoryButtonExpand
* @extends ExpandButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {{font:string,fill:string}} options.nameLabelStyle
* @param {{font:string,fill:string}} options.deleteLabelStyle
* @param {{font:string,fill:string}} options.addLabelStyle
* @param {number} options.openOffset
* @constructor
*/
App.CategoryButtonExpand = function CategoryButtonExpand(poolIndex,options)
{
App.ExpandButton.call(this,options.width,options.height,true);
this.allocated = false;
this.poolIndex = poolIndex;
this._model = null;
this._mode = null;
this._pixelRatio = options.pixelRatio;
this._surface = new App.CategoryButtonSurface(options);
this._subCategoryList = new App.SubCategoryList(options);
this._layoutDirty = true;
this._setContent(this._subCategoryList);
this.addChild(this._subCategoryList);
this.addChild(this._surface);
};
App.CategoryButtonExpand.prototype = Object.create(App.ExpandButton.prototype);
/**
* Render
* @private
*/
App.CategoryButtonExpand.prototype._render = function _render()
{
this._surface.render(this._model.name,this._model.icon,this._model.color);
};
/**
* Update
* @param {App.Category} model
* @param {string} mode
*/
App.CategoryButtonExpand.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._layoutDirty = true;
this._render();
this.close(true);
};
/**
* Click handler
* @param {InteractionData} data
*/
App.CategoryButtonExpand.prototype.onClick = function onClick(data)
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.CLOSED || this._transitionState === TransitionState.CLOSING)
{
this.open();
}
else
{
if (data.getLocalPosition(this).y <= this._buttonHeight)
{
this.close();
}
else
{
this._eventDispatcher.dispatchEvent(App.EventType.COMPLETE,this); // To cancel any parent's processes
var button = this._subCategoryList.getItemUnderPoint(data);
if (button)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
EventType = App.EventType,
changeScreenData = ModelLocator.getProxy(ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
if (button instanceof App.AddNewButton)
{
changeScreenData.screenName = App.ScreenName.EDIT;
changeScreenData.headerName = App.ScreenTitle.ADD_SUB_CATEGORY;
App.Controller.dispatchEvent(EventType.CHANGE_SUB_CATEGORY,{
type:EventType.CREATE,
category:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else
{
changeScreenData.backSteps = ModelLocator.getProxy(ModelName.SCREEN_HISTORY).peek(2).screenName === App.ScreenName.ACCOUNT ? 2 : 1;
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(EventType.CHANGE_TRANSACTION,{
type:EventType.CHANGE,
account:ModelLocator.getProxy(ModelName.ACCOUNTS).find("id",this._model.account),
category:this._model,
subCategory:button.getModel(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
}
}
}
};
/**
* Open
*/
App.CategoryButtonExpand.prototype.open = function open()
{
if (this._layoutDirty)
{
this._subCategoryList.update(this._model,this._mode);
this._contentHeight = this._subCategoryList.boundingBox.height;
this._layoutDirty = false;
}
App.ExpandButton.prototype.open.call(this);
};
/**
* Disable
*/
App.CategoryButtonExpand.prototype.disable = function disable()
{
this.close(true);
};
<file_sep>/**
* @class EditScreen
* @param {Object} layout
* @constructor
*/
App.EditScreen = function EditScreen(layout)
{
App.Screen.call(this,layout,0.4);
var r = layout.pixelRatio,
inputWidth = layout.width - Math.round(20 * r),
inputHeight = Math.round(40 * r);
this._target = null;
this._background = this.addChild(new PIXI.Graphics());
this._input = this.addChild(new App.Input("",20,inputWidth,inputHeight,r,true));
this._deleteButton = new App.PopUpButton("Delete","",{
width:inputWidth,
height:inputHeight,
pixelRatio:r,
popUpLayout:{x:Math.round(10*r),y:0,width:Math.round(inputWidth-20*r),height:Math.round(layout.height/2),overlayWidth:layout.width,overlayHeight:0}
});
this._renderAll = true;
};
App.EditScreen.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.EditScreen.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
ScreenMode = App.ScreenMode,
r = this._layout.pixelRatio,
padding = Math.round(10 * r),
inputHeight = Math.round(60 * r),
w = this._layout.width - padding * 2;
if (this._renderAll)
{
this._renderAll = false;
this._input.x = padding;
this._input.y = padding;
this._deleteButton.setPosition(padding,inputHeight+padding);
}
if (this._mode === ScreenMode.EDIT)
{
if (!this.contains(this._deleteButton)) this.addChild(this._deleteButton);
//TODO use skin
GraphicUtils.drawRects(this._background,ColorTheme.GREY,1,[0,0,w+padding*2,inputHeight*2],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_DARK,1,[padding,inputHeight-1,w,1],false,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_LIGHT,1,[padding,inputHeight,w,1],false,true);
}
else if (this._mode === ScreenMode.ADD)
{
if (this.contains(this._deleteButton)) this.removeChild(this._deleteButton);
GraphicUtils.drawRect(this._background,ColorTheme.GREY,1,0,0,w+padding*2,inputHeight);
}
};
/**
* Hide
*/
App.EditScreen.prototype.hide = function hide()
{
this._unRegisterDeleteButtonListeners();
App.Screen.prototype.hide.call(this);
};
/**
* Enable
*/
App.EditScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._input.enable();
};
/**
* Disable
*/
App.EditScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._input.disable();
};
/**
* Update
* @param {{category:App.Category,subCategory:App.SubCategory}} model
* @param {string} mode
*/
App.EditScreen.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._target = this._model instanceof App.Account ? App.Account : App.SubCategory;
this._deleteButton.hidePopUp(true);
if (this._target === App.Account)
{
this._input.setValue(this._model.name);
this._deleteButton.setMessage("Are you sure you want to\ndelete this account with all its\ndata and categories?");
}
else if (this._target === App.SubCategory && this._model.subCategory)
{
this._input.setValue(this._model.subCategory.name);
this._deleteButton.setMessage("Are you sure you want to\ndelete this sub-category?");
}
this._render();
};
/**
* Register delete button event listeners
* @private
*/
App.EditScreen.prototype._registerDeleteButtonListeners = function _registerDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.addEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.addEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.addEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* UnRegister delete button event listeners
* @private
*/
App.EditScreen.prototype._unRegisterDeleteButtonListeners = function _unRegisterDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.removeEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.removeEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.removeEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* On delete cancel
* @private
*/
App.EditScreen.prototype._onDeleteCancel = function _onDeleteCancel()
{
this._deleteButton.hidePopUp();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
};
/**
* On delete confirm
* @private
*/
App.EditScreen.prototype._onDeleteConfirm = function _onDeleteConfirm()
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
this._onHidePopUpComplete();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
changeScreenData.updateBackScreen = true;
if (this._target === App.Account)
{
App.Controller.dispatchEvent(EventType.CHANGE_ACCOUNT,{
type:EventType.DELETE,
account:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else if (this._target === App.SubCategory)
{
App.Controller.dispatchEvent(EventType.CHANGE_SUB_CATEGORY,{
type:EventType.DELETE,
subCategory:this._model.subCategory,
category:this._model.category,
nextCommand:new App.ChangeCategory(),
nextCommandData:{
type:EventType.CHANGE,
category:this._model.category,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
}
});
}
};
/**
* On Delete PopUp hide complete
* @private
*/
App.EditScreen.prototype._onHidePopUpComplete = function _onHidePopUpComplete()
{
this._unRegisterDeleteButtonListeners();
this.enable();
this._registerEventListeners(App.EventLevel.LEVEL_2);
};
/**
* Click handler
* @private
*/
App.EditScreen.prototype._onClick = function _onClick()
{
if (this._deleteButton.hitTest(this.stage.getTouchData().getLocalPosition(this).y))
{
if (this._input.isFocused())
{
this._input.blur();
}
else
{
this.disable();
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
App.ViewLocator.getViewSegment(App.ViewName.HEADER).disableActions();
this._registerDeleteButtonListeners();
this._deleteButton.setPopUpLayout(0,this._layout.headerHeight,0,this._layout.contentHeight > this._background.height ? this._layout.contentHeight : this._background.height);
this._deleteButton.showPopUp();
}
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.EditScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
this._input.blur();
//TODO check first if value is set
if (action === App.HeaderAction.CONFIRM)
{
changeScreenData.updateBackScreen = true;
if (this._target === App.Account)
{
App.Controller.dispatchEvent(EventType.CHANGE_ACCOUNT,{
type:EventType.CHANGE,
account:this._model,
name:this._input.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else if (this._target === App.SubCategory)
{
App.Controller.dispatchEvent(EventType.CHANGE_SUB_CATEGORY,{
type:EventType.CHANGE,
subCategory:this._model.subCategory,
category:this._model.category,
name:this._input.getValue(),
nextCommand:new App.ChangeCategory(),
nextCommandData:{
type:EventType.CHANGE,
category:this._model.category,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
}
});
}
}
else if (action === App.HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(EventType.CHANGE_SCREEN,changeScreenData);
}
};
<file_sep>/**
* @class Radio
* @param {number} pixelRatio
* @param {boolean} selected
* @constructor
*/
App.Radio = function Radio(pixelRatio,selected)
{
PIXI.Graphics.call(this);
this._selected = selected;
this._size = Math.round(20 * pixelRatio);
this._pixelRatio = pixelRatio;
this._check = new PIXI.Graphics();
this.boundingBox = new App.Rectangle(0,0,this._size,this._size);
this._render();
this._check.alpha = selected ? 1.0 : 0.0;
this.addChild(this._check);
};
App.Radio.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Radio.prototype._render = function _render()
{
var drawArc = App.GraphicUtils.drawArc,
ColorTheme = App.ColorTheme,
size = this._size,
center = new PIXI.Point(Math.round(size/2),Math.round(size/2));
drawArc(this,center,size,size,Math.round(2*this._pixelRatio),0,360,20,0,0,0,ColorTheme.GREY,1);
size -= Math.round(8*this._pixelRatio);
drawArc(this._check,center,size,size,Math.round(6*this._pixelRatio),0,360,20,0,0,0,ColorTheme.BLUE,1);
};
/**
* Select
*/
App.Radio.prototype.select = function select()
{
this._selected = true;
this._check.alpha = 1.0;
};
/**
* Select
*/
App.Radio.prototype.deselect = function deselect()
{
this._selected = false;
this._check.alpha = 0.0;
};
<file_sep>/**
* @class ChangeScreen
* @extends {Command}
* @constructor
*/
App.ChangeScreen = function ChangeScreen()
{
App.Command.call(this,false,App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
};
App.ChangeScreen.prototype = Object.create(App.Command.prototype);
/**
* Execute the command
*
* @method execute
* @param {App.ChangeScreenData} data
*/
App.ChangeScreen.prototype.execute = function execute(data)
{
var ViewLocator = App.ViewLocator,
ViewName = App.ViewName,
ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
changeScreenDataPool = ModelLocator.getProxy(ModelName.CHANGE_SCREEN_DATA_POOL),
screenHistory = ModelLocator.getProxy(ModelName.SCREEN_HISTORY),
screenStack = ViewLocator.getViewSegment(ViewName.SCREEN_STACK),
screen = null;
if (data.screenName === App.ScreenName.BACK)
{
var updateBackScreen = data.updateBackScreen,
i = 0,
l = data.backSteps;
for (;i<l;i++) changeScreenDataPool.release(screenHistory.pop());
changeScreenDataPool.release(data);
data = screenHistory.peek();
screen = screenStack.getChildByIndex(data.screenName);
if (updateBackScreen) screen.update(data.updateData,data.screenMode);
}
else
{
if (data.headerLeftAction !== App.HeaderAction.CANCEL && data.headerRightAction !== App.HeaderAction.CANCEL && data.screenMode !== App.ScreenMode.SELECT)
{
this._clearHistory(screenHistory,changeScreenDataPool);
}
screen = screenStack.getChildByIndex(data.screenName);
screen.update(data.updateData,data.screenMode);
screenHistory.push(data);
}
// console.log("Stack: ",screenHistory._source);
// console.log("Pool: ",changeScreenDataPool._freeItems);
ViewLocator.getViewSegment(ViewName.HEADER).change(data.headerLeftAction,data.headerRightAction,data.headerName);
screenStack.selectChild(screen);
this.dispatchEvent(App.EventType.COMPLETE,this);
};
/**
* Clear history
* @param {App.Stack} screenHistory
* @param {App.ObjectPool} changeScreenDataPool
* @private
*/
App.ChangeScreen.prototype._clearHistory = function _clearHistory(screenHistory,changeScreenDataPool)
{
// console.log("Before clear: ------------------");
// console.log("Stack: ",screenHistory._source);
// console.log("Pool: ",changeScreenDataPool._freeItems);
var item = screenHistory.pop();
while (item)
{
changeScreenDataPool.release(item);
item = screenHistory.pop();
}
screenHistory.clear();
// console.log("After clear: ------------------");
// console.log("Stack: ",screenHistory._source);
// console.log("Pool: ",changeScreenDataPool._freeItems);
// console.log("---------------------------------");
};
<file_sep>/**
* ColorTheme
* @enum {number}
* @type {{
* WHITE:number,
* BLUE: number,
* BLUE_DARK:number,
* BLUE_LIGHT:number,
* GREY: number,
* GREY_DARK: number,
* GREY_DARKER: number,
* GREY_LIGHT: number,
* RED:number,
* RED_DARK:number,
* RED_LIGHT:number,
* GREEN:number,
* INPUT_HIGHLIGHT:number,
* BLACK:number
* }}
*/
App.ColorTheme = {
WHITE:0xfffffe,
BLUE:0x394264,
BLUE_DARK:0x252B44,
BLUE_LIGHT:0x50597B,
GREY:0xefefef,
GREY_DARK:0xcccccc,
GREY_DARKER:0x999999,
GREY_LIGHT:0xffffff,
RED:0xE53013,
RED_DARK:0x990000,
RED_LIGHT:0xFF3300,
GREEN:0x33CC33,
INPUT_HIGHLIGHT:0x0099ff,
BLACK:0x000000
};
<file_sep>"use strict";
/**
* Function prototype bind polyfill
* ! @source http://code.famo.us/lib/functionPrototypeBind.js
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* Object.create() polyfill
* ! @source https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
*/
if (typeof Object.create != 'function') {
(function () {
var F = function () {};
Object.create = function (o) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (o === null) {
throw Error('Cannot set a null [[Prototype]]');
}
if (typeof o != 'object') {
throw TypeError('Argument must be an object');
}
F.prototype = o;
return new F();
};
})();
}
/**
* requestAnimationFrame polyfill
*/
window.requestAnimationFrame || (window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback)
{
return window.setTimeout(function() {
callback();
}, 1000 / 60);
});
/**
* @module App
*/
var App = App || {};
/** @type {{
* rgbToHex:Function,
* hexToRgb:Function,
* rgbToHsl:Function,
* hslToRgb:Function,
* rgbToHsv:Function,
* hsvToRgb:Function
* }} */
App.MathUtils = {
/**
* Convert RGB values to HEX value
* @param {number} red
* @param {number} green
* @param {number} blue
* @returns {string}
*/
rgbToHex:function rgbToHex(red,green,blue)
{
return ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
},
/**
* Convert HEX value to r, g, and b color component values
* @param {string} hex
* @param {Object|null} container
* @returns {{r:number,g:number,b:number}|null}
*/
hexToRgb:function hexToRgb(hex,container)
{
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (result)
{
if (container)
{
container.r = parseInt(result[1],16);
container.g = parseInt(result[2],16);
container.b = parseInt(result[3],16);
return container;
}
else
{
return {r:parseInt(result[1],16),g:parseInt(result[2],16),b:parseInt(result[3],16)};
}
}
return null;
},
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @param {Object|null} container
* @return {{h:number,s:number,l:number}} The HSL representation
*/
rgbToHsl:function rgbToHsl(r,g,b,container)
{
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r,g,b),
min = Math.min(r,g,b),
h,
s,
l = (max + min) / 2;
if(max == min)
{
h = s = 0; // achromatic
}
else
{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max)
{
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
if (container)
{
container.h = h;
container.s = s;
container.l = l;
return container;
}
return {h:h,s:s,l:l};
},
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} l The lightness
* @param {Object|null} container
* @return {{r:number,g:number,b:number}} The RGB representation
*/
hslToRgb:function hslToRgb(h,s,l,container)
{
var r = l,
g = l,
b = l;
if (s !== 0)
{
var q = l < 0.5 ? l * (1 + s) : l + s - l * s,
p = 2 * l - q;
r = this._hueToRgb(p,q,h+1/3);
g = this._hueToRgb(p,q,h);
b = this._hueToRgb(p,q,h-1/3);
}
if (container)
{
container.r = r * 255;
container.g = g * 255;
container.b = b * 255;
return container;
}
return {r:r*255,g:g*255,b:b*255};
},
/**
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and v in the set [0, 1].
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @param {Object|null} container
* @return {{h:number,s:number,v:number}} The HSV representation
*/
rgbToHsv:function rgbToHsv(r,g,b,container)
{
r = r / 255;
g = g / 255;
b = b / 255;
var max = Math.max(r,g,b),
min = Math.min(r,g,b),
d = max - min,
s = max === 0 ? 0 : d / max,
h = 0;
if(max !== min)
{
switch(max)
{
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
if (container)
{
container.h = h;
container.s = s;
container.v = max;
return container;
}
return {h:h,s:s,v:max};
},
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and v are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} v The value
* @param {Object|null} container
* @return {{r:number,g:number,b:number}} The RGB representation
*/
hsvToRgb:function hsvToRgb(h,s,v,container)
{
var i = Math.floor(h * 6),
f = h * 6 - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
r = 0,
g = 0,
b = 0;
switch(i % 6)
{
case 0:
r = v, g = t, b = p;
break;
case 1:
r = q, g = v, b = p;
break;
case 2:
r = p, g = v, b = t;
break;
case 3:
r = p, g = q, b = v;
break;
case 4:
r = t, g = p, b = v;
break;
case 5:
r = v, g = p, b = q;
break;
}
if (container)
{
container.r = r * 255;
container.g = g * 255;
container.b = b * 255;
return container;
}
return {r:r*255,g:g*255,b:b*255};
},
/**
* Converts Hue to RGB
* @param {number} p
* @param {number} q
* @param {number} t
* @return {number}
*/
_hueToRgb:function _hueToRgb(p,q,t)
{
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
};
/** @type {{
* _daysInMonth:Array.<number>,
* _monthLabels:Array.<string>,
* _dayLabels:Array.<string>,
* getMonthLabel:Function,
* getDayLabels:Function,
* getMonth:Function,
* getDaysInMonth:Function
* }} */
App.DateUtils = {
_daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],
_monthLabels:["January","February","March","April","May","June","July","August","September","October","November","December"],
_dayLabels:["S","M","T","W","T","F","S"],
/**
* Return month label according to month index passed in
* @param {number} month
* @returns {string}
*/
getMonthLabel:function getMonthLabel(month)
{
return this._monthLabels[month];
},
/**
* Return array of day labels in order from start of week passed in
* @param {number} startOfWeek
* @return {Array.<string>}
*/
getDayLabels:function getDayLabels(startOfWeek)
{
var i = startOfWeek;
while (i)
{
this._dayLabels.push(this._dayLabels.shift());
i--;
}
return this._dayLabels;
},
/**
* Calculate and generate all days in a month, based on starting day of a week passed in
* Returns 2-dimensional array, where rows are weeks, and columns particular days in a week
* @param {Date} date
* @param {number} startOfWeek 0 = Sunday, 1 = Monday, ... , 6 = Saturday
* @return {Array.<Array.<number>>} Days in Week array is twice as long, as the second offsetting number indicate if the day belongs to other month(1) or not(0)
*/
getMonth:function getMonth(date,startOfWeek)
{
//TODO allocate arrays from pool?
var year = date.getFullYear(),
currentMonth = date.getMonth(),
previousMonth = currentMonth ? currentMonth - 1 : 11,
daysInCurrentMonth = this.getDaysInMonth(year,currentMonth),
daysInPreviousMonth = this.getDaysInMonth(year,previousMonth),
firstDayOfMonth = new Date(year,currentMonth,1).getDay(),
dayOffset = firstDayOfMonth >= startOfWeek ? firstDayOfMonth - startOfWeek : 7 + firstDayOfMonth - startOfWeek,
firstDateOfWeek = 7 + 1 - dayOffset,
weeks = [],
days = null,
otherMonth = 0,
l = 6 * 7,// 6 weeks of 7 days
i = 0,
j = 0;
if (firstDateOfWeek !== 1)
{
firstDateOfWeek = daysInPreviousMonth + 1 - dayOffset;
otherMonth = 1;
}
for (;i<l;i++)
{
if (firstDateOfWeek > daysInPreviousMonth && otherMonth === 1)
{
firstDateOfWeek = 1;
otherMonth = 0;
}
if (firstDateOfWeek > daysInCurrentMonth && otherMonth === 0)
{
firstDateOfWeek = 1;
otherMonth = 1;
}
if (i % 7 === 0)
{
days = new Array(7*2);
weeks[weeks.length] = days;
j = 0;
}
days[j++] = firstDateOfWeek++;
days[j++] = otherMonth;
}
return weeks;
},
/**
* Return number of days in particular month passed in
* Also check for Leap year
* @param {number} year
* @param {number} month zero-based
* @return {number}
*/
getDaysInMonth:function getDaysInMonth(year,month)
{
return (month === 1 && (year % 400 === 0 || year % 4 === 0)) ? 29 : this._daysInMonth[month];
},
/**
* Format and return military time
* @param {Date} time
* @returns {string}
*/
getMilitaryTime:function getMilitaryTime(time)
{
var padFunction = App.StringUtils.pad;
return padFunction(time.getHours()) + ":" + padFunction(time.getMinutes());
}
};
/**
* Device
* @type {{TOUCH_SUPPORTED:boolean}}
*/
App.Device = {
TOUCH_SUPPORTED:('ontouchstart' in window) // iOS
|| (window.navigator['msPointerEnabled'] && window.navigator['msMaxTouchPoints'] > 0) // IE10
|| (window.navigator['pointerEnabled'] && window.navigator['maxTouchPoints'] > 0) // IE11+
};
/**
* GraphicUtils
* @type {{drawRect: Function,drawRects:Function}}
*/
App.GraphicUtils = {
/**
* Draw rectangle into graphics passed in
* @param {PIXI.Graphics} graphics
* @param {number} color
* @param {number} alpha
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
*/
drawRect:function drawRect(graphics,color,alpha,x,y,width,height)
{
graphics.clear();
graphics.beginFill(color,alpha);
graphics.drawRect(x,y,width,height);
graphics.endFill();
},
/**
* Draw multiple rectangles
* @param {PIXI.Graphics} graphics
* @param {number} color
* @param {number} alpha
* @param {Array.<number>} data
* @param {boolean} clear
* @param {boolean} end
*/
drawRects:function drawRects(graphics,color,alpha,data,clear,end)
{
if (clear) graphics.clear();
graphics.beginFill(color,alpha);
var i = 0,
l = data.length;
for (;i<l;) graphics.drawRect(data[i++],data[i++],data[i++],data[i++]);
if (end) graphics.endFill();
},
/**
* Draw rounded rectangle into graphics passed in
* @param {PIXI.Graphics} graphics
* @param {number} color
* @param {number} alpha
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {number} radius
*/
drawRoundedRect:function drawRoundedRect(graphics,color,alpha,x,y,width,height,radius)
{
graphics.clear();
graphics.beginFill(color,alpha);
graphics.drawRoundedRect(x,y,width,height,radius);
graphics.endFill();
},
/**
* Draw arc
* @param {PIXI.Graphics} graphics
* @param {PIXI.Point} center
* @param {number} width
* @param {number} height
* @param {number} thickness
* @param {number} startAngle
* @param {number} endAngle
* @param {number} smoothSteps
* @param {number} lineColor
* @param {number} lineAlpha
* @param {number} lineThickness
* @param {number} fillColor
* @param {number} fillAlpha
*/
drawArc:function drawArc(graphics,center,width,height,thickness,startAngle,endAngle,smoothSteps,lineColor,lineAlpha,lineThickness,fillColor,fillAlpha)
{
startAngle -= 90;
endAngle -= 90;
var angle = startAngle,
angleStep = (endAngle - startAngle) / smoothSteps,
degToRad = Math.PI / 180,
radians = angle * degToRad,
radiusX = width / 2,
radiusY = height / 2,
centerX = center.x,
centerY = center.y,
i = 0;
graphics.clear();
graphics.lineStyle(lineThickness,lineColor,lineAlpha);
graphics.beginFill(fillColor,fillAlpha);
graphics.moveTo(centerX+Math.cos(radians)*radiusX,centerY+Math.sin(radians)*radiusY);
for (;i<smoothSteps;)
{
angle = startAngle + angleStep * i++;
radians = angle * degToRad;
graphics.lineTo(centerX+Math.cos(radians)*radiusX,centerY+Math.sin(radians)*radiusY);
}
radians = endAngle * degToRad;
graphics.lineTo(centerX+Math.cos(radians)*radiusX,centerY+Math.sin(radians)*radiusY);
for (i=smoothSteps;i>=0;)
{
angle = startAngle + angleStep * i--;
radians = angle * degToRad;
graphics.lineTo(centerX+Math.cos(radians)*(radiusX-thickness),centerY+Math.sin(radians)*(radiusY-thickness));
}
graphics.endFill();
}
};
/**
* LayoutUtils
* @type {{update: Function}}
*/
App.LayoutUtils = {
/**
* Update layout
* @param {Array.<{x:number,y:number,boundingBox:Rectangle}>} items
* @param {string} direction
* @param {number} originalPosition
*/
update:function update(items,direction,originalPosition)
{
var i = 0,
l = items.length,
item = null,
position = originalPosition || 0,
Direction = App.Direction;
if (direction === Direction.X)
{
for (;i<l;)
{
item = items[i++];
item.x = position;
position = Math.round(position + item.boundingBox.width);
}
}
else if (direction === Direction.Y)
{
for (;i<l;)
{
item = items[i++];
item.y = position;
position = Math.round(position + item.boundingBox.height);
}
}
}
};
/**
* StringUtils
* @type {{encode: Function}}
*/
App.StringUtils = {
_threeCharPattern:/.{1,3}/g,
/**
* Encode URI component
* @param {string} str
* @returns {string}
*/
encode:function encode(str)
{
//return encodeURIComponent(str).replace(/[!'()]/g,escape).replace(/\*/g,"%2A");// 'escape' is depreciated
return encodeURIComponent(str).replace(/[!'()*]/g,function(c) {return '%'+c.charCodeAt(0).toString(16);});
},
/**
* Add leading zero to number passed in
* @param {number} value
*/
pad:function pad(value)
{
if (value < 10) return '0' + value;
return value;
},
/**
* Format number passed in
* @param {number} value
* @param {number} decimal Fixed number of decimal places
* @param {string} separator
*/
formatNumber:function formatNumber(value,decimal,separator)
{
var num = String(value.toFixed(decimal)),
decimals = num.split("."),
integer = decimals[0],
reversed = integer.split("").reverse().join(""),
formatted = reversed.length > 3 ? reversed.match(this._threeCharPattern).join(separator) : reversed;
return formatted.split("").reverse().join("") + "." + decimals[1];
}
};
/**
* Event type
* @enum {string}
* @return {{
* CHANGE_SCREEN:string,
* CHANGE_TRANSACTION:string,
* CHANGE_ACCOUNT:string,
* CHANGE_CATEGORY:string,
* CHANGE_SUB_CATEGORY:string,
* CHANGE_CURRENCY_PAIR:string,
* CREATE:string,
* CANCEL:string,
* CONFIRM:string,
* COPY:string,
* DELETE:string,
* START:string,
* COMPLETE:string,
* UPDATE:string,
* PROGRESS:string,
* ERROR:string,
* CHANGE:string,
* LAYOUT_UPDATE:string,
* TICK:string,
* ADDED:string,
* REMOVED:string,
* RESIZE:string,
* MOUSE_ENTER:string,
* MOUSE_LEAVE:string,
* MOUSE_DOWN:string,
* MOUSE_UP:string,
* MOUSE_MOVE:string,
* CLICK:string,
* FOCUS:string,
* BLUR:string,
* KEY_PRESS:string,
* PASTE:string,
* TEXT_INPUT:string,
* INPUT:string}}
*/
App.EventType = {
// Commands
CHANGE_SCREEN:"CHANGE_SCREEN",
CHANGE_TRANSACTION:"CHANGE_TRANSACTION",
CHANGE_ACCOUNT:"CHANGE_ACCOUNT",
CHANGE_CATEGORY:"CHANGE_CATEGORY",
CHANGE_SUB_CATEGORY:"CHANGE_SUB_CATEGORY",
CHANGE_CURRENCY_PAIR:"CHANGE_CURRENCY_PAIR",
// App
CREATE:"CREATE",
CANCEL:"CANCEL",
CONFIRM:"CONFIRM",
COPY:"COPY",
DELETE:"DELETE",
START:"START",
COMPLETE:"COMPLETE",
UPDATE:"UPDATE",
PROGRESS:"PROGRESS",
ERROR:"ERROR",
CHANGE:"change",
LAYOUT_UPDATE:"LAYOUT_UPDATE",
TICK:"TICK",
// Collection
ADDED:"ADDED",
REMOVED:"REMOVED",
// DOM
RESIZE:"resize",
MOUSE_ENTER:"mouseenter",
MOUSE_LEAVE:"mouseleave",
MOUSE_DOWN:"mousedown",
MOUSE_UP:"mouseup",
MOUSE_MOVE:"mousemove",
CLICK:"click",
FOCUS:"focus",
BLUR:"blur",
KEY_PRESS:"keypress",
PASTE:"paste",
TEXT_INPUT:"textInput",
INPUT:"input"
};
/**
* Model Proxy name
* @enum {number}
* @return {{
* TICKER:number,
* EVENT_LISTENER_POOL:number,
* PAYMENT_METHODS:number,
* CURRENCY_PAIRS:number,
* CURRENCY_SYMBOLS:number,
* SUB_CATEGORIES:number,
* CATEGORIES:number,
* ACCOUNTS:number,
* TRANSACTIONS:number,
* SETTINGS:number,
* ICONS:number,
* CHANGE_SCREEN_DATA_POOL:number,
* SCREEN_HISTORY:number
* }}
*/
App.ModelName = {
TICKER:0,
EVENT_LISTENER_POOL:1,
PAYMENT_METHODS:2,
CURRENCY_PAIRS:3,
CURRENCY_SYMBOLS:4,
SUB_CATEGORIES:5,
CATEGORIES:6,
ACCOUNTS:7,
TRANSACTIONS:8,
SETTINGS:9,
ICONS:10,
CHANGE_SCREEN_DATA_POOL:11,
SCREEN_HISTORY:12
};
/**
* View Segment state
* @enum {number}
* @return {{
* APPLICATION_VIEW:number,
* HEADER:number,
* SCREEN_STACK:number,
* ACCOUNT_BUTTON_POOL:number,
* CATEGORY_BUTTON_EXPAND_POOL:number,
* CATEGORY_BUTTON_EDIT_POOL:number,
* SUB_CATEGORY_BUTTON_POOL:number,
* TRANSACTION_BUTTON_POOL:number,
* SKIN:number}}
*/
App.ViewName = {
APPLICATION_VIEW:0,
HEADER:1,
SCREEN_STACK:2,
ACCOUNT_BUTTON_POOL:3,
CATEGORY_BUTTON_EXPAND_POOL:4,
CATEGORY_BUTTON_EDIT_POOL:5,
SUB_CATEGORY_BUTTON_POOL:6,
TRANSACTION_BUTTON_POOL:7,
SKIN:8
};
/**
* Interactive state
* @enum {string}
* @return {{OVER:string,OUT:string,DRAGGING:string,SCROLLING:string,SNAPPING:string,SWIPING:string}}
*/
App.InteractiveState = {
OVER:"OVER",
OUT:"OUT",
DRAGGING:"DRAGGING",
SCROLLING:"SCROLLING",
SNAPPING:"SNAPPING",
SWIPING:"SWIPING"
};
/**
* Transition state
* @enum {string}
* @return {{SHOWING:string,SHOWN:string,HIDING:string,HIDDEN:string,OPEN:string,OPENING:string,CLOSED:string,CLOSING:string}}
*/
App.TransitionState = {
SHOWING:"SHOWING",
SHOWN:"SHOWN",
HIDING:"HIDING",
HIDDEN:"HIDDEN",
OPEN:"OPEN",
OPENING:"OPENING",
CLOSED:"CLOSED",
CLOSING:"CLOSING"
};
/**
* Scroll Policy
* @enum {string}
* @return {{ON:string,OFF:string,AUTO:string}}
*/
App.ScrollPolicy = {
ON:"ON",
OFF:"OFF",
AUTO:"AUTO"
};
/**
* Direction
* @enum {string}
* @return {{X:string,Y:string,LEFT:string,RIGHT:string}}
*/
App.Direction = {
X:"x",
Y:"y",
LEFT:"LEFT",
RIGHT:"RIGHT"
};
/**
* Screen Name
* @enum {number}
* @return {{
* BACK:number,
* ACCOUNT:number,
* CATEGORY:number,
* SELECT_TIME:number,
* EDIT_CATEGORY:number,
* TRANSACTIONS:number,
* REPORT:number,
* ADD_TRANSACTION:number,
* EDIT:number,
* CURRENCY_PAIRS:number,
* EDIT_CURRENCY_RATE:number,
* CURRENCIES:number,
* SETTINGS:number,
* MENU:number
* }}
*/
App.ScreenName = {
BACK:-1,
ACCOUNT:0,
CATEGORY:1,
SELECT_TIME:2,
EDIT_CATEGORY:3,
TRANSACTIONS:4,
REPORT:5,
ADD_TRANSACTION:6,
EDIT:7,
CURRENCY_PAIRS:8,
EDIT_CURRENCY_RATE:9,
CURRENCIES:10,
SETTINGS:11,
MENU:12
};
/**
* HeaderAction
* @enum {number}
* @return {{NONE:number,MENU:number,CANCEL:number,CONFIRM:number,ADD_TRANSACTION:number}}
*/
App.HeaderAction = {
NONE:-1,
MENU:1,
CANCEL:2,
CONFIRM:3,
ADD_TRANSACTION:4
};
/**
* TransactionType
* @type {{EXPENSE: number, INCOME: number, toString: Function}}
*/
App.TransactionType = {
EXPENSE:1,
INCOME:2,
toString:function toString(type)
{
return type === App.TransactionType.INCOME ? "Income" : "Expense";
}
};
/**
* ScreenMode
* @type {{DEFAULT: number, ADD: number, EDIT: number, SELECT: number}}
*/
App.ScreenMode = {
DEFAULT:1,
ADD:2,
EDIT:3,
SELECT:4
};
/**
* ScreenTitle
* @type {{
* MENU: string,
* ACCOUNTS:string,
* EDIT_ACCOUNT:string,
* ADD_ACCOUNT:string,
* CATEGORIES:string,
* SELECT_ACCOUNT: string,
* SELECT_CATEGORY: string,
* ADD_CATEGORY: string,
* EDIT_CATEGORY: string,
* EDIT_SUB_CATEGORY:string,
* ADD_SUB_CATEGORY:string,
* SELECT_TIME: string,
* TRANSACTIONS:string,
* ADD_TRANSACTION: string,
* EDIT_TRANSACTION: string,
* REPORT:string,
* CURRENCY_RATES:string,
* SELECT_CURRENCY:string,
* EDIT_CURRENCY_RATE:string,
* SETTINGS:string
* }}
*/
App.ScreenTitle = {
MENU:"Menu",
ACCOUNTS:"Accounts",
EDIT_ACCOUNT:"Edit Account",
ADD_ACCOUNT:"Add Account",
SELECT_ACCOUNT:"Select Account",
CATEGORIES:"Categories",
SELECT_CATEGORY:"Select Category",
ADD_CATEGORY:"Add Category",
EDIT_CATEGORY:"Edit Category",
EDIT_SUB_CATEGORY:"Edit SubCategory",
ADD_SUB_CATEGORY:"Add SubCategory",
SELECT_TIME:"Select Time & Date",
TRANSACTIONS:"Transactions",
ADD_TRANSACTION:"Add Transaction",
EDIT_TRANSACTION:"Edit Transaction",
REPORT:"Report",
CURRENCY_RATES:"Currency Rates",
SELECT_CURRENCY:"Select Currency",
EDIT_CURRENCY_RATE:"Edit Currency Rate",
SETTINGS:"Settings"
};
/**
* EventLevel
* @type {{NONE: number, LEVEL_1: number,LEVEL_2: number}}
*/
App.EventLevel = {
NONE:0,
LEVEL_1:1,
LEVEL_2:2
};
/**
* LifeCycle state
* @enum {number}
* @return {{CREATED:number,ACTIVE:number,DELETED:number}}
*/
App.LifeCycleState = {
CREATED:1,
ACTIVE:2,
DELETED:3
};
App.StorageKey = Object.create(null,{
SETTINGS:{value:"settings",writable:false,configurable:false,enumerable:true},
CURRENCY_PAIRS:{value:"currencyPairs",writable:false,configurable:false,enumerable:true},
SUB_CATEGORIES:{value:"subCategories",writable:false,configurable:false,enumerable:true},
CATEGORIES:{value:"categories",writable:false,configurable:false,enumerable:true},
ACCOUNTS:{value:"accounts",writable:false,configurable:false,enumerable:true},
TRANSACTIONS_META:{value:"transactionsMeta",writable:false,configurable:false,enumerable:true},
TRANSACTIONS:{value:"transactions",writable:false,configurable:false,enumerable:true}
});
/**
* Service name enum
* @enum {number}
* @type {{STORAGE: number}}
*/
App.ServiceName = {
STORAGE:1
};
/**
* @class EventListener
* @param {number} index
* @constructor
*/
App.EventListener = function EventListener(index)
{
this.allocated = false;
this.poolIndex = index;
this.type = null;
this.scope = null;
this.handler = null;
};
/**
* @method reset Reset item returning to pool
*/
App.EventListener.prototype.reset = function reset()
{
this.allocated = false;
this.type = null;
this.scope = null;
this.handler = null;
};
/**
* @class EventDispatcher
* @constructor
*/
App.EventDispatcher = function EventDispatcher(listenerPool)
{
this._listeners = [];
this._listenersPool = listenerPool;
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.EventDispatcher.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
if (!this.hasEventListener(eventType,scope,listener))
{
var eventListener = this._listenersPool.allocate();
eventListener.type = eventType;
eventListener.scope = scope;
eventListener.handler = listener;
this._listeners[this._listeners.length] = eventListener;
}
};
/**
* @method hasEventListener
* @param {string} eventType
* @param {Object} scope
* @param {Function} handler
* @return {boolean}
*/
App.EventDispatcher.prototype.hasEventListener = function hasEventListener(eventType,scope,handler)
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;)
{
listener = this._listeners[i++];
if (listener.type === eventType && listener.scope === scope && listener.handler === handler)
{
listener = null;
return true;
}
}
listener = null;
return false;
};
/**
* Remove event listener
* @param {String} eventType
* @param {Object} scope
* @param {Function} handler
*/
App.EventDispatcher.prototype.removeEventListener = function removeEventListener(eventType,scope,handler)
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;i++)
{
listener = this._listeners[i];
if (listener.type === eventType && listener.scope === scope && listener.handler === handler)
{
this._listenersPool.release(listener);
listener.reset();
this._listeners.splice(i,1);
break;
}
}
listener = null;
};
/**
* Remove all listeners
*/
App.EventDispatcher.prototype.removeAllListeners = function removeAllListeners()
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;i++)
{
listener = this._listeners[i];
this._listenersPool.release(listener);
listener.reset();
this._listeners.splice(i,1);
}
listener = null;
this._listeners.length = 0;
};
/**
* Dispatch event
* @param {string} eventType
* @param {Object|null} data
*/
App.EventDispatcher.prototype.dispatchEvent = function dispatchEvent(eventType,data)
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;)
{
listener = this._listeners[i++];
if (listener && listener.type === eventType)
{
listener.handler.call(listener.scope,data,eventType);
}
}
listener = null;
};
/**
* @method pipe Link incoming and outcoming events; dispatch incoming events further
* @param {Object} target
* @param {string} eventType
*/
App.EventDispatcher.prototype.pipe = function pipe(target,eventType)
{
target.addEventListener(eventType,this,this._pipeListener);
};
/**
* @method unpipe Remove event target from pipe
* @param {Object} target
* @param {string} eventType
*/
App.EventDispatcher.prototype.unPipe = function unPipe(target,eventType)
{
target.removeEventListener(eventType,this,this._pipeListener);
};
/**
* @method pipeListener Listens for events piped in, and dispatch them further
* @param {string} eventType
* @param {Object|null} data
* @private
*/
App.EventDispatcher.prototype._pipeListener = function _pipeListener(data,eventType)
{
this.dispatchEvent(eventType,data);
};
/**
* Destroy
*/
App.EventDispatcher.prototype.destroy = function destroy()
{
this.removeAllListeners();
this._listeners.length = 0;
this._listeners = null;
this._listenersPool = null;
};
/**
* @class Rectangle
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @constructor
*/
App.Rectangle = function Rectangle(x,y,width,height)
{
//this.allocated = false;
//this.poolIndex = poolIndex;
this.x = x || 0;
this.y = y || 0;
this.width = width || 0;
this.height = height || 0;
};
/**
* @method reset Reset item returning to pool
*/
/*App.EventListener.prototype.reset = function reset()
{
this.allocated = false;
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
};*/
/**
* @class Stack
* @constructor
*/
App.Stack = function Stack()
{
this._source = [];
this._top = 0;
};
/**
* Push item into stack
* @param {*} item
*/
App.Stack.prototype.push = function push(item)
{
this._source[this._top++] = item;
};
/**
* Remove item from top of the stack
* @returns {*}
*/
App.Stack.prototype.pop = function pop()
{
var item = this._source[this._top-1];
if (item) this._source[--this._top] = null;
return item;
};
/**
* Peek what on top of the stack
* @returns {*}
*/
App.Stack.prototype.peek = function peek(index)
{
if (!index) index = 1;
return this._source[this._top-index];
};
/**
* Return size of the stack
* @returns {number}
*/
App.Stack.prototype.length = function length()
{
return this._top;
};
/**
* Clear stack
*/
App.Stack.prototype.clear = function clear()
{
this._top = 0;
};
/**
* ChangeScreenData
* @param {number} index
* @constructor
*/
App.ChangeScreenData = function ChangeScreenData(index)
{
this.allocated = false;
this.poolIndex = index;
this.screenName = App.ScreenName.ADD_TRANSACTION;
this.screenMode = App.ScreenMode.ADD;
this.updateData = null;
this.headerLeftAction = App.HeaderAction.CANCEL;
this.headerRightAction = App.HeaderAction.CONFIRM;
this.headerName = App.ScreenTitle.ADD_TRANSACTION;
this.backSteps = 1;
this.updateBackScreen = false;
};
/**
* Update
* @param {number} screenName
* @param {number} screenMode
* @param {Object} updateData
* @param {number} headerLeftAction
* @param {number} headerRightAction
* @param {string} headerName
* @param {number} [backSteps=1]
* @param {boolean} [updateBackScreen=false]
* @returns {App.ChangeScreenData}
*/
App.ChangeScreenData.prototype.update = function update(screenName,screenMode,updateData,headerLeftAction,headerRightAction,headerName,backSteps,updateBackScreen)
{
this.screenName = isNaN(screenName) ? App.ScreenName.ADD_TRANSACTION : screenName;
this.screenMode = screenMode || App.ScreenMode.ADD;
this.updateData = updateData;
this.headerLeftAction = headerLeftAction || App.HeaderAction.CANCEL;
this.headerRightAction = headerRightAction || App.HeaderAction.CONFIRM;
this.headerName = headerName || App.ScreenTitle.ADD_TRANSACTION;
this.backSteps = backSteps || 1;
this.updateBackScreen = updateBackScreen;
return this;
};
/**
* @class ModelLocator
* @type {{_proxies:Object,addProxy:Function,hasProxy:Function,getProxy:Function}}
*/
App.ModelLocator = {
_proxies:{},
/**
* Initialize with array of proxies passed in
* @param {Array.<>} proxies
*/
init:function init(proxies)
{
var i = 0,
l = proxies.length;
for (;i<l;) this._proxies[proxies[i++]] = proxies[i++];
},
/**
* @method addPoxy Add proxy to the locator
* @param {string} proxyName
* @param {*} proxy
*/
addProxy:function addProxy(proxyName,proxy)
{
if (this._proxies[proxyName]) throw Error("Proxy "+proxyName+" already exist");
this._proxies[proxyName] = proxy;
},
/**
* @method hasProxy Check if proxy already exist
* @param {string} proxyName
* @return {boolean}
*/
hasProxy:function hasProxy(proxyName)
{
return this._proxies[proxyName];
},
/**
* @method getProxy Returns proxy by name passed in
* @param {string} proxyName
* @return {*}
*/
getProxy:function getProxy(proxyName)
{
return this._proxies[proxyName];
}
};
/**
* @class ObjectPool
* @param {Function} objectClass
* @param {number} size
* @param {Object} constructorData
* @constructor
*/
App.ObjectPool = function ObjectPool(objectClass,size,constructorData)
{
this._objectClass = objectClass;
this._size = size;
this._constructorData = constructorData;
this._items = [];
this._freeItems = [];
};
/**
* Pre-allocate objectClass instances
*/
App.ObjectPool.prototype.preAllocate = function preAllocate()
{
var oldSize = this._items.length,
newSize = oldSize + this._size,
i = oldSize;
this._items.length = newSize;
for (;i < newSize;i++)
{
this._items[i] = new this._objectClass(i,this._constructorData);
this._freeItems.push(i);
}
};
/**
* @method allocate Allocate object instance
* @returns {{poolIndex:number,allocated:boolean}}
*/
App.ObjectPool.prototype.allocate = function allocate()
{
if (this._freeItems.length === 0) this.preAllocate();
var index = this._freeItems.shift();
var item = this._items[index];
item.allocated = true;
return item;
};
/**
* @method release Release item into pool
* @param {{poolIndex:number,allocated:boolean}} item
*/
App.ObjectPool.prototype.release = function release(item)
{
item.allocated = false;
this._freeItems.push(item.poolIndex);
};
/**
* @class Collection
* @param {Array} source
* @param {Function} itemConstructor
* @param {Object} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Collection = function Collection(source,itemConstructor,parent,eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
if (source)
{
var i = 0, l = source.length;
this._items = new Array(l);
for (;i<l;i++) this._items[i] = new itemConstructor(source[i],this,parent,eventListenerPool);
}
if (!this._items) this._items = [];
this._currentItem = null;
this._currentIndex = -1;
};
App.Collection.prototype = Object.create(App.EventDispatcher.prototype);
/**
* @method addItem Add item into collection
* @param {*} item
*/
App.Collection.prototype.addItem = function addItem(item)
{
this._items[this._items.length] = item;
this.dispatchEvent(App.EventType.ADDED,item);
};
/**
* @method setCurrent Set current item of collection
* @param {*} value item to set as current
* @param {?boolean} [force=null] force to execute the method, even if the value is same as current item
*/
App.Collection.prototype.setCurrent = function setCurrent(value,force)
{
if (value === this._currentItem && !force) return;
//var data = {oldItem:this._currentItem};
this._currentItem = value;
this._updateCurrentIndex();
//data.currentItem = this._currentItem;
this.dispatchEvent(App.EventType.CHANGE/*,data*/);
};
/**
* @method getCurrent Returns current item
* @returns {null|*}
*/
App.Collection.prototype.getCurrent = function getCurrent()
{
return this._currentItem;
};
/**
* @method getItemAt Return item at index passed in
* @param {number} index
* @return {*} item
*/
App.Collection.prototype.getItemAt = function getItemAt(index)
{
return this._items[index];
};
/**
* Return copy of underlying array
* @returns {Array}
*/
App.Collection.prototype.copySource = function copySource()
{
return this._items.concat();
};
/**
* Serialize collection data
* @returns {Array}
*/
App.Collection.prototype.serialize = function serialize()
{
var data = [],
i = 0,
l = this._items.length;
for (;i<l;) data.push(this._items[i++].serialize());
return data;
};
/**
* Filter collection against value passed in
* @param {string|Array} value
* @param {string} [property=null]
* @returns {Array}
*/
App.Collection.prototype.filter = function filter(value,property)
{
if (value)
{
var i = 0,
l = this._items.length,
result = [];
if (property)
{
for (;i<l;i++)
{
if (value.indexOf(this._items[i][property]) > -1) result.push(this._items[i]);
}
}
else
{
for (;i<l;i++)
{
if (value.indexOf(this._items[i]) > -1) result.push(this._items[i]);
}
}
return result;
}
return this._items;
};
/**
* Find and return item by key and value passed in
* @param {string} key
* @param {*} value
*/
App.Collection.prototype.find = function find(key,value)
{
var i = 0,
l = this._items.length;
for (;i<l;i++)
{
if (this._items[i][key] === value) return this._items[i];
}
return null;
};
/**
* @method previous Return previous item
* @returns {*}
*/
App.Collection.prototype.previous = function previous()
{
var index = this._currentIndex;
if (index === -1) index = 0;
if (index <= 0) index = this._items.length - 1;
else index -= 1;
return this._items[index];
};
/**
* @method next Return next item
* @returns {*}
*/
App.Collection.prototype.next = function next()
{
var index = this._currentIndex;
if (index === -1 || index >= this._items.length-1) index = 0;
else index += 1;
return this._items[index];
};
/**
* @method other Go to either prev or next item, based on delta passed in
* @param {number} delta
*/
App.Collection.prototype.other = function other(delta)
{
var l = this._items.length;
return this._items[this._currentIndex + l + delta] % l;
};
/**
* @method hasItem Check if the item is already in collection
* @param {*} item
* @return {boolean}
*/
App.Collection.prototype.hasItem = function hasItem(item)
{
return this.indexOf(item) > -1;
};
/**
* @method removeItem Remove item passed in
* @param {*} item
* @return {*} item
*/
App.Collection.prototype.removeItem = function removeItem(item)
{
return this.removeItemAt(this.indexOf(item));
};
/**
* @method removeItemAt Remove item at index passed in
* @return {*} item
*/
App.Collection.prototype.removeItemAt = function removeItemAt(index)
{
var item = this._items.splice(index,1)[0];
this._updateCurrentIndex();
if (this._currentIndex === -1) this._currentItem = null;
this.dispatchEvent(App.EventType.REMOVED,item);
return item;
};
/**
* @method updateCurrentIndex Return currentItem's index
* @private
*/
App.Collection.prototype._updateCurrentIndex = function _updateCurrentIndex()
{
this._currentIndex = this.indexOf(this._currentItem);
};
/**
* @method indexOf Return currentItem's index
* @param {Object} item
* @return {number}
*/
App.Collection.prototype.indexOf = function indexOf(item)
{
var multiplier = 8, i = 0, l = Math.floor(this._items.length / multiplier) * multiplier;
for (;i<l;)
{
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
if (this._items[i++] === item) return i-1;
}
l = this._items.length;
for (;i<l;)
{
if (this._items[i++] === item) return i-1;
}
return -1;
};
/**
* Return current item's index
* @method index
* @returns {number}
*/
App.Collection.prototype.index = function index()
{
return this._currentIndex;
};
/**
* @method length Return length of the collection
* @return {number}
*/
App.Collection.prototype.length = function length()
{
return this._items.length;
};
/**
* @class TransactionCollection
* @param {Object} data
* @param {App.ObjectPool} eventListenerPool
* @constructor
*/
App.TransactionCollection = function TransactionCollection(data,eventListenerPool)
{
var StorageKey = App.StorageKey,
ids = data.ids.sort(function(a,b){return a-b;}),
transactions = [],
i = 0,
l = ids.length;
for (;i<l;) transactions = transactions.concat(data[StorageKey.TRANSACTIONS+ids[i++]]);
App.Collection.call(this,transactions,App.Transaction,null,eventListenerPool);
this._maxSegmentSize = 3;
this._meta = [];
this._initMeta(data[StorageKey.TRANSACTIONS_META],ids);
};
App.TransactionCollection.prototype = Object.create(App.Collection.prototype);
/**
* Initialize meta information object
* @param {Array.<number>} meta
* @param {Array.<number>} ids
* @private
*/
App.TransactionCollection.prototype._initMeta = function _initMeta(meta,ids)
{
var i = 0,
l = meta.length,
item = null;
for (;i<l;i++)
{
item = meta[i];
// Initialize only meta objects with one or more transactions
if (item[1]) this._meta[i] = {metaId:item[0],length:item[1],transactionId:item[2],loaded:ids.indexOf(item[0]) > -1};
}
};
/**
* Serialize and return meta information
* @returns {Array}
*/
App.TransactionCollection.prototype.serializeMeta = function serializeMeta()
{
var i = 0,
l = this._meta.length,
data = [],
meta = null;
for (;i<l;)
{
meta = this._meta[i++];
data.push([meta.metaId,meta.length,meta.transactionId]);
}
return data;
};
/**
* Create and return new transaction ID
* @returns {string}
*/
App.TransactionCollection.prototype.getTransactionId = function getTransactionId()
{
var meta = this._meta[this._meta.length-1];
if (meta)
{
if (meta.length >= this._maxSegmentSize)
{
this._meta[this._meta.length] = {metaId:meta.metaId+1,length:0,transactionId:0,loaded:true};
meta = this._meta[this._meta.length-1];
}
}
else
{
meta = {metaId:0,length:0,transactionId:0,loaded:true};
this._meta[this._meta.length] = meta;
}
return meta.metaId + "." + meta.transactionId++;
};
/**
* Find and return meta object bu id passed in
* @param {number} id
* @returns {{metaId:number,length:number,transactionId:number,loaded:boolean}}
* @private
*/
App.TransactionCollection.prototype._getMetaById = function _getMetaById(id)
{
for (var i= 0,l=this._meta.length;i<l;i++)
{
if (this._meta[i].metaId === id) return this._meta[i];
}
return this._meta[this._meta.length-1];
};
/**
* @method addItem Add item into collection
* @param {*} item
*/
App.TransactionCollection.prototype.addItem = function addItem(item)
{
// Bump up length of meta object
this._getMetaById(parseInt(item.id.split(".")[0],10)).length++;
this._items[this._items.length] = item;
this.dispatchEvent(App.EventType.ADDED,item);
};
/**
* @method removeItem Remove item passed in
* @param {*} item
* @return {*} item
*/
App.TransactionCollection.prototype.removeItem = function removeItem(item)
{
// Decrease length of meta object
var meta = this._getMetaById(parseInt(item.id.split(".")[0],10));
if (meta.length > 0) meta.length--;
return this.removeItemAt(this.indexOf(item));
};
/**
* Serialize and return transaction data for segment specified by ID passed in
* @param {string} metaId
* @param {boolean} serializeData
* @returns {Array}
*/
App.TransactionCollection.prototype.serialize = function serialize(metaId,serializeData)
{
var transaction = null,
data = [],
i = 0,
l = this._items.length;
for (;i<l;)
{
transaction = this._items[i++];
if (metaId === transaction.id.split(".")[0]) data.push(transaction.getData(serializeData));
}
return data;
};
/**
* @class Settings
* @param {Array} data
* @constructor
*/
App.Settings = function Settings(data)
{
this._data = data;
this._startOfWeek = data[0];
this.baseCurrency = data[1] || "USD";
this.defaultCurrencyQuote = data[2] || "USD";
this._defaultAccount = null;
this._defaultCategory = null;
this._defaultSubCategory = null;
this._defaultPaymentMethod = null;
};
/**
* @property startOfWeek
* @type number
*/
Object.defineProperty(App.Settings.prototype,'startOfWeek',{
get:function()
{
return this._startOfWeek;
},
set:function(value)
{
if (value >= 0 && value <= 6) this.startOfWeek = value;
}
});
/**
* @property defaultAccount
* @type App.Account
*/
Object.defineProperty(App.Settings.prototype,'defaultAccount',{
get:function()
{
if (!this._defaultAccount)
{
if (this._data) this._defaultAccount = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).find("id",this._data[3]);
else this._defaultAccount = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).getItemAt(0);
}
return this._defaultAccount;
},
set:function(value)
{
this._defaultAccount = value;
}
});
/**
* @property defaultCategory
* @type App.Category
*/
Object.defineProperty(App.Settings.prototype,'defaultCategory',{
get:function()
{
if (!this._defaultCategory)
{
if (this._data) this._defaultCategory = App.ModelLocator.getProxy(App.ModelName.CATEGORIES).find("id",this._data[4]);
else this._defaultCategory = App.ModelLocator.getProxy(App.ModelName.CATEGORIES).getItemAt(0);
}
return this._defaultCategory;
},
set:function(value)
{
this._defaultCategory = value;
}
});
/**
* @property defaultSubCategory
* @type App.SubCategory
*/
Object.defineProperty(App.Settings.prototype,'defaultSubCategory',{
get:function()
{
if (!this._defaultSubCategory)
{
if (this._data) this._defaultSubCategory = App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).find("id",this._data[5]);
else this._defaultSubCategory = App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).getItemAt(0);
}
return this._defaultSubCategory;
},
set:function(value)
{
this._defaultSubCategory = value;
}
});
/**
* @property defaultPaymentMethod
* @type App.PaymentMethod
*/
Object.defineProperty(App.Settings.prototype,'defaultPaymentMethod',{
get:function()
{
if (!this._defaultPaymentMethod)
{
if (this._data) this._defaultPaymentMethod = App.ModelLocator.getProxy(App.ModelName.PAYMENT_METHODS).find("id",this._data[6]);
else this._defaultPaymentMethod = App.ModelLocator.getProxy(App.ModelName.PAYMENT_METHODS).getItemAt(0);
}
return this._defaultPaymentMethod;
},
set:function(value)
{
this._defaultPaymentMethod = value;
}
});
/**
* @class PaymentMethod
* @param {string} name
* @param {Collection} collection
* @param {*} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.PaymentMethod = function PaymentMethod(name,collection,parent,eventListenerPool)
{
this.id = App.PaymentMethod._ID++;
this.name = name;
};
App.PaymentMethod._ID = 1;
App.PaymentMethod.CASH = "Cash";
App.PaymentMethod.CREDIT_CARD = "Credit-Card";
//TODO add vouchers (or let user add his own method)
/**
* @class CurrencyPair
* @param {Array} data
* @param {Collection} collection
* @param {*} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.CurrencyPair = function CurrencyPair(data,collection,parent,eventListenerPool)
{
this.id = data[0];
this.base = data[1];
this.symbol = data[2];//quote symbol
this.rate = data[3];
};
/**
* Serialize
* @return {Array}
*/
App.CurrencyPair.prototype.serialize = function serialize()
{
return [this.id,this.base,this.symbol,this.rate];
};
/**
* @class CurrencyPairCollection
* @param {Array} source
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.CurrencyPairCollection = function CurrencyPairCollection(source,eventListenerPool)
{
App.Collection.call(this,source,App.CurrencyPair,null,eventListenerPool);
};
App.CurrencyPairCollection.prototype = Object.create(App.Collection.prototype);
/**
* Find and return rate between base and symbol(spent) currency symbols passed in
* In case there is no direct rate, EUR is used as cross since all currency have EUR-pair
* @param {string} base
* @param {string} symbol
* @private
*/
App.CurrencyPairCollection.prototype.findRate = function findRate(base,symbol)
{
var pair = null,
basePair = null,
symbolPair = null,
i = 0,
l = this._items.length;
// First, check if both base and spent currency are in one pair ...
for (;i<l;)
{
pair = this._items[i++];
if ((base === pair.base && symbol === pair.symbol) || (base === pair.symbol && symbol === pair.base))
{
if (base === pair.base && symbol === pair.symbol) return pair.rate;
else if (base === pair.symbol && symbol === pair.base) return 1 / pair.rate;
}
}
// .. if not, use EUR pair as cross
for (i=0;i<l;)
{
pair = this._items[i++];
if (pair.base === "EUR")
{
if (pair.symbol === base) basePair = pair;
if (pair.symbol === symbol) symbolPair = pair;
}
}
if (basePair && symbolPair) return symbolPair.rate / basePair.rate;
return 1.0;
};
/**
* @class CurrencySymbol
* @param {string} symbol
* @constructor
*/
App.CurrencySymbol = function CurrencySymbol(symbol)
{
this.symbol = symbol;
};
/**
* @class Transaction
* @param {Array} [data=null]
* @param {Collection} [collection=null]
* @param {*} [parent=null]
* @param {ObjectPool} [eventListenerPool=null]
* @constructor
*/
App.Transaction = function Transaction(data,collection,parent,eventListenerPool)
{
if (data)
{
this._data = data;
this.id = data[0];
this.amount = data[1];
this.type = data[2];
this.pending = data[3] === 1;
this.repeat = data[4] === 1;
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
this._currencyBase = null;
this._currencyQuote = null;
// this._currencyRate = 1.0;
this.note = data[9] ? decodeURIComponent(data[9]) : "";
}
else
{
this._data = null;
this.id = null;
this.amount = "";
this.type = App.TransactionType.EXPENSE;
this.pending = false;
this.repeat = false;
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
this._currencyBase = null;
this._currencyQuote = null;
// this._currencyRate = 1.0;
this.note = "";
}
};
/**
* Destroy
*/
App.Transaction.prototype.destroy = function destroy()
{
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
};
/**
* Check if the transaction is saved, i.e. has data
* @returns {Array|null}
*/
App.Transaction.prototype.isSaved = function isSaved()
{
return this._data;
};
/**
* Save
*/
App.Transaction.prototype.save = function save()
{
this._data = this.serialize();
};
/**
* Revoke all changes to the last saved ones
*/
App.Transaction.prototype.revokeState = function revokeState()
{
if (this._data)
{
this.id = this._data[0];
this.amount = this._data[1];
this.type = this._data[2];
this.pending = this._data[3] === 1;
this.repeat = this._data[4] === 1;
this._account = null;
this._category = null;
this._subCategory = null;
this._method = null;
this._date = null;
this._currencyBase = null;
this._currencyQuote = null;
// this._currencyRate = 1.0;
this.note = this._data[9] ? decodeURIComponent(this._data[9]) : "";
}
};
/**
* Serialize
* @returns {Array}
*/
App.Transaction.prototype.serialize = function serialize()
{
// If base and quote currency are same, I don't need to save whole 'base/quote@rate' format - it's redundant; save just one quote.
var base = this.currencyBase,
quote = this.currencyQuote,
currency = base === quote ? quote : base + "/" + quote + "@" + App.ModelLocator.getProxy(App.ModelName.CURRENCY_PAIRS).findRate(base,quote),
data = [
this.id,
parseFloat(this.amount),
this.type,
this.pending ? 1 : 0,
this.repeat ? 1 : 0,
this.account.id + "." + this.category.id + "." + this.subCategory.id,
this.method.id,
this.date.getTime(),
currency
];
if (this.note && this.note.length) data.push(App.StringUtils.encode(this.note));
return data;
};
/**
* Return serialized data
* @param {boolean} serialize If set to true, return result of 'serialize' call
* @returns {Array}
*/
App.Transaction.prototype.getData = function getData(serialize)
{
return serialize ? this.serialize() : this._data;
};
/**
* Create and return copy of itself
* @returns {App.Transaction}
*/
App.Transaction.prototype.copy = function copy()
{
var copy = new App.Transaction();
copy.amount = this.amount;
copy.type = this.type;
copy.pending = this.pending;
copy.repeat = this.repeat;
copy.account = this.account;
copy.category = this.category;
copy.subCategory = this.subCategory;
copy.method = this.method;
copy.date = this.date;
copy.currencyBase = this.currencyBase;
copy.currencyQuote = this.currencyQuote;
copy.note = this.note;
return copy;
};
/**
* @property savedAmount
* @type number
*/
Object.defineProperty(App.Transaction.prototype,'savedAmount',{
get:function()
{
if (this._data) return this._data[1];
else return 0.0;
}
});
/**
* @property savedType
* @type number
*/
Object.defineProperty(App.Transaction.prototype,'savedType',{
get:function()
{
if (this._data) return this._data[2];
else return 1;
}
});
/**
* @property savedPending
* @type boolean
*/
Object.defineProperty(App.Transaction.prototype,'savedPending',{
get:function()
{
if (this._data) return this._data[3] === 1;
else return false;
}
});
/**
* @property savedSubCategory
* @type App.SubCategory
*/
Object.defineProperty(App.Transaction.prototype,'savedSubCategory',{
get:function()
{
return App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).find("id",this._data[5].split(".")[2]);
}
});
/**
* @property savedCurrencyBase
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'savedCurrencyBase',{
get:function()
{
if (this._data[8].indexOf("@") === -1) return this._data[8];
else return this._data[8].split("@")[0].split("/")[0];
}
});
/**
* @property savedCurrencyQuote
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'savedCurrencyQuote',{
get:function()
{
if (this._data[8].indexOf("@") === -1) return this._data[8];
else return this._data[8].split("@")[0].split("/")[1];
}
});
/**
* @property savedCurrencyRate
* @type number
*/
Object.defineProperty(App.Transaction.prototype,'savedCurrencyRate',{
get:function()
{
if (this._data[8].indexOf("@") === -1) return null;
else return parseFloat(this._data[8].split("@")[1]);
}
});
/**
* @property account
* @type Account
*/
Object.defineProperty(App.Transaction.prototype,'account',{
get:function()
{
if (!this._account)
{
if (this._data) this._account = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).find("id",this._data[5].split(".")[0]);
else this._account = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultAccount;
}
return this._account;
},
set:function(value)
{
this._account = value;
}
});
/**
* @property category
* @type Category
*/
Object.defineProperty(App.Transaction.prototype,'category',{
get:function()
{
if (!this._category)
{
if (this._data)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
ids = this._data[5].split(".");
this._category = ModelLocator.getProxy(ModelName.CATEGORIES).find("id",ids[1]);
this._subCategory = ModelLocator.getProxy(ModelName.SUB_CATEGORIES).find("id",ids[2]);
}
else
{
this._category = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultCategory;
this._subCategory = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultSubCategory;
}
}
return this._category;
},
set:function(value)
{
this._category = value;
}
});
/**
* @property subCategory
* @type SubCategory
*/
Object.defineProperty(App.Transaction.prototype,'subCategory',{
get:function()
{
if (!this._subCategory)
{
if (this._data) this._subCategory = this.savedSubCategory;
else this._subCategory = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultSubCategory;
}
return this._subCategory;
},
set:function(value)
{
this._subCategory = value;
}
});
/**
* @property method
* @type PaymentMethod
*/
Object.defineProperty(App.Transaction.prototype,'method',{
get:function()
{
if (!this._method)
{
if (this._data) this._method = App.ModelLocator.getProxy(App.ModelName.PAYMENT_METHODS).find("id",this._data[6]);
else this._method = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultPaymentMethod;
}
return this._method;
},
set:function(value)
{
this._method = value;
}
});
/**
* @property date
* @type Date
*/
Object.defineProperty(App.Transaction.prototype,'date',{
get:function()
{
if (!this._date)
{
if (this._data) this._date = new Date(this._data[7]);
else this._date = new Date();
}
return this._date;
},
set:function(value)
{
this._date = value;
}
});
/**
* @property currency
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'currencyBase',{
get:function()
{
if (!this._currencyBase)
{
if (this._data) this._currencyBase = this.savedCurrencyBase;
else this._currencyBase = App.ModelLocator.getProxy(App.ModelName.SETTINGS).baseCurrency;
}
return this._currencyBase;
},
set:function(value)
{
this._currencyBase = value;
}
});
/**
* @property currency
* @type string
*/
Object.defineProperty(App.Transaction.prototype,'currencyQuote',{
get:function()
{
if (!this._currencyQuote)
{
if (this._data) this._currencyQuote = this.savedCurrencyQuote;
else this._currencyQuote = App.ModelLocator.getProxy(App.ModelName.SETTINGS).defaultCurrencyQuote;
}
return this._currencyQuote;
},
set:function(value)
{
this._currencyQuote = value;
}
});
/**
* @class SubCategory
* @param {Array} data
* @param {Collection} collection
* @param {*} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.SubCategory = function SubCategory(data,collection,parent,eventListenerPool)
{
if (data)
{
if (parseInt(data[0],10) >= App.SubCategory._UID) App.SubCategory._UID = parseInt(data[0],10);
this.id = data[0];
this.name = decodeURIComponent(data[1]);
this.balance = isNaN(data[2]) ? 0.0 : parseFloat(data[2]);
}
else
{
this.id = String(++App.SubCategory._UID);
this.name = "SubCategory" + this.id;
this.balance = 0.0;
}
this._state = null;
};
App.SubCategory._UID = 0;
/**
* Serialize
* @return {Array}
*/
App.SubCategory.prototype.serialize = function serialize()
{
if (this.balance) return [this.id,App.StringUtils.encode(this.name),this.balance];
else return [this.id,App.StringUtils.encode(this.name)];
};
/**
* Save current state
*/
App.SubCategory.prototype.saveState = function saveState()
{
if (!this._state) this._state = this.name;
};
/**
* Revoke last state
*/
App.SubCategory.prototype.revokeState = function revokeState()
{
if (this._state) this.name = this._state;
};
/**
* Clear saved state
*/
App.SubCategory.prototype.clearSavedState = function clearSavedState()
{
this._state = null;
};
/**
* @class Category
* @param {Array} data
* @param {Collection} collection
* @param {*} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Category = function Category(data,collection,parent,eventListenerPool)
{
if (data)
{
this._data = data;
if (parseInt(data[0],10) >= App.Category._UID) App.Category._UID = parseInt(data[0],10);
this.id = data[0];
this.name = decodeURIComponent(data[1]);
this.color = data[2];
this.icon = data[3];
this.account = data[4];
this.budget = data[6];
this._subCategories = null;
}
else
{
this._data = null;
this.id = String(++App.Category._UID);
this.name = "Category" + this.id;
this.color = null;
this.icon = null;
this.account = null;
this.budget = null;
this._subCategories = null;
}
this.balance = 0.0;
this._states = null;
};
App.Category._UID = 0;
/**
* Destroy
* Don't erase strings, since they can still be used in TransactionButton
*/
App.Category.prototype.destroy = function destroy()
{
var i = 0,
l = this._subCategories.length;
for (;i<l;) this._subCategories[i++] = null;
this._subCategories.length = 0;
this._subCategories = null;
if (this._states && this._states.length)
{
for (i=0,l=this._states.length;i<l;) this._states[i++] = null;
this._states.length = 0;
this._states = null;
}
this._data = null;
};
/**
* Calculate balance
* @returns {number}
*/
App.Category.prototype.calculateBalance = function calculateBalance()
{
var collection = this.subCategories, // Inflate subCategories
i = 0,
l = this._subCategories.length;
this.balance = 0.0;
for (;i<l;) this.balance += this._subCategories[i++].balance;
return this.balance;
};
/**
* Add subCategory
* @param {App.SubCategory} subCategory
*/
App.Category.prototype.addSubCategory = function addSubCategory(subCategory)
{
if (this._subCategories)
{
var i = 0,
l = this._subCategories.length;
for (;i<l;)
{
if (this._subCategories[i++] === subCategory) return;
}
this._subCategories.push(subCategory);
}
else
{
this._subCategories = [subCategory];
}
};
/**
* Remove subCategory
* @param {App.SubCategory} subCategory
*/
App.Category.prototype.removeSubCategory = function removeSubCategory(subCategory)
{
var i = 0,
l = this._subCategories.length;
for (;i<l;i++)
{
if (this._subCategories[i] === subCategory)
{
this._subCategories.splice(i,1);
break;
}
}
};
/**
* Serialize
* @returns {Array}
*/
App.Category.prototype.serialize = function serialize()
{
var collection = this.subCategories,
data = [this.id,App.StringUtils.encode(this.name),this.color,this.icon,this.account],
subCategoryIds = "",
i = 0,
l = this._subCategories.length;
for (;i<l;) subCategoryIds += this._subCategories[i++].id + ",";
subCategoryIds = subCategoryIds.substring(0,subCategoryIds.length-1);
data.push(subCategoryIds);
if (this.budget) data.push(this.budget);
return data;
};
/**
* Save current state
*/
App.Category.prototype.saveState = function saveState()
{
if (!this._states) this._states = [];
this._states[this._states.length] = this.serialize();
};
/**
* Revoke last state
*/
App.Category.prototype.revokeState = function revokeState()
{
if (this._states && this._states.length)
{
var state = this._states.pop();
this.name = decodeURIComponent(state[1]);
this.color = state[2];
this.icon = state[3];
this.account = state[4];
this.budget = state[6];
this._inflateSubCategories(state[5]);
}
};
/**
* Clear saved states
*/
App.Category.prototype.clearSavedStates = function clearSavedStates()
{
if (this._states) this._states.length = 0;
var i = 0,
l = this._subCategories.length;
for (;i<l;) this._subCategories[i++].clearSavedState();
};
/**
* Populate array of SubCategory object from their respective IDs
* @param {string} ids
* @private
*/
App.Category.prototype._inflateSubCategories = function _inflateSubCategories(ids)
{
this._subCategories = App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).filter(ids.split(","),"id");
};
/**
* @property subCategories
* @type Array.<App.SubCategory>
*/
Object.defineProperty(App.Category.prototype,'subCategories',{
get:function()
{
if (!this._subCategories)
{
if (this._data)
{
this._inflateSubCategories(this._data[5]);
}
else
{
var subCategory = new App.SubCategory();
subCategory.category = this.id;
this._subCategories = [subCategory];
}
}
return this._subCategories;
}
});
/**
* @class Account
* @param {Array} data
* @param {Collection} collection
* @param {Object} parent
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Account = function Account(data,collection,parent,eventListenerPool)
{
if (data)
{
this._data = data;
if (parseInt(data[0],10) >= App.Account._UID) App.Account._UID = parseInt(data[0],10);
this.id = this._data[0];
this.name = decodeURIComponent(this._data[1]);
this.lifeCycleState = parseInt(this._data[2],10) ? App.LifeCycleState.ACTIVE : App.LifeCycleState.DELETED;
this._categories = null;
}
else
{
this._data = null;
this.id = String(++App.Account._UID);
this.name = "Account" + this.id;
this.lifeCycleState = App.LifeCycleState.CREATED;
this._categories = null;
}
this.balance = 0.0;
};
App.Account._UID = 0;
/**
* Serialize
* @return {Array}
*/
App.Account.prototype.serialize = function serialize()
{
var categoryCollection = this.categories,
encodedName = App.StringUtils.encode(this.name),
lifeCycle = this.lifeCycleState === App.LifeCycleState.DELETED ? 0 : 1;
if (categoryCollection.length)
{
var i = 0,
l = categoryCollection.length,
ids = [];
for (;i<l;) ids.push(categoryCollection[i++].id);
return [this.id,encodedName,lifeCycle,ids.join(",")];
}
else
{
return [this.id,encodedName,lifeCycle];
}
};
/**
* Add category
* @param {App.Category} category
* @private
*/
App.Account.prototype.addCategory = function addCategory(category)
{
if (this._categories) this._categories.push(category);
else this._categories = [category];
};
/**
* Remove category
* @param {App.Category} category
* @private
*/
App.Account.prototype.removeCategory = function removeCategory(category)
{
var i = 0,
l = this._categories.length;
for (;i<l;i++)
{
if (this._categories[i] === category)
{
this._categories.splice(i,1);
break;
}
}
};
/**
* Calculate balance
* @returns {number}
*/
App.Account.prototype.calculateBalance = function calculateBalance()
{
var collection = this.categories, // Inflate categories
i = 0,
l = this._categories.length;
this.balance = 0.0;
for (;i<l;) this.balance += this._categories[i++].calculateBalance();
return this.balance;
};
/**
* @property categories
* @type Array.<Category>
*/
Object.defineProperty(App.Account.prototype,'categories',{
get:function()
{
if (!this._categories)
{
if (this._data && this._data[3]) this._categories = App.ModelLocator.getProxy(App.ModelName.CATEGORIES).filter(this._data[3].split(","),"id");
else this._categories = [];
}
return this._categories;
}
});
App.Filter = function Filter(startDate,endDate,categories)
{
this.startDate = startDate;
this.endDate = endDate;
this.categories = categories;
};
/**
* @class ViewLocator
* @type {{_viewSegments:Object,init:Function, addViewSegment: Function, hasViewSegment: Function, getViewSegment: Function}}
*/
App.ViewLocator = {
_viewSegments:{},
/**
* Initialize with array of segments passed in
* @param {Array.<>} segments
*/
init:function init(segments)
{
var i = 0,
l = segments.length;
for (;i<l;) this._viewSegments[segments[i++]] = segments[i++];
},
/**
* Add view segment
* @param {string} segmentName
* @param {*} segment
*/
addViewSegment:function addViewSegment(segmentName,segment)
{
if (this._viewSegments[segmentName]) throw Error("View segment "+segmentName+" already exist");
this._viewSegments[segmentName] = segment;
return segment;
},
/**
* Check if view segment already exist
* @param {string} segmentName
* @return {boolean}
*/
hasViewSegment:function hasViewSegment(segmentName)
{
return this._viewSegments[segmentName];
},
/**
* Return view segment by name passed in
* @param {string} segmentName
* @return {*}
*/
getViewSegment:function getViewSegment(segmentName)
{
return this._viewSegments[segmentName];
}
};
/**
* ColorTheme
* @enum {number}
* @type {{
* WHITE:number,
* BLUE: number,
* BLUE_DARK:number,
* BLUE_LIGHT:number,
* GREY: number,
* GREY_DARK: number,
* GREY_DARKER: number,
* GREY_LIGHT: number,
* RED:number,
* RED_DARK:number,
* RED_LIGHT:number,
* GREEN:number,
* INPUT_HIGHLIGHT:number,
* BLACK:number
* }}
*/
App.ColorTheme = {
WHITE:0xfffffe,
BLUE:0x394264,
BLUE_DARK:0x252B44,
BLUE_LIGHT:0x50597B,
GREY:0xefefef,
GREY_DARK:0xcccccc,
GREY_DARKER:0x999999,
GREY_LIGHT:0xffffff,
RED:0xE53013,
RED_DARK:0x990000,
RED_LIGHT:0xFF3300,
GREEN:0x33CC33,
INPUT_HIGHLIGHT:0x0099ff,
BLACK:0x000000
};
/**
* @class FontStyle
* @type {{init: Function, get: Function, WHITE: string, BLUE: string, BLUE_LIGHT: string, BLUE_DARK: string, GREY: string, GREY_DARK: string, GREY_DARKER: string,BLACK_LIGHT:string, RED_DARK: string}}
*/
App.FontStyle = {
/**
* @private
*/
_pixelRatio:1,
_styles:[],
/**
* Init
* @param {number} pixelRatio
*/
init:function init(pixelRatio)
{
this._pixelRatio = pixelRatio;
return this;
},
/**
* Construct and return font style object
* @param {number} fontSize
* @param {string} color
* @param {string} [align=null]
* @param {string} [font=null]
* @returns {{font: string, fill: string}}
*/
get:function get(fontSize,color,align,font)
{
var i = 0,
l = this._styles.length,
style = null;
font = font || this.CONDENSED;
for (;i<l;)
{
style = this._styles[i++];
if (style.fontSize === fontSize && style.fill === color && style.fontName === font)
{
if (align)
{
if (style.align === align)
{
return style;
}
}
else
{
return style;
}
}
}
style = {fontSize:fontSize,font:Math.round(fontSize * this._pixelRatio)+"px "+font,fill:color,align:align ? align : "left",fontName:font};
this._styles.push(style);
return style;
},
CONDENSED:"HelveticaNeueCond",
LIGHT_CONDENSED:"HelveticaNeueLightCond",
WHITE:"#ffffff",
BLUE:"#394264",
BLUE_LIGHT:"#50597B",
BLUE_DARK:"#252B44",
GREY:"#efefef",
GREY_DARK:"#cccccc",
GREY_DARKER:"#999999",
BLACK_LIGHT:"#333333",
RED_DARK:"#990000"
};
/**
* @class Skin
* @param {number} width
* @param {number} pixelRatio
* @constructor
*/
App.Skin = function Skin(width,pixelRatio)
{
var ColorTheme = App.ColorTheme,
defaultScaleMode = PIXI.scaleModes.DEFAULT,
padding = Math.round(10 * pixelRatio),
graphics = new PIXI.Graphics(),
w = width - padding * 2,
h = Math.round(40 * pixelRatio),
draw = App.GraphicUtils.drawRects,
color = ColorTheme.GREY,
lightColor = ColorTheme.GREY_LIGHT,
darkColor = ColorTheme.GREY_DARK;
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_40 = graphics.generateTexture(1,defaultScaleMode);
draw(graphics,ColorTheme.WHITE,1,[0,0,width,h],true,false);
draw(graphics,color,1,[padding,h-1,w,1],false,true);
this.WHITE_40 = graphics.generateTexture(1,defaultScaleMode);
h = Math.round(50 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_50 = graphics.generateTexture(1,defaultScaleMode);
h = Math.round(60 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_60 = graphics.generateTexture(1,defaultScaleMode);
h = Math.round(70 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_70 = graphics.generateTexture(1,defaultScaleMode);
draw(graphics,ColorTheme.RED,1,[0,0,width,h],true,false);
draw(graphics,ColorTheme.RED_LIGHT,1,[padding,0,w,1],false,false);
draw(graphics,ColorTheme.RED_DARK,1,[padding,h-1,w,1],false,true);
this.RED_70 = graphics.generateTexture(1,defaultScaleMode);
w = Math.round(40 * pixelRatio);
h = w;
/*graphics.clear();
graphics.beginFill(ColorTheme.BLUE_DARK,1.0);
graphics.drawRect(0,0,w,h);
graphics.beginFill(ColorTheme.BLUE_LIGHT,1.0);
graphics.drawRect(0,h/2,w/2,h/2);
graphics.beginFill(ColorTheme.BLUE,1.0);
graphics.drawShape(new PIXI.Polygon([0,0,w,0,w,h,0,0]));
graphics.endFill();
this.BLUE_PATTERN = graphics.generateTexture(1,defaultScaleMode);*/
graphics.clear();
graphics.beginFill(ColorTheme.GREY_DARK,1.0);
graphics.drawRect(0,0,w,h);
graphics.beginFill(ColorTheme.GREY,1.0);
graphics.drawRect(0,h/2,w/2,h/2);
graphics.beginFill(0xdedede,1.0);
graphics.drawShape(new PIXI.Polygon([0,0,w,0,w,h,0,0]));
graphics.endFill();
this.GREY_PATTERN = graphics.generateTexture(1,defaultScaleMode);
w = width - padding * 4;
h = Math.round(40 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.NARROW_GREY_40 = graphics.generateTexture(1,defaultScaleMode);
draw(graphics,ColorTheme.WHITE,1,[0,0,width,h],true,false);
draw(graphics,color,1,[padding,h-1,w,1],false,true);
this.NARROW_WHITE_40 = graphics.generateTexture(1,defaultScaleMode);
};
/**
* @class HeaderSegment
* @extends DisplayObjectContainer
* @param {number} value
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.HeaderSegment = function HeaderSegment(value,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
this._action = value;
this._width = width;
this._height = height;
this._pixelRatio = pixelRatio;
this._frontElement = null;
this._backElement = null;
this._middlePosition = Math.round(15 * pixelRatio);
this._needsUpdate = true;
this._mask = new PIXI.Graphics();
this.mask = this._mask;
this.addChild(this._mask);
};
App.HeaderSegment.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.HeaderSegment.prototype._render = function _render()
{
var padding = Math.round(10 * this._pixelRatio);
App.GraphicUtils.drawRect(this._mask,0xff0000,0.5,0,0,this._width,this._height-padding*2);
this._mask.y = padding;
};
/**
* Change
* @param {number} action
*/
App.HeaderSegment.prototype.change = function change(action)
{
if (this._action === action)
{
this._needsUpdate = false;
}
else
{
var tempIcon = this._frontElement;
this._frontElement = this._backElement;
this._backElement = tempIcon;
this._needsUpdate = true;
}
this._action = action;
};
/**
* Update
* @param {number} progress
*/
App.HeaderSegment.prototype.update = function update(progress)
{
if (this._needsUpdate)
{
this._frontElement.y = Math.round((this._middlePosition + this._frontElement.height) * progress - this._frontElement.height);
this._backElement.y = Math.round(this._middlePosition + (this._height - this._middlePosition) * progress);
}
};
/**
* Return action
* @returns {number}
*/
App.HeaderSegment.prototype.getAction = function getAction()
{
return this._action;
};
/**
* @class HeaderIcon
* @extends HeaderSegment
* @param {number} value
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.HeaderIcon = function HeaderIcon(value,width,height,pixelRatio)
{
App.HeaderSegment.call(this,value,width,height,pixelRatio);
this._frontElement = PIXI.Sprite.fromFrame(this._getIconByAction(value));
this._backElement = PIXI.Sprite.fromFrame(this._getIconByAction(value));
this._iconResizeRatio = Math.round(20 * pixelRatio) / this._frontElement.height;
this._render();
this.addChild(this._frontElement);
this.addChild(this._backElement);
};
App.HeaderIcon.prototype = Object.create(App.HeaderSegment.prototype);
/**
* Render
* @private
*/
App.HeaderIcon.prototype._render = function _render()
{
App.HeaderSegment.prototype._render.call(this);
var ColorTheme = App.ColorTheme;
this._frontElement.scale.x = this._iconResizeRatio;
this._frontElement.scale.y = this._iconResizeRatio;
this._frontElement.x = this._middlePosition;
this._frontElement.y = this._height;
this._frontElement.tint = ColorTheme.WHITE;
this._frontElement.alpha = 0.0;
this._backElement.scale.x = this._iconResizeRatio;
this._backElement.scale.y = this._iconResizeRatio;
this._backElement.x = this._middlePosition;
this._backElement.y = this._height;
this._backElement.tint = ColorTheme.WHITE;
this._backElement.alpha = 0.0;
};
/**
* Return icon name by action passed in
* @param {number} action
* @returns {string}
* @private
*/
App.HeaderIcon.prototype._getIconByAction = function _getIconByAction(action)
{
var HeaderAction = App.HeaderAction,
iconName = null;
if (action === HeaderAction.MENU) iconName = "menu-app";
else if (action === HeaderAction.CANCEL) iconName = "close-app";
else if (action === HeaderAction.CONFIRM) iconName = "apply-app";
else if (action === HeaderAction.ADD_TRANSACTION) iconName = "plus-app";
return iconName;
};
/**
* Change
* @param {number} action
*/
App.HeaderIcon.prototype.change = function change(action)
{
App.HeaderSegment.prototype.change.call(this,action);
var iconName = this._getIconByAction(action);
if (iconName === null)
{
this._frontElement.alpha = 0.0;
}
else
{
this._frontElement.setTexture(PIXI.TextureCache[iconName]);
this._frontElement.alpha = 1.0;
}
};
/**
* @class HeaderTitle
* @extends HeaderSegment
* @param {string} value
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {{font:string,fill:string}} fontStyle
* @constructor
*/
App.HeaderTitle = function HeaderTitle(value,width,height,pixelRatio,fontStyle)
{
App.HeaderSegment.call(this,value,width,height,pixelRatio);
this._frontElement = new PIXI.Text(value,fontStyle);
this._backElement = new PIXI.Text(value,fontStyle);
this._render();
this.addChild(this._frontElement);
this.addChild(this._backElement);
};
App.HeaderTitle.prototype = Object.create(App.HeaderSegment.prototype);
/**
* Render
* @private
*/
App.HeaderTitle.prototype._render = function _render()
{
App.HeaderSegment.prototype._render.call(this);
this._middlePosition = Math.round(18 * this._pixelRatio);
this._frontElement.x = Math.round((this._width - this._frontElement.width) / 2);
this._frontElement.y = this._height;
this._frontElement.alpha = 0.0;
this._backElement.x = Math.round((this._width - this._backElement.width) / 2);
this._backElement.y = this._height;
this._backElement.alpha = 0.0;
};
/**
* Change
* @param {string} name
*/
App.HeaderTitle.prototype.change = function change(name)
{
App.HeaderSegment.prototype.change.call(this,name);
this._frontElement.setText(name);
this._frontElement.x = Math.round((this._width - this._frontElement.width) / 2);
this._frontElement.alpha = 1.0;
};
/**
* @class Header
* @extends Graphics
* @param {Object} layout
* @constructor
*/
App.Header = function Header(layout)
{
PIXI.Graphics.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
HeaderIcon = App.HeaderIcon,
HeaderAction = App.HeaderAction,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
listenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
this._layout = layout;
this._iconSize = Math.round(50 * r);
this._leftIcon = new HeaderIcon(HeaderAction.ADD_TRANSACTION,this._iconSize,this._iconSize,r);
this._rightIcon = new HeaderIcon(HeaderAction.MENU,this._iconSize,this._iconSize,r);
this._title = new App.HeaderTitle("Cashius",this._layout.width-this._iconSize*2,this._iconSize,r,FontStyle.get(20,FontStyle.WHITE));
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._tween = new App.TweenProxy(0.7,App.Easing.outExpo,0,listenerPool);
this._eventDispatcher = new App.EventDispatcher(listenerPool);
this._actionEnabled = true;
this._render();
this.addChild(this._leftIcon);
this.addChild(this._title);
this.addChild(this._rightIcon);
this._registerEventListeners();
};
App.Header.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Header.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._layout.pixelRatio,
w = this._layout.width,
h = this._layout.headerHeight,
offset = h - this._iconSize,
padding = Math.round(10 * r);
this._title.x = this._iconSize;
this._rightIcon.x = w - this._iconSize;
GraphicUtils.drawRects(this,ColorTheme.BLUE,1,[0,0,w,h],true,false);
GraphicUtils.drawRects(this,ColorTheme.BLUE_LIGHT,1,[
this._iconSize+1,offset+padding,1,this._iconSize-padding*2,
w-this._iconSize,offset+padding,1,this._iconSize-padding*2
],false,false);
GraphicUtils.drawRects(this,ColorTheme.BLUE_DARK,1,[
0,h-1,w,1,
this._iconSize,offset+padding,1,this._iconSize-padding*2,
w-this._iconSize-1,offset+padding,1,this._iconSize-padding*2
],false,true);
};
/**
* Register event listeners
* @private
*/
App.Header.prototype._registerEventListeners = function _registerEventListeners()
{
var EventType = App.EventType;
App.ViewLocator.getViewSegment(App.ViewName.SCREEN_STACK).addEventListener(EventType.CHANGE,this,this._onScreenChange);
if (App.Device.TOUCH_SUPPORTED) this.tap = this._onClick;
else this.click = this._onClick;
this._tween.addEventListener(EventType.COMPLETE,this,this._onTweenComplete);
this.interactive = true;
};
/**
* Enable actions
*/
App.Header.prototype.enableActions = function enableActions()
{
this._actionEnabled = true;
};
/**
* Disable actions
*/
App.Header.prototype.disableActions = function disableActions()
{
this._actionEnabled = false;
};
/**
* On screen change
* @private
*/
App.Header.prototype._onScreenChange = function _onScreenChange()
{
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._tween.restart();
};
/**
* Change
* @param {number} leftAction
* @param {number} rightAction
* @param {string} name
* @private
*/
App.Header.prototype.change = function change(leftAction,rightAction,name)
{
this._leftIcon.change(leftAction);
this._title.change(name);
this._rightIcon.change(rightAction);
};
/**
* On RAF Tick
* @private
*/
App.Header.prototype._onTick = function _onTick()
{
this._onTweenUpdate();
};
/**
* On tween update
* @private
*/
App.Header.prototype._onTweenUpdate = function _onTweenUpdate()
{
var progress = this._tween.progress;
//TODO offset each segment for effect
this._leftIcon.update(progress);
this._title.update(progress);
this._rightIcon.update(progress);
};
/**
* On tween complete
* @private
*/
App.Header.prototype._onTweenComplete = function _onTweenComplete()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._onTweenUpdate();
};
/**
* On click
* @param {InteractionData} data
* @private
*/
App.Header.prototype._onClick = function _onClick(data)
{
if (this._actionEnabled)
{
var position = data.getLocalPosition(this).x,
HeaderAction = App.HeaderAction,
action = HeaderAction.NONE;
if (position <= this._iconSize) action = this._leftIcon.getAction();
else if (position >= this._layout.width - this._iconSize) action = this._rightIcon.getAction();
if (action !== HeaderAction.NONE) this._eventDispatcher.dispatchEvent(App.EventType.CLICK,action);
}
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Header.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Header.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* @class ScrollIndicator
* @extends Graphics
* @param {string} direction
* @param {number} pixelRatio
* @constructor
*/
App.ScrollIndicator = function ScrollIndicator(direction,pixelRatio)
{
PIXI.Graphics.call(this);
this.visible = false;
this.boundingBox = new PIXI.Rectangle(0,0,0,0);
this._direction = direction;
this._pixelRatio = pixelRatio;
this._minIndicatorSize = Math.round(50 * pixelRatio);
this._padding = Math.round(4 * pixelRatio);
this._size = 0;
this._indicatorSize = 0;
this._indicatorThickness = 0;
this._contentPosition = 0;
this._positionStep = 0;
this._showHideTween = new App.TweenProxy(0.2,App.Easing.linear,0,App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
this._state = App.TransitionState.HIDDEN;
};
App.ScrollIndicator.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Show
*/
App.ScrollIndicator.prototype.show = function show()
{
var TransitionState = App.TransitionState;
if (this._state === TransitionState.HIDING || this._state === TransitionState.HIDDEN)
{
this._state = TransitionState.SHOWING;
this.visible = true;
this._showHideTween.start(true);
}
};
/**
* Hide
*
* @param {boolean} [immediate=false]
*/
App.ScrollIndicator.prototype.hide = function hide(immediate)
{
var TransitionState = App.TransitionState;
if (immediate)
{
this._state = TransitionState.HIDDEN;
this.alpha = 0.0;
this.visible = false;
}
else
{
if (this._state === TransitionState.SHOWING || this._state === TransitionState.SHOWN)
{
this._state = TransitionState.HIDING;
this._showHideTween.start(true);
}
}
};
/**
* Update indicator according to position passed in
* @param {number} contentPosition
*/
App.ScrollIndicator.prototype.update = function update(contentPosition)
{
this._contentPosition = contentPosition;
var TransitionState = App.TransitionState;
if (this._state === TransitionState.SHOWING || this._state === TransitionState.HIDING)
{
this._updateVisibility(TransitionState);
}
this._render();
};
/**
* Update visibility
* @param {App.TransitionState} TransitionState
* @private
*/
App.ScrollIndicator.prototype._updateVisibility = function _updateVisibility(TransitionState)
{
var progress = this._showHideTween.progress;
if (this._state === TransitionState.SHOWING)
{
this.alpha = progress;
if (progress === 1.0) this._state = TransitionState.SHOWN;
}
else if (this._state === TransitionState.HIDING)
{
this.alpha = 1.0 - progress;
if (progress === 1.0)
{
this._state = TransitionState.HIDDEN;
this.visible = false;
}
}
};
/**
* Resize
* @param {number} size
* @param {number} contentSize
*/
App.ScrollIndicator.prototype.resize = function resize(size,contentSize)
{
this._size = size;
if (this._direction === App.Direction.X)
{
this.boundingBox.width = this._size;
this.boundingBox.height = Math.round(7 * this._pixelRatio);
this._indicatorThickness = this.boundingBox.height - this._padding;
this._indicatorSize = Math.round(this._size * (this._size / contentSize));
if (this._indicatorSize < this._minIndicatorSize) this._indicatorSize = this._minIndicatorSize;
this._positionStep = (this._size - this._indicatorSize) / (contentSize - this._size);
}
else if (this._direction === App.Direction.Y)
{
this.boundingBox.width = Math.round(7 * this._pixelRatio);
this.boundingBox.height = this._size;
this._indicatorThickness = this.boundingBox.width - this._padding;
this._indicatorSize = Math.round(this._size * (this._size / contentSize));
if (this._indicatorSize < this._minIndicatorSize) this._indicatorSize = this._minIndicatorSize;
this._positionStep = (this._size - this._indicatorSize) / (contentSize - this._size);
}
this._render();
};
/**
* Render indicator
* @private
*/
App.ScrollIndicator.prototype._render = function _render()
{
var indicatorSize = this._indicatorSize,
position = -Math.round(this._contentPosition * this._positionStep);
if (position + indicatorSize > this._size)
{
indicatorSize = this._size - position;
}
else if (position < 0)
{
indicatorSize = indicatorSize + position;
position = 0;
}
this.clear();
this.beginFill(0x000000,0.3);
if (this._direction === App.Direction.X)
{
this.drawRoundedRect(
position + this._padding,
Math.round(this._padding * 0.5),
indicatorSize - this._padding * 2,
this._indicatorThickness,
this._indicatorThickness * 0.5
);
}
else if (this._direction === App.Direction.Y)
{
this.drawRoundedRect(
Math.round(this._padding * 0.5),
position + this._padding,
this._indicatorThickness,
indicatorSize - this._padding * 2,
this._indicatorThickness * 0.5
);
}
this.endFill();
};
/**
* Destroy
*/
App.ScrollIndicator.prototype.destroy = function destroy()
{
//TODO also destroy PIXI's Graphics object!
this._showHideTween.destroy();
this._showHideTween = null;
this.boundingBox = null;
this._direction = null;
this._state = null;
this.clear();
};
/**
* @class Input
* @extends Graphics
* @param {string} placeholder
* @param {number} fontSize
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {boolean} displayIcon
* @constructor
*/
App.Input = function Input(placeholder,fontSize,width,height,pixelRatio,displayIcon)
{
PIXI.Graphics.call(this);
var FontStyle = App.FontStyle;
this.boundingBox = new App.Rectangle(0,0,width,height);
this._fontSize = fontSize;
this._width = width;
this._height = height;
this._pixelRatio = pixelRatio;
this._enabled = false;
this._focused = false;
this._eventDispatcher = new App.EventDispatcher(App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
this._placeholder = placeholder;
this._placeholderStyle = FontStyle.get(fontSize,FontStyle.GREY);
this._currentStyle = this._placeholderStyle;
this._textStyle = FontStyle.get(fontSize,FontStyle.BLUE);
this._restrictPattern = null;
this._text = "";
this._textField = new PIXI.Text(this._placeholder,this._currentStyle);
this._inputProxy = document.getElementById("textInputProxy");
this._inputProxyListeners = {
focus:this._onFocus.bind(this),
blur:this._onBlur.bind(this),
change:this._onChange.bind(this)
};
if (displayIcon) this._icon = PIXI.Sprite.fromFrame("clear-app");
this._iconHitThreshold = Math.round(this._width - 40 * this._pixelRatio);
this._render();
this.addChild(this._textField);
if (this._icon) this.addChild(this._icon);
};
App.Input.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Input.prototype._render = function _render()
{
var r = this._pixelRatio;
this._renderBackground(false,r);
this._textField.x = Math.round(10 * r);
this._textField.y = Math.round((this._height - this._textField.height) / 2 + r);
if (this._icon)
{
this._icon.width = Math.round(20 * r);
this._icon.height = Math.round(20 * r);
this._icon.x = Math.round(this._width - this._icon.width - 10 * r);
this._icon.y = Math.round((this._height - this._icon.height) / 2);
this._icon.tint = 0xdddddd;
}
};
/**
* Highlight focused input
* @param {boolean} highlight
* @param {number} r pixelRatio
* @private
*/
App.Input.prototype._renderBackground = function _renderBackground(highlight,r)
{
var ColorTheme = App.ColorTheme;
this.clear();
this.beginFill(highlight ? ColorTheme.INPUT_HIGHLIGHT : ColorTheme.GREY_DARK);
this.drawRoundedRect(0,0,this._width,this._height,Math.round(5 * r));
this.beginFill(0xffffff);
this.drawRoundedRect(Math.round(r),Math.round(r),this._width-Math.round(2 * r),this._height-Math.round(2 * r),Math.round(4 * r));
this.endFill();
};
/**
* Enable
*/
App.Input.prototype.enable = function enable()
{
if (!this._enabled)
{
this._enabled = true;
this._registerEventListeners();
this.interactive = true;
}
};
/**
* Disable
*/
App.Input.prototype.disable = function disable()
{
this._unRegisterEventListeners();
this._unRegisterProxyEventListeners();
this.interactive = false;
this._enabled = false;
};
/**
* Set restriction pattern
* @param {RegExp} pattern
*/
App.Input.prototype.restrict = function restrict(pattern)
{
this._restrictPattern = pattern;
};
/**
* Is input focused?
* @returns {boolean}
*/
App.Input.prototype.isFocused = function isFocused()
{
return this._focused;
};
/**
* Focus
*/
App.Input.prototype.focus = function focus()
{
if (!this._focused)
{
this._renderBackground(true,this._pixelRatio);
this._registerProxyEventListeners();
this._inputProxy.focus();// requires Cordova preference: <preference name="KeyboardDisplayRequiresUserAction" value="false"/>
this._focused = true;
}
};
/**
* Remove focus
*/
App.Input.prototype.blur = function blur()
{
this._inputProxy.blur();
this._unRegisterProxyEventListeners();
this._focused = false;
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Input.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Input.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* Register event listeners
* @private
*/
App.Input.prototype._registerEventListeners = function _registerEventListeners()
{
if (App.Device.TOUCH_SUPPORTED) this.tap = this._onClick;
else this.click = this._onClick;
};
/**
* UnRegister event listeners
* @private
*/
App.Input.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
if (App.Device.TOUCH_SUPPORTED) this.tap = null;
else this.click = null;
};
/**
* Register input proxy event listeners
* @private
*/
App.Input.prototype._registerProxyEventListeners = function _registerProxyEventListeners()
{
var EventType = App.EventType;
this._inputProxy.addEventListener(EventType.FOCUS,this._inputProxyListeners.focus,false);
this._inputProxy.addEventListener(EventType.BLUR,this._inputProxyListeners.blur,false);
this._inputProxy.addEventListener(EventType.CHANGE,this._inputProxyListeners.change,false);
this._inputProxy.addEventListener(EventType.KEY_PRESS,this._inputProxyListeners.change,false);
this._inputProxy.addEventListener(EventType.PASTE,this._inputProxyListeners.change,false);
this._inputProxy.addEventListener(EventType.TEXT_INPUT,this._inputProxyListeners.change,false);
this._inputProxy.addEventListener(EventType.INPUT,this._inputProxyListeners.change,false);
};
/**
* Register input proxy event listeners
* @private
*/
App.Input.prototype._unRegisterProxyEventListeners = function _unRegisterProxyEventListeners()
{
var EventType = App.EventType;
this._inputProxy.removeEventListener(EventType.FOCUS,this._inputProxyListeners.focus,false);
this._inputProxy.removeEventListener(EventType.BLUR,this._inputProxyListeners.blur,false);
this._inputProxy.removeEventListener(EventType.CHANGE,this._inputProxyListeners.change,false);
this._inputProxy.removeEventListener(EventType.KEY_PRESS,this._inputProxyListeners.change,false);
this._inputProxy.removeEventListener(EventType.PASTE,this._inputProxyListeners.change,false);
this._inputProxy.removeEventListener(EventType.TEXT_INPUT,this._inputProxyListeners.change,false);
this._inputProxy.removeEventListener(EventType.INPUT,this._inputProxyListeners.change,false);
};
/**
* On click
* @param {InteractionData} data
* @private
*/
App.Input.prototype._onClick = function _onClick(data)
{
if (this._inputProxy !== document.activeElement) this.focus();
if (this._icon)
{
// If user click/tap at 'close' icon, erase actual text
if (data.getLocalPosition(this).x >= this._iconHitThreshold)
{
this._inputProxy.value = "";
this._onChange();
}
}
};
/**
* On input proxy focus
* @private
*/
App.Input.prototype._onFocus = function _onFocus()
{
var r = this._pixelRatio,
localPoint = this.toLocal(new PIXI.Point(this.x,this.y),this.stage);
this._focused = true;
this._inputProxy.style.display = "none";
this._inputProxy.style.left = Math.round((this.x - localPoint.x) / r) +"px";
this._inputProxy.style.top = Math.round((this.y - localPoint.y) / r) + "px";
this._inputProxy.style.width = this._icon ? Math.round(this._iconHitThreshold / r) + "px" : Math.round(this._width / r) + "px";
this._inputProxy.style.height = Math.round(this._height / r) + "px";
this._inputProxy.style.fontSize = this._fontSize + "px";
this._inputProxy.style.lineHeight = this._fontSize + "px";
this._inputProxy.value = this._text;
this._inputProxy.style.display = "block";
this._eventDispatcher.dispatchEvent(App.EventType.FOCUS);
};
/**
* On input proxy blur
* @private
*/
App.Input.prototype._onBlur = function _onBlur()
{
this._focused = false;
this._updateText(true);
this._inputProxy.style.top = "-1000px";
this._inputProxy.value = "";
this._renderBackground(false,this._pixelRatio);
this._unRegisterProxyEventListeners();
this._eventDispatcher.dispatchEvent(App.EventType.BLUR);
};
/**
* Input change handler
* @param {Event} [e=null]
* @private
*/
App.Input.prototype._onChange = function _onChange(e)
{
this._updateText(false);
// If RETURN is hit, remove focus
if (e && e.keyCode === 13) this._inputProxy.blur();
};
/**
* Update text
* @param {boolean} [finish=false]
* @private
*/
App.Input.prototype._updateText = function _updateText(finish)
{
//TODO limit text length to the input's width (minus 'clear' button width)
this._text = this._format(finish);
if (this._text === this._placeholder || this._text.length === 0)
{
if (this._currentStyle === this._textStyle)
{
this._currentStyle = this._placeholderStyle;
this._textField.setStyle(this._currentStyle);
}
this._textField.setText(this._placeholder);
}
else
{
if (this._currentStyle === this._placeholderStyle)
{
this._currentStyle = this._textStyle;
this._textField.setStyle(this._currentStyle);
}
this._textField.setText(this._text);
}
};
/**
* Format the text input
* @param {boolean} [finish=false]
* @private
*/
App.Input.prototype._format = function _format(finish)
{
if (this._restrictPattern)
{
var result = this._inputProxy.value.match(this._restrictPattern);
if (result && result.length > 0) this._inputProxy.value = result[0];
else this._inputProxy.value = "";
}
return this._inputProxy.value;
};
/**
* Set value
* @param {string} value
*/
App.Input.prototype.setValue = function setValue(value)
{
this._inputProxy.value = value;
this._updateText(false);
};
/**
* Set value
* @returns {string}
*/
App.Input.prototype.getValue = function getValue()
{
return this._text;
};
/**
* Set value
* @param {string} value
*/
App.Input.prototype.setPlaceholder = function setPlaceholder(value)
{
//TODO is this used?
this._placeholder = value;
this._updateText(false);
};
/**
* Test if position passed in falls within this input boundaries
* @param {number} position
* @returns {boolean}
*/
App.Input.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* @class TimeInput
* @extends Input
* @param {string} placeholder
* @param {number} fontSize
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {boolean} displayIcon
* @constructor
*/
App.TimeInput = function TimeInput(placeholder,fontSize,width,height,pixelRatio,displayIcon)
{
App.Input.call(this,placeholder,fontSize,width,height,pixelRatio,displayIcon);
this._inputProxy = document.getElementById("timeInputProxy");
};
App.TimeInput.prototype = Object.create(App.Input.prototype);
/**
* Render
* @private
*/
App.TimeInput.prototype._render = function _render()
{
var r = this._pixelRatio;
this._renderBackground(false,r);
this._updateAlignment();
this._textField.y = Math.round(9 * r);
};
/**
* Update text
* @param {boolean} [finish=false]
* @private
*/
App.TimeInput.prototype._updateText = function _updateText(finish)
{
App.Input.prototype._updateText.call(this,finish);
this._updateAlignment();
};
/**
* Format the text input
* @param {boolean} [finish=false]
* @private
*/
App.TimeInput.prototype._format = function _format(finish)
{
if (this._inputProxy.value.length === 0) return "";
var value = this._inputProxy.value.replace(/\D/g,""),
hours = value.substr(0,2),
minutes = value.substr(2,2);
if (hours.length === 2 && parseInt(hours,10) > 24) hours = "24";
else if (minutes.length === 1 && parseInt(minutes,10) > 5) minutes = "5";
else if (minutes.length >= 2 && parseInt(minutes,10) > 59) minutes = "59";
if (finish)
{
if (hours.length === 1) hours = "0" + hours;
if (minutes.length === 0) minutes += "00";
else if (minutes.length === 1) minutes += "0";
}
if (minutes.length > 0) value = hours + ":" + minutes;
else value = hours;
this._inputProxy.value = value;
return value;
};
/**
* Update text's alignment
* @private
*/
App.TimeInput.prototype._updateAlignment = function _updateAlignment()
{
this._textField.x = Math.round((this._width - this._textField.width) / 2);
};
/**
* @class Button
* @extend Graphics
* @param {string} label
* @param {{width:number,height:number,pixelRatio:number,style:Object,backgroundColor:number}} options
* @constructor
*/
App.Button = function Button(label,options)
{
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._pixelRatio = options.pixelRatio;
this._label = label;
this._style = options.style;
this._backgroundColor = options.backgroundColor;
this._labelField = new PIXI.Text(label,this._style);
this._render();
this.addChild(this._labelField);
};
App.Button.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Button.prototype._render = function _render()
{
var w = this.boundingBox.width,
h = this.boundingBox.height;
App.GraphicUtils.drawRoundedRect(this,this._backgroundColor,1,0,0,w,h,Math.round(5 * this._pixelRatio));
this._labelField.x = Math.round((w - this._labelField.width) / 2);
this._labelField.y = Math.round((h - this._labelField.height) / 2);
};
/**
* Resize
* @param {number} width
* @param {number} height
*/
App.Button.prototype.resize = function resize(width,height)
{
this.boundingBox.width = width || this.boundingBox.width;
this.boundingBox.height = height || this.boundingBox.height;
this._render();
};
/**
* Test if position passed in falls within this button bounds
* @param {Point} position
* @returns {boolean}
*/
App.Button.prototype.hitTest = function hitTest(position)
{
return position.x >= this.x && position.x < this.x + this.boundingBox.width && position.y >= this.y && position.y < this.y + this.boundingBox.height;
};
/**
* @class CalendarWeekRow
* @extend Graphics
* @param {{font:string,fill:string}} weekTextStyle
* @param {{font:string,fill:string}} weekSelectedStyle
* @param {number} width
* @param {number} pixelRatio
* @constructor
*/
App.CalendarWeekRow = function CalendarWeekRow(weekTextStyle,weekSelectedStyle,width,pixelRatio)
{
PIXI.Graphics.call(this);
var daysInWeek = 7,
Text = PIXI.Text,
index = 0,
i = 0;
this.boundingBox = new App.Rectangle(0,0,width,Math.round(40*pixelRatio));
this._week = null;
this._width = width;
this._pixelRatio = pixelRatio;
this._textStyle = weekTextStyle;
this._selectedStyle = weekSelectedStyle;
this._dateFields = new Array(7);
this._selectedDayIndex = -1;
this._highlightBackground = new PIXI.Graphics();
for (;i<daysInWeek;i++,index+=2) this._dateFields[i] = new Text("",this._textStyle);
this.addChild(this._highlightBackground);
for (i = 0;i<daysInWeek;) this.addChild(this._dateFields[i++]);
};
App.CalendarWeekRow.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.CalendarWeekRow.prototype._render = function _render()
{
var ColorTheme = App.ColorTheme,
daysInWeek = this._week.length / 2,
cellWidth = Math.round(this._width / daysInWeek),
cellHeight = this.boundingBox.height,
textField = null,
otherBGStart = -1,
otherBGEnd = -1,
index = 0,
i = 0;
this.clear();
this.beginFill(ColorTheme.GREY_LIGHT);
this.drawRect(0,0,this._width,cellHeight);
this.beginFill(ColorTheme.GREY);
for (;i<daysInWeek;i++,index+=2)
{
textField = this._dateFields[i];
textField.x = Math.round((i * cellWidth) + (cellWidth - textField.width) / 2 + 1);
textField.y = Math.round((cellHeight - textField.height) / 2 + 1);
if (this._week[index+1])
{
if (otherBGStart === -1) otherBGStart = i;
}
else
{
if (otherBGEnd === -1 && otherBGStart > -1) otherBGEnd = i;
if (i) this.drawRect(Math.round(i * cellWidth),0,1,cellHeight);
}
}
// Highlight days from other months
if (otherBGStart > -1)
{
this.drawRect(
otherBGStart ? otherBGStart * cellWidth : 0,
0,
otherBGEnd === -1 ? this._width : otherBGEnd * cellWidth,
cellHeight);
}
this.endFill();
App.GraphicUtils.drawRect(this._highlightBackground,ColorTheme.BLUE,1,0,0,cellWidth-1,cellHeight);
this._highlightBackground.alpha = 0.0;
};
/**
* Find and return day by date passed in
* @param {number} day
* @returns {{day:number,otherMonth:number,index:number}} position
*/
App.CalendarWeekRow.prototype._getDayByDate = function _getDayByDate(day)
{
var index = 0,
i = 0,
l = this._week.length / 2,
dayInWeek = -1;
for (;i<l;i++,index+=2)
{
dayInWeek = this._week[index];
if (dayInWeek === day) return {day:dayInWeek,otherMonth:this._week[index+1],index:i};
}
return null;
};
/**
* Find and return day by position passed in
* @param {number} position
* @returns {{day:number,otherMonth:number,index:number}} position
*/
App.CalendarWeekRow.prototype.getDayByPosition = function getDayByPosition(position)
{
var index = 0,
i = 0,
l = this._week.length / 2,
cellWidth = Math.round(this._width / l);
for (;i<l;i++,index+=2)
{
if (position >= i * cellWidth && position <= i * cellWidth + cellWidth)
{
return {day:this._week[index],otherMonth:this._week[index+1],index:i};
}
}
return null;
};
/**
* Select day
* @param {{day:number,otherMonth:number,index:number}} day
* @private
*/
App.CalendarWeekRow.prototype._selectDay = function _selectDay(day)
{
//TODO fade-in?
this._highlightBackground.x = day.index * Math.round(this._width / (this._week.length / 2)) + Math.round(this._pixelRatio);
this._highlightBackground.alpha = 1.0;
if (this._selectedDayIndex > -1) this._dateFields[this._selectedDayIndex].setStyle(this._textStyle);
this._selectedDayIndex = day.index;
this._dateFields[this._selectedDayIndex].setStyle(this._selectedStyle);
};
/**
* Deselect day
* @private
*/
App.CalendarWeekRow.prototype._deselectDay = function _deselectDay()
{
if (this._selectedDayIndex > -1)
{
this._dateFields[this._selectedDayIndex].setStyle(this._textStyle);
this._selectedDayIndex = -1;
}
//TODO fade-out?
this._highlightBackground.alpha = 0.0;
};
/**
* Update selection
* @param {number} date Day of a month to select
*/
App.CalendarWeekRow.prototype.updateSelection = function updateSelection(date)
{
var day = this._getDayByDate(date);
if (day && day.otherMonth === 0) this._selectDay(day);
else this._deselectDay();
};
/**
* Change week
* @param {Array.<Number>} week
* @param {number} currentDay
*/
App.CalendarWeekRow.prototype.change = function change(week,currentDay)
{
this._week = week;
var daysInWeek = week.length / 2,
dayField = null,
index = 0,
i = 0;
for (;i<daysInWeek;i++,index+=2)
{
dayField = this._dateFields[i];
dayField.setText(week[index]);
dayField.setStyle(this._textStyle);
}
this._render();
if (currentDay > -1) this.updateSelection(currentDay);
};
/**
* @class Calendar
* @extend Graphic
* @param {number} width
* @param {number} pixelRatio
* @constructor
*/
App.Calendar = function Calendar(width,pixelRatio)
{
PIXI.Graphics.call(this);
var dayLabelStyle = {font:"bold " + Math.round(12 * pixelRatio)+"px Arial",fill:"#999999"},
CalendarWeekRow = App.CalendarWeekRow,
Text = PIXI.Text,
DateUtils = App.DateUtils,
FontStyle = App.FontStyle,
startOfWeek = App.ModelLocator.getProxy(App.ModelName.SETTINGS).startOfWeek,
weekTextStyle = FontStyle.get(14,FontStyle.GREY_DARK),
weekSelectedStyle = FontStyle.get(14,FontStyle.WHITE),
dayLabels = DateUtils.getDayLabels(startOfWeek),
daysInWeek = dayLabels.length,
weeksInMonth = 6,
i = 0;
this.boundingBox = new App.Rectangle(0,0,width);
this._date = null;
this._selectedDate = null;
this._width = width;
this._pixelRatio = pixelRatio;
this._weekRowPosition = Math.round(81 * pixelRatio);
this._monthField = new PIXI.Text("",FontStyle.get(18,FontStyle.BLUE));
this._prevButton = PIXI.Sprite.fromFrame("arrow-app");
this._nextButton = PIXI.Sprite.fromFrame("arrow-app");
this._dayLabelFields = new Array(daysInWeek);
this._weekRows = new Array(weeksInMonth);
this._separatorContainer = new PIXI.Graphics();
for (;i<daysInWeek;i++) this._dayLabelFields[i] = new Text(dayLabels[i],dayLabelStyle);
for (i = 0;i<weeksInMonth;i++) this._weekRows[i] = new CalendarWeekRow(weekTextStyle,weekSelectedStyle,width,pixelRatio);
this._render();
this.addChild(this._monthField);
this.addChild(this._prevButton);
this.addChild(this._nextButton);
for (i = 0;i<daysInWeek;) this.addChild(this._dayLabelFields[i++]);
for (i = 0;i<weeksInMonth;) this.addChild(this._weekRows[i++]);
this.addChild(this._separatorContainer);
};
App.Calendar.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
*
* @private
*/
App.Calendar.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._pixelRatio,
w = this._width,
arrowResizeRatio = Math.round(12 * r) / this._prevButton.height,
separatorPadding = Math.round(15 * r),
separatorWidth = w - separatorPadding * 2,
dayLabel = null,
dayLabelWidth = Math.round(w / this._dayLabelFields.length),
dayLabelOffset = Math.round(40 * r),
weekRow = this._weekRows[0],
weekRowHeight = weekRow.boundingBox.height,
l = this._dayLabelFields.length,
i = 0;
this._monthField.y = Math.round((dayLabelOffset - this._monthField.height) / 2);
this._prevButton.scale.x = arrowResizeRatio;
this._prevButton.scale.y = arrowResizeRatio;
this._prevButton.x = Math.round(20 * r + this._prevButton.width);
this._prevButton.y = Math.round((dayLabelOffset - this._prevButton.height) / 2 + this._prevButton.height);
this._prevButton.rotation = Math.PI;
this._prevButton.tint = ColorTheme.BLUE;
this._nextButton.scale.x = arrowResizeRatio;
this._nextButton.scale.y = arrowResizeRatio;
this._nextButton.x = Math.round(w - 20 * r - this._nextButton.width);
this._nextButton.y = Math.round((dayLabelOffset - this._prevButton.height) / 2);
this._nextButton.tint = ColorTheme.BLUE;
for (;i<l;i++)
{
dayLabel = this._dayLabelFields[i];
dayLabel.x = Math.round((i * dayLabelWidth) + (dayLabelWidth - dayLabel.width) / 2);
dayLabel.y = Math.round(dayLabelOffset + r + (dayLabelOffset - dayLabel.height) / 2);
}
i = 0;
l = this._weekRows.length;
this._separatorContainer.clear();
this._separatorContainer.beginFill(ColorTheme.GREY,1.0);
for (;i<l;i++)
{
weekRow = this._weekRows[i];
weekRow.y = this._weekRowPosition + i * weekRowHeight;
this._separatorContainer.drawRect(0,weekRow.y + weekRowHeight,w,1);
}
this._separatorContainer.endFill();
this.boundingBox.height = weekRow.y + weekRowHeight;
//TODO I dont need this (can use screen's bg) ... and can extend from DOContainer instead
GraphicUtils.drawRects(this,ColorTheme.GREY,1,[0,0,w,this.boundingBox.height],true,false);
GraphicUtils.drawRects(this,ColorTheme.GREY_DARK,1,[0,Math.round(80 * r),w,1,separatorPadding,dayLabelOffset,separatorWidth,1],false,false);
GraphicUtils.drawRects(this,ColorTheme.GREY_LIGHT,1,[separatorPadding,dayLabelOffset+1,separatorWidth,1],false,true);
};
/**
* Update
* @param {Date} date
*/
App.Calendar.prototype.update = function update(date)
{
this._date = date;
if (this._selectedDate) this._selectedDate.setTime(this._date.valueOf());
else this._selectedDate = new Date(this._date.valueOf());
var month = App.DateUtils.getMonth(this._date,App.ModelLocator.getProxy(App.ModelName.SETTINGS).startOfWeek),
selectedDate = this._selectedDate.getDate(),
weeksInMonth = month.length,
i = 0;
for (i = 0;i<weeksInMonth;i++) this._weekRows[i].change(month[i],selectedDate);
this._updateMonthLabel();
};
/**
* Return selected date
* @returns {Date}
*/
App.Calendar.prototype.getSelectedDate = function getSelectedDate()
{
return this._selectedDate;
};
/**
* Update month label
* @private
*/
App.Calendar.prototype._updateMonthLabel = function _updateMonthLabel()
{
this._monthField.setText(App.DateUtils.getMonthLabel(this._date.getMonth()) + " " + this._date.getFullYear());
this._monthField.x = Math.round((this._width - this._monthField.width) / 2);
};
/**
* On click
*/
App.Calendar.prototype.onClick = function onClick()
{
var position = this.stage.getTouchData().getLocalPosition(this),
x = position.x,
y = position.y;
// Click into the actual calendar
if (y >= this._weekRowPosition)
{
this._selectDay(x,y);
}
// Click at one of the prev-, next-buttons
else
{
var prevDX = this._prevButton.x - this._prevButton.width / 2 - x,
nextDX = this._nextButton.x + this._nextButton.width / 2 - x,
dy = this._nextButton.y + this._nextButton.height / 2 - y,
prevDist = prevDX * prevDX - dy * dy,
nextDist = nextDX * nextDX - dy * dy,
threshold = 20 * this._pixelRatio;
if (Math.sqrt(Math.abs(prevDist)) < threshold) this._changeDate(App.Direction.LEFT,-1);
else if (Math.sqrt(Math.abs(nextDist)) < threshold) this._changeDate(App.Direction.RIGHT,-1);
}
};
/**
* Find and return week row by position passed in
* @param {number} position
* @private
*/
App.Calendar.prototype._getWeekByPosition = function _getWeekByPosition(position)
{
var weekRowHeight = this._weekRows[0].boundingBox.height,
weekRow = null,
l = this._weekRows.length,
i = 0;
for (;i<l;)
{
weekRow = this._weekRows[i++];
if (weekRow.y <= position && weekRow.y + weekRowHeight > position)
{
return weekRow;
}
}
return null;
};
/**
* Select day by position passed in
* @param {number} x
* @param {number} y
* @private
*/
App.Calendar.prototype._selectDay = function _selectDay(x,y)
{
var week = this._getWeekByPosition(y),
day = week.getDayByPosition(x),
date = day.day,
l = this._weekRows.length,
i = 0;
if (day.otherMonth)
{
if (date > 20) this._changeDate(App.Direction.LEFT,date);
else this._changeDate(App.Direction.RIGHT,date);
}
else
{
for (;i<l;)this._weekRows[i++].updateSelection(date);
this._selectedDate.setFullYear(this._date.getFullYear(),this._date.getMonth(),date);
}
};
/**
* Change date
* @param {string} direction
* @param {number} selectDate
* @private
*/
App.Calendar.prototype._changeDate = function _changeDate(direction,selectDate)
{
var currentMonth = this._date.getMonth(),
currentYear = this._date.getFullYear(),
newMonth = currentMonth < 11 ? currentMonth + 1 : 0,
newYear = newMonth ? currentYear : currentYear + 1;
if (direction === App.Direction.LEFT)
{
newMonth = currentMonth ? currentMonth - 1 : 11;
newYear = currentMonth ? currentYear : currentYear - 1;
}
this._date.setFullYear(newYear,newMonth);
if (selectDate > -1) this._selectedDate.setFullYear(newYear,newMonth,selectDate);
this._updateMonthLabel();
var month = App.DateUtils.getMonth(this._date,App.ModelLocator.getProxy(App.ModelName.SETTINGS).startOfWeek),
weeksInMonth = month.length,
selectedMonth = this._selectedDate.getFullYear() === newYear && this._selectedDate.getMonth() === newMonth,
selectedDate = selectedMonth ? this._selectedDate.getDate() : -1,
i = 0;
for (i = 0;i<weeksInMonth;i++) this._weekRows[i].change(month[i],selectedDate);
};
/**
* @class Radio
* @param {number} pixelRatio
* @param {boolean} selected
* @constructor
*/
App.Radio = function Radio(pixelRatio,selected)
{
PIXI.Graphics.call(this);
this._selected = selected;
this._size = Math.round(20 * pixelRatio);
this._pixelRatio = pixelRatio;
this._check = new PIXI.Graphics();
this.boundingBox = new App.Rectangle(0,0,this._size,this._size);
this._render();
this._check.alpha = selected ? 1.0 : 0.0;
this.addChild(this._check);
};
App.Radio.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Radio.prototype._render = function _render()
{
var drawArc = App.GraphicUtils.drawArc,
ColorTheme = App.ColorTheme,
size = this._size,
center = new PIXI.Point(Math.round(size/2),Math.round(size/2));
drawArc(this,center,size,size,Math.round(2*this._pixelRatio),0,360,20,0,0,0,ColorTheme.GREY,1);
size -= Math.round(8*this._pixelRatio);
drawArc(this._check,center,size,size,Math.round(6*this._pixelRatio),0,360,20,0,0,0,ColorTheme.BLUE,1);
};
/**
* Select
*/
App.Radio.prototype.select = function select()
{
this._selected = true;
this._check.alpha = 1.0;
};
/**
* Select
*/
App.Radio.prototype.deselect = function deselect()
{
this._selected = false;
this._check.alpha = 0.0;
};
/**
* @class Pane
* @extends {DisplayObjectContainer}
* @param {string} xScrollPolicy
* @param {string} yScrollPolicy
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {boolean} useMask
* @constructor
*/
App.Pane = function Pane(xScrollPolicy,yScrollPolicy,width,height,pixelRatio,useMask)
{
PIXI.DisplayObjectContainer.call(this);
this.boundingBox = new PIXI.Rectangle(0,0,width,height);
this._ticker = App.ModelLocator.getProxy(App.ModelName.TICKER);
this._content = null;
this._contentHeight = 0;
this._contentWidth = 0;
this._contentBoundingBox = new App.Rectangle();
this._useMask = useMask;
this.hitArea = this.boundingBox;
this._enabled = false;
this._eventsRegistered = false;
this._state = null;
this._xOriginalScrollPolicy = xScrollPolicy;
this._yOriginalScrollPolicy = yScrollPolicy;
this._xScrollPolicy = xScrollPolicy;
this._yScrollPolicy = yScrollPolicy;
this._xScrollIndicator = new App.ScrollIndicator(App.Direction.X,pixelRatio);
this._yScrollIndicator = new App.ScrollIndicator(App.Direction.Y,pixelRatio);
this._mouseData = null;
this._oldMouseX = 0.0;
this._oldMouseY = 0.0;
this._xSpeed = 0.0;//TODO Average speed to avoid 'jumps'?
this._ySpeed = 0.0;
this._xOffset = 0.0;
this._yOffset = 0.0;
this._friction = 0.9;
this._dumpForce = 0.5;
this._snapForce = 0.2;//TODO allow to disable snapping?
if (this._useMask)
{
this._mask = new PIXI.Graphics();
this.mask = this._mask;
this.addChild(this._mask);
}
};
App.Pane.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Set content of the pane
*
* @method setContent
* @param {PIXI.DisplayObjectContainer} content
*/
App.Pane.prototype.setContent = function setContent(content)
{
this.removeContent();
this._content = content;
this._contentHeight = Math.round(this._content.height);
this._contentWidth = Math.round(this._content.width);
this._contentBoundingBox.width = this._contentWidth;
this._contentBoundingBox.height = this._contentHeight;
this.addChildAt(this._content,0);
this._updateScrollers();
if (this._useMask) this._updateMask();
};
/**
* Remove content
*
* @method removeContent
*/
App.Pane.prototype.removeContent = function removeContent()
{
if (this._content && this.contains(this._content))
{
this.removeChild(this._content);
this._content = null;
}
};
/**
* Resize
*
* @param {number} width
* @param {number} height
*/
App.Pane.prototype.resize = function resize(width,height)
{
this.boundingBox.width = width || this.boundingBox.width;
this.boundingBox.height = height || this.boundingBox.height;
if (this._content)
{
this._contentHeight = Math.round(this._content.height);
this._contentWidth = Math.round(this._content.width);
this._contentBoundingBox.width = this._contentWidth;
this._contentBoundingBox.height = this._contentHeight;
this._checkPosition();
this._updateScrollers();
if (this._useMask) this._updateMask();
}
};
/**
* Return content bounding box
* @returns {Rectangle|*}
*/
App.Pane.prototype.getContentBounds = function getContentBounds()
{
return this._contentBoundingBox;
};
/**
* Re-draw mask
* @private
*/
App.Pane.prototype._updateMask = function _updateMask()
{
App.GraphicUtils.drawRect(this._mask,0xff0000,1,0,0,this.boundingBox.width,this.boundingBox.height);
};
/**
* Update content's x position
* @param {number} position
* @private
*/
App.Pane.prototype._updateX = function _updateX(position)
{
this._content.x = Math.round(position);
};
/**
* Update content's y position
* @param {number} position
* @private
*/
App.Pane.prototype._updateY = function _updateY(position)
{
this._content.y = Math.round(position);
};
/**
* Enable
*/
App.Pane.prototype.enable = function enable()
{
if (!this._enabled)
{
var ScrollPolicy = App.ScrollPolicy;
if (this._xScrollPolicy !== ScrollPolicy.OFF || this._yScrollPolicy !== ScrollPolicy.OFF) this._registerEventListeners();
this.interactive = true;
this._enabled = true;
}
};
/**
* Disable
*/
App.Pane.prototype.disable = function disable()
{
this._unRegisterEventListeners();
this.cancelScroll();
this._checkPosition();
this.interactive = false;
this._enabled = false;
};
/**
* Reset content scroll
*/
App.Pane.prototype.resetScroll = function resetScroll()
{
this._state = null;
this._xSpeed = 0.0;
this._ySpeed = 0.0;
if (this._content)
{
this._updateX(0);
this._updateY(0);
this._xScrollIndicator.hide(true);
this._yScrollIndicator.hide(true);
}
};
/**
* Cancel scroll
*/
App.Pane.prototype.cancelScroll = function cancelScroll()
{
this._state = null;
this._xSpeed = 0.0;
this._ySpeed = 0.0;
this._xScrollIndicator.hide(true);
this._yScrollIndicator.hide(true);
};
/**
* Register event listeners
* @private
*/
App.Pane.prototype._registerEventListeners = function _registerEventListeners()
{
if (!this._eventsRegistered)
{
this._eventsRegistered = true;
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = this._onPointerDown;
this.touchend = this._onPointerUp;
this.touchendoutside = this._onPointerUp;
this.touchmove = this._onPointerMove;
}
else
{
this.mousedown = this._onPointerDown;
this.mouseup = this._onPointerUp;
this.mouseupoutside = this._onPointerUp;
this.mousemove = this._onPointerMove;
}
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
}
};
/**
* UnRegister event listeners
* @private
*/
App.Pane.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = null;
this.touchend = null;
this.touchendoutside = null;
this.touchmove = null;
}
else
{
this.mousedown = null;
this.mouseup = null;
this.mouseupoutside = null;
this.mousemove = null;
}
this._eventsRegistered = false;
};
/**
* Pointer Down handler
*
* @method _onPointerDown
* @param {InteractionData} data
* @private
*/
App.Pane.prototype._onPointerDown = function _onPointerDown(data)
{
//TODO make sure just one input is registered (multiple inputs on touch screens) ...
this._mouseData = data;
var mp = this._mouseData.getLocalPosition(this.stage);
this._xOffset = mp.x - this._content.x;
this._yOffset = mp.y - this._content.y;
this._xSpeed = 0.0;
this._ySpeed = 0.0;
this._state = App.InteractiveState.DRAGGING;
if (this._xScrollPolicy === App.ScrollPolicy.ON) this._xScrollIndicator.show();
if (this._yScrollPolicy === App.ScrollPolicy.ON) this._yScrollIndicator.show();
};
/**
* On pointer up
*
* @param {InteractionData} data
* @private
*/
App.Pane.prototype._onPointerUp = function _onPointerUp(data)
{
if (this._isContentPulled())
{
this._state = App.InteractiveState.SNAPPING;
this._xSpeed = 0.0;
this._ySpeed = 0.0;
}
else
{
this._state = App.InteractiveState.SCROLLING;
}
this._mouseData = null;
};
/**
* On pointer move
* @param {InteractionData} data
* @private
*/
App.Pane.prototype._onPointerMove = function _onPointerMove(data)
{
this._mouseData = data;
};
/**
* Tick handler
*
* @private
*/
App.Pane.prototype._onTick = function _onTick()
{
var InteractiveState = App.InteractiveState;
if (this._state === InteractiveState.DRAGGING) this._drag(App.ScrollPolicy);
else if (this._state === InteractiveState.SCROLLING) this._scroll(App.ScrollPolicy,InteractiveState);
else if (this._state === InteractiveState.SNAPPING) this._snap(App.ScrollPolicy,InteractiveState);
if (this._xScrollIndicator.visible) this._xScrollIndicator.update(this._content.x);
if (this._yScrollIndicator.visible) this._yScrollIndicator.update(this._content.y);
};
/**
* Perform drag operation
*
* @param {App.ScrollPolicy} ScrollPolicy
* @private
*/
App.Pane.prototype._drag = function _drag(ScrollPolicy)
{
var pullDistance = 0;
if (this.stage)
{
if (this._xScrollPolicy === ScrollPolicy.ON)
{
var w = this.boundingBox.width,
mouseX = this._mouseData.getLocalPosition(this.stage).x,
contentX = this._content.x,
contentRight = contentX + this._contentWidth,
contentLeft = contentX - this._contentWidth;
if (mouseX <= -10000) return;
// If content is pulled from beyond screen edges, dump the drag effect
if (contentX > 0)
{
pullDistance = (1 - contentX / w) * this._dumpForce;
this._updateX(mouseX * pullDistance - this._xOffset * pullDistance);
}
else if (contentRight < w)
{
pullDistance = (contentRight / w) * this._dumpForce;
this._updateX(contentLeft - (w - mouseX) * pullDistance + (this._contentWidth - this._xOffset) * pullDistance);
}
else
{
this._updateX(mouseX - this._xOffset);
}
this._xSpeed = mouseX - this._oldMouseX;
this._oldMouseX = mouseX;
}
if (this._yScrollPolicy === ScrollPolicy.ON)
{
var h = this.boundingBox.height,
mouseY = this._mouseData.getLocalPosition(this.stage).y,
contentY = this._content.y,
contentBottom = contentY + this._contentHeight,
contentTop = h - this._contentHeight;
if (mouseY <= -10000) return;
// If content is pulled from beyond screen edges, dump the drag effect
if (contentY > 0)
{
pullDistance = (1 - contentY / h) * this._dumpForce;
this._updateY(mouseY * pullDistance - this._yOffset * pullDistance);
}
else if (contentBottom < h)
{
pullDistance = (contentBottom / h) * this._dumpForce;
this._updateY(contentTop - (h - mouseY) * pullDistance + (this._contentHeight - this._yOffset) * pullDistance);
}
else
{
this._updateY(mouseY - this._yOffset);
}
this._ySpeed = mouseY - this._oldMouseY;
this._oldMouseY = mouseY;
}
}
};
/**
* Perform scroll operation
*
* @param {App.ScrollPolicy} ScrollPolicy
* @param {App.InteractiveState} InteractiveState
* @private
*/
App.Pane.prototype._scroll = function _scroll(ScrollPolicy,InteractiveState)
{
if (this._xScrollPolicy === ScrollPolicy.ON)
{
this._updateX(this._content.x + this._xSpeed);
var w = this.boundingBox.width,
contentX = this._content.x,
contentRight = contentX + this._contentWidth;
// If content is scrolled from beyond screen edges, dump the speed
if (contentX > 0)
{
this._xSpeed *= (1 - contentX / w) * this._dumpForce;
}
else if (contentRight < w)
{
this._xSpeed *= (contentRight / w) * this._dumpForce;
}
// If the speed is very low, stop it.
// Also, if the content is scrolled beyond screen edges, switch to 'snap' state
if (Math.abs(this._xSpeed) < .1)
{
this._xSpeed = 0.0;
this._state = null;
this._xScrollIndicator.hide();
if (contentX > 0 || contentRight < w) this._state = InteractiveState.SNAPPING;
}
else
{
this._xSpeed *= this._friction;
}
}
if (this._yScrollPolicy === ScrollPolicy.ON)
{
this._updateY(this._content.y + this._ySpeed);
var h = this.boundingBox.height,
contentY = this._content.y,
contentBottom = contentY + this._contentHeight;
// If content is scrolled from beyond screen edges, dump the speed
if (contentY > 0)
{
this._ySpeed *= (1 - contentY / h) * this._dumpForce;
}
else if (contentBottom < h)
{
this._ySpeed *= (contentBottom / h) * this._dumpForce;
}
// If the speed is very low, stop it.
// Also, if the content is scrolled beyond screen edges, switch to 'snap' state
if (Math.abs(this._ySpeed) < .1)
{
this._ySpeed = 0.0;
this._state = null;
this._yScrollIndicator.hide();
if (contentY > 0 || contentBottom < h) this._state = InteractiveState.SNAPPING;
}
else
{
this._ySpeed *= this._friction;
}
}
};
/**
* Perform snap operation
*
* @param {App.ScrollPolicy} ScrollPolicy
* @private
*/
App.Pane.prototype._snap = function _snap(ScrollPolicy)
{
if (this._xScrollPolicy === ScrollPolicy.ON)
{
var w = this.boundingBox.width,
contentX = this._content.x,
contentRight = contentX + this._contentWidth,
contentLeft = contentX - this._contentWidth,
result = contentX * this._snapForce;
if (contentX > 0)
{
if (result < 5)
{
this._state = null;
this._updateX(0);
this._xScrollIndicator.hide();
}
else
{
this._updateX(result);
}
}
else if (contentRight < w)
{
result = contentLeft + (contentX - contentLeft) * this._snapForce;
if (result >= w - 5)
{
this._state = null;
this._updateX(contentLeft);
this._xScrollIndicator.hide();
}
else
{
this._updateX(result);
}
}
}
if (this._yScrollPolicy === ScrollPolicy.ON)
{
var h = this.boundingBox.height,
contentY = this._content.y,
contentBottom = contentY + this._contentHeight,
contentTop = h - this._contentHeight;
if (contentY > 0)
{
result = contentY * this._snapForce;
if (result < 5)
{
this._state = null;
this._updateY(0);
this._yScrollIndicator.hide();
}
else
{
this._updateY(result);
}
}
else if (contentBottom < h)
{
result = contentTop + (contentY - contentTop) * this._snapForce;
if (result >= contentTop - 5)
{
this._state = null;
this._updateY(contentTop);
this._yScrollIndicator.hide();
}
else
{
this._updateY(result);
}
}
}
};
/**
* Is content pulled
* @returns {boolean}
* @private
*/
App.Pane.prototype._isContentPulled = function _isContentPulled()
{
if (this._contentHeight > this.boundingBox.height)
{
if (this._content.y > 0) return true;
else if (this._content.y + this._contentHeight < this.boundingBox.height) return true;
}
if (this._contentWidth > this.boundingBox.width)
{
if (this._content.x > 0) return true;
else if (this._content.x + this._contentWidth < this.boundingBox.width) return true;
}
return false;
};
/**
* Update scroll indicators
* @private
*/
App.Pane.prototype._updateScrollers = function _updateScrollers()
{
var ScrollPolicy = App.ScrollPolicy,
w = this.boundingBox.width,
h = this.boundingBox.height;
if (this._xOriginalScrollPolicy === ScrollPolicy.AUTO)
{
if (this._contentWidth >= w)
{
this._xScrollPolicy = ScrollPolicy.ON;
this._xScrollIndicator.resize(w,this._contentWidth);
this._xScrollIndicator.x = h - this._xScrollIndicator.boundingBox.height;
if (!this.contains(this._xScrollIndicator)) this.addChild(this._xScrollIndicator);
}
else
{
this._xScrollPolicy = ScrollPolicy.OFF;
this._xScrollIndicator.hide();
if (this.contains(this._xScrollIndicator)) this.removeChild(this._xScrollIndicator);
}
}
if (this._yOriginalScrollPolicy === ScrollPolicy.AUTO)
{
if (this._contentHeight >= h)
{
this._yScrollPolicy = ScrollPolicy.ON;
this._yScrollIndicator.resize(h,this._contentHeight);
this._yScrollIndicator.x = w - this._yScrollIndicator.boundingBox.width;
if (!this.contains(this._yScrollIndicator)) this.addChild(this._yScrollIndicator);
}
else
{
this._yScrollPolicy = ScrollPolicy.OFF;
this._yScrollIndicator.hide();
if (this.contains(this._yScrollIndicator)) this.removeChild(this._yScrollIndicator);
}
}
if (this._xScrollPolicy === ScrollPolicy.OFF && this._yScrollPolicy === ScrollPolicy.OFF) this._unRegisterEventListeners();
else this._registerEventListeners();
};
/**
* Check position
* @private
*/
App.Pane.prototype._checkPosition = function _checkPosition()
{
var w = this.boundingBox.width,
h = this.boundingBox.height;
if (this._contentWidth > w)
{
if (this._content.x > 0) this._updateX(0);
else if (this._content.x + this._contentWidth < w) this._updateX(w - this._contentWidth);
}
else if (this._contentWidth <= w)
{
if (this._content.x !== 0) this._updateX(0);
}
if (this._contentHeight > h)
{
if (this._content.y > 0) this._updateY(0);
else if (this._content.y + this._contentHeight < h) this._updateY(h - this._contentHeight);
}
else if (this._contentHeight <= h)
{
if (this._content.y !== 0) this._updateY(0);
}
};
/**
* @class InfiniteList
* @extends DisplayObjectContainer
* @param {Array} model
* @param {Function} itemClass
* @param {string} direction
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.InfiniteList = function InfiniteList(model,itemClass,direction,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var Direction = App.Direction,
item = new itemClass(0,model[0],pixelRatio),
itemSize = direction === Direction.X ? item.boundingBox.width : item.boundingBox.height,
itemCount = direction === Direction.X ? Math.ceil(width / itemSize) + 1 : Math.ceil(height / itemSize) + 1,
modelLength = model.length - 1,
index = 0,
i = 0;
this.boundingBox = new PIXI.Rectangle(0,0,width,height);
this.hitArea = this.boundingBox;
this._ticker = App.ModelLocator.getProxy(App.ModelName.TICKER);
this._model = model;
this._itemClass = itemClass;//TODO use pool instead of classes?
this._direction = direction;
this._width = width;
this._height = height;
this._pixelRatio = pixelRatio;
this._items = new Array(itemCount);
this._itemSize = itemSize;
this._selectedModelIndex = -1;
this._enabled = false;
this._state = null;
this._mouseData = null;
this._virtualPosition = 0;
this._oldMousePosition = 0.0;
this._speed = 0.0;
this._offset = 0.0;
this._friction = 0.9;
for (;i<itemCount;i++,index++)
{
if(index > modelLength) index = 0;
if (i > 0) item = new itemClass(index,model[index],pixelRatio);
this._items[i] = item;
this.addChild(item);
}
this._updateLayout(false);
};
App.InfiniteList.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Enable
*/
App.InfiniteList.prototype.enable = function enable()
{
if (!this._enabled)
{
this._enabled = true;
this._registerEventListeners();
this.interactive = true;
}
};
/**
* Disable
*/
App.InfiniteList.prototype.disable = function disable()
{
this.interactive = false;
this._unRegisterEventListeners();
this._enabled = false;
};
/**
* Find and select item under position passed in
* @param {number} position
* @returns {*}
*/
App.InfiniteList.prototype.selectItemByPosition = function selectItemByPosition(position)
{
var i = 0,
l = this._items.length,
itemSize = this._itemSize,
itemProperty = this._direction === App.Direction.X ? "x" : "y",
item = null,
itemPosition = 0;
this._selectedModelIndex = -1;
for (;i<l;)
{
item = this._items[i++];
itemPosition = item[itemProperty];
if (itemPosition <= position && itemPosition + itemSize > position)
{
this._selectedModelIndex = item.getModelIndex();
break;
}
}
for (i=0;i<l;) this._items[i++].select(this._selectedModelIndex);
return item;
};
/**
* Find and select item under position passed in
* @param {string} value
*/
App.InfiniteList.prototype.selectItemByValue = function selectItemByValue(value)
{
var i = 0,
l = this._model.length;
this._selectedModelIndex = -1;
for (;i<l;i++)
{
if (this._model[i] === value)
{
this._selectedModelIndex = i;
break;
}
}
l = this._items.length;
for (i=0;i<l;) this._items[i++].select(this._selectedModelIndex);
};
/**
* Return selected model
* @returns {*}
*/
App.InfiniteList.prototype.getSelectedValue = function getSelectedValue()
{
return this._model[this._selectedModelIndex];
};
/**
* Cancel scroll
*/
App.InfiniteList.prototype.cancelScroll = function cancelScroll()
{
this._speed = 0.0;
this._state = null;
};
/**
* Register event listeners
* @private
*/
App.InfiniteList.prototype._registerEventListeners = function _registerEventListeners()
{
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = this._onPointerDown;
this.touchend = this._onPointerUp;
this.touchendoutside = this._onPointerUp;
}
else
{
this.mousedown = this._onPointerDown;
this.mouseup = this._onPointerUp;
this.mouseupoutside = this._onPointerUp;
}
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
};
/**
* UnRegister event listeners
* @private
*/
App.InfiniteList.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = null;
this.touchend = null;
this.touchendoutside = null;
}
else
{
this.mousedown = null;
this.mouseup = null;
this.mouseupoutside = null;
}
};
/**
* REF Tick handler
* @private
*/
App.InfiniteList.prototype._onTick = function _onTick()
{
var InteractiveState = App.InteractiveState;
if (this._state === InteractiveState.DRAGGING) this._drag(App.Direction);
else if (this._state === InteractiveState.SCROLLING) this._scroll(App.Direction);
};
/**
* On pointer down
* @param {InteractionData} data
* @private
*/
App.InfiniteList.prototype._onPointerDown = function _onPointerDown(data)
{
this._mouseData = data;
var mousePosition = this._mouseData.getLocalPosition(this.stage).x;
if (this._direction === App.Direction.Y) mousePosition = this._mouseData.getLocalPosition(this.stage).y;
this._offset = mousePosition - this._virtualPosition;
this._speed = 0.0;
this._state = App.InteractiveState.DRAGGING;
};
/**
* On pointer up
* @param {InteractionData} data
* @private
*/
App.InfiniteList.prototype._onPointerUp = function _onPointerUp(data)
{
this._state = App.InteractiveState.SCROLLING;
this._mouseData = null;
};
/**
* Perform drag operation
* @param {{X:string,Y:string}} Direction
* @private
*/
App.InfiniteList.prototype._drag = function _drag(Direction)
{
if (this.stage)
{
if (this._direction === Direction.X)
{
var mousePosition = this._mouseData.getLocalPosition(this.stage).x;
if (mousePosition <= -10000) return;
this._updateX(mousePosition - this._offset);
}
else if (this._direction === Direction.Y)
{
mousePosition = this._mouseData.getLocalPosition(this.stage).y;
if (mousePosition <= -10000) return;
this._updateY(mousePosition - this._offset);
}
this._speed = mousePosition - this._oldMousePosition;
this._oldMousePosition = mousePosition;
}
};
/**
* Perform scroll operation
*
* @param {{X:string,Y:string}} Direction
* @private
*/
App.InfiniteList.prototype._scroll = function _scroll(Direction)
{
if (this._direction === Direction.X) this._updateX(this._virtualPosition + this._speed);
else if (this._direction === Direction.Y) this._updateY(this._virtualPosition + this._speed);
// If the speed is very low, stop it.
if (Math.abs(this._speed) < 0.1)
{
this._speed = 0.0;
this._state = null;
}
else
{
this._speed *= this._friction;
}
};
/**
* Update X position
* @param {number} position
* @private
*/
App.InfiniteList.prototype._updateX = function _updateX(position)
{
position = Math.round(position);
var i = 0,
l = this._items.length,
itemSize = this._itemSize,
width = this._width,
positionDifference = position - this._virtualPosition,
itemScreenIndex = 0,
virtualIndex = Math.floor(position / itemSize),
xIndex = 0,
modelIndex = 0,
modelLength = this._model.length,
x = 0,
item = null;
this._virtualPosition = position;
for (;i<l;)
{
item = this._items[i++];
x = item.x + positionDifference;
if (x + itemSize < 0 || x > width)
{
itemScreenIndex = -Math.floor(x / width);
x += itemScreenIndex * l * itemSize;
xIndex = Math.floor(x / itemSize);
if (virtualIndex >= 0) modelIndex = (xIndex - (virtualIndex % modelLength)) % modelLength;
else modelIndex = (xIndex - virtualIndex) % modelLength;
if (modelIndex < 0) modelIndex = modelLength + modelIndex;
else if (modelIndex >= modelLength) modelIndex = modelLength - 1;
//TODO check that I don't set the model way too many times!
item.setModel(modelIndex,this._model[modelIndex],this._selectedModelIndex);
}
item.x = x;
}
};
/**
* Update Y position
* @param {number} position
* @private
*/
App.InfiniteList.prototype._updateY = function _updateY(position)
{
position = Math.round(position);
var i = 0,
l = this._items.length,
itemSize = this._itemSize,
height = this._height,
positionDifference = position - this._virtualPosition,
itemScreenIndex = 0,
virtualIndex = Math.floor(position / itemSize),
yIndex = 0,
modelIndex = 0,
modelLength = this._model.length,
y = 0,
item = null;
this._virtualPosition = position;
for (;i<l;)
{
item = this._items[i++];
y = item.y + positionDifference;
if (y + itemSize < 0 || y > height)
{
itemScreenIndex = -Math.floor(y / height);
y += itemScreenIndex * l * itemSize;
yIndex = Math.floor(y / itemSize);
if (virtualIndex >= 0) modelIndex = (yIndex - (virtualIndex % modelLength)) % modelLength;
else modelIndex = (yIndex - virtualIndex) % modelLength;
if (modelIndex < 0) modelIndex = modelLength + modelIndex;
else if (modelIndex >= modelLength) modelIndex = modelLength - 1;
item.setModel(modelIndex,this._model[modelIndex],this._selectedModelIndex);
}
item.y = y;
}
};
/**
* Update layout
* @param {boolean} [updatePosition=false]
* @private
*/
App.InfiniteList.prototype._updateLayout = function _updateLayout(updatePosition)
{
var i = 0,
l = this._items.length,
child = null,
position = 0,
Direction = App.Direction;
if (this._direction === Direction.X)
{
for (;i<l;)
{
child = this._items[i++];
child.x = position;
position = Math.round(position + child.boundingBox.width);
}
if (updatePosition) this._updateX(this.x);
}
else if (this._direction === Direction.Y)
{
for (;i<l;)
{
child = this._items[i++];
child.y = position;
position = Math.round(position + child.boundingBox.height);
}
if (updatePosition) this._updateY(this.y);
}
};
/**
* Test if position passed in falls within this list boundaries
* @param {number} position
* @returns {boolean}
*/
App.InfiniteList.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* Difference between VirtualList and InfiniteList is, that VirtualList doesn't repeat its items infinitely; it just scroll from first model to last.
* Also, if there are less models than items items would fill, then VirtualList will not fill whole size and will not scroll
*
* @class VirtualList
* @extends DisplayObjectContainer
* @param {App.ObjectPool} itemPool
* @param {string} direction
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.VirtualList = function VirtualList(itemPool,direction,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var item = itemPool.allocate(),
itemSize = direction === App.Direction.X ? item.boundingBox.width : item.boundingBox.height;
this.boundingBox = new PIXI.Rectangle(0,0,width,height);
this._model = null;
this._itemPool = itemPool;
this._direction = direction;
this._width = width;
this._height = height;
this._pixelRatio = pixelRatio;
this._items = [];
this._itemSize = itemSize;
this._virtualX = 0;
this._virtualY = 0;
itemPool.release(item);
};
App.VirtualList.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Find and select item under point passed in
* @param {InteractionData} pointerData
*/
App.VirtualList.prototype.getItemUnderPoint = function getItemUnderPoint(pointerData)
{
var position = pointerData.getLocalPosition(this).x,
Direction = App.Direction,
i = 0,
l = this._items.length,
size = 0,
itemPosition = 0,
item = null;
if (this._direction === Direction.X)
{
for (;i<l;)
{
item = this._items[i++];
itemPosition = item.x;
size = item.boundingBox.width;
if (itemPosition <= position && itemPosition + size >= position)
{
return item;
}
}
}
else if (this._direction === Direction.Y)
{
position = pointerData.getLocalPosition(this).y;
for (;i<l;)
{
item = this._items[i++];
itemPosition = item.y;
size = item.boundingBox.height;
if (itemPosition <= position && itemPosition + size >= position)
{
return item;
}
}
}
return null;
};
/**
* Update X position
* @param {number} position
* @private
*/
App.VirtualList.prototype.updateX = function updateX(position)
{
position = Math.round(position);
var i = 0,
l = this._items.length,
positionDifference = position - this._virtualX,
virtualIndex = Math.floor(position / this._itemSize),
itemScreenIndex = 0,
xIndex = 0,
modelIndex = 0,
modelLength = this._model.length,
maxEnd = l - 2,
maxBeginning = modelLength - l,
moveToEnd = false,
moveToBeginning = false,
itemX = 0,
item = null;
this._virtualX = position;
for (;i<l;)
{
item = this._items[i++];
itemX = item.x + positionDifference;
moveToBeginning = itemX > this._width && positionDifference > 0;
moveToEnd = itemX + this._itemSize < 0 && positionDifference < 0;
if (moveToBeginning || moveToEnd)
{
itemScreenIndex = -Math.floor(itemX / this._width);
itemX += itemScreenIndex * l * this._itemSize;
xIndex = Math.floor(itemX / this._itemSize);
if (virtualIndex >= 0) modelIndex = (xIndex - (virtualIndex % modelLength)) % modelLength;
else modelIndex = (xIndex - virtualIndex) % modelLength;
if (modelIndex < 0) modelIndex = modelLength + modelIndex;
else if (modelIndex >= modelLength) modelIndex = modelLength - 1;
if ((moveToEnd && modelIndex > maxEnd) || (moveToBeginning && modelIndex < maxBeginning))
{
item.setModel(this._model[modelIndex]);
}
else
{
itemX = item.x + positionDifference;
}
}
item.x = itemX;
}
};
/**
* Update Y position
* @param {number} position
* @private
*/
App.VirtualList.prototype.updateY = function updateY(position)
{
position = Math.round(position);
var i = 0,
l = this._items.length,
positionDifference = position - this._virtualY,
virtualIndex = Math.floor(position / this._itemSize),
itemScreenIndex = 0,
yIndex = 0,
modelIndex = 0,
modelLength = this._model.length,
maxEnd = l - 2,
maxBeginning = modelLength - l,
moveToEnd = false,
moveToBeginning = false,
itemY = 0,
item = null;
this._virtualY = position;
for (;i<l;)
{
item = this._items[i++];
itemY = item.y + positionDifference;
moveToBeginning = itemY > this._height && positionDifference > 0;
moveToEnd = itemY + this._itemSize < 0 && positionDifference < 0;
if (moveToBeginning || moveToEnd)
{
itemScreenIndex = -Math.floor(itemY / this._height);
itemY += itemScreenIndex * l * this._itemSize;
yIndex = Math.floor(itemY / this._itemSize);
if (virtualIndex >= 0) modelIndex = (yIndex - (virtualIndex % modelLength)) % modelLength;
else modelIndex = (yIndex - virtualIndex) % modelLength;
if (modelIndex < 0) modelIndex = modelLength + modelIndex;
else if (modelIndex >= modelLength) modelIndex = modelLength - 1;
if ((moveToEnd && modelIndex > maxEnd) || (moveToBeginning && modelIndex < maxBeginning))
{
item.setModel(this._model[modelIndex]);
}
else
{
itemY = item.y + positionDifference;
}
}
item.y = itemY;
}
};
/**
* Reset scroll position
*/
App.VirtualList.prototype.reset = function reset()
{
var Direction = App.Direction,
position = 0,
item = null,
i = 0,
l = this._items.length;
if (this._direction === Direction.X)
{
for (;i<l;i++)
{
item = this._items[i];
item.x = position;
item.setModel(this._model[i]);
position = Math.round(position + this._itemSize);
}
}
else if (this._direction === Direction.Y)
{
for (;i<l;i++)
{
item = this._items[i];
item.y = position;
item.setModel(this._model[i]);
position = Math.round(position + this._itemSize);
}
}
};
/**
* Update
* @param {Array.<App.Transaction>} model
*/
App.VirtualList.prototype.update = function update(model)
{
this._model = model;
var Direction = App.Direction,
itemCount = Math.ceil(this._width / this._itemSize) + 1,
listSize = this._model.length * this._itemSize,
item = null,
position = 0,
l = this._items.length,
i = 0;
this.boundingBox.width = listSize;
this.boundingBox.height = this._height;
// Reset scroll
this._virtualX = 0;
this._virtualY = 0;
// Remove items
for (;i<l;i++)
{
this._itemPool.release(this.removeChild(this._items[i]));
this._items[i] = null;
}
this._items.length = 0;
// And add items again, according to model
if (this._direction === Direction.X)
{
if (itemCount > this._model.length) itemCount = this._model.length;
for (i=0,l=itemCount;i<l;i++)
{
item = this._itemPool.allocate();
item.x = position;
item.setModel(this._model[i]);
this._items.push(item);
this.addChild(item);
position = Math.round(position + this._itemSize);
}
}
else if (this._direction === Direction.Y)
{
itemCount = Math.ceil(this._height / this._itemSize) + 1;
this.boundingBox.width = this._width;
this.boundingBox.height = listSize;
if (itemCount > this._model.length) itemCount = this._model.length;
for (i=0,l=itemCount;i<l;i++)
{
item = this._itemPool.allocate();
item.y = position;
item.setModel(this._model[i]);
this._items.push(item);
this.addChild(item);
position = Math.round(position + this._itemSize);
}
}
};
/**
* Update layout
* @param {boolean} [updatePosition=false]
* @private
*/
App.VirtualList.prototype._updateLayout = function _updateLayout(updatePosition)
{
var i = 0,
l = this._items.length,
item = null,
position = 0,
Direction = App.Direction;
if (this._direction === Direction.X)
{
for (;i<l;)
{
item = this._items[i++];
item.x = position;
position = Math.round(position + this._itemSize);
}
if (updatePosition) this.updateX(this.x);
}
else if (this._direction === Direction.Y)
{
for (;i<l;)
{
item = this._items[i++];
item.y = position;
position = Math.round(position + this._itemSize);
}
if (updatePosition) this.updateY(this.y);
}
};
/**
* Return virtual property instead of real one
*
* @property x
* @type Number
*/
Object.defineProperty(App.VirtualList.prototype,'x',{
get: function() {
return this._virtualX;
}
});
/**
* Return virtual property instead of real one
*
* @property y
* @type Number
*/
Object.defineProperty(App.VirtualList.prototype,'y',{
get: function() {
return this._virtualY;
}
});
/**
* @class List
* @extends DisplayObjectContainer
* @param {string} direction
* @constructor
*/
App.List = function List(direction)
{
PIXI.DisplayObjectContainer.call(this);
this.boundingBox = new App.Rectangle();
this._direction = direction;
this._items = [];
};
App.List.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Add item
* @param {DisplayObject} item
* @param {boolean} [updateLayout=false]
* @returns {DisplayObject} returns item added
*/
App.List.prototype.add = function add(item,updateLayout)
{
this._items[this._items.length] = item;
this.addChild(item);
if (updateLayout) this.updateLayout();
return item;
};
/**
* Remove item passed in
* @param {DisplayObject} item
*/
App.List.prototype.remove = function remove(item)
{
this.removeItemAt(this._items.indexOf(item));
};
/**
* Remove item at index passed in
* @param {number} index
*/
App.List.prototype.removeItemAt = function removeItemAt(index)
{
var item = this._items.splice(index,1)[0];
this.removeChild(item);
return item;
};
/**
* Return
* @param {number} index
*/
App.List.prototype.getItemAt = function getItemAt(index)
{
return this._items[index];
};
/**
* Update layout
*/
App.List.prototype.updateLayout = function updateLayout()
{
var i = 0,
l = this._items.length,
item = null,
position = 0,
Direction = App.Direction;
if (this._direction === Direction.X)
{
for (;i<l;)
{
item = this._items[i++];
item.x = position;
position = Math.round(position + item.boundingBox.width);
}
this.boundingBox.width = position;
this.boundingBox.height = item.boundingBox.height;
}
else if (this._direction === Direction.Y)
{
for (;i<l;)
{
item = this._items[i++];
item.y = position;
position = Math.round(position + item.boundingBox.height);
}
this.boundingBox.height = position;
this.boundingBox.width = item.boundingBox.width;
}
};
/**
* Find and return item under point passed in
* @param {InteractionData} data PointerData to get the position from
*/
App.List.prototype.getItemUnderPoint = function getItemUnderPoint(data)
{
var position = data.getLocalPosition(this).x,
boundsProperty = "width",
itemPosition = 0,
itemProperty = "x",
item = null,
i = 0,
l = this._items.length;
if (this._direction === App.Direction.Y)
{
position = data.getLocalPosition(this).y;
itemProperty = "y";
boundsProperty = "height";
}
for (;i<l;)
{
item = this._items[i++];
itemPosition = item[itemProperty];
if (itemPosition <= position && itemPosition + item.boundingBox[boundsProperty] >= position)
{
return item;
}
}
return null;
};
/**
* Test if position passed in falls within this list boundaries
* @param {number} position
* @returns {boolean}
*/
App.List.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* @property length
* @type number
*/
Object.defineProperty(App.List.prototype,'length',{
get:function()
{
return this._items.length;
}
});
/**
* @class TileList
* @extends List
* @param {string} direction
* @param {number} windowSize
* @constructor
*/
App.TileList = function TileList(direction,windowSize)
{
App.List.call(this,direction);
this._windowSize = windowSize;
};
App.TileList.prototype = Object.create(App.List.prototype);
/**
* Update X position
* @param {number} position
*/
App.TileList.prototype.updateX = function updateX(position)
{
this.x = Math.round(position);
var i = 0,
l = this._items.length,
width = 0,
childX = 0,
child = null;
for (;i<l;)
{
child = this._items[i++];
width = child.boundingBox.width;
childX = this.x + child.x;
child.visible = childX + width > 0 && childX < this._windowSize;
}
};
/**
* Update Y position
* @param {number} position
*/
App.TileList.prototype.updateY = function updateY(position)
{
this.y = Math.round(position);
var i = 0,
l = this._items.length,
height = 0,
childY = 0,
child = null;
for (;i<l;)
{
child = this._items[i++];
height = child.boundingBox.height;
childY = this.y + child.y;
child.visible = childY + height > 0 && childY < this._windowSize;
}
};
/**
* Update layout
* @param {boolean} [updatePosition=false]
*/
App.TileList.prototype.updateLayout = function updateLayout(updatePosition)
{
App.List.prototype.updateLayout.call(this);
if (updatePosition)
{
if (this._direction === App.Direction.X) this.updateX(this.x);
else if (this._direction === App.Direction.Y) this.updateY(this.y);
}
};
/**
* @class TilePane
* @extends Pane
* @param {string} xScrollPolicy
* @param {string} yScrollPolicy
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {boolean} useMask
* @constructor
*/
App.TilePane = function TilePane(xScrollPolicy,yScrollPolicy,width,height,pixelRatio,useMask)
{
App.Pane.call(this,xScrollPolicy,yScrollPolicy,width,height,pixelRatio,useMask);
};
App.TilePane.prototype = Object.create(App.Pane.prototype);
/**
* Set content of the pane
*
* @method setContent
* @param {TileList} content
*/
App.TilePane.prototype.setContent = function setContent(content)
{
this.removeContent();
this._content = content;
this._contentHeight = Math.round(this._content.boundingBox.height);
this._contentWidth = Math.round(this._content.boundingBox.width);
this._contentBoundingBox.width = this._contentWidth;
this._contentBoundingBox.height = this._contentHeight;
this.addChildAt(this._content,0);
this._updateScrollers();
if (this._useMask) this._updateMask();
};
/**
* Resize
*
* @param {number} width
* @param {number} height
*/
App.TilePane.prototype.resize = function resize(width,height)
{
this.boundingBox.width = width || this.boundingBox.width;
this.boundingBox.height = height || this.boundingBox.height;
if (this._content)
{
this._contentHeight = Math.round(this._content.boundingBox.height);
this._contentWidth = Math.round(this._content.boundingBox.width);
this._contentBoundingBox.width = this._contentWidth;
this._contentBoundingBox.height = this._contentHeight;
this._checkPosition();
this._updateScrollers();
if (this._useMask) this._updateMask();
}
};
/**
* Update content's x position
* @param {number} position
* @private
*/
App.TilePane.prototype._updateX = function _updateX(position)
{
this._content.updateX(position);
};
/**
* Update content's y position
* @param {number} position
* @private
*/
App.TilePane.prototype._updateY = function _updateY(position)
{
this._content.updateY(position);
};
/**
* @class ViewStack
* @extends DisplayObjectContainer
* @param {Array} children
* @param {boolean} [addToStage=false]
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ViewStack = function ViewStack(children,addToStage,eventListenerPool)
{
PIXI.DisplayObjectContainer.call(this);
this._children = [];
this._selectedChild = null;
this._selectedIndex = -1;
this._childrenToHide = [];
this._eventDispatcher = new App.EventDispatcher(eventListenerPool);
if (children)
{
var i = 0, l = children.length;
for (;i<l;) this.add(children[i++],addToStage);
}
};
App.ViewStack.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Add child to stack
*
* @param {Screen} child
* @param {boolean} [addToStage=false]
*/
App.ViewStack.prototype.add = function add(child,addToStage)
{
this._children[this._children.length] = child;
if (addToStage) this.addChild(child);
};
/**
* Select child
*
* @param {Screen} child
*/
App.ViewStack.prototype.selectChild = function selectChild(child)
{
if (this._selectedChild)
{
if (!child || this._selectedChild === child) return;
this._childrenToHide[this._childrenToHide.length] = this._selectedChild;
}
var i = 0, l = this._children.length;
for (;i<l;)
{
if (child === this._children[i++])
{
this._selectedChild = child;
this._selectedIndex = i - 1;
break;
}
}
this._eventDispatcher.dispatchEvent(App.EventType.CHANGE);
};
/**
* Select child by index passed in
*
* @param {number} index
*/
App.ViewStack.prototype.selectChildByIndex = function selectChildByIndex(index)
{
if (index < 0 || index >= this._children.length) return;
if (this._selectedChild)
{
if (this._selectedChild === this._children[index]) return;
this._childrenToHide[this._childrenToHide.length] = this._selectedChild;
}
this._selectedChild = this._children[index];
this._selectedIndex = index;
this._eventDispatcher.dispatchEvent(App.EventType.CHANGE);
};
/**
* Return selected child
* @returns {Screen}
*/
App.ViewStack.prototype.getSelectedChild = function getSelectedChild()
{
return this._selectedChild;
};
/**
* Return index of selected child
* @returns {number}
*/
App.ViewStack.prototype.getSelectedIndex = function getSelectedIndex()
{
return this._selectedIndex;
};
/**
* Return child by index passed in
* @param {number} index
* @returns {Screen|null}
*/
App.ViewStack.prototype.getChildByIndex = function getChildByIndex(index)
{
if (index < 0 || index >= this._children.length) return null;
return this._children[index];
};
/**
* Show
*/
App.ViewStack.prototype.show = function show()
{
if (this._selectedChild)
{
// First check if the child to show is not actually hiding
var i = 0, l = this._childrenToHide.length;
for (;i<l;i++)
{
if (this._selectedChild === this._childrenToHide[i])
{
this._selectedChild.removeEventListener(App.EventType.COMPLETE,this,this._onHideComplete);
this._childrenToHide.splice(i,1);
break;
}
}
if (!this.contains(this._selectedChild)) this.addChild(this._selectedChild);
this._selectedChild.show();
}
};
/**
* Hide
*/
App.ViewStack.prototype.hide = function hide()
{
var i = 0, l = this._childrenToHide.length, child = null, EventType = App.EventType;
for (;i<l;)
{
child = this._childrenToHide[i++];
child.addEventListener(EventType.COMPLETE,this,this._onHideComplete);
child.hide();
}
};
/**
* On hide complete
* @param {{target:Screen,state:string}} data
* @private
*/
App.ViewStack.prototype._onHideComplete = function _onHideComplete(data)
{
if (data.state === App.TransitionState.HIDDEN)
{
/**@type Screen */
var screen = data.target;
screen.removeEventListener(App.EventType.COMPLETE,this,this._onHideComplete);
if (this.contains(screen)) this.removeChild(screen);
var i = 0, l = this._childrenToHide.length;
for (;i<l;i++)
{
if (screen === this._childrenToHide[i])
{
this._childrenToHide.splice(i,1);
break;
}
}
}
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ViewStack.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ViewStack.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* @class ListHeader
* @param {string} label
* @param {number} width
* @param {number} pixelRatio
* @constructor
*/
App.ListHeader = function ListHeader(label,width,pixelRatio)
{
PIXI.Graphics.call(this);
this._width = width;
this._pixelRatio = pixelRatio;
this._textField = new PIXI.Text(label,App.FontStyle.get(12,App.FontStyle.GREY_DARKER));
this._render();
this.addChild(this._textField);
};
App.ListHeader.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.ListHeader.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
h = Math.round(30 * this._pixelRatio);
GraphicUtils.drawRect(this,ColorTheme.GREY_DARK,1,0,0,this._width,h);
this._textField.x = Math.round((this._width - this._textField.width) / 2);
this._textField.y = Math.round((h - this._textField.height) / 2);
};
/**
* @class AddNewButton
* @extends DisplayObjectContainer
* @param {string} label
* @param {{font:string,fill:string}} fontStyle
* @param {Texture} skin
* @param {number} pixelRatio
* @constructor
*/
App.AddNewButton = function AddNewButton(label,fontStyle,skin,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
this.boundingBox = new App.Rectangle(0,0,skin.width,skin.height);
this._label = label;
this._pixelRatio = pixelRatio;
this._skin = new PIXI.Sprite(skin);
this._icon = PIXI.Sprite.fromFrame("plus-app");
this._iconResizeRatio = Math.round(20 * pixelRatio) / this._icon.height;
this._labelField = new PIXI.Text(label,fontStyle);
this._render();
this.addChild(this._skin);
this.addChild(this._icon);
this.addChild(this._labelField);
};
App.AddNewButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.AddNewButton.prototype._render = function _render()
{
var gap = Math.round(10 * this._pixelRatio),
h = this.boundingBox.height,
position = 0;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
position = Math.round((this.boundingBox.width - (this._labelField.width + gap + this._icon.width)) / 2);
this._icon.x = position;
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = App.ColorTheme.GREY_DARK;
this._labelField.x = position + this._icon.width + gap;
this._labelField.y = Math.round((h - this._labelField.height) / 2);
};
/**
* @class SwipeButton
* @extends DisplayObjectContainer
* @param {number} width
* @param {number} openOffset
* @constructor
*/
App.SwipeButton = function SwipeButton(width,openOffset)
{
PIXI.DisplayObjectContainer.call(this);
this._width = width;
this._interactionEnabled = false;
this._interactiveState = null;
this._dragFriction = 0.5;
this._snapForce = 0.5;
this._openOffset = openOffset;
this._isOpen = false;
this._ticker = App.ModelLocator.getProxy(App.ModelName.TICKER);
};
App.SwipeButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Disable
*/
App.SwipeButton.prototype.disable = function disable()
{
this._disableInteraction();
this.close(true);
};
/**
* Enable interaction
* @private
*/
App.SwipeButton.prototype._enableInteraction = function _enableInteraction()
{
if (!this._interactionEnabled)
{
this._interactionEnabled = true;
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this.interactive = true;
}
};
/**
* Disable interaction
* @private
*/
App.SwipeButton.prototype._disableInteraction = function _disableInteraction()
{
this.interactive = false;
this._interactiveState = null;
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._interactionEnabled = false;
};
/**
* Tick handler
* @private
*/
App.SwipeButton.prototype._onTick = function _onTick()
{
var InteractiveState = App.InteractiveState;
if (this._interactiveState === InteractiveState.SWIPING) this._swipe();
else if (this._interactiveState === InteractiveState.SNAPPING) this._snap();
};
/**
* @method swipeStart
* @param {string} direction
*/
App.SwipeButton.prototype.swipeStart = function swipeStart(direction)
{
var Direction = App.Direction,
InteractiveState = App.InteractiveState;
if (!this._interactiveState)
{
if (!this._isOpen && direction === Direction.LEFT)
{
this._interactiveState = InteractiveState.SWIPING;
this._enableInteraction();
}
else if (this._isOpen && direction === Direction.RIGHT)
{
this._interactiveState = InteractiveState.SNAPPING;
this._enableInteraction();
}
}
};
/**
* @method swipeEnd
*/
App.SwipeButton.prototype.swipeEnd = function swipeEnd()
{
if (this._interactiveState === App.InteractiveState.SWIPING) this._interactiveState = App.InteractiveState.SNAPPING;
};
/**
* @method _swipe
* @private
*/
App.SwipeButton.prototype._swipe = function _swipe()
{
if (this.stage && !this._isOpen)
{
var x = this.stage.getTouchPosition().x;
if (x <= -10000) return;
this._updateSwipePosition(-Math.round(this._width * (1 - (x / this._width)) * this._dragFriction));
}
};
/**
* @method _snap
* @private
*/
App.SwipeButton.prototype._snap = function _snap()
{
var swipePosition = this._getSwipePosition(),
result = Math.round(swipePosition * this._snapForce);
// Snap to open
if (swipePosition < -this._openOffset)
{
if (result >= -this._openOffset)
{
this._isOpen = true;
this._disableInteraction();
this._updateSwipePosition(-this._openOffset);
}
else
{
this._updateSwipePosition(result);
}
}
// Snap to close
else
{
if (result >= -1)
{
this._isOpen = false;
this._disableInteraction();
this._updateSwipePosition(0);
}
else
{
this._updateSwipePosition(result);
}
}
};
/**
* Close Edit button
* @param {boolean} [immediate=false]
*/
App.SwipeButton.prototype.close = function close(immediate)
{
if (this._isOpen)
{
if (immediate)
{
this._updateSwipePosition(0);
this._isOpen = false;
}
else
{
this._interactiveState = App.InteractiveState.SNAPPING;
this._enableInteraction();
}
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.SwipeButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
// Abstract
};
/**
* Return swipe position
* @private
*/
App.SwipeButton.prototype._getSwipePosition = function _getSwipePosition()
{
// Abstract
};
/**
* @class ExpandButton
* @extends DisplayObjectContainer
* @param {number} width
* @param {number} height
* @param {boolean} useMask
* @constructor
*/
App.ExpandButton = function ExpandButton(width,height,useMask)
{
PIXI.DisplayObjectContainer.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
eventListenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
this.boundingBox = new App.Rectangle(0,0,width,height);
this._content = null;
this._contentHeight = height;
this._buttonHeight = height;
this._useMask = useMask;
this._updateBoundsInTransition = false;
this._eventsRegistered = false;
this._transitionState = App.TransitionState.CLOSED;
this._expandTween = new App.TweenProxy(0.4,App.Easing.outExpo,0,eventListenerPool);
this._eventDispatcher = new App.EventDispatcher(eventListenerPool);
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
if (this._useMask)
{
this._mask = new PIXI.Graphics();
this.mask = this._mask;
this._updateMask();
this.addChild(this._mask);
}
};
App.ExpandButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Set content
* @param {Object} content
* @private
*/
App.ExpandButton.prototype._setContent = function _setContent(content)
{
this._content = content;
this._contentHeight = this._content.boundingBox ? this._content.boundingBox.height : this._content.height;
this._content.visible = false;
this._content.y = this._buttonHeight;
};
/**
* Enable interaction
* @private
*/
App.ExpandButton.prototype._registerEventListeners = function _registerEventListeners()
{
if (!this._eventsRegistered)
{
this._eventsRegistered = true;
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._expandTween.addEventListener(App.EventType.COMPLETE,this,this._onTransitionComplete);
}
};
/**
* Disable interaction
* @private
*/
App.ExpandButton.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
this._expandTween.removeEventListener(App.EventType.COMPLETE,this,this._onTransitionComplete);
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._eventsRegistered = false;
};
/**
* Tick handler
* @private
*/
App.ExpandButton.prototype._onTick = function _onTick()
{
if (this._expandTween.isRunning()) this._updateTransition();
};
/**
* Update transition
* @private
*/
App.ExpandButton.prototype._updateTransition = function _updateTransition()
{
this._updateBounds(this._updateBoundsInTransition);
if (this._useMask) this._updateMask();
};
/**
* On transition complete
* @private
*/
App.ExpandButton.prototype._onTransitionComplete = function _onTransitionComplete()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.OPENING)
{
this._transitionState = TransitionState.OPEN;
}
else if (this._transitionState === TransitionState.CLOSING)
{
this._transitionState = TransitionState.CLOSED;
this._content.visible = false;
}
this._unRegisterEventListeners();
this._updateBounds(this._updateBoundsInTransition);
if (this._useMask) this._updateMask();
if (!this.isInTransition())
{
this._updateBoundsInTransition = false;
this._eventDispatcher.dispatchEvent(App.EventType.COMPLETE,this);
}
};
/**
* Update bounds
* @param {boolean} [updateContent=false]
* @private
*/
App.ExpandButton.prototype._updateBounds = function _updateBounds(updateContent)
{
var TransitionState = App.TransitionState;
if (updateContent)
{
this._contentHeight = this._content.boundingBox ? this._content.boundingBox.height : this._content.height;
}
if (this._transitionState === TransitionState.OPENING)
{
this.boundingBox.height = Math.round(this._buttonHeight + this._contentHeight * this._expandTween.progress);
}
else if (this._transitionState === TransitionState.OPEN)
{
this.boundingBox.height = this._buttonHeight + this._contentHeight;
}
else if (this._transitionState === TransitionState.CLOSING)
{
this.boundingBox.height = Math.round(this._buttonHeight + this._contentHeight * (1 - this._expandTween.progress));
}
else if (this._transitionState === TransitionState.CLOSED)
{
this.boundingBox.height = this._buttonHeight;
}
};
/**
* Re-draw mask
* @private
*/
App.ExpandButton.prototype._updateMask = function _updateMask()
{
App.GraphicUtils.drawRect(this._mask,0xff0000,1,0,0,this.boundingBox.width,this.boundingBox.height);
};
/**
* Click handler
* @param {Point} position
*/
App.ExpandButton.prototype.onClick = function onClick(position)
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.CLOSED || this._transitionState === TransitionState.CLOSING) this.open();
else if (this._transitionState === TransitionState.OPEN || this._transitionState === TransitionState.OPENING) this.close();
};
/**
* Check if its open
* @returns {boolean}
*/
App.ExpandButton.prototype.isOpen = function isOpen()
{
return this._transitionState !== App.TransitionState.CLOSED;
};
/**
* Check if its opening
* @returns {boolean}
*/
App.ExpandButton.prototype.isOpening = function isOpening()
{
return this._transitionState === App.TransitionState.OPENING;
};
/**
* Check if button is in transition
* @returns {boolean}
*/
App.ExpandButton.prototype.isInTransition = function isInTransition()
{
return this._transitionState === App.TransitionState.OPENING || this._transitionState === App.TransitionState.CLOSING;
};
/**
* Open
* @param {boolean} [updateBounds=false]
*/
App.ExpandButton.prototype.open = function open(updateBounds)
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.CLOSED || this._transitionState === TransitionState.CLOSING)
{
this._registerEventListeners();
this._content.visible = true;
this._transitionState = TransitionState.OPENING;
this._updateBoundsInTransition = updateBounds;
this._expandTween.restart();
}
};
/**
* Close
* @param {boolean} [immediate=false]
* @param {boolean} [updateBounds=false]
*/
App.ExpandButton.prototype.close = function close(immediate,updateBounds)
{
var TransitionState = App.TransitionState,
EventType = App.EventType;
if (immediate)
{
this._transitionState = TransitionState.CLOSING;
this._updateBoundsInTransition = updateBounds;
this._expandTween.stop();
this._onTransitionComplete();
}
else
{
if (this._transitionState === TransitionState.OPEN || this._transitionState === TransitionState.OPENING)
{
this._registerEventListeners();
this._transitionState = TransitionState.CLOSING;
this._updateBoundsInTransition = updateBounds;
this._expandTween.start(true);
}
else
{
// Already closed - but dispatch event so parent can cancel its processes
this._eventDispatcher.dispatchEvent(EventType.COMPLETE,this);
}
}
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ExpandButton.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ExpandButton.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* @class PopUpButton
* @extend DisplayObjectContainer
* @param {string} label
* @param {string} message
* @param {{width:number,height:number,pixelRatio:number,popUpLayout:{x:number,y:number,width:number,height:number,overlayWidth:number,overlayHeight:number}}} options
* @constructor
*/
App.PopUpButton = function PopUpButton(label,message,options)
{
PIXI.DisplayObjectContainer.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
Button = App.Button,
Graphics = PIXI.Graphics,
FontStyle = App.FontStyle,
ColorTheme = App.ColorTheme,
r = options.pixelRatio,
w = options.width;
this.boundingBox = new App.Rectangle(0,0,w,options.height);
this._pixelRatio = r;
this._popUpLayout = options.popUpLayout;
this._backgroundColor = ColorTheme.RED;
this._transitionState = App.TransitionState.HIDDEN;
this._eventsRegistered = App.EventLevel.NONE;
this._overlay = this.addChild(new Graphics());
this._container = this.addChild(new Graphics());
this._popUpBackground = this._container.addChild(new Graphics());
this._labelField = this._container.addChild(new PIXI.Text(label,FontStyle.get(18,FontStyle.WHITE)));
this._messageField = this._container.addChild(new PIXI.Text(message,FontStyle.get(18,FontStyle.BLUE,"center",FontStyle.LIGHT_CONDENSED)));
this._cancelButton = this._container.addChild(new Button("Cancel",{
width:w,
height:Math.round(50*r),
pixelRatio:r,
style:FontStyle.get(18,FontStyle.BLACK_LIGHT,null,FontStyle.LIGHT_CONDENSED),
backgroundColor:ColorTheme.GREY_DARK
}));
this._confirmButton = this._container.addChild(new Button("Delete",{
width:w,
height:Math.round(30*r),
pixelRatio:r,
style:FontStyle.get(16,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
backgroundColor:ColorTheme.RED
}));
this._containerMask = this._container.addChild(new Graphics());
this._container.mask = this._containerMask;
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._eventDispatcher = new App.EventDispatcher(ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL));
this._tween = new App.TweenProxy(0.3,App.Easing.outExpo,0,ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL));
this._updateLayout(0);
};
App.PopUpButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Set position
* @param {number} x
* @param {number} y
*/
App.PopUpButton.prototype.setPosition = function setPosition(x,y)
{
this.boundingBox.x = x;
this.boundingBox.y = y;
this.x = x;
this.y = y;
this._overlay.x = -x;
this._overlay.y = -y;
};
/**
* Set message
* @param {string} message
*/
App.PopUpButton.prototype.setMessage = function setMessage(message)
{
this._messageField.setText(message);
};
/**
* Set popUp layout
* @param {number} x
* @param {number} y
* @param {number} overlayWidth
* @param {number} overlayHeight
* @param {number} width
* @param {number} height
*/
App.PopUpButton.prototype.setPopUpLayout = function setPopUpLayout(x,y,overlayWidth,overlayHeight,width,height)
{
this._popUpLayout.overlayWidth = overlayWidth || this._popUpLayout.overlayWidth;
this._popUpLayout.overlayHeight = overlayHeight || this._popUpLayout.overlayHeight;
this._popUpLayout.width = width || this._popUpLayout.width;
this._popUpLayout.height = height || this._popUpLayout.height;
this._popUpLayout.x = x || this._popUpLayout.x;
this._popUpLayout.y = this._popUpLayout.height / 2 - this.boundingBox.y - y;
};
/**
* Show popUp
*/
App.PopUpButton.prototype.showPopUp = function showPopUp()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.HIDDEN || this._transitionState === TransitionState.HIDING)
{
this._registerEventListeners(App.EventLevel.LEVEL_1);
this._onShowStart();
this._transitionState = TransitionState.SHOWING;
this._tween.restart();
}
};
/**
* Hide popUp
* @param {boolean} immediate
*/
App.PopUpButton.prototype.hidePopUp = function hidePopUp(immediate)
{
var TransitionState = App.TransitionState;
if (immediate)
{
this._unRegisterEventListeners(App.EventLevel.LEVEL_2);
this._transitionState = TransitionState.HIDDEN;
this._tween.stop();
this._updateLayout(0);
this._onHideComplete();
}
else
{
if (this._transitionState === TransitionState.SHOWN || this._transitionState === TransitionState.SHOWING)
{
this._unRegisterEventListeners(App.EventLevel.LEVEL_2);
this._transitionState = TransitionState.HIDING;
this._tween.start(true);
}
}
};
/**
* Register event listeners
* @param {number} level
* @private
*/
App.PopUpButton.prototype._registerEventListeners = function _registerEventListeners(level)
{
var EventLevel = App.EventLevel;
if (level === EventLevel.LEVEL_1 && this._eventsRegistered !== EventLevel.LEVEL_1)
{
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._tween.addEventListener(App.EventType.COMPLETE,this,this._onTweenComplete);
}
if (level === EventLevel.LEVEL_2 && this._eventsRegistered !== EventLevel.LEVEL_2)
{
if (App.Device.TOUCH_SUPPORTED) this.tap = this._onClick;
else this.click = this._onClick;
this.interactive = true;
}
this._eventsRegistered = level;
};
/**
* UnRegister event listeners
* @param {number} level
* @private
*/
App.PopUpButton.prototype._unRegisterEventListeners = function _unRegisterEventListeners(level)
{
var EventLevel = App.EventLevel;
if (level === EventLevel.LEVEL_1)
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._tween.removeEventListener(App.EventType.COMPLETE,this,this._onTweenComplete);
this._eventsRegistered = EventLevel.NONE;
}
if (level === EventLevel.LEVEL_2)
{
this.interactive = false;
if (App.Device.TOUCH_SUPPORTED) this.tap = null;
else this.click = null;
this._eventsRegistered = EventLevel.LEVEL_1;
}
};
/**
* Click handler
* @param {PIXI.InteractionData} data
* @private
*/
App.PopUpButton.prototype._onClick = function _onClick(data)
{
var position = this.stage.getTouchData().getLocalPosition(this._container);
if (this._cancelButton.hitTest(position)) this._eventDispatcher.dispatchEvent(App.EventType.CANCEL);
else if (this._confirmButton.hitTest(position)) this._eventDispatcher.dispatchEvent(App.EventType.CONFIRM);
};
/**
* On tick
* @private
*/
App.PopUpButton.prototype._onTick = function _onTick()
{
if (this._tween.isRunning())
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWING) this._updateLayout(this._tween.progress);
else if (this._transitionState === TransitionState.HIDING) this._updateLayout(1.0 - this._tween.progress);
}
};
/**
* On show start
* @private
*/
App.PopUpButton.prototype._onShowStart = function _onShowStart()
{
var padding = Math.round(10 * this._pixelRatio);
this._cancelButton.x = padding;
this._confirmButton.x = padding;
App.GraphicUtils.drawRect(this._overlay,App.ColorTheme.BLUE,1,0,0,this._popUpLayout.overlayWidth,this._popUpLayout.overlayHeight);
this._overlay.alpha = 0.0;
this._overlay.visible = true;
this._popUpBackground.alpha = 0.0;
this._popUpBackground.visible = true;
this._messageField.alpha = 0.0;
this._messageField.visible = true;
this._cancelButton.alpha = 0.0;
this._cancelButton.visible = true;
this._confirmButton.alpha = 0.0;
this._confirmButton.visible = true;
};
/**
* Update layout
* @param {number} progress
* @private
*/
App.PopUpButton.prototype._updateLayout = function _updateLayout(progress)
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._pixelRatio,
bw = this.boundingBox.width,
bh = this.boundingBox.height,
w = Math.round(bw + (this._popUpLayout.width - bw) * progress),
h = Math.round(bh + (this._popUpLayout.height - bh) * progress),
padding = Math.round(10 * r),
radius = Math.round(5 * r),
buttonWidth = Math.round(w - padding * 2),
buttonsHeight = this._cancelButton.boundingBox.height + this._confirmButton.boundingBox.height + padding;
GraphicUtils.drawRect(this._containerMask,ColorTheme.BLACK,1,0,0,w,h);
GraphicUtils.drawRoundedRect(this._container,ColorTheme.RED,1,0,0,w,h,radius);
GraphicUtils.drawRoundedRect(this._popUpBackground,ColorTheme.GREY,1,0,0,w,h,radius);
this._container.x = Math.round(this._popUpLayout.x * progress);
this._container.y = Math.round(this._popUpLayout.y * progress);
this._cancelButton.resize(buttonWidth);
this._cancelButton.y = h - buttonsHeight - padding;
this._confirmButton.resize(buttonWidth);
this._confirmButton.y = this._cancelButton.y + this._cancelButton.boundingBox.height + padding;
this._labelField.x = Math.round((w - this._labelField.width) / 2);
this._labelField.y = Math.round((h - this._labelField.height) / 2);
this._messageField.x = Math.round((w - this._messageField.width) / 2);
this._messageField.y = Math.round((h - buttonsHeight - padding - this._messageField.height) / 2);
this._overlay.alpha = 0.8 * progress;
this._popUpBackground.alpha = progress;
this._messageField.alpha = progress;
this._cancelButton.alpha = progress;
this._confirmButton.alpha = progress;
this._labelField.alpha = 1.0 - progress;
};
/**
* On tween complete
* @private
*/
App.PopUpButton.prototype._onTweenComplete = function _onTweenComplete()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWING)
{
this._transitionState = TransitionState.SHOWN;
this._registerEventListeners(App.EventLevel.LEVEL_2);
this._updateLayout(1);
}
else if (this._transitionState === TransitionState.HIDING)
{
this._transitionState = TransitionState.HIDDEN;
this._updateLayout(0);
this._onHideComplete();
}
};
/**
* On hide complete
* @private
*/
App.PopUpButton.prototype._onHideComplete = function _onHideComplete()
{
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
this._overlay.visible = false;
this._popUpBackground.visible = false;
this._messageField.visible = false;
this._cancelButton.visible = false;
this._confirmButton.visible = false;
this._eventDispatcher.dispatchEvent(App.EventType.COMPLETE,{target:this,state:this._transitionState});
};
/**
* Test if position passed in falls within this input boundaries
* @param {number} position
* @returns {boolean}
*/
App.PopUpButton.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.PopUpButton.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.PopUpButton.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* Abstract Screen
*
* @class Screen
* @extends DisplayObjectContainer
* @param {Object} layout
* @param {number} tweenDuration
* @constructor
*/
App.Screen = function Screen(layout,tweenDuration)
{
PIXI.DisplayObjectContainer.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
pixelRatio = layout.pixelRatio;
this._model = null;
this._layout = layout;
this._enabled = false;
this._eventsRegistered = App.EventLevel.NONE;
this._transitionState = App.TransitionState.HIDDEN;
this._interactiveState = null;
this._mouseDownPosition = null;
this._mouseX = 0.0;
this._mouseY = 0.0;
this._leftSwipeThreshold = 15 * pixelRatio;
this._rightSwipeThreshold = 5 * pixelRatio;
this._clickThreshold = 5 * pixelRatio;
this._swipeEnabled = false;
this._preferScroll = true;
this._mode = App.ScreenMode.DEFAULT;
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._eventDispatcher = new App.EventDispatcher(ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL));
this._showHideTween = new App.TweenProxy(tweenDuration,App.Easing.outExpo,0,ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL));
this.alpha = 0.0;
};
App.Screen.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Show
*/
App.Screen.prototype.show = function show()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.HIDDEN || this._transitionState === TransitionState.HIDING)
{
this.enable();
this._transitionState = TransitionState.SHOWING;
this._showHideTween.restart();
this.visible = true;
}
};
/**
* Hide
*/
App.Screen.prototype.hide = function hide()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWN || this._transitionState === TransitionState.SHOWING)
{
this.disable();
this._transitionState = TransitionState.HIDING;
this._showHideTween.start(true);
}
};
/**
* Enable
*/
App.Screen.prototype.enable = function enable()
{
if (!this._enabled)
{
this._registerEventListeners(App.EventLevel.LEVEL_1);
this._enabled = true;
}
};
/**
* Disable
*/
App.Screen.prototype.disable = function disable()
{
this._unRegisterEventListeners(App.EventLevel.LEVEL_2);
this._enabled = false;
this._interactiveState = null;
};
/**
* Update
*/
App.Screen.prototype.update = function update(data,mode)
{
this._mode = mode;
//TODO mark layout/UI as 'dirty' and update/render on Tick event
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Screen.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Screen.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* Register event listeners
* @param {number} level
* @private
*/
App.Screen.prototype._registerEventListeners = function _registerEventListeners(level)
{
var EventLevel = App.EventLevel;
if (level === EventLevel.LEVEL_1 && this._eventsRegistered !== EventLevel.LEVEL_1)
{
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._showHideTween.addEventListener(App.EventType.COMPLETE,this,this._onTweenComplete);
}
if (level === EventLevel.LEVEL_2 && this._eventsRegistered !== EventLevel.LEVEL_2)
{
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = this._onPointerDown;
this.touchend = this._onPointerUp;
this.touchendoutside = this._onPointerUp;
}
else
{
this.mousedown = this._onPointerDown;
this.mouseup = this._onPointerUp;
this.mouseupoutside = this._onPointerUp;
}
App.ViewLocator.getViewSegment(App.ViewName.HEADER).addEventListener(App.EventType.CLICK,this,this._onHeaderClick);
this.interactive = true;
}
this._eventsRegistered = level;
};
/**
* UnRegister event listeners
* @param {number} level
* @private
*/
App.Screen.prototype._unRegisterEventListeners = function _unRegisterEventListeners(level)
{
var EventLevel = App.EventLevel;
if (level === EventLevel.LEVEL_1)
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._showHideTween.removeEventListener(App.EventType.COMPLETE,this,this._onTweenComplete);
this._eventsRegistered = EventLevel.NONE;
}
if (level === EventLevel.LEVEL_2)
{
this.interactive = false;
App.ViewLocator.getViewSegment(App.ViewName.HEADER).removeEventListener(App.EventType.CLICK,this,this._onHeaderClick);
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = null;
this.touchend = null;
this.touchendoutside = null;
}
else
{
this.mousedown = null;
this.mouseup = null;
this.mouseupoutside = null;
}
this._eventsRegistered = EventLevel.LEVEL_1;
}
};
/**
* On tick
* @private
*/
App.Screen.prototype._onTick = function _onTick()
{
if (this._showHideTween.isRunning())
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWING) this.alpha = this._showHideTween.progress;
else if (this._transitionState === TransitionState.HIDING) this.alpha = 1.0 - this._showHideTween.progress;
}
if (this._swipeEnabled && this._interactiveState === App.InteractiveState.DRAGGING) this._drag();
};
/**
* On tween complete
* @private
*/
App.Screen.prototype._onTweenComplete = function _onTweenComplete()
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.SHOWING)
{
this._transitionState = TransitionState.SHOWN;
this.alpha = 1.0;
this._registerEventListeners(App.EventLevel.LEVEL_2);
}
else if (this._transitionState === TransitionState.HIDING)
{
this._transitionState = TransitionState.HIDDEN;
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
this.alpha = 0.0;
this.visible = false;
this._eventDispatcher.dispatchEvent(App.EventType.COMPLETE,{target:this,state:this._transitionState});
}
};
/**
* On pointer down
*
* @param {Object} data
* @private
*/
App.Screen.prototype._onPointerDown = function _onPointerDown(data)
{
if (this.stage)
{
this._mouseDownPosition = data.getLocalPosition(this.stage);
this._mouseX = this._mouseDownPosition.x;
this._mouseY = this._mouseDownPosition.y;
}
if (this._swipeEnabled) this._interactiveState = App.InteractiveState.DRAGGING;
};
/**
* On pointer up
* @param {Object} data
* @private
*/
App.Screen.prototype._onPointerUp = function _onPointerUp(data)
{
if (this._swipeEnabled)
{
if (this._interactiveState === App.InteractiveState.SWIPING) this._swipeEnd();
this._interactiveState = null;
}
if (this.stage && this._mouseDownPosition && this._enabled)
{
var oldX = this._mouseDownPosition.x,
oldY = this._mouseDownPosition.y;
this._mouseDownPosition = data.getLocalPosition(this.stage,this._mouseDownPosition);
var dx = oldX - this._mouseDownPosition.x,
dy = oldY - this._mouseDownPosition.y,
dist = dx * dx - dy * dy,
TransitionState = App.TransitionState;
if (Math.abs(dist) < this._clickThreshold && (this._transitionState === TransitionState.SHOWING || this._transitionState === TransitionState.SHOWN)) this._onClick();
this._mouseDownPosition = null;
}
};
/**
* Drag
* @private
*/
App.Screen.prototype._drag = function _drag()
{
var InteractiveState = App.InteractiveState;
if (this._interactiveState === InteractiveState.DRAGGING)
{
if (this.stage && this._mouseX)
{
var position = this.stage.getTouchPosition(),
newX = position.x,
newY = position.y;
if (this._mouseX - newX > this._leftSwipeThreshold)
{
this._interactiveState = InteractiveState.SWIPING;
this._swipeStart(Math.abs(this._mouseY-newY) > Math.abs(this._mouseX-newX) && this._preferScroll,App.Direction.LEFT);
}
else if (newX - this._mouseX > this._rightSwipeThreshold)
{
this._interactiveState = InteractiveState.SWIPING;
this._swipeStart(Math.abs(this._mouseY-newY) > Math.abs(this._mouseX-newX) && this._preferScroll,App.Direction.RIGHT);
}
this._mouseX = newX;
this._mouseY = newY;
}
}
};
/**
* Click handler
* @private
*/
App.Screen.prototype._onClick = function _onClick()
{
this._eventDispatcher.dispatchEvent(App.EventType.CLICK);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.Screen.prototype._onHeaderClick = function _onHeaderClick(action)
{
// Abstract
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @private
*/
App.Screen.prototype._swipeStart = function _swipeStart(preferScroll)
{
// Abstract
};
/**
* Called when swipe ends
* @param {string} direction
* @private
*/
App.Screen.prototype._swipeEnd = function _swipeEnd(direction)
{
// Abstract
};
/**
* @class EditScreen
* @param {Object} layout
* @constructor
*/
App.EditScreen = function EditScreen(layout)
{
App.Screen.call(this,layout,0.4);
var r = layout.pixelRatio,
inputWidth = layout.width - Math.round(20 * r),
inputHeight = Math.round(40 * r);
this._target = null;
this._background = this.addChild(new PIXI.Graphics());
this._input = this.addChild(new App.Input("",20,inputWidth,inputHeight,r,true));
this._deleteButton = new App.PopUpButton("Delete","",{
width:inputWidth,
height:inputHeight,
pixelRatio:r,
popUpLayout:{x:Math.round(10*r),y:0,width:Math.round(inputWidth-20*r),height:Math.round(layout.height/2),overlayWidth:layout.width,overlayHeight:0}
});
this._renderAll = true;
};
App.EditScreen.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.EditScreen.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
ScreenMode = App.ScreenMode,
r = this._layout.pixelRatio,
padding = Math.round(10 * r),
inputHeight = Math.round(60 * r),
w = this._layout.width - padding * 2;
if (this._renderAll)
{
this._renderAll = false;
this._input.x = padding;
this._input.y = padding;
this._deleteButton.setPosition(padding,inputHeight+padding);
}
if (this._mode === ScreenMode.EDIT)
{
if (!this.contains(this._deleteButton)) this.addChild(this._deleteButton);
//TODO use skin
GraphicUtils.drawRects(this._background,ColorTheme.GREY,1,[0,0,w+padding*2,inputHeight*2],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_DARK,1,[padding,inputHeight-1,w,1],false,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_LIGHT,1,[padding,inputHeight,w,1],false,true);
}
else if (this._mode === ScreenMode.ADD)
{
if (this.contains(this._deleteButton)) this.removeChild(this._deleteButton);
GraphicUtils.drawRect(this._background,ColorTheme.GREY,1,0,0,w+padding*2,inputHeight);
}
};
/**
* Hide
*/
App.EditScreen.prototype.hide = function hide()
{
this._unRegisterDeleteButtonListeners();
App.Screen.prototype.hide.call(this);
};
/**
* Enable
*/
App.EditScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._input.enable();
};
/**
* Disable
*/
App.EditScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._input.disable();
};
/**
* Update
* @param {{category:App.Category,subCategory:App.SubCategory}} model
* @param {string} mode
*/
App.EditScreen.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._target = this._model instanceof App.Account ? App.Account : App.SubCategory;
this._deleteButton.hidePopUp(true);
if (this._target === App.Account)
{
this._input.setValue(this._model.name);
this._deleteButton.setMessage("Are you sure you want to\ndelete this account with all its\ndata and categories?");
}
else if (this._target === App.SubCategory && this._model.subCategory)
{
this._input.setValue(this._model.subCategory.name);
this._deleteButton.setMessage("Are you sure you want to\ndelete this sub-category?");
}
this._render();
};
/**
* Register delete button event listeners
* @private
*/
App.EditScreen.prototype._registerDeleteButtonListeners = function _registerDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.addEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.addEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.addEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* UnRegister delete button event listeners
* @private
*/
App.EditScreen.prototype._unRegisterDeleteButtonListeners = function _unRegisterDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.removeEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.removeEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.removeEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* On delete cancel
* @private
*/
App.EditScreen.prototype._onDeleteCancel = function _onDeleteCancel()
{
this._deleteButton.hidePopUp();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
};
/**
* On delete confirm
* @private
*/
App.EditScreen.prototype._onDeleteConfirm = function _onDeleteConfirm()
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
this._onHidePopUpComplete();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
changeScreenData.updateBackScreen = true;
if (this._target === App.Account)
{
App.Controller.dispatchEvent(EventType.CHANGE_ACCOUNT,{
type:EventType.DELETE,
account:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else if (this._target === App.SubCategory)
{
App.Controller.dispatchEvent(EventType.CHANGE_SUB_CATEGORY,{
type:EventType.DELETE,
subCategory:this._model.subCategory,
category:this._model.category,
nextCommand:new App.ChangeCategory(),
nextCommandData:{
type:EventType.CHANGE,
category:this._model.category,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
}
});
}
};
/**
* On Delete PopUp hide complete
* @private
*/
App.EditScreen.prototype._onHidePopUpComplete = function _onHidePopUpComplete()
{
this._unRegisterDeleteButtonListeners();
this.enable();
this._registerEventListeners(App.EventLevel.LEVEL_2);
};
/**
* Click handler
* @private
*/
App.EditScreen.prototype._onClick = function _onClick()
{
if (this._deleteButton.hitTest(this.stage.getTouchData().getLocalPosition(this).y))
{
if (this._input.isFocused())
{
this._input.blur();
}
else
{
this.disable();
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
App.ViewLocator.getViewSegment(App.ViewName.HEADER).disableActions();
this._registerDeleteButtonListeners();
this._deleteButton.setPopUpLayout(0,this._layout.headerHeight,0,this._layout.contentHeight > this._background.height ? this._layout.contentHeight : this._background.height);
this._deleteButton.showPopUp();
}
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.EditScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
this._input.blur();
//TODO check first if value is set
if (action === App.HeaderAction.CONFIRM)
{
changeScreenData.updateBackScreen = true;
if (this._target === App.Account)
{
App.Controller.dispatchEvent(EventType.CHANGE_ACCOUNT,{
type:EventType.CHANGE,
account:this._model,
name:this._input.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else if (this._target === App.SubCategory)
{
App.Controller.dispatchEvent(EventType.CHANGE_SUB_CATEGORY,{
type:EventType.CHANGE,
subCategory:this._model.subCategory,
category:this._model.category,
name:this._input.getValue(),
nextCommand:new App.ChangeCategory(),
nextCommandData:{
type:EventType.CHANGE,
category:this._model.category,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
}
});
}
}
else if (action === App.HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(EventType.CHANGE_SCREEN,changeScreenData);
}
};
/**
* @class InputScrollScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.InputScrollScreen = function InputScrollScreen(layout)
{
App.Screen.call(this,layout,0.4);
//TODO also disable header actions if input is focused and soft keyboard shown
//TODO add other 'scroll-' properties into TweenProxy?
this._scrollTween = new App.TweenProxy(0.5,App.Easing.outExpo,0,App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
this._scrollState = App.TransitionState.HIDDEN;
this._scrollInput = null;
this._scrollPosition = 0;
this._inputPadding = Math.round(10 * layout.pixelRatio);
};
App.InputScrollScreen.prototype = Object.create(App.Screen.prototype);
/**
* On tick
* @private
*/
App.InputScrollScreen.prototype._onTick = function _onTick()
{
App.Screen.prototype._onTick.call(this);
if (this._scrollTween.isRunning()) this._onScrollTweenUpdate();
};
/**
* On scroll tween update
* @private
*/
App.InputScrollScreen.prototype._onScrollTweenUpdate = function _onScrollTweenUpdate()
{
var TransitionState = App.TransitionState;
if (this._scrollState === TransitionState.SHOWING)
{
this._pane.y = -Math.round((this._scrollPosition + this._container.y) * this._scrollTween.progress);
}
else if (this._scrollState === TransitionState.HIDING)
{
this._pane.y = -Math.round((this._scrollPosition + this._container.y) * (1 - this._scrollTween.progress));
}
};
/**
* On scroll tween complete
* @private
*/
App.InputScrollScreen.prototype._onScrollTweenComplete = function _onScrollTweenComplete()
{
var TransitionState = App.TransitionState;
this._onScrollTweenUpdate();
if (this._scrollState === TransitionState.SHOWING)
{
this._scrollState = TransitionState.SHOWN;
this._scrollInput.enable();
this._scrollInput.focus();
}
else if (this._scrollState === TransitionState.HIDING)
{
this._scrollState = TransitionState.HIDDEN;
this._pane.enable();
App.ViewLocator.getViewSegment(App.ViewName.APPLICATION_VIEW).scrollTo(0);
}
};
/**
* Focus budget
* @param {boolean} [immediate=false] Flag if input should be focused immediately without tweening
* @private
*/
App.InputScrollScreen.prototype._focusInput = function _focusInput(immediate)
{
var TransitionState = App.TransitionState;
if (this._scrollState === TransitionState.HIDDEN || this._scrollState === TransitionState.HIDING)
{
this._scrollState = TransitionState.SHOWING;
this._pane.disable();
if (immediate)
{
this._scrollPosition = 0;
this._onScrollTweenComplete();
}
else
{
this._scrollPosition = this._scrollInput.y - this._inputPadding;
this._scrollTween.start();
}
}
};
/**
* On budget field blur
* @private
*/
App.InputScrollScreen.prototype._onInputBlur = function _onInputBlur()
{
var TransitionState = App.TransitionState;
if (this._scrollState === TransitionState.SHOWN || this._scrollState === TransitionState.SHOWING)
{
this._scrollState = TransitionState.HIDING;
this._scrollInput.disable();
if (this._scrollPosition > 0)
{
this._scrollTween.restart();
}
else
{
this._pane.resetScroll();
this._onScrollTweenComplete();
}
}
};
/**
* Reset screen scroll
*/
App.InputScrollScreen.prototype.resetScroll = function resetScroll()
{
if (this._scrollInput) this._scrollInput.blur();
this._scrollTween.stop();
this._pane.y = 0;
this._pane.resetScroll();
App.ViewLocator.getViewSegment(App.ViewName.APPLICATION_VIEW).scrollTo(0);
};
/**
* @class TransactionToggleButton
* @extends Button
* @param {string} iconName
* @param {string} label
* @param {{width:number,height:number,pixelRatio:number,style:Object,toggleStyle:Object}} options
* @param {{icon:string,label:string,toggleColor:boolean}} toggleOptions
* @constructor
*/
App.TransactionToggleButton = function TransactionToggleButton(iconName,label,options,toggleOptions)
{
this._iconName = iconName;
this._toggleStyle = options.toggleStyle;
this._toggleOptions = toggleOptions;
this._icon = PIXI.Sprite.fromFrame(iconName);
this._selected = false;
this._iconResizeRatio = Math.round(20 * options.pixelRatio) / this._icon.height;
App.Button.call(this,label,options);
this._render(true);
this.addChild(this._icon);
};
App.TransactionToggleButton.prototype = Object.create(App.Button.prototype);
/**
* Render
* @param {boolean} [updateAll=false]
* @private
*/
App.TransactionToggleButton.prototype._render = function _render(updateAll)
{
var r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
gap = Math.round(10 * r),
padding = Math.round(5 * r);
if (this._selected)
{
if (this._toggleOptions.icon) this._icon.setTexture(PIXI.TextureCache[this._toggleOptions.icon]);
if (this._toggleOptions.label) this._labelField.setText(this._toggleOptions.label);
if (this._toggleOptions.toggleColor)
{
this._icon.tint = 0xFFFFFE;
this._labelField.setStyle(this._toggleStyle);
this.clear();
this.beginFill(App.ColorTheme.BLUE);
this.drawRoundedRect(padding,padding,w-padding*2,h-padding*2,padding);
this.endFill();
}
}
else
{
if (this._toggleOptions.icon) this._icon.setTexture(PIXI.TextureCache[this._iconName]);
if (this._toggleOptions.label) this._labelField.setText(this._label);
if (this._toggleOptions.toggleColor)
{
this._icon.tint = App.ColorTheme.BLUE;
this._labelField.setStyle(this._style);
this.clear();
}
}
if (updateAll)
{
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = App.ColorTheme.BLUE;
this._labelField.y = Math.round((h - this._labelField.height) / 2);
}
this._icon.x = Math.round((w - this._icon.width - gap - this._labelField.width) / 2);
this._labelField.x = Math.round(this._icon.x + this._icon.width + gap);
};
/**
* Toggle
*/
App.TransactionToggleButton.prototype.toggle = function toggle()
{
this._selected = !this._selected;
this._render(false);
};
/**
* Set selection state
* @param {boolean} value
*/
App.TransactionToggleButton.prototype.setState = function setState(value)
{
this._selected = value;
this._render(false);
};
/**
* Is button selected?
* @returns {boolean}
*/
App.TransactionToggleButton.prototype.isSelected = function isSelected()
{
return this._selected;
};
/**
* @class TransactionOptionButton
* @extends Graphics
* @param {string} iconName
* @param {string} name
* @param {{width:number,height:number,pixelRatio:number,nameStyle:Object,valueStyle:Object,valueDetailStyle:Object}} options
* @constructor
*/
App.TransactionOptionButton = function TransactionOptionButton(iconName,name,options)
{
PIXI.DisplayObjectContainer.call(this);
var Text = PIXI.Text,
Sprite = PIXI.Sprite;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._options = options;
this._value = null;
this._pixelRatio = options.pixelRatio;
this._skin = new Sprite(options.skin);
this._icon = new Sprite.fromFrame(iconName);
this._nameField = new Text(name,options.nameStyle);
this._valueField = new Text("",options.valueStyle);
this._valueDetailField = null;
this._arrow = new Sprite.fromFrame("arrow-app");
this._iconResizeRatio = Math.round(20 * this._pixelRatio) / this._icon.height;
this._arrowResizeRatio = Math.round(12 * this._pixelRatio) / this._arrow.height;
this._render();
this._update();
this.addChild(this._skin);
this.addChild(this._icon);
this.addChild(this._nameField);
this.addChild(this._valueField);
this.addChild(this._arrow);
};
App.TransactionOptionButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.TransactionOptionButton.prototype._render = function _render()
{
var ColorTheme = App.ColorTheme,
r = this._pixelRatio,
h = this.boundingBox.height;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round(15 * r);
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = ColorTheme.GREY_DARK;
this._nameField.x = Math.round(50 * r);
this._nameField.y = Math.round((h - this._nameField.height) / 2);
this._arrow.scale.x = this._arrowResizeRatio;
this._arrow.scale.y = this._arrowResizeRatio;
this._arrow.x = Math.round(this.boundingBox.width - 15 * r - this._arrow.width);
this._arrow.y = Math.round((h - this._arrow.height) / 2);
this._arrow.tint = ColorTheme.GREY_DARK;
};
/**
* Update
* @private
*/
App.TransactionOptionButton.prototype._update = function _update()
{
var r = this._pixelRatio,
offset = this.boundingBox.width - 35 * r;
this._valueField.x = Math.round(offset - this._valueField.width);
if (this._valueDetailField && this.contains(this._valueDetailField))
{
this._valueField.y = Math.round(9 * r);
this._valueDetailField.y = Math.round(30 * r);
this._valueDetailField.x = Math.round(offset - this._valueDetailField.width);
}
else
{
this._valueField.y = Math.round((this.boundingBox.height - this._valueField.height) / 2);
}
};
/**
* Set value
* @param {string} value
* @param {string} [details=null]
*/
App.TransactionOptionButton.prototype.setValue = function setValue(value,details)
{
this._value = value;
this._valueField.setText(value);
if (details)
{
if (this._valueDetailField) this._valueDetailField.setText(details);
else this._valueDetailField = new PIXI.Text(details,this._options.valueDetailStyle);
if (!this.contains(this._valueDetailField)) this.addChild(this._valueDetailField);
}
else
{
if (this._valueDetailField && this.contains(this._valueDetailField)) this.removeChild(this._valueDetailField);
}
this._update();
};
/**
* Return value
* @returns {string}
*/
App.TransactionOptionButton.prototype.getValue = function getValue()
{
return this._value;
};
/**
* @class AddTransactionScreen
* @extends InputScrollScreen
* @param {Object} layout
* @constructor
*/
App.AddTransactionScreen = function AddTransactionScreen(layout)
{
App.InputScrollScreen.call(this,layout);
var TransactionOptionButton = App.TransactionOptionButton,
TransactionToggleButton = App.TransactionToggleButton,
FontStyle = App.FontStyle,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
r = layout.pixelRatio,
w = layout.width,
inputWidth = w - Math.round(10 * r) * 2,
inputHeight = Math.round(40 * r),
toggleOptions = {
width:Math.round(w / 3),
height:Math.round(40 * r),
pixelRatio:r,
style:FontStyle.get(14,FontStyle.BLUE),
toggleStyle:FontStyle.get(14,FontStyle.WHITE)
},
options = {
pixelRatio:r,
width:w,
height:Math.round(50*r),
skin:skin.GREY_50,
nameStyle:FontStyle.get(18,FontStyle.GREY_DARKER),
valueStyle:FontStyle.get(18,FontStyle.BLUE,"right"),
valueDetailStyle:FontStyle.get(14,FontStyle.BLUE)
};
this._pane = new App.Pane(App.ScrollPolicy.OFF,App.ScrollPolicy.AUTO,w,layout.contentHeight,r,false);
this._container = new PIXI.DisplayObjectContainer();
this._background = new PIXI.Graphics();
this._transactionInput = new App.Input("00.00",24,inputWidth,inputHeight,r,true);
this._noteInput = new App.Input("Add Note",20,inputWidth,inputHeight,r,true);
this._separators = new PIXI.Graphics();
this._deleteBackground = new PIXI.Sprite(skin.GREY_60);
this._deleteButton = new App.PopUpButton("Delete","Are you sure you want to\ndelete this transaction?",{
width:inputWidth,
height:inputHeight,
pixelRatio:r,
popUpLayout:{x:Math.round(10*r),y:0,width:Math.round(inputWidth-20*r),height:Math.round(layout.height/2),overlayWidth:w,overlayHeight:0}
});
this._optionList = new App.List(App.Direction.Y);
this._accountOption = this._optionList.add(new TransactionOptionButton("account","Account",options));
this._categoryOption = this._optionList.add(new TransactionOptionButton("folder-app","Category",options));
this._timeOption = this._optionList.add(new TransactionOptionButton("calendar","Time",options));
this._methodOption = this._optionList.add(new TransactionOptionButton("credit-card","Method",options));
this._currencyOption = this._optionList.add(new TransactionOptionButton("currencies","Currency",options),true);
this._toggleButtonList = new App.List(App.Direction.X);
this._typeToggle = this._toggleButtonList.add(new TransactionToggleButton("expense","Expense",toggleOptions,{icon:"income",label:"Income",toggleColor:false}));
this._pendingToggle = this._toggleButtonList.add(new TransactionToggleButton("pending-app","Pending",toggleOptions,{toggleColor:true}));
this._repeatToggle = this._toggleButtonList.add(new TransactionToggleButton("repeat-app","Repeat",toggleOptions,{toggleColor:true}),true);
this._renderAll = true;
//TODO automatically focus input when this screen is shown?
//TODO add repeat frequency when 'repeat' is on?
this._transactionInput.restrict(/\d{1,}(\.\d*){0,1}/g);
this._container.addChild(this._background);
this._container.addChild(this._transactionInput);
this._container.addChild(this._toggleButtonList);
this._container.addChild(this._optionList);
this._container.addChild(this._noteInput);
this._container.addChild(this._separators);
this._pane.setContent(this._container);
this.addChild(this._pane);
this._clickThreshold = 10 * r;
};
App.AddTransactionScreen.prototype = Object.create(App.InputScrollScreen.prototype);
/**
* Render
* @private
*/
App.AddTransactionScreen.prototype._render = function _render()
{
var w = this._layout.width,
r = this._layout.pixelRatio,
padding = Math.round(10 * r);
if (this._renderAll)
{
var ColorTheme = App.ColorTheme,
GraphicUtils = App.GraphicUtils,
inputHeight = Math.round(60 * r),
toggleHeight = this._toggleButtonList.boundingBox.height,
toggleWidth = Math.round(w / 3),
separatorWidth = w - padding * 2,
bottom = 0;
this._renderAll = false;
this._transactionInput.x = padding;
this._transactionInput.y = padding;
this._toggleButtonList.y = inputHeight;
this._optionList.y = this._toggleButtonList.y + toggleHeight;
bottom = this._optionList.y + this._optionList.boundingBox.height;
this._noteInput.x = padding;
this._noteInput.y = bottom + padding;
GraphicUtils.drawRects(this._separators,ColorTheme.GREY_LIGHT,1,[
padding,inputHeight,separatorWidth,1,
toggleWidth,inputHeight+padding,1,toggleHeight-padding*2,
toggleWidth*2,inputHeight+padding,1,toggleHeight-padding*2,
padding,bottom,separatorWidth,1
],true,false);
bottom = this._noteInput.y + this._noteInput.boundingBox.height + padding;
this._deleteBackground.y = bottom;
this._deleteButton.setPosition(padding,this._deleteBackground.y + padding);
GraphicUtils.drawRects(this._separators,ColorTheme.GREY_DARK,1,[
padding,inputHeight-1,separatorWidth,1,
toggleWidth-1,inputHeight+padding,1,toggleHeight-padding*2,
toggleWidth*2-1,inputHeight+padding,1,toggleHeight-padding*2,
padding,inputHeight+toggleHeight-1,separatorWidth,1,
padding,bottom-1,separatorWidth,1
],false,true);
}
if (this._mode === App.ScreenMode.EDIT)
{
App.GraphicUtils.drawRect(this._background,App.ColorTheme.GREY,1,0,0,w,this._deleteButton.y+this._deleteButton.boundingBox.height+padding);
if (!this._container.contains(this._deleteBackground)) this._container.addChild(this._deleteBackground);
if (!this._container.contains(this._deleteButton)) this._container.addChild(this._deleteButton);
}
else
{
App.GraphicUtils.drawRect(this._background,App.ColorTheme.GREY,1,0,0,w,this._noteInput.y+this._noteInput.boundingBox.height+padding);
if (this._container.contains(this._deleteBackground)) this._container.removeChild(this._deleteBackground);
if (this._container.contains(this._deleteButton)) this._container.removeChild(this._deleteButton);
}
};
/**
* Update
* @param {App.Transaction} data
* @param {number} mode
*/
App.AddTransactionScreen.prototype.update = function update(data,mode)
{
this._model = data || this._model;
this._mode = mode || this._mode;
//TODO check if the default values are not already deleted
var settings = App.ModelLocator.getProxy(App.ModelName.SETTINGS),
account = this._model.account ? this._model.account : settings.defaultAccount,
category = this._model.category ? this._model.category : settings.defaultCategory,
subCategory = this._model.subCategory ? this._model.subCategory : settings.defaultSubCategory;
this._transactionInput.setValue(this._model.amount);
this._typeToggle.setState(this._model.type === App.TransactionType.INCOME);
this._pendingToggle.setState(this._model.pending);
this._repeatToggle.setState(this._model.repeat);
this._accountOption.setValue(account.name);
this._categoryOption.setValue(subCategory.name,category.name);
this._timeOption.setValue(App.DateUtils.getMilitaryTime(this._model.date),this._model.date.toDateString());
this._methodOption.setValue(this._model.method.name);
this._currencyOption.setValue(this._model.currencyQuote);
this._deleteButton.hidePopUp(true);
this._noteInput.setValue(this._model.note);
this._render();
this._pane.resize();
this.resetScroll();
};
/**
* Hide
*/
App.AddTransactionScreen.prototype.hide = function hide()
{
this._unRegisterDeleteButtonListeners();
App.Screen.prototype.hide.call(this);
};
/**
* Enable
*/
App.AddTransactionScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.enable();
};
/**
* Disable
*/
App.AddTransactionScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._transactionInput.disable();
this._noteInput.disable();
this._pane.disable();
};
/**
* Register event listeners
* @param {number} level
* @private
*/
App.AddTransactionScreen.prototype._registerEventListeners = function _registerEventListeners(level)
{
App.Screen.prototype._registerEventListeners.call(this,level);
if (level === App.EventLevel.LEVEL_2)
{
var EventType = App.EventType;
this._scrollTween.addEventListener(EventType.COMPLETE,this,this._onScrollTweenComplete);
this._transactionInput.addEventListener(EventType.BLUR,this,this._onInputBlur);
this._noteInput.addEventListener(EventType.BLUR,this,this._onInputBlur);
}
};
/**
* UnRegister event listeners
* @param {number} level
* @private
*/
App.AddTransactionScreen.prototype._unRegisterEventListeners = function _unRegisterEventListeners(level)
{
App.Screen.prototype._unRegisterEventListeners.call(this,level);
var EventType = App.EventType;
this._scrollTween.removeEventListener(EventType.COMPLETE,this,this._onScrollTweenComplete);
this._transactionInput.removeEventListener(EventType.BLUR,this,this._onInputBlur);
this._noteInput.removeEventListener(EventType.BLUR,this,this._onInputBlur);
};
/**
* Register delete button event listeners
* @private
*/
App.AddTransactionScreen.prototype._registerDeleteButtonListeners = function _registerDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.addEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.addEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.addEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* UnRegister delete button event listeners
* @private
*/
App.AddTransactionScreen.prototype._unRegisterDeleteButtonListeners = function _unRegisterDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.removeEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.removeEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.removeEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* On delete cancel
* @private
*/
App.AddTransactionScreen.prototype._onDeleteCancel = function _onDeleteCancel()
{
this._deleteButton.hidePopUp();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
};
/**
* On delete confirm
* @private
*/
App.AddTransactionScreen.prototype._onDeleteConfirm = function _onDeleteConfirm()
{
var HeaderAction = App.HeaderAction,
changeTransactionData = this._getChangeTransactionData(
App.ScreenName.TRANSACTIONS,
0,
null,
HeaderAction.MENU,
HeaderAction.ADD_TRANSACTION,
App.ScreenTitle.TRANSACTIONS
);
this._onHidePopUpComplete();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
App.ModelLocator.getProxy(App.ModelName.TRANSACTIONS).setCurrent(this._model);
changeTransactionData.type = App.EventType.DELETE;
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,changeTransactionData);
};
/**
* On Delete PopUp hide complete
* @private
*/
App.AddTransactionScreen.prototype._onHidePopUpComplete = function _onHidePopUpComplete()
{
this._unRegisterDeleteButtonListeners();
this.enable();
this._registerEventListeners(App.EventLevel.LEVEL_2);
};
/**
* Click handler
* @private
*/
App.AddTransactionScreen.prototype._onClick = function _onClick()
{
this._pane.cancelScroll();
var inputFocused = this._scrollState === App.TransitionState.SHOWN && this._scrollInput,
pointerData = this.stage.getTouchData(),
position = pointerData.getLocalPosition(this._container).y;
if (this._transactionInput.hitTest(position))
{
this._scrollInput = this._transactionInput;
this._focusInput(this._scrollInput.y + this._container.y > 0);
}
else if (this._toggleButtonList.hitTest(position))
{
if (inputFocused) this._scrollInput.blur();
else this._toggleButtonList.getItemUnderPoint(pointerData).toggle();
}
else if (this._optionList.hitTest(position))
{
if (inputFocused) this._scrollInput.blur();
var button = this._optionList.getItemUnderPoint(pointerData);
if (button === this._accountOption) this._onAccountOptionClick();
else if (button === this._categoryOption) this._onCategoryOptionClick();
else if (button === this._timeOption) this._onTimeOptionClick();
else if (button === this._methodOption) this._onMethodOptionClick();
else if (button === this._currencyOption) this._onCurrencyOptionClick();
}
else if (this._noteInput.hitTest(position))
{
this._scrollInput = this._noteInput;
this._focusInput(false);
}
else if (this._deleteButton.hitTest(position))
{
if (inputFocused)
{
this._scrollInput.blur();
}
else
{
this.disable();
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
App.ViewLocator.getViewSegment(App.ViewName.HEADER).disableActions();
this._registerDeleteButtonListeners();
this._deleteButton.setPopUpLayout(0,this._container.y + this._layout.headerHeight,0,this._layout.contentHeight > this._container.height ? this._layout.contentHeight : this._container.height);
this._deleteButton.showPopUp();
}
}
else
{
if (inputFocused) this._scrollInput.blur();
}
};
/**
* On account option button click
* @private
*/
App.AddTransactionScreen.prototype._onAccountOptionClick = function _onAccountOptionClick()
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.ACCOUNT,
App.ScreenMode.SELECT,
null,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_ACCOUNT
));
};
/**
* On category option button click
* @private
*/
App.AddTransactionScreen.prototype._onCategoryOptionClick = function _onCategoryOptionClick()
{
var account = this._model.account;
if (account && account.lifeCycleState !== App.LifeCycleState.DELETED)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.CATEGORY,
App.ScreenMode.SELECT,
account,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_CATEGORY
));
}
else
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.ACCOUNT,
App.ScreenMode.SELECT,
null,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_ACCOUNT
));
}
};
/**
* On time option button click
* @private
*/
App.AddTransactionScreen.prototype._onTimeOptionClick = function _onTimeOptionClick()
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.SELECT_TIME,
App.ScreenMode.SELECT,
this._model.date,
0,
0,
App.ScreenTitle.SELECT_TIME
));
};
/**
* On payment method option button click
* @private
*/
App.AddTransactionScreen.prototype._onMethodOptionClick = function _onMethodOptionClick()
{
this._methodOption.setValue(this._methodOption.getValue() === App.PaymentMethod.CASH ? App.PaymentMethod.CREDIT_CARD : App.PaymentMethod.CASH);
};
/**
* On currency option button click
* @private
*/
App.AddTransactionScreen.prototype._onCurrencyOptionClick = function _onCurrencyOptionClick()
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.CURRENCIES,
App.ScreenMode.SELECT,
null,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_CURRENCY
));
};
/**
* On Header click
* @param {number} action
* @private
*/
App.AddTransactionScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeTransactionData = this._getChangeTransactionData(
App.ScreenName.TRANSACTIONS,
0,
App.ModelLocator.getProxy(App.ModelName.TRANSACTIONS).copySource().reverse(),
HeaderAction.MENU,
HeaderAction.ADD_TRANSACTION,
App.ScreenTitle.TRANSACTIONS
);
if (this._scrollState === App.TransitionState.SHOWN && this._scrollInput) this._scrollInput.blur();
if (action === HeaderAction.CONFIRM)
{
changeTransactionData.type = App.EventType.CONFIRM;
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,changeTransactionData);
}
else
{
changeTransactionData.type = App.EventType.CANCEL;
changeTransactionData.nextCommandData.screenName = App.ScreenName.BACK;
changeTransactionData.nextCommandData.updateBackScreen = true;
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,changeTransactionData);
}
};
/**
* Construct and return change transaction data object
* @param {number} screenName
* @param {number} screenMode
* @param {*} updateData
* @param {number} headerLeftAction
* @param {number} headerRightAction
* @param {string} headerName
* @returns {{type:string,amount:string,transactionType:string,pending:boolean,repeat:boolean,method:string,note:string,nextCommand:App.ChangeScreen,nextCommandData:Object}}
* @private
*/
App.AddTransactionScreen.prototype._getChangeTransactionData = function _getChangeTransactionData(screenName,screenMode,updateData,headerLeftAction,headerRightAction,headerName)
{
return {
type:App.EventType.CHANGE,
amount:this._transactionInput.getValue(),
transactionType:this._typeToggle.isSelected() ? App.TransactionType.INCOME : App.TransactionType.EXPENSE,
pending:this._pendingToggle.isSelected(),
repeat:this._repeatToggle.isSelected(),
method:this._methodOption.getValue(),
note:this._noteInput.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
screenName,
screenMode,
updateData,
headerLeftAction,
headerRightAction,
headerName
)
};
};
/**
* @class SelectTimeScreen
* @extends InputScrollScreen
* @param {Object} layout
* @constructor
*/
App.SelectTimeScreen = function SelectTimeScreen(layout)
{
App.InputScrollScreen.call(this,layout);
var r = layout.pixelRatio,
w = layout.width,
ScrollPolicy = App.ScrollPolicy;
this._pane = new App.Pane(ScrollPolicy.OFF,ScrollPolicy.AUTO,w,layout.contentHeight,r,false);
this._container = new PIXI.DisplayObjectContainer();
this._inputBackground = new PIXI.Graphics();//TODO do I need BG? I can use BG below whole screen ...
this._input = new App.TimeInput("00:00",30,w - Math.round(20 * r),Math.round(40 * r),r);
this._header = new App.ListHeader("Select Date",w,r);
this._calendar = new App.Calendar(w,r);
//TODO enable 'swiping' for interactively changing calendar's months
this._render();
this._container.addChild(this._inputBackground);
this._container.addChild(this._header);
this._container.addChild(this._calendar);
this._container.addChild(this._input);
this._pane.setContent(this._container);
this.addChild(this._pane);
};
App.SelectTimeScreen.prototype = Object.create(App.InputScrollScreen.prototype);
/**
* Render
* @private
*/
App.SelectTimeScreen.prototype._render = function _render()
{
var ColorTheme = App.ColorTheme,
GraphicUtils = App.GraphicUtils,
r = this._layout.pixelRatio,
inputBgHeight = Math.round(60 * r),
w = this._layout.width;
GraphicUtils.drawRects(this._inputBackground,ColorTheme.GREY,1,[0,0,w,inputBgHeight],true,false);
GraphicUtils.drawRects(this._inputBackground,ColorTheme.GREY_DARK,1,[0,inputBgHeight-1,w,1],false,true);
this._input.x = Math.round(10 * r);
this._input.y = Math.round((inputBgHeight - this._input.height) / 2);
this._header.y = inputBgHeight;
this._calendar.y = Math.round(this._header.y + this._header.height);
};
/**
* Enable
*/
App.SelectTimeScreen.prototype.enable = function enable()
{
App.InputScrollScreen.prototype.enable.call(this);
this._pane.enable();
};
/**
* Disable
*/
App.SelectTimeScreen.prototype.disable = function disable()
{
this.resetScroll();
App.InputScrollScreen.prototype.disable.call(this);
this._input.disable();
this._pane.disable();
};
/**
* Update
* @param {Date} date
* @param {string} mode
* @private
*/
App.SelectTimeScreen.prototype.update = function update(date,mode)
{
this._input.setValue(App.DateUtils.getMilitaryTime(date));
this._calendar.update(date);
};
/**
* Register event listeners
* @param {number} level
* @private
*/
App.SelectTimeScreen.prototype._registerEventListeners = function _registerEventListener(level)
{
App.Screen.prototype._registerEventListeners.call(this,level);
if (level === App.EventLevel.LEVEL_2)
{
var EventType = App.EventType;
this._scrollTween.addEventListener(EventType.COMPLETE,this,this._onScrollTweenComplete);
this._input.addEventListener(EventType.BLUR,this,this._onInputBlur);
}
};
/**
* UnRegister event listeners
* @param {number} level
* @private
*/
App.SelectTimeScreen.prototype._unRegisterEventListeners = function _unRegisterEventListener(level)
{
App.Screen.prototype._unRegisterEventListeners.call(this,level);
var EventType = App.EventType;
this._scrollTween.removeEventListener(EventType.COMPLETE,this,this._onScrollTweenComplete);
this._input.removeEventListener(EventType.BLUR,this,this._onInputBlur);
};
/**
* Click handler
* @private
*/
App.SelectTimeScreen.prototype._onClick = function _onClick()
{
this._pane.cancelScroll();
var inputFocused = this._scrollState === App.TransitionState.SHOWN && this._scrollInput,
pointerData = this.stage.getTouchData(),
position = pointerData.getLocalPosition(this._container).y;
if (this._input.hitTest(position))
{
this._scrollInput = this._input;
this._focusInput(this._input.y + this._container.y > 0);
}
else
{
if (inputFocused) this._scrollInput.blur();
else this._calendar.onClick();
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.SelectTimeScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
if (this._scrollState === App.TransitionState.SHOWN && this._scrollInput) this._scrollInput.blur();
if (action === HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
else if (action === HeaderAction.CONFIRM)
{
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CHANGE,
date:this._calendar.getSelectedDate(),
time:this._input.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
};
/**
* @class AccountButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {PIXI.Texture} options.skin
* @param {{font:string,fill:string}} options.nameStyle
* @param {{font:string,fill:string}} options.detailStyle
* @param {{font:string,fill:string}} options.editStyle
* @param {number} options.openOffset
* @constructor
*/
App.AccountButton = function AccountButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new PIXI.Rectangle(0,0,options.width,options.height);
this._model = null;
this._mode = App.ScreenMode.SELECT;
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._editLabel = this.addChild(new PIXI.Text("Edit",options.editStyle));
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._skin = this._swipeSurface.addChild(new PIXI.Sprite(options.skin));
this._nameLabel = this._swipeSurface.addChild(new PIXI.Text("",options.nameStyle));
this._detailsLabel = this._swipeSurface.addChild(new PIXI.Text("",options.detailStyle));
this._renderAll = true;
};
App.AccountButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* @method render
* @param {number} showDetails
* @private
*/
App.AccountButton.prototype._render = function _render(showDetails)
{
if (this._renderAll)
{
var w = this.boundingBox.width,
h = this.boundingBox.height,
r = this._pixelRatio,
offset = Math.round(15 * r);
this._renderAll = false;
App.GraphicUtils.drawRect(this._background,App.ColorTheme.RED,1,0,0,w,h);
this._editLabel.x = Math.round(w - 50 * this._pixelRatio);
this._editLabel.y = Math.round((h - this._editLabel.height) / 2);
this._nameLabel.x = offset;
this._detailsLabel.x = offset;
this._detailsLabel.y = Math.round(45 * r);
if (showDetails)
{
this._nameLabel.y = offset;
this._swipeSurface.addChild(this._detailsLabel);
}
else
{
this._nameLabel.y = Math.round((h - this._nameLabel.height) / 2);
}
}
};
/**
* Set model
* @param {App.Account} model
* @param {string} mode
*/
App.AccountButton.prototype.setModel = function getModel(model,mode)
{
this._model = model;
this._mode = mode;
this._nameLabel.setText(this._model.name);
var balance = this._model.calculateBalance().toFixed(2);
if (balance) this._detailsLabel.setText("Expenses: "+balance);
this._render(balance);
};
/**
* Return model
* @returns {Account}
*/
App.AccountButton.prototype.getModel = function getModel()
{
return this._model;
};
/**
* Click handler
* @param {InteractionData} data
* @returns {number}
*/
App.AccountButton.prototype.getClickMode = function getClickMode(data)
{
if (this._isOpen && data.getLocalPosition(this).x >= this._width - this._openOffset) return App.ScreenMode.EDIT;
else return App.ScreenMode.SELECT;
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.AccountButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.AccountButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
/**
* @class AccountScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.AccountScreen = function AccountScreen(layout)
{
App.Screen.call(this,layout,0.4);
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width,
h = layout.contentHeight,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:w,
height:Math.round(70 * r),
pixelRatio:r,
skin:skin.GREY_70,
nameStyle:FontStyle.get(24,FontStyle.BLUE),
detailStyle:FontStyle.get(12,FontStyle.GREY_DARKER,null,FontStyle.LIGHT_CONDENSED),
editStyle:FontStyle.get(18,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
openOffset:Math.round(80 * r)
};
this._model = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS);
this._buttonPool = new App.ObjectPool(App.AccountButton,2,buttonOptions);
this._interactiveButton = null;
this._buttonList = new App.TileList(App.Direction.Y,h);
this._addNewButton = new App.AddNewButton("ADD ACCOUNT",FontStyle.get(16,FontStyle.GREY_DARK),App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_60,r);
this._pane = new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,layout.width,h,r,false);
this._pane.setContent(this._buttonList);
this.addChild(this._pane);
};
App.AccountScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.AccountScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.resetScroll();
this._pane.enable();
};
/**
* Disable
*/
App.AccountScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
};
/**
* Update
* @param {App.Collection} data
* @param {string} mode
*/
App.AccountScreen.prototype.update = function update(data,mode)
{
this._buttonList.remove(this._addNewButton);
var i = 0,
l = this._buttonList.length,
deletedState = App.LifeCycleState.DELETED,
account = null,
button = null;
for (;i<l;i++) this._buttonPool.release(this._buttonList.removeItemAt(0));
for (i=0,l=this._model.length();i<l;)
{
account = this._model.getItemAt(i++);
if (account.lifeCycleState !== deletedState)
{
button = this._buttonPool.allocate();
button.setModel(account,mode);
this._buttonList.add(button);
}
}
this._buttonList.add(this._addNewButton);
this._buttonList.updateLayout(true);
this._pane.resize();
this._mode = mode;
this._swipeEnabled = mode === App.ScreenMode.EDIT;
};
/**
* On tween complete
* @private
*/
App.AccountScreen.prototype._onTweenComplete = function _onTweenComplete()
{
App.Screen.prototype._onTweenComplete.call(this);
if (this._transitionState === App.TransitionState.HIDDEN) this._closeButtons(true);
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.AccountScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button && !(button instanceof App.AddNewButton))
{
if (!preferScroll) this._pane.cancelScroll();
this._interactiveButton = button;
this._interactiveButton.swipeStart(direction);
this._closeButtons(false);
}
};
/**
* Called when swipe ends
* @private
*/
App.AccountScreen.prototype._swipeEnd = function _swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.AccountScreen.prototype._closeButtons = function _closeButtons(immediate)
{
if (this._mode === App.ScreenMode.EDIT)
{
var i = 0,
l = this._buttonList.length - 1,// last button is 'AddNewButton'
button = null;
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
}
};
/**
* Click handler
* @private
*/
App.AccountScreen.prototype._onClick = function _onClick()
{
var data = this.stage.getTouchData(),
button = this._buttonList.getItemUnderPoint(data);
if (button)
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.EDIT);
if (button instanceof App.AddNewButton)
{
changeScreenData.headerName = App.ScreenTitle.ADD_ACCOUNT;
App.Controller.dispatchEvent(EventType.CHANGE_ACCOUNT,{
type:EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else
{
var ScreenMode = App.ScreenMode,
HeaderAction = App.HeaderAction;
if (this._mode === ScreenMode.EDIT)
{
if (button.getClickMode(data) === ScreenMode.EDIT)
{
App.Controller.dispatchEvent(EventType.CHANGE_SCREEN,changeScreenData.update(
App.ScreenName.EDIT,
App.ScreenMode.EDIT,
button.getModel(),
0,
0,
App.ScreenTitle.EDIT_ACCOUNT
));
}
else
{
App.Controller.dispatchEvent(EventType.CHANGE_SCREEN,changeScreenData.update(
App.ScreenName.CATEGORY,
this._mode,
button.getModel(),
HeaderAction.MENU,
HeaderAction.ADD_TRANSACTION,
App.ScreenTitle.CATEGORIES
));
}
}
else
{
App.Controller.dispatchEvent(EventType.CHANGE_SCREEN,changeScreenData.update(
App.ScreenName.CATEGORY,
this._mode,
button.getModel(),
0,
HeaderAction.NONE,
App.ScreenTitle.SELECT_CATEGORY
));
}
}
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.AccountScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate();
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(App.ScreenName.MENU,0,null,HeaderAction.NONE,HeaderAction.CANCEL,App.ScreenTitle.MENU));
}
else if (action === HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(App.ScreenName.BACK));
}
};
/**
* @class SubCategoryButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {number} options.openOffset
* @param {Texture} options.whiteSkin
* @param {Texture} options.greySkin
* @param {{font:string,fill:string}} options.nameLabelStyle
* @param {{font:string,fill:string}} options.editLabelStyle
* @constructor
*/
App.SubCategoryButton = function SubCategoryButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._mode = null;
this._options = options;
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._deleteLabel = this.addChild(new PIXI.Text("Edit",options.editLabelStyle));
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._skin = this._swipeSurface.addChild(new PIXI.Sprite(options.whiteSkin));
this._icon = PIXI.Sprite.fromFrame("subcategory-app");
this._nameLabel = this._swipeSurface.addChild(new PIXI.Text("",options.nameLabelStyle));
this._renderAll = true;
};
App.SubCategoryButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* Render
* @private
*/
App.SubCategoryButton.prototype._render = function _render()
{
this._nameLabel.setText(this._model.name);
if (this._renderAll)
{
this._renderAll = false;
var ColorTheme = App.ColorTheme,
r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
offset = Math.round(25 * r),
iconResizeRatio = Math.round(20 * r) / this._icon.height;
App.GraphicUtils.drawRect(this._background,ColorTheme.RED,1,0,0,w,h);
this._deleteLabel.x = Math.round(w - 50 * r);
this._deleteLabel.y = Math.round((h - this._deleteLabel.height) / 2);
this._icon.scale.x = iconResizeRatio;
this._icon.scale.y = iconResizeRatio;
this._icon.x = offset;
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = ColorTheme.GREY;
this._nameLabel.y = Math.round((h - this._nameLabel.height) / 2);
}
if (this._mode === App.ScreenMode.SELECT)
{
this._skin.setTexture(this._options.whiteSkin);
this._nameLabel.x = Math.round(64 * this._pixelRatio);
if (!this._swipeSurface.contains(this._icon)) this._swipeSurface.addChild(this._icon);
}
else if (this._mode === App.ScreenMode.EDIT)
{
this._skin.setTexture(this._options.greySkin);
this._nameLabel.x = this._icon.x;
if (this._swipeSurface.contains(this._icon)) this._swipeSurface.removeChild(this._icon);
}
};
/**
* Disable
*/
App.SubCategoryButton.prototype.disable = function disable()
{
App.SwipeButton.prototype.disable.call(this);
};
/**
* Update
* @param {App.SubCategory} model
* @param {string} mode
*/
App.SubCategoryButton.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._render();
this.close(true);
};
/**
* Return model
* @returns {App.SubCategory}
*/
App.SubCategoryButton.prototype.getModel = function getModel()
{
return this._model;
};
/**
* Click handler
* @param {InteractionData} interactionData
* @param {App.Category} category
* @param {number} screenMode
*/
App.SubCategoryButton.prototype.onClick = function onClick(interactionData,category,screenMode)
{
if (this._mode === App.ScreenMode.EDIT)
{
if (this._isOpen && interactionData.getLocalPosition(this).x >= this._width - this._openOffset)
{
this._model.saveState();
App.Controller.dispatchEvent(
App.EventType.CHANGE_SCREEN,
App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT,
screenMode,
{subCategory:this._model,category:category},
0,
0,
App.ScreenTitle.EDIT_SUB_CATEGORY
)
);
}
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.SubCategoryButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.SubCategoryButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
/**
* @class SubCategoryList
* @extends Graphics
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {boolean} options.displayHeader
* @param {{font:string,fill:string}} options.nameLabelStyle
* @param {{font:string,fill:string}} options.deleteLabelStyle
* @param {{font:string,fill:string}} options.addLabelStyle
* @param {number} options.openOffset
* @constructor
*/
App.SubCategoryList = function SubCategoryList(options)
{
PIXI.DisplayObjectContainer.call(this);
var FontStyle = App.FontStyle,
r = options.pixelRatio,
w = options.width,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:w,
height:Math.round(40 * r),
pixelRatio:r,
whiteSkin:skin.WHITE_40,
greySkin:skin.GREY_40,
nameLabelStyle:FontStyle.get(14,FontStyle.BLUE),
editLabelStyle:FontStyle.get(16,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
openOffset:Math.round(80 * r)
};
this.boundingBox = new App.Rectangle(0,0,w,0);
this._model = null;
this._mode = null;
this._width = w;
this._pixelRatio = r;
this._buttonPool = new App.ObjectPool(App.SubCategoryButton,5,buttonOptions);
this._interactiveButton = null;
if (options.displayHeader) this._header = this.addChild(new App.ListHeader("Sub-Categories",this._width,this._pixelRatio));
this._buttonList = this.addChild(new App.List(App.Direction.Y));
this._addNewButton = new App.AddNewButton("ADD SUB-CATEGORY",options.addLabelStyle,options.addButtonSkin,this._pixelRatio);
};
App.SubCategoryList.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Update layout
* @private
*/
App.SubCategoryList.prototype._render = function _render()
{
if (this._header) this._buttonList.y = this._header.height;
this.boundingBox.height = this._buttonList.y + this._buttonList.boundingBox.height;
};
/**
* @method update
* @param {App.Category} model
* @param {string} mode
*/
App.SubCategoryList.prototype.update = function update(model,mode)
{
this._model = model;
this._buttonList.remove(this._addNewButton);
var subCategories = model.subCategories,
i = 0,
l = this._buttonList.length,
button = null;
for (;i<l;i++) this._buttonPool.release(this._buttonList.removeItemAt(0));
i = 0;
l = subCategories.length;
for (;i<l;)
{
button = this._buttonPool.allocate();
button.update(subCategories[i++],mode);
this._buttonList.add(button,false);
}
this._buttonList.add(this._addNewButton);
this._buttonList.updateLayout();
this._render();
this._mode = mode;
};
/**
* Called when swipe starts
* @param {string} direction
* @private
*/
App.SubCategoryList.prototype.swipeStart = function swipeStart(direction)
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button && !(button instanceof App.AddNewButton))
{
this._interactiveButton = button;
this._interactiveButton.swipeStart(direction);
this.closeButtons(false);
}
};
/**
* Called when swipe ends
* @private
*/
App.SubCategoryList.prototype.swipeEnd = function swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.SubCategoryList.prototype.closeButtons = function closeButtons(immediate)
{
var i = 0,
l = this._buttonList.length - 1,// last button is 'AddNewButton'
button = null;
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
};
/**
* Find and return item under point passed in
* @param {InteractionData} data PointerData to get the position from
*/
App.SubCategoryList.prototype.getItemUnderPoint = function getItemUnderPoint(data)
{
return this._buttonList.getItemUnderPoint(data);
};
/**
* Test if position passed in falls within this list boundaries
* @param {number} position
* @returns {boolean}
*/
App.SubCategoryList.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
/**
* @property length
* @type number
*/
Object.defineProperty(App.SubCategoryList.prototype,'length',{
get:function()
{
// Subtract one; last button is 'Add' button
return this._buttonList.length - 1;
}
});
/**
* @class CategoryButtonSurface
* @extends DisplayObjectContainer
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {{font:string,fill:string}} options.nameLabelStyle
* @constructor
*/
App.CategoryButtonSurface = function CategoryButtonSurface(options)
{
PIXI.DisplayObjectContainer.call(this);
this._width = options.width;
this._height = options.height;
this._pixelRatio = options.pixelRatio;
this._skin = this.addChild(new PIXI.Sprite(options.skin));
this._colorStripe = this.addChild(new PIXI.Graphics());
this._icon = null;
this._nameLabel = this.addChild(new PIXI.Text("",options.nameLabelStyle));
this._renderAll = true;
};
App.CategoryButtonSurface.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @param {string} label
* @param {string} iconName
* @param {string} color
*/
App.CategoryButtonSurface.prototype.render = function render(label,iconName,color)
{
this._nameLabel.setText(label);
if (this._icon) this._icon.setTexture(PIXI.TextureCache[iconName]);
App.GraphicUtils.drawRect(this._colorStripe,"0x"+color,1,0,0,Math.round(4 * this._pixelRatio),this._height);
if (this._renderAll)
{
this._renderAll = false;
this._icon = PIXI.Sprite.fromFrame(iconName);
this.addChild(this._icon);
this._icon.width = Math.round(20 * this._pixelRatio);
this._icon.height = Math.round(20 * this._pixelRatio);
this._icon.x = Math.round(25 * this._pixelRatio);
this._icon.y = Math.round((this._height - this._icon.height) / 2);
this._nameLabel.x = Math.round(64 * this._pixelRatio);
this._nameLabel.y = Math.round(18 * this._pixelRatio);
}
this._icon.tint = parseInt(color,16);
};
/**
* @class CategoryButtonEdit
* @extends SwipeButton
* @param {number} poolIndex
* @param {{width:number,height:number,pixelRatio:number,nameLabelStyle:{font:string,fill:string},editLabelStyle:{font:string,fill:string}}} options
* @constructor
*/
App.CategoryButtonEdit = function CategoryButtonEdit(poolIndex,options)
{
App.SwipeButton.call(this,options.width,Math.round(80*options.pixelRatio));
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._mode = null;
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._editLabel = this.addChild(new PIXI.Text("Edit",options.editLabelStyle));
this._swipeSurface = this.addChild(new App.CategoryButtonSurface(options));
this._renderAll = true;
};
App.CategoryButtonEdit.prototype = Object.create(App.SwipeButton.prototype);
/**
* Render
* @private
*/
App.CategoryButtonEdit.prototype._render = function _render()
{
var w = this.boundingBox.width,
h = this.boundingBox.height;
this._swipeSurface.render(this._model.name,this._model.icon,this._model.color);
if (this._renderAll)
{
this._renderAll = false;
App.GraphicUtils.drawRect(this._background,App.ColorTheme.RED,1,0,0,w,h);
this._editLabel.x = Math.round(w - 50 * this._pixelRatio);
this._editLabel.y = Math.round(18 * this._pixelRatio);
}
};
/**
* Disable
*/
App.CategoryButtonEdit.prototype.disable = function disable()
{
App.SwipeButton.prototype.disable.call(this);
};
/**
* Update
* @param {App.Category} model
* @param {string} mode
*/
App.CategoryButtonEdit.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._render();
this.close(true);
};
/**
* Click handler
* @param {InteractionData} data
*/
App.CategoryButtonEdit.prototype.onClick = function onClick(data)
{
if (this._isOpen && data.getLocalPosition(this).x >= this._width - this._openOffset)
{
this._model.saveState();
App.Controller.dispatchEvent(
App.EventType.CHANGE_SCREEN,
App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT_CATEGORY,
App.ScreenMode.EDIT,
this._model,
0,
0,
App.ScreenTitle.EDIT_CATEGORY
)
);
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.CategoryButtonEdit.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.CategoryButtonEdit.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
/**
* @class CategoryButtonExpand
* @extends ExpandButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {{font:string,fill:string}} options.nameLabelStyle
* @param {{font:string,fill:string}} options.deleteLabelStyle
* @param {{font:string,fill:string}} options.addLabelStyle
* @param {number} options.openOffset
* @constructor
*/
App.CategoryButtonExpand = function CategoryButtonExpand(poolIndex,options)
{
App.ExpandButton.call(this,options.width,options.height,true);
this.allocated = false;
this.poolIndex = poolIndex;
this._model = null;
this._mode = null;
this._pixelRatio = options.pixelRatio;
this._surface = new App.CategoryButtonSurface(options);
this._subCategoryList = new App.SubCategoryList(options);
this._layoutDirty = true;
this._setContent(this._subCategoryList);
this.addChild(this._subCategoryList);
this.addChild(this._surface);
};
App.CategoryButtonExpand.prototype = Object.create(App.ExpandButton.prototype);
/**
* Render
* @private
*/
App.CategoryButtonExpand.prototype._render = function _render()
{
this._surface.render(this._model.name,this._model.icon,this._model.color);
};
/**
* Update
* @param {App.Category} model
* @param {string} mode
*/
App.CategoryButtonExpand.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._layoutDirty = true;
this._render();
this.close(true);
};
/**
* Click handler
* @param {InteractionData} data
*/
App.CategoryButtonExpand.prototype.onClick = function onClick(data)
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.CLOSED || this._transitionState === TransitionState.CLOSING)
{
this.open();
}
else
{
if (data.getLocalPosition(this).y <= this._buttonHeight)
{
this.close();
}
else
{
this._eventDispatcher.dispatchEvent(App.EventType.COMPLETE,this); // To cancel any parent's processes
var button = this._subCategoryList.getItemUnderPoint(data);
if (button)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
EventType = App.EventType,
changeScreenData = ModelLocator.getProxy(ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
if (button instanceof App.AddNewButton)
{
changeScreenData.screenName = App.ScreenName.EDIT;
changeScreenData.headerName = App.ScreenTitle.ADD_SUB_CATEGORY;
App.Controller.dispatchEvent(EventType.CHANGE_SUB_CATEGORY,{
type:EventType.CREATE,
category:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else
{
changeScreenData.backSteps = ModelLocator.getProxy(ModelName.SCREEN_HISTORY).peek(2).screenName === App.ScreenName.ACCOUNT ? 2 : 1;
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(EventType.CHANGE_TRANSACTION,{
type:EventType.CHANGE,
account:ModelLocator.getProxy(ModelName.ACCOUNTS).find("id",this._model.account),
category:this._model,
subCategory:button.getModel(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
}
}
}
};
/**
* Open
*/
App.CategoryButtonExpand.prototype.open = function open()
{
if (this._layoutDirty)
{
this._subCategoryList.update(this._model,this._mode);
this._contentHeight = this._subCategoryList.boundingBox.height;
this._layoutDirty = false;
}
App.ExpandButton.prototype.open.call(this);
};
/**
* Disable
*/
App.CategoryButtonExpand.prototype.disable = function disable()
{
this.close(true);
};
/**
* @class CategoryScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.CategoryScreen = function CategoryScreen(layout)
{
App.Screen.call(this,layout,0.4);
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
ObjectPool = App.ObjectPool,
r = layout.pixelRatio,
w = layout.width,
h = layout.contentHeight,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:w,
height:Math.round(50 * r),
pixelRatio:r,
skin:skin.GREY_50,
addButtonSkin:skin.WHITE_40,
nameLabelStyle:FontStyle.get(18,FontStyle.BLUE),
editLabelStyle:FontStyle.get(18,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
addLabelStyle:FontStyle.get(14,FontStyle.GREY_DARK),
displayHeader:false
};
this._interactiveButton = null;
this._buttonsInTransition = [];
this._layoutDirty = false;
this._buttonExpandPool = new ObjectPool(App.CategoryButtonExpand,5,buttonOptions);
this._buttonEditPool = new ObjectPool(App.CategoryButtonEdit,5,buttonOptions);
this._buttonList = new App.TileList(App.Direction.Y,h);
this._addNewButton = new App.AddNewButton("ADD CATEGORY",FontStyle.get(14,FontStyle.GREY_DARK),App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_50,r);
this._pane = new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,layout.width,h,r,false);
this._pane.setContent(this._buttonList);
this.addChild(this._pane);
};
App.CategoryScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.CategoryScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.resetScroll();
this._pane.enable();
};
/**
* Disable
*/
App.CategoryScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._layoutDirty = false;
this._pane.disable();
};
/**
* Update
* @param {App.Account} data
* @param {string} mode
* @private
*/
App.CategoryScreen.prototype.update = function update(data,mode)
{
this._model = data;
this._buttonList.remove(this._addNewButton);
var ScreenMode = App.ScreenMode,
buttonPool = this._mode === ScreenMode.SELECT ? this._buttonExpandPool : this._buttonEditPool,
categories = this._model.categories,
i = 0,
l = this._buttonList.length,
button = null;
for (;i<l;i++) buttonPool.release(this._buttonList.removeItemAt(0));
buttonPool = mode === ScreenMode.SELECT ? this._buttonExpandPool : this._buttonEditPool;
for (i=0,l=categories.length;i<l;)
{
button = buttonPool.allocate();
button.update(categories[i++],mode);
this._buttonList.add(button,false);
}
this._buttonList.add(this._addNewButton);
this._updateLayout();
this._mode = mode;
this._swipeEnabled = mode === ScreenMode.EDIT;
};
/**
* On tick
* @private
*/
App.CategoryScreen.prototype._onTick = function _onTick()
{
App.Screen.prototype._onTick.call(this);
if (this._layoutDirty) this._updateLayout();
};
/**
* On tween complete
* @private
*/
App.CategoryScreen.prototype._onTweenComplete = function _onTweenComplete()
{
App.Screen.prototype._onTweenComplete.call(this);
if (this._transitionState === App.TransitionState.HIDDEN) this._closeButtons(true);
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.CategoryScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button && !(button instanceof App.AddNewButton))
{
if (!preferScroll) this._pane.cancelScroll();
this._interactiveButton = button;
this._interactiveButton.swipeStart(direction);
this._closeButtons(false);
}
};
/**
* Called when swipe ends
* @private
*/
App.CategoryScreen.prototype._swipeEnd = function _swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.CategoryScreen.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._buttonList.length - 1,// last button is 'AddNewButton'
button = null,
ScreenMode = App.ScreenMode,
EventType = App.EventType;
if (this._mode === ScreenMode.SELECT)
{
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton && button.isOpen())
{
if (this._buttonsInTransition.indexOf(button) === -1)
{
this._buttonsInTransition.push(button);
button.addEventListener(EventType.COMPLETE,this,this._onButtonTransitionComplete);
this._layoutDirty = true;
}
button.close(immediate);
}
}
}
else if (this._mode === ScreenMode.EDIT)
{
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
}
};
/**
* Click handler
* @private
*/
App.CategoryScreen.prototype._onClick = function _onClick()
{
var data = this.stage.getTouchData(),
button = this._buttonList.getItemUnderPoint(data);
if (button)
{
if (button instanceof App.AddNewButton)
{
var changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.EDIT_CATEGORY);
changeScreenData.headerName = App.ScreenTitle.ADD_CATEGORY;
App.Controller.dispatchEvent(App.EventType.CHANGE_CATEGORY,{
type:App.EventType.CREATE,
account:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else
{
if (this._mode === App.ScreenMode.SELECT)
{
this._interactiveButton = button;
if (this._buttonsInTransition.indexOf(this._interactiveButton) === -1)
{
this._buttonsInTransition.push(this._interactiveButton);
this._interactiveButton.addEventListener(App.EventType.COMPLETE,this,this._onButtonTransitionComplete);
this._layoutDirty = true;
}
this._interactiveButton.onClick(data);
this._pane.cancelScroll();
}
else if (this._mode === App.ScreenMode.EDIT)
{
button.onClick(data);
}
}
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.CategoryScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.MENU,
0,
null,
HeaderAction.NONE,
HeaderAction.CANCEL,
App.ScreenTitle.MENU
);
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
else if (action === HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(App.ScreenName.BACK));
}
};
/**
* On button transition complete
* @param {App.ExpandButton} button
* @private
*/
App.CategoryScreen.prototype._onButtonTransitionComplete = function _onButtonTransitionComplete(button)
{
var i = 0,
l = this._buttonsInTransition.length,
EventType = App.EventType;
button.removeEventListener(EventType.COMPLETE,this,this._onButtonTransitionComplete);
for (;i<l;i++)
{
if (button === this._buttonsInTransition[i])
{
this._buttonsInTransition.splice(i,1);
break;
}
}
if (this._buttonsInTransition.length === 0)
{
this._interactiveButton = null;
this._layoutDirty = false;
this._updateLayout();
}
};
/**
* Update layout
* @private
*/
App.CategoryScreen.prototype._updateLayout = function _updateLayout()
{
this._buttonList.updateLayout(true);
this._pane.resize();
};
/**
* @class ColorSample
* @extends Graphics
* @param {number} modelIndex
* @param {number} color
* @param {number} pixelRatio
* @constructor
*/
App.ColorSample = function ColorSample(modelIndex,color,pixelRatio)
{
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,Math.round(40*pixelRatio),Math.round(50*pixelRatio));
this._modelIndex = modelIndex;
this._pixelRatio = pixelRatio;
this._color = color.toString();
this._selected = false;
this._render();
};
App.ColorSample.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.ColorSample.prototype._render = function _render()
{
var xPadding = Math.round((this._selected ? 0 : 5) * this._pixelRatio),
yPadding = Math.round((this._selected ? 5 : 10) * this._pixelRatio),
w = this.boundingBox.width,
h = this.boundingBox.height;
this.clear();
this.beginFill("0x"+this._color);
this.drawRoundedRect(xPadding,yPadding,w-xPadding*2,h-yPadding*2,Math.round(5*this._pixelRatio));
this.endFill();
};
/**
* Set color
* @param {number} index
* @param {number} color
* @param {number} selectedIndex
*/
App.ColorSample.prototype.setModel = function setModel(index,color,selectedIndex)
{
this._modelIndex = index;
this._color = color;
this._selected = selectedIndex === this._modelIndex;
this._render();
};
/**
* Return model index
* @return {number}
*/
App.ColorSample.prototype.getModelIndex = function getModelIndex()
{
return this._modelIndex;
};
/**
* Return value
* @returns {string}
*/
App.ColorSample.prototype.getValue = function getValue()
{
return this._color;
};
/**
* Select
* @param {number} selectedIndex Index of selected item in the collection
*/
App.ColorSample.prototype.select = function select(selectedIndex)
{
var selected = this._modelIndex === selectedIndex;
if (this._selected === selected) return;
this._selected = selected;
this._render();
};
/**
* @class IconSample
* @extends DisplayObjectContainer
* @param {number} modelIndex
* @param {string} model
* @param {number} pixelRatio
* @constructor
*/
App.IconSample = function IconSample(modelIndex,model,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var size = Math.round(64 * pixelRatio);
this.boundingBox = new App.Rectangle(0,0,size,size);
this._modelIndex = modelIndex;
this._model = model;
this._pixelRatio = pixelRatio;
this._icon = PIXI.Sprite.fromFrame(model);
this._iconResizeRatio = Math.round(32 * pixelRatio) / this._icon.height;
this._selected = false;
this._render();
this.addChild(this._icon);
};
App.IconSample.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.IconSample.prototype._render = function _render()
{
var ColorTheme = App.ColorTheme,
size = this.boundingBox.width;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round((size - this._icon.width) / 2);
this._icon.y = Math.round((size - this._icon.height) / 2);
this._icon.tint = this._selected ? ColorTheme.BLUE : ColorTheme.GREY_DARK;
};
/**
* Set color
* @param {number} index
* @param {string} model
* @param {number} selectedIndex
*/
App.IconSample.prototype.setModel = function setModel(index,model,selectedIndex)
{
this._modelIndex = index;
this._model = model;
this._icon.setTexture(PIXI.TextureCache[model]);
this._selected = selectedIndex === this._modelIndex;
this._render();
};
/**
* Return model index
* @return {number}
*/
App.IconSample.prototype.getModelIndex = function getModelIndex()
{
return this._modelIndex;
};
/**
* Return value
* @returns {string}
*/
App.IconSample.prototype.getValue = function getValue()
{
return this._model;
};
/**
* Select
* @param {number} selectedIndex Index of selected item in the collection
*/
App.IconSample.prototype.select = function select(selectedIndex)
{
var selected = this._modelIndex === selectedIndex;
if (this._selected === selected) return;
this._selected = selected;
this._render();
};
/**
* @class EditCategoryScreen
* @extends InputScrollScreen
* @param {Object} layout
* @constructor
*/
App.EditCategoryScreen = function EditCategoryScreen(layout)
{
App.InputScrollScreen.call(this,layout);
var ScrollPolicy = App.ScrollPolicy,
InfiniteList = App.InfiniteList,
Direction = App.Direction,
IconSample = App.IconSample,
FontStyle = App.FontStyle,
Input = App.Input,
r = layout.pixelRatio,
w = layout.width,
inputWidth = w - Math.round(20 * r),
inputHeight = Math.round(40 * r),
icons = App.ModelLocator.getProxy(App.ModelName.ICONS),
iconsHeight = Math.round(64 * r),
subCategoryButtonOptions = {
width:w,
height:inputHeight,
pixelRatio:r,
addButtonSkin:App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_40,
addLabelStyle:FontStyle.get(14,FontStyle.GREY_DARK),
displayHeader:true
};
this._pane = new App.Pane(ScrollPolicy.OFF,ScrollPolicy.AUTO,w,layout.contentHeight,r,false);
this._container = new PIXI.DisplayObjectContainer();
this._background = this._container.addChild(new PIXI.Graphics());
this._colorStripe = this._container.addChild(new PIXI.Graphics());
this._icon = PIXI.Sprite.fromFrame("currencies");
this._iconResizeRatio = Math.round(32 * r) / this._icon.height;
this._input = this._container.addChild(new Input("Enter Category Name",20,w - Math.round(70 * r),Math.round(40 * r),r,true));
this._separators = this._container.addChild(new PIXI.Graphics());
this._colorList = this._container.addChild(new InfiniteList(this._getColorSamples(),App.ColorSample,Direction.X,w,Math.round(50 * r),r));
this._topIconList = this._container.addChild(new InfiniteList(icons.slice(0,Math.floor(icons.length/2)),IconSample,Direction.X,w,iconsHeight,r));
this._bottomIconList = this._container.addChild(new InfiniteList(icons.slice(Math.floor(icons.length/2)),IconSample,Direction.X,w,iconsHeight,r));
this._subCategoryList = this._container.addChild(new App.SubCategoryList(subCategoryButtonOptions));
this._budgetHeader = this._container.addChild(new App.ListHeader("Budget",w,r));
this._budget = this._container.addChild(new Input("Enter Budget",20,inputWidth,inputHeight,r,true));
this._deleteButton = new App.PopUpButton("Delete","Are you sure you want to\ndelete this category with all its\ndata and sub-categories?",{
width:inputWidth,
height:inputHeight,
pixelRatio:r,
popUpLayout:{x:Math.round(10*r),y:0,width:Math.round(inputWidth-20*r),height:Math.round(layout.height/2),overlayWidth:w,overlayHeight:0}
});
this._renderAll = true;
//TODO center selected color/icon when shown
this._budget.restrict(/\d{1,}(\.\d{0,2}){0,1}/g);
this._pane.setContent(this._container);
this.addChild(this._pane);
this._swipeEnabled = true;
};
App.EditCategoryScreen.prototype = Object.create(App.InputScrollScreen.prototype);
/**
* Render
* @private
*/
App.EditCategoryScreen.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._layout.pixelRatio,
w = this._layout.width,
inputFragmentHeight = Math.round(60 * r),
colorListHeight = this._colorList.boundingBox.height,
separatorWidth = w - this._inputPadding * 2,
icon = this._getSelectedIcon(),
color = this._colorList.getSelectedValue(),
bottom = 0;
GraphicUtils.drawRect(this._colorStripe,"0x"+color,1,0,0,Math.round(4*r),Math.round(59 * r));
if (this._icon)
{
this._icon.setTexture(PIXI.TextureCache[icon]);
this._icon.tint = parseInt(color,16);
}
if (this._renderAll)
{
this._renderAll = false;
this._icon = PIXI.Sprite.fromFrame(icon);
this._iconResizeRatio = Math.round(32 * r) / this._icon.height;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round(15 * r);
this._icon.y = Math.round((inputFragmentHeight - this._icon.height) / 2);
this._icon.tint = parseInt(color,16);
this._container.addChild(this._icon);
this._input.x = Math.round(60 * r);
this._input.y = Math.round((inputFragmentHeight - this._input.height) / 2);
this._colorList.y = inputFragmentHeight;
this._topIconList.y = inputFragmentHeight + this._colorList.boundingBox.height;
this._bottomIconList.y = this._topIconList.y + this._topIconList.boundingBox.height;
this._subCategoryList.y = this._bottomIconList.y + this._bottomIconList.boundingBox.height;
this._budget.x = this._inputPadding;
this._separators.x = this._inputPadding;
}
this._budgetHeader.y = this._subCategoryList.y + this._subCategoryList.boundingBox.height;
bottom = this._budgetHeader.y + this._budgetHeader.height;
this._budget.y = bottom + this._inputPadding;
if (this._mode === App.ScreenMode.EDIT)
{
bottom = bottom + inputFragmentHeight;
this._deleteButton.setPosition(this._inputPadding,bottom+this._inputPadding);
if (!this._container.contains(this._deleteButton)) this._container.addChild(this._deleteButton);
}
else
{
if (this._container.contains(this._deleteButton)) this._container.removeChild(this._deleteButton);
}
GraphicUtils.drawRect(this._background,ColorTheme.GREY,1,0,0,w,bottom+inputFragmentHeight);
GraphicUtils.drawRects(this._separators,ColorTheme.GREY_DARK,1,[
0,inputFragmentHeight-1,separatorWidth,1,
0,inputFragmentHeight+colorListHeight,separatorWidth,1,
0,bottom-1,separatorWidth,1
],true,false);
GraphicUtils.drawRects(this._separators,ColorTheme.GREY_LIGHT,1,[
0,inputFragmentHeight,separatorWidth,1,
0,inputFragmentHeight+colorListHeight+1,separatorWidth,1,
0,bottom,separatorWidth,1
],false,true);
};
/**
* Hide
*/
App.EditCategoryScreen.prototype.hide = function hide()
{
this._unRegisterDeleteButtonListeners();
App.Screen.prototype.hide.call(this);
};
/**
* Update
* @param {App.Category} model
* @param {string} mode
*/
App.EditCategoryScreen.prototype.update = function update(model,mode)
{
this._model = model;
this._mode = mode;
this._input.setValue(this._model.name);
if (this._model.color) this._colorList.selectItemByValue(this._model.color);
else this._colorList.selectItemByPosition(0);
if (this._model.icon)
{
this._topIconList.selectItemByValue(this._model.icon);
this._bottomIconList.selectItemByValue(this._model.icon);
}
else
{
this._topIconList.selectItemByPosition(0);
this._bottomIconList.selectItemByValue(-10000);
}
this._subCategoryList.update(this._model,App.ScreenMode.EDIT);
this._budget.setValue(this._model.budget);
this._deleteButton.hidePopUp(true);
this._render();
this._pane.resize();
this.resetScroll();
};
/**
* Enable
*/
App.EditCategoryScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._colorList.enable();
this._topIconList.enable();
this._bottomIconList.enable();
this._pane.enable();
};
/**
* Disable
*/
App.EditCategoryScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._input.disable();
this._colorList.disable();
this._topIconList.disable();
this._bottomIconList.disable();
this._budget.disable();
this._pane.disable();
};
/**
* Register event listeners
* @param {number} level
* @private
*/
App.EditCategoryScreen.prototype._registerEventListeners = function _registerEventListeners(level)
{
App.Screen.prototype._registerEventListeners.call(this,level);
if (level === App.EventLevel.LEVEL_2)
{
var EventType = App.EventType;
this._scrollTween.addEventListener(EventType.COMPLETE,this,this._onScrollTweenComplete);
this._input.addEventListener(EventType.BLUR,this,this._onInputBlur);
this._budget.addEventListener(EventType.BLUR,this,this._onInputBlur);
}
};
/**
* UnRegister event listeners
* @param {number} level
* @private
*/
App.EditCategoryScreen.prototype._unRegisterEventListeners = function _unRegisterEventListeners(level)
{
App.Screen.prototype._unRegisterEventListeners.call(this,level);
var EventType = App.EventType;
this._scrollTween.removeEventListener(EventType.COMPLETE,this,this._onScrollTweenComplete);
this._budget.removeEventListener(EventType.BLUR,this,this._onInputBlur);
this._input.removeEventListener(EventType.BLUR,this,this._onInputBlur);
};
/**
* Register delete button event listeners
* @private
*/
App.EditCategoryScreen.prototype._registerDeleteButtonListeners = function _registerDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.addEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.addEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.addEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* UnRegister delete button event listeners
* @private
*/
App.EditCategoryScreen.prototype._unRegisterDeleteButtonListeners = function _unRegisterDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.removeEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.removeEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.removeEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* On delete cancel
* @private
*/
App.EditCategoryScreen.prototype._onDeleteCancel = function _onDeleteCancel()
{
this._deleteButton.hidePopUp();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
};
/**
* On delete confirm
* @private
*/
App.EditCategoryScreen.prototype._onDeleteConfirm = function _onDeleteConfirm()
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
this._onHidePopUpComplete();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(EventType.CHANGE_CATEGORY,{
type:EventType.DELETE,
category:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
};
/**
* On Delete PopUp hide complete
* @private
*/
App.EditCategoryScreen.prototype._onHidePopUpComplete = function _onHidePopUpComplete()
{
this._unRegisterDeleteButtonListeners();
this.enable();
this._registerEventListeners(App.EventLevel.LEVEL_2);
};
/**
* Click handler
* @private
*/
App.EditCategoryScreen.prototype._onClick = function _onClick()
{
this._pane.cancelScroll();
var inputFocused = this._scrollState === App.TransitionState.SHOWN && this._scrollInput,
touchData = this.stage.getTouchData(),
position = touchData.getLocalPosition(this._container),
y = position.y;
if (this._input.hitTest(y))
{
this._scrollInput = this._input;
this._focusInput(this._scrollInput.y + this._container.y > 0);
this._subCategoryList.closeButtons();
}
else if (this._colorList.hitTest(y))
{
this._onSampleClick(this._colorList,position.x,inputFocused);
}
else if (this._topIconList.hitTest(y))
{
this._onSampleClick(this._topIconList,position.x,inputFocused);
}
else if (this._bottomIconList.hitTest(y))
{
this._onSampleClick(this._bottomIconList,position.x,inputFocused);
}
else if (this._subCategoryList.hitTest(y))
{
var button = this._subCategoryList.getItemUnderPoint(touchData),
ScreenMode = App.ScreenMode;
if (button)
{
if (inputFocused) this._scrollInput.blur();
//TODO if in new category, newly set name will be lost of change screen here ...
if (button instanceof App.AddNewButton)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SUB_CATEGORY,{
type:App.EventType.CREATE,
category:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT,
ScreenMode.ADD,
null,
0,
0,
App.ScreenTitle.ADD_SUB_CATEGORY
)
});
}
else
{
button.onClick(touchData,this._model,this._subCategoryList.length > 1 ? ScreenMode.EDIT : ScreenMode.ADD);
}
}
this._subCategoryList.closeButtons();
}
else if (this._budget.hitTest(y))
{
this._scrollInput = this._budget;
this._focusInput(false);
this._subCategoryList.closeButtons();
}
else if (this._deleteButton.hitTest(y))
{
if (inputFocused)
{
this._scrollInput.blur();
}
else
{
this.disable();
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
App.ViewLocator.getViewSegment(App.ViewName.HEADER).disableActions();
this._registerDeleteButtonListeners();
this._deleteButton.setPopUpLayout(0,this._container.y + this._layout.headerHeight,0,this._layout.contentHeight > this._container.height ? this._layout.contentHeight : this._container.height);
this._deleteButton.showPopUp();
}
}
else
{
if (inputFocused) this._scrollInput.blur();
}
};
/**
* On sample click
* @param {App.InfiniteList} list
* @param {number} position
* @param {boolean} inputFocused
* @private
*/
App.EditCategoryScreen.prototype._onSampleClick = function _onSampleClick(list,position,inputFocused)
{
if (inputFocused) this._scrollInput.blur();
list.cancelScroll();
var sample = list.selectItemByPosition(position);
if (sample instanceof App.ColorSample)
{
App.GraphicUtils.drawRect(this._colorStripe,"0x"+sample.getValue(),1,0,0,this._colorStripe.width,this._colorStripe.height);
this._icon.tint = parseInt(sample.getValue(),16);
}
else if (sample instanceof App.IconSample)
{
this._icon.setTexture(PIXI.TextureCache[sample.getValue()]);
(list === this._topIconList ? this._bottomIconList : this._topIconList).selectItemByPosition(-10000);
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.EditCategoryScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK),
changeCategoryData = {
type:EventType.CONFIRM,
category:this._model,
name:this._input.getValue(),
color:this._colorList.getSelectedValue(),
icon:this._getSelectedIcon(),
budget:this._budget.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
};
if (this._scrollState === App.TransitionState.SHOWN && this._scrollInput) this._scrollInput.blur();
if (action === App.HeaderAction.CONFIRM)
{
this._model.clearSavedStates();
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(EventType.CHANGE_CATEGORY,changeCategoryData);
}
else if (action === App.HeaderAction.CANCEL)
{
changeCategoryData.type = EventType.CANCEL;
App.Controller.dispatchEvent(EventType.CHANGE_CATEGORY,changeCategoryData);
}
};
/**
* Return selected icon
* @returns {string}
* @private
*/
App.EditCategoryScreen.prototype._getSelectedIcon = function _getSelectedIcon()
{
var selectedIcon = this._topIconList.getSelectedValue();
if (!selectedIcon) selectedIcon = this._bottomIconList.getSelectedValue();
return selectedIcon;
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.EditCategoryScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
if (!preferScroll) this._pane.cancelScroll();
this._subCategoryList.swipeStart(direction);
};
/**
* Called when swipe ends
* @private
*/
App.EditCategoryScreen.prototype._swipeEnd = function _swipeEnd()
{
this._subCategoryList.swipeEnd();
};
/**
* Generate and return array of color samples
* @returns {Array.<number>}
* @private
*/
App.EditCategoryScreen.prototype._getColorSamples = function _getColorSamples()
{
var convertFn = App.MathUtils.rgbToHex,
i = 0,
l = 30,
frequency = 2 * Math.PI/l,
amplitude = 127,
center = 128,
colorSamples = new Array(l);
for (;i<l;i++)
{
colorSamples[i] = convertFn(
Math.round(Math.sin(frequency * i + 0) * amplitude + center),
Math.round(Math.sin(frequency * i + 2) * amplitude + center),
Math.round(Math.sin(frequency * i + 4) * amplitude + center)
);
}
return colorSamples;
};
/**
* @class TransactionButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {{width:number,height:number,pixelRatio:number:labelStyles:Object}} options
* @constructor
*/
App.TransactionButton = function TransactionButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
var Text = PIXI.Text,
Graphics = PIXI.Graphics,
editStyle = options.labelStyles.edit;
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._pixelRatio = options.pixelRatio;
this._labelStyles = options.labelStyles;
this._isPending = void 0;
this._background = this.addChild(new Graphics());
this._copyLabel = this.addChild(new Text("Copy",editStyle));
this._editLabel = this.addChild(new Text("Edit",editStyle));
this._icon = null;
this._iconResizeRatio = -1;
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._redSkin = this._swipeSurface.addChild(new PIXI.Sprite(options.redSkin));
this._greySkin = this._swipeSurface.addChild(new PIXI.Sprite(options.greySkin));
this._colorStripe = this._swipeSurface.addChild(new Graphics());
this._accountField = this._swipeSurface.addChild(new Text("",editStyle));
this._categoryField = this._swipeSurface.addChild(new Text("",editStyle));
this._amountField = this._swipeSurface.addChild(new Text("",editStyle));
this._currencyField = this._swipeSurface.addChild(new Text("",editStyle));
this._dateField = this._swipeSurface.addChild(new Text("",editStyle));
this._pendingFlag = this._swipeSurface.addChild(new Graphics());
this._pendingLabel = this._pendingFlag.addChild(new Text("PENDING",this._labelStyles.pending));
};
App.TransactionButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* Update
* @param {boolean} [updateAll=false]
* @private
*/
App.TransactionButton.prototype._update = function _update(updateAll)
{
var pending = this._model.pending,
date = this._model.date,
dateText = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
this._accountField.setText(this._model.account.name);
this._amountField.setText(this._model.amount);
this._currencyField.setText(" " + this._model.currencyQuote);
this._categoryField.setText(this._model.subCategory.name+" / "+this._model.category.name);
this._dateField.setText(pending ? "Due by\n"+dateText : dateText);
if (this._icon) this._icon.setTexture(PIXI.TextureCache[this._model.category.icon]);
else this._icon = this._swipeSurface.addChild(PIXI.Sprite.fromFrame(this._model.category.icon));
if (pending !== this._isPending)
{
if (pending)
{
this._accountField.setStyle(this._labelStyles.accountPending);
this._amountField.setStyle(this._labelStyles.amountPending);
this._currencyField.setStyle(this._labelStyles.currencyPending);
this._categoryField.setStyle(this._labelStyles.accountPending);
this._dateField.setStyle(this._labelStyles.datePending);
}
else
{
this._accountField.setStyle(this._labelStyles.accountIncome);
this._amountField.setStyle(this._labelStyles.amountIncome);
this._currencyField.setStyle(this._labelStyles.currencyIncome);
this._categoryField.setStyle(this._labelStyles.accountIncome);
this._dateField.setStyle(this._labelStyles.date);
}
}
this._render(updateAll,pending);
this._updateLayout(updateAll,pending);
this.close(true);
this._isPending = pending;
};
/**
* Render
* @param {boolean} [renderAll=false]
* @param {boolean} pending
* @private
*/
App.TransactionButton.prototype._render = function _render(renderAll,pending)
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
swipeOptionWidth = Math.round(this._openOffset / 2);
if (renderAll)
{
GraphicUtils.drawRects(this._background,ColorTheme.GREEN,1,[0,0,w-swipeOptionWidth,h],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.RED,1,[w-swipeOptionWidth,0,swipeOptionWidth,h],false,true);
GraphicUtils.drawRect(this._pendingFlag,0x000000,1,0,0,Math.round(this._pendingLabel.width+10*r),Math.round(this._pendingLabel.height+6*r));
}
GraphicUtils.drawRect(this._colorStripe,"0x"+this._model.category.color,1,0,0,Math.round(4 * r),h);
if (pending !== this._isPending)
{
if (pending)
{
this._greySkin.visible = false;
this._redSkin.visible = true;
this._pendingFlag.visible = true;
}
else
{
this._greySkin.visible = true;
this._redSkin.visible = false;
this._pendingFlag.visible = false;
}
}
this._icon.tint = pending ? ColorTheme.RED_DARK : parseInt(this._model.category.color,16);
};
/**
* Update layout
* @param {boolean} [updateAll=false]
* @param {boolean} pending
* @private
*/
App.TransactionButton.prototype._updateLayout = function _updateLayout(updateAll,pending)
{
var r = this._pixelRatio,
w = this.boundingBox.width,
h = this.boundingBox.height,
swipeOptionWidth = Math.round(60 * r),
padding = Math.round(10 * r);
if (updateAll)
{
this._copyLabel.x = w - swipeOptionWidth * 2 + Math.round((swipeOptionWidth - this._copyLabel.width) / 2);
this._copyLabel.y = Math.round((h - this._copyLabel.height) / 2);
this._editLabel.x = w - swipeOptionWidth + Math.round((swipeOptionWidth - this._editLabel.width) / 2);
this._editLabel.y = Math.round((h - this._editLabel.height) / 2);
if (this._iconResizeRatio === -1) this._iconResizeRatio = Math.round(32 * this._pixelRatio) / this._icon.height;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round(20 * r);
this._icon.y = Math.round((h - this._icon.height) / 2);
this._accountField.x = Math.round(70 * r);
this._accountField.y = Math.round(7 * r);
this._amountField.x = Math.round(70 * r);
this._amountField.y = Math.round(26 * r);
this._currencyField.y = Math.round(33 * r);
this._categoryField.x = Math.round(70 * r);
this._categoryField.y = Math.round(52 * r);
this._pendingLabel.x = Math.round(5 * r);
this._pendingLabel.y = Math.round(4 * r);
this._pendingFlag.x = Math.round(w - padding - this._pendingFlag.width);
this._pendingFlag.y = Math.round(7 * r);
}
this._currencyField.x = Math.round(this._amountField.x + this._amountField.width);
this._dateField.x = Math.round(w - padding - this._dateField.width);
this._dateField.y = pending ? Math.round(38 * r) : Math.round(52 * r);
};
/**
* Set model
* @param {App.Transaction} model
*/
App.TransactionButton.prototype.setModel = function setModel(model)
{
this._model = model;
this._update(this._icon === null);
};
/**
* Click handler
* @param {PIXI.InteractionData} data
*/
App.TransactionButton.prototype.onClick = function onClick(data)
{
var position = data.getLocalPosition(this).x;
if (this._isOpen && position >= this._width - this._openOffset)
{
var changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update();
// Edit
if (position >= this._width - this._openOffset / 2)
{
App.ModelLocator.getProxy(App.ModelName.TRANSACTIONS).setCurrent(this._model);
changeScreenData.screenMode = App.ScreenMode.EDIT;
changeScreenData.updateData = this._model;
changeScreenData.headerName = App.ScreenTitle.EDIT_TRANSACTION;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
// Copy
else
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.COPY,
transaction:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.TransactionButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.TransactionButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
/**
* @class TransactionScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.TransactionScreen = function TransactionScreen(layout)
{
App.Screen.call(this,layout,0.4);
//TODO display message/tutorial in case of empty screen
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width,
h = layout.contentHeight,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
labelStyles:{
edit:FontStyle.get(18,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
accountIncome:FontStyle.get(14,FontStyle.BLUE_LIGHT,null,FontStyle.LIGHT_CONDENSED),
amountIncome:FontStyle.get(26,FontStyle.BLUE),
currencyIncome:FontStyle.get(16,FontStyle.BLUE_DARK,null,FontStyle.LIGHT_CONDENSED),
date:FontStyle.get(14,FontStyle.GREY_DARK),
pending:FontStyle.get(12,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
accountPending:FontStyle.get(14,FontStyle.RED_DARK),
amountPending:FontStyle.get(26,FontStyle.WHITE),
currencyPending:FontStyle.get(16,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
datePending:FontStyle.get(14,FontStyle.WHITE,"right",FontStyle.LIGHT_CONDENSED)
},
greySkin:skin.GREY_70,
redSkin:skin.RED_70,
width:w,
height:Math.round(70 * r),
pixelRatio:r,
openOffset:Math.round(120 * r)
};
this._interactiveButton = null;
this._buttonPool = new App.ObjectPool(App.TransactionButton,4,buttonOptions);
this._buttonList = new App.VirtualList(this._buttonPool,App.Direction.Y,w,h,r);
this._pane = this.addChild(new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,w,h,r,false));
this._pane.setContent(this._buttonList);
};
App.TransactionScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.TransactionScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.enable();
this._swipeEnabled = true;
};
/**
* Disable
*/
App.TransactionScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
this._swipeEnabled = false;
};
/**
* Update
*/
App.TransactionScreen.prototype.update = function update(model)
{
this._model = model;
this._buttonList.update(model);
this._pane.resize();
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.TransactionScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
this._interactiveButton = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (this._interactiveButton) this._interactiveButton.swipeStart(direction);
this._closeButtons(false);
};
/**
* Called when swipe ends
* @private
*/
App.TransactionScreen.prototype._swipeEnd = function _swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.TransactionScreen.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._buttonList.children.length,
button = null;
for (;i<l;)
{
button = this._buttonList.getChildAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
};
/**
* Click handler
* @private
*/
App.TransactionScreen.prototype._onClick = function _onClick()
{
var data = this.stage.getTouchData(),
button = this._buttonList.getItemUnderPoint(data);
if (button) button.onClick(data);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.TransactionScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate();
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
changeScreenData.update(App.ScreenName.MENU,0,null,HeaderAction.NONE,HeaderAction.CANCEL,App.ScreenTitle.MENU);
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
};
/**
* @class ReportSubCategoryButton
* @extends DisplayObjectContainer
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {Object} options.labelStyles
* @constructor
*/
App.ReportSubCategoryButton = function ReportSubCategoryButton(poolIndex,options)
{
PIXI.DisplayObjectContainer.call(this);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._model = null;
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Sprite(options.skin));
this._colorStripe = this.addChild(new PIXI.Graphics());
this._nameField = this.addChild(new PIXI.Text("",options.labelStyles.name));
this._percentField = this.addChild(new PIXI.Text("%",options.labelStyles.percent));
this._amountField = this.addChild(new PIXI.Text("",options.labelStyles.amount));
this._renderAll = true;
};
App.ReportSubCategoryButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @param {number} color
* @private
*/
App.ReportSubCategoryButton.prototype._render = function _render(color)
{
var padding = Math.round(10 * this._pixelRatio),
w = this.boundingBox.width,
h = this.boundingBox.height;
if (this._renderAll)
{
this._renderAll = false;
this._nameField.x = padding * 2;
this._nameField.y = Math.round((h - this._nameField.height) / 2);
this._percentField.y = Math.round((h - this._percentField.height) / 2);
this._amountField.y = Math.round((h - this._amountField.height) / 2);
}
App.GraphicUtils.drawRect(this._colorStripe,color,1,0,0,Math.round(2 * this._pixelRatio),h);
this._percentField.x = Math.round(w * 0.7 - this._percentField.width);
this._amountField.x = Math.round(w - padding - this._amountField.width);
};
/**
* Set model
* @param {App.SubCategory} model
* @param {number} accountBalance
* @param {string} color
*/
App.ReportSubCategoryButton.prototype.setModel = function setModel(model,accountBalance,color)
{
this._model = model;
this._nameField.setText(this._model.name);
this._percentField.setText(((this._model.balance / accountBalance) * 100).toFixed(1) + " %");
this._amountField.setText(App.StringUtils.formatNumber(Math.abs(this._model.balance),2,","));
this._render(color);
};
/**
* Update
* @param {string} color
* @private
*/
App.ReportSubCategoryButton.prototype._update = function _update(color)
{
this._nameField.setText(this._model.name);
this._render();
};
/**
* @class ReportCategoryButton
* @extends ExpandButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Texture} options.skin
* @param {Object} options.labelStyles
* @param {App.ObjectPool} options.subCategoryButtonPool
* @constructor
*/
App.ReportCategoryButton = function ReportCategoryButton(poolIndex,options)
{
App.ExpandButton.call(this,options.width,options.height,false);
this.allocated = false;
this.poolIndex = poolIndex;
this._model = null;
this._accountBalance = 0.0;
this._pixelRatio = options.pixelRatio;
this._buttonPool = options.subCategoryButtonPool;
this._background = this.addChild(new PIXI.Sprite(options.skin));
this._colorStripe = this.addChild(new PIXI.Graphics());
this._nameField = this.addChild(new PIXI.Text("",options.labelStyles.name));
this._percentField = this.addChild(new PIXI.Text("%",options.labelStyles.percent));
this._amountField = this.addChild(new PIXI.Text("",options.labelStyles.amount));
this._subCategoryList = new App.List(App.Direction.Y);
this._renderAll = true;
this._updated = false;
this._setContent(this._subCategoryList);
this.addChild(this._subCategoryList);
};
App.ReportCategoryButton.prototype = Object.create(App.ExpandButton.prototype);
/**
* Render
* @private
*/
App.ReportCategoryButton.prototype._render = function _render()
{
var padding = Math.round(10 * this._pixelRatio),
w = this.boundingBox.width,
h = this.boundingBox.height;
if (this._renderAll)
{
this._renderAll = false;
this._nameField.x = Math.round(15 * this._pixelRatio);
this._nameField.y = Math.round((h - this._nameField.height) / 2);
this._percentField.y = Math.round((h - this._percentField.height) / 2);
this._amountField.y = Math.round((h - this._amountField.height) / 2);
}
App.GraphicUtils.drawRect(this._colorStripe,"0x" + this._model.color,1,0,0,Math.round(4 * this._pixelRatio),h);
this._percentField.x = Math.round(w * 0.7 - this._percentField.width);
this._amountField.x = Math.round(w - padding - this._amountField.width);
};
/**
* Set model
* @param {App.Category} model
* @param {number} accountBalance
*/
App.ReportCategoryButton.prototype.setModel = function setModel(model,accountBalance)
{
this._updated = false;
this._model = model;
this._accountBalance = accountBalance;
this.close(true);
this._nameField.setText(this._model.name);
this._percentField.setText(((this._model.balance / this._accountBalance) * 100).toFixed(1) + " %");
this._amountField.setText(App.StringUtils.formatNumber(Math.abs(this._model.balance),2,","));
this._render();
};
/**
* Return model
* @returns {App.Category}
*/
App.ReportCategoryButton.prototype.getModel = function getModel()
{
return this._model;
};
/**
* Update
* @private
*/
App.ReportCategoryButton.prototype._update = function _update()
{
this._updated = true;
var i = 0,
l = this._subCategoryList.length,
subCategories = this._model.subCategories,
color = "0x" + this._model.color,
subCategory = null,
button = null;
for (;i<l;i++) this._buttonPool.release(this._subCategoryList.removeItemAt(0));
for (i=0,l=subCategories.length;i<l;)
{
subCategory = subCategories[i++];
button = this._buttonPool.allocate();
button.setModel(subCategory,this._accountBalance,color);
this._subCategoryList.add(button);
}
this._subCategoryList.updateLayout();
};
/**
* Click handler
* @param {Point} position
*/
App.ReportCategoryButton.prototype.onClick = function onClick(position)
{
var TransitionState = App.TransitionState;
if (this._transitionState === TransitionState.CLOSED || this._transitionState === TransitionState.CLOSING)
{
if (!this._updated) this._update();
this.open(true);
}
else if (this._transitionState === TransitionState.OPEN || this._transitionState === TransitionState.OPENING)
{
this.close(false,true);
}
};
/**
* @class ReportAccountButton
* @extends ExpandButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {Object} options.labelStyles
* @param {App.ObjectPool} options.categoryButtonPool
* @constructor
*/
App.ReportAccountButton = function ReportAccountButton(poolIndex,options)
{
App.ExpandButton.call(this,options.width,options.height,true);
this.allocated = false;
this.poolIndex = poolIndex;
this._model = null;
this._height = options.height;
this._pixelRatio = options.pixelRatio;
this._buttonPool = options.categoryButtonPool;
this._background = this.addChild(new PIXI.Graphics());
this._nameField = this.addChild(new PIXI.Text("",options.labelStyles.name));
this._amountField = this.addChild(new PIXI.Text("",options.labelStyles.amount));
this._categoryList = new App.List(App.Direction.Y);
this._interactiveButton = null;
this._renderAll = true;
this._updated = false;
this._setContent(this._categoryList);
this.addChild(this._categoryList);
};
App.ReportAccountButton.prototype = Object.create(App.ExpandButton.prototype);
/**
* Render
* @private
*/
App.ReportAccountButton.prototype._render = function _render()
{
var w = this.boundingBox.width;
if (this._renderAll)
{
this._renderAll = false;
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
h = this.boundingBox.height;
GraphicUtils.drawRects(this._background,ColorTheme.BLUE,1,[0,0,w,h],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.BLUE_DARK,1,[0,h-1,w,1],false,true);
this._nameField.x = Math.round(10 * this._pixelRatio);
this._nameField.y = Math.round((h - this._nameField.height) / 2);
this._amountField.y = Math.round((h - this._amountField.height) / 2);
}
this._amountField.x = Math.round(w - this._amountField.width - 10 * this._pixelRatio);
};
/**
* Set model
* @param {App.Account} model
*/
App.ReportAccountButton.prototype.setModel = function setModel(model)
{
this._updated = false;
this._model = model;
this.close(true);
this._nameField.setText(this._model.name);
this._amountField.setText(App.StringUtils.formatNumber(Math.abs(this._model.balance),2,","));
this._render();
};
/**
* Return button's model
* @returns {App.Account}
*/
App.ReportAccountButton.prototype.getModel = function getModel()
{
return this._model;
};
/**
* Update
*/
App.ReportAccountButton.prototype._update = function _update()
{
this._updated = true;
var i = 0,
l = this._categoryList.length,
accountBalance = this._model.balance,
categories = this._model.categories,
category = null,
button = null;
for (;i<l;i++) this._buttonPool.release(this._categoryList.removeItemAt(0));
for (i=0,l=categories.length;i<l;)
{
category = categories[i++];
button = this._buttonPool.allocate();
button.setModel(category,accountBalance);
this._categoryList.add(button);
}
this._categoryList.updateLayout();
};
/**
* Close opened buttons
* @private
*/
App.ReportAccountButton.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._categoryList.children.length,
button = null;
for (;i<l;)
{
button = this._categoryList.getChildAt(i++);
if (button !== this._interactiveButton && button.isOpen()) button.close(immediate);
}
};
/**
* Click handler
* @param {PIXI.InteractionData} pointerData
*/
App.ReportAccountButton.prototype.onClick = function onClick(pointerData)
{
var position = pointerData.getLocalPosition(this).y,
TransitionState = App.TransitionState;
// Click on button itself
if (position <= this._height)
{
if (this._transitionState === TransitionState.CLOSED || this._transitionState === TransitionState.CLOSING)
{
this.open();
}
else if (this._transitionState === TransitionState.OPEN || this._transitionState === TransitionState.OPENING)
{
this.close(false,true);
}
return null;
}
// Click on category sub-list
else if (position > this._height)
{
this._interactiveButton = this._categoryList.getItemUnderPoint(pointerData);
if (this._interactiveButton)
{
this._interactiveButton.onClick(position);
this._closeButtons();
return this._interactiveButton;
}
}
return null;
};
/**
* Open
*/
App.ReportAccountButton.prototype.open = function open()
{
if (!this._updated) this._update();
this._interactiveButton = null;
this._closeButtons(true);
App.ExpandButton.prototype.open.call(this,true);
};
/**
* Update layout
* @private
*/
App.ReportAccountButton.prototype.updateLayout = function updateLayout()
{
this._categoryList.updateLayout();
this._updateBounds(true);
this._updateMask();
};
/**
* Check if button is in transition
* @returns {boolean}
*/
App.ReportAccountButton.prototype.isInTransition = function isInTransition()
{
var inTransition = App.ExpandButton.prototype.isInTransition.call(this),
i = 0,
l = this._categoryList.children.length;
if (this.isOpen())
{
for (;i<l;)
{
if (this._categoryList.getChildAt(i++).isInTransition())
{
inTransition = true;
break;
}
}
}
return inTransition;
};
/**
* @class ReportChartHighlight
* @extends Graphics
* @param {Point} center
* @param {number} width
* @param {number} height
* @param {number} thickness
* @constructor
*/
App.ReportChartHighlight = function ReportChartHighlight(center,width,height,thickness)
{
PIXI.Graphics.call(this);
this._width = width;
this._height = height;
this._center = center;
this._thickness = thickness;
this._oldStart = 0;
this._oldEnd = 0;
this._oldSteps = 0;
this._start = 0;
this._end = 0;
this._steps = 10;
this._color = 0x000000;
};
App.ReportChartHighlight.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Change
* @param {App.ReportChartSegment} segment
*/
App.ReportChartHighlight.prototype.change = function change(segment)
{
this._oldStart = this._start;
this._oldEnd = this._end;
this._oldSteps = this._steps;
if (segment)
{
this._start = segment.startAngle;
this._end = segment.endAngle;
this._steps = segment.steps;
this._color = "0x"+segment.color;
}
else
{
this._start = 0.0;
this._end = 0.0;
this._steps = 10;
}
};
/**
* Update change by progress passed in
* @param {number} progress
*/
App.ReportChartHighlight.prototype.update = function update(progress)
{
var start = this._oldStart + (this._start - this._oldStart) * progress,
end = this._oldEnd + (this._end - this._oldEnd) * progress,
alpha = this._end === this._start ? 1 - progress : 1.0,
steps = Math.round(this._oldSteps + (this._steps - this._oldSteps) * progress);
App.GraphicUtils.drawArc(this,this._center,this._width,this._height,this._thickness,start,end,steps,0,0,0,this._color,alpha);
};
/**
* @class ReportChartSegment
* @param {number} poolIndex
* @constructor
*/
App.ReportChartSegment = function ReportChartSegment(poolIndex)
{
PIXI.Graphics.call(this);
this.allocated = false;
this.poolIndex = poolIndex;
this._model = null;
this.color = 0;
this.fraction = 0.0;
this.startAngle = 0.0;
this.endAngle = 0.0;
this.steps = 10;
this.fullyRendered = false;
};
App.ReportChartSegment.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Set model
* @param {App.Category} model
* @param {number} totalBalance
* @param {number} previousBalance
*/
App.ReportChartSegment.prototype.setModel = function setModel(model,totalBalance,previousBalance)
{
this._model = model;
this.color = this._model.color;
this.fraction = (this._model.balance / totalBalance) ;
this.startAngle = Math.abs(previousBalance / totalBalance) * 360;
this.endAngle = this.startAngle + this.fraction * 360;
this.steps = Math.ceil(this.fraction * 60);
this.fullyRendered = false;
this.clear();
};
/**
* Check if this segment renders model passed in
* @param {App.Category} model
* @returns {boolean}
*/
App.ReportChartSegment.prototype.rendersModel = function rendersModel(model)
{
return this._model === model;
};
/**
* @class ReportChart
* @extends Graphics
* @param {App.Collection} model
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.ReportChart = function ReportChart(model,width,height,pixelRatio)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
eventListenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,width,height);
this._model = model;
this._eventsRegistered = false;
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._segmentTween = new App.TweenProxy(1,App.Easing.outExpo,0,eventListenerPool);
this._highlightTween = new App.TweenProxy(1,App.Easing.outExpo,0,eventListenerPool);
this._segmentPool = new App.ObjectPool(App.ReportChartSegment,5);
this._segments = null;
this._showSegments = void 0;
this._hideSegments = void 0;
this._highlightSegment = void 0;
this._center = new PIXI.Point(Math.round(width/2),Math.round(height/2));
this._thickness = Math.round(width * 0.07 * pixelRatio);
this._chartSize = width - Math.round(5 * pixelRatio * 2);// 5px margin on sides for highlight line
this._highlight = this.addChild(new App.ReportChartHighlight(this._center,width,height,Math.round(3 * pixelRatio)));
};
App.ReportChart.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Update
*/
App.ReportChart.prototype.update = function update()
{
var i = 0,
l = this._model.length(),
j = 0,
k = 0,
totalBalance = 0.0,
previousBalance = 0.0,
deletedState = App.LifeCycleState.DELETED,
segmentArray = null,
segment = null,
account = null,
category = null,
categories = null;
// Reset segments and highlight
this._showSegments = null;
this._hideSegments = null;
this._highlight.change(null);
this._highlight.update(1);
// Release segments back to pool
if (this._segments)
{
for (var prop in this._segments)
{
segmentArray = this._segments[prop];
while (segmentArray.length)
{
segment = segmentArray.pop();
this.removeChild(segment);
this._segmentPool.release(segment);
}
}
}
else
{
this._segments = Object.create(null);
}
// Populate segments again
for (i=0;i<l;)
{
account = this._model.getItemAt(i++);
totalBalance = account.balance;
if (account.lifeCycleState !== deletedState && !isNaN(totalBalance) && totalBalance !== 0.0)
{
if (!this._segments[account.id]) this._segments[account.id] = [];
segmentArray = this._segments[account.id];
previousBalance = 0.0;
category = null;
categories = account.categories;
for (j=0,k=categories.length;j<k;)
{
if (category) previousBalance += category.balance;
category = categories[j++];
segment = this._segmentPool.allocate();
segment.setModel(category,totalBalance,previousBalance);
segmentArray.push(segment);
this.addChild(segment);
}
}
}
};
/**
* Show segments associated with account passed in
* @param {App.Account} account
*/
App.ReportChart.prototype.showSegments = function showSegments(account)
{
if (this._showSegments)
{
if (this._showSegments === this._segments[account.id]) return;
this._hideSegments = this._showSegments;
}
else
{
this._hideSegments = null;
}
this._showSegments = this._segments[account.id];
for (var i=0,l=this._showSegments.length;i<l;) this._showSegments[i++].fullyRendered = false;
this._registerEventListeners();
this._segmentTween.restart();
};
/**
* Highlight segment
* @param {App.Category} category
*/
App.ReportChart.prototype.highlightSegment = function highlightSegment(category)
{
//TODO add icon of highlighted category in the middle of chart
if (this._showSegments)
{
var segment = this._getSegmentByCategory(category);
if (segment === this._highlightSegment) return;
this._highlightSegment = segment;
this._highlight.change(segment);
this._registerEventListeners();
this._highlightTween.restart();
}
};
/**
* Find and return segment by category passed in
* @param {App.Category} category
* @returns {App.ReportChartSegment}
* @private
*/
App.ReportChart.prototype._getSegmentByCategory = function _getSegmentByCategory(category)
{
var i = 0,
l = this._showSegments.length;
for (;i<l;i++)
{
if (this._showSegments[i].rendersModel(category)) return this._showSegments[i];
}
return null;
};
/**
* Register event listeners
* @private
*/
App.ReportChart.prototype._registerEventListeners = function _registerEventListeners()
{
if (!this._eventsRegistered)
{
this._eventsRegistered = true;
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._segmentTween.addEventListener(App.EventType.COMPLETE,this,this._onSegmentTweenComplete);
this._highlightTween.addEventListener(App.EventType.COMPLETE,this,this._onHighlightTweenComplete);
}
};
/**
* UnRegister event listeners
* @private
*/
App.ReportChart.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._segmentTween.removeEventListener(App.EventType.COMPLETE,this,this._onSegmentTweenComplete);
this._highlightTween.removeEventListener(App.EventType.COMPLETE,this,this._onHighlightTweenComplete);
this._eventsRegistered = false;
};
/**
* RAF tick handler
* @private
*/
App.ReportChart.prototype._onTick = function _onTick()
{
if (this._segmentTween.isRunning()) this._updateSegmentTween();
if (this._highlightTween.isRunning()) this._highlight.update(this._highlightTween.progress);
};
/**
* Update show hide tween
* @private
*/
App.ReportChart.prototype._updateSegmentTween = function _updateSegmentTween()
{
var GraphicUtils = App.GraphicUtils,
progress = this._segmentTween.progress,
progressAngle = progress * 360,
size = this._chartSize,
i = 0,
l = this._showSegments.length,
end = 0,
segment = null;
if (this._showSegments)
{
for (;i<l;i++)
{
segment = this._showSegments[i];
if (progressAngle >= segment.startAngle && !segment.fullyRendered)
{
end = progressAngle;
if (end >= segment.endAngle)
{
end = segment.endAngle;
segment.fullyRendered = true;
}
GraphicUtils.drawArc(segment,this._center,size,size,this._thickness,segment.startAngle,end,segment.steps,0,0,0,"0x"+segment.color,1);
}
}
}
if (this._hideSegments)
{
progress = 1 - progress;
size = this._chartSize * progress;
for (i=0,l=this._hideSegments.length;i<l;i++)
{
segment = this._hideSegments[i];
GraphicUtils.drawArc(segment,this._center,size,size,this._thickness,segment.startAngle,segment.endAngle,20,0,0,0,"0x"+segment.color,progress);
}
}
};
/**
* On segment tweenc omplete
* @private
*/
App.ReportChart.prototype._onSegmentTweenComplete = function _onSegmentTweenComplete()
{
if (!this._segmentTween.isRunning() && !this._highlightTween.isRunning()) this._unRegisterEventListeners();
this._updateSegmentTween();
};
/**
* On Highlight tween complete
* @private
*/
App.ReportChart.prototype._onHighlightTweenComplete = function _onHighlightTweenComplete()
{
if (!this._segmentTween.isRunning() && !this._highlightTween.isRunning()) this._unRegisterEventListeners();
this._highlight.update(1);
};
/**
* @class ReportScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.ReportScreen = function ReportScreen(layout)
{
App.Screen.call(this,layout,0.4);
//TODO display message/tutorial in case of empty screen
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
ObjectPool = App.ObjectPool,
h = layout.contentHeight,
r = layout.pixelRatio,
chartSize = Math.round(h * 0.3 - 20 * r),
listWidth = Math.round(layout.width - 20 * r),// 10pts padding on both sides
listHeight = Math.round(h * 0.7),
itemHeight = Math.round(40 * r),
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:listWidth,
height:itemHeight,
pixelRatio:r,
labelStyles:{
name:FontStyle.get(20,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
amount:FontStyle.get(16,FontStyle.WHITE)
},
categoryButtonPool:new ObjectPool(App.ReportCategoryButton,5,{
width:listWidth,
height:itemHeight,
pixelRatio:r,
skin:skin.NARROW_GREY_40,
labelStyles:{
name:FontStyle.get(18,FontStyle.BLUE),
percent:FontStyle.get(14,FontStyle.GREY_DARK),
amount:FontStyle.get(14,FontStyle.BLUE)
},
subCategoryButtonPool:new ObjectPool(App.ReportSubCategoryButton,5,{
width:listWidth,
height:itemHeight,
pixelRatio:r,
skin:skin.NARROW_WHITE_40,
labelStyles:{
name:FontStyle.get(14,FontStyle.BLUE),
percent:FontStyle.get(14,FontStyle.GREY_DARK),
amount:FontStyle.get(14,FontStyle.BLUE)
}
})
})
};
this._model = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS);
this._buttonPool = new ObjectPool(App.ReportAccountButton,2,buttonOptions);
this._chart = this.addChild(new App.ReportChart(this._model,chartSize,chartSize,r));
this._buttonList = new App.TileList(App.Direction.Y,listHeight);
this._pane = this.addChild(new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,listWidth,listHeight,r,true));
this._pane.setContent(this._buttonList);
this._updateLayout();
this._interactiveButton = null;
this._layoutDirty = false;
};
App.ReportScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.ReportScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.enable();
};
/**
* Disable
*/
App.ReportScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._layoutDirty = false;
this._pane.disable();
};
/**
* Update
*/
App.ReportScreen.prototype.update = function update()
{
var i = 0,
l = this._buttonList.length,
deletedState = App.LifeCycleState.DELETED,
account = null,
button = null,
balance = 0.0;
for (;i<l;i++) this._buttonPool.release(this._buttonList.removeItemAt(0));
for (i=0,l=this._model.length();i<l;)
{
account = this._model.getItemAt(i++);
balance = account.calculateBalance();
if (account.lifeCycleState !== deletedState && !isNaN(balance) && balance !== 0.0)
{
button = this._buttonPool.allocate();
button.setModel(account);
this._buttonList.add(button);
}
}
if (this._buttonList.length)
{
this._buttonList.updateLayout(true);
this._pane.resize();
this._chart.update();
}
};
/**
* On screen show/hide tween complete
* @private
*/
App.ReportScreen.prototype._onTweenComplete = function _onTweenComplete()
{
App.Screen.prototype._onTweenComplete.call(this);
if (this._transitionState === App.TransitionState.SHOWN)
{
if (this._buttonList.length)
{
var button = this._buttonList.getItemAt(0);
if (!button.isOpen()) button.open();
this._chart.showSegments(button.getModel());
this._layoutDirty = true;
}
}
};
/**
* Update layout
* @private
*/
App.ReportScreen.prototype._updateLayout = function _updateLayout()
{
var w = this._layout.width,
padding = Math.round(10 * this._layout.pixelRatio),
chartBounds = this._chart.boundingBox;
this._chart.x = Math.round((w - chartBounds.width) / 2);
this._chart.y = padding;
this._pane.x = padding;
this._pane.y = Math.round(this._layout.contentHeight * 0.3);
};
/**
* On tick
* @private
*/
App.ReportScreen.prototype._onTick = function _onTick()
{
App.Screen.prototype._onTick.call(this);
if (this._layoutDirty)
{
this._layoutDirty = this._buttonsInTransition();
this._updateListLayout(false);
}
};
/**
* Close opened buttons
* @private
*/
App.ReportScreen.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._buttonList.children.length,
button = null;
for (;i<l;)
{
button = this._buttonList.getChildAt(i++);
if (button !== this._interactiveButton && button.isOpen()) button.close(immediate);
}
};
/**
* Click handler
* @private
*/
App.ReportScreen.prototype._onClick = function _onClick()
{
var pointerData = this.stage.getTouchData(),
accountButtonOpen = false,
categoryButton = null;
this._interactiveButton = this._buttonList.getItemUnderPoint(pointerData);
if (this._interactiveButton)
{
accountButtonOpen = this._interactiveButton.isOpen();
categoryButton = this._interactiveButton.onClick(pointerData);
if (categoryButton)
{
if (categoryButton.isOpening()) this._chart.highlightSegment(categoryButton.getModel());
else this._chart.highlightSegment(null);
}
else
{
this._closeButtons();
this._chart.highlightSegment(null);
if (!accountButtonOpen) this._chart.showSegments(this._interactiveButton.getModel());
}
this._pane.cancelScroll();
this._layoutDirty = true;
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.ReportScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate();
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(
App.ScreenName.MENU,
0,
null,
HeaderAction.NONE,
HeaderAction.CANCEL,
App.ScreenTitle.MENU
));
}
};
/**
* Update list layout
* @private
*/
App.ReportScreen.prototype._updateListLayout = function _updateListLayout()
{
if (this._interactiveButton) this._interactiveButton.updateLayout();
this._buttonList.updateLayout(true);
this._pane.resize();
};
/**
* Check if buttons are in transition
* @returns {boolean}
* @private
*/
App.ReportScreen.prototype._buttonsInTransition = function _buttonsInTransition()
{
var i = 0,
l = this._buttonList.children.length,
inTransition = false;
for (;i<l;)
{
if (this._buttonList.getChildAt(i++).isInTransition())
{
inTransition = true;
break;
}
}
return inTransition;
};
/**
* @class CurrencyButton
* @extends DisplayObjectContainer
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {PIXI.Texture} options.skin
* @param {{font:string,fill:string}} options.symbolLabelStyle
* @constructor
*/
App.CurrencyButton = function CurrencyButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new PIXI.Rectangle(0,0,options.width,options.height);
this._model = null;
this._pixelRatio = options.pixelRatio;
this._skin = this.addChild(new PIXI.Sprite(options.skin));
this._symbolLabel = this.addChild(new PIXI.Text("",options.symbolLabelStyle));
this._renderAll = true;
this._render();
};
App.CurrencyButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* @method render
* @private
*/
App.CurrencyButton.prototype._render = function _render()
{
if (this._renderAll)
{
this._renderAll = false;
this._symbolLabel.x = Math.round(20 * this._pixelRatio);
this._symbolLabel.y = Math.round((this.boundingBox.height - this._symbolLabel.height) / 2);
}
};
/**
* Set model
* @param {App.CurrencySymbol} model
*/
App.CurrencyButton.prototype.setModel = function getModel(model)
{
this._model = model;
this._symbolLabel.setText(this._model.symbol);
};
/**
* Click handler
*/
App.CurrencyButton.prototype.onClick = function onClick()
{
var EventType = App.EventType,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
changeScreenData.updateBackScreen = true;
App.Controller.dispatchEvent(EventType.CHANGE_TRANSACTION,{
type:EventType.CHANGE,
currencyQuote:this._model.symbol,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
};
/**
* @class CurrencyScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.CurrencyScreen = function CurrencyScreen(layout)
{
App.Screen.call(this,layout,0.4);
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
h = layout.contentHeight,
w = layout.width,
r = layout.pixelRatio,
buttonOptions = {
width:w,
height:Math.round(50 * r),
pixelRatio:r,
skin:App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_50,
symbolLabelStyle:FontStyle.get(18,FontStyle.BLUE)
};
this._model = App.ModelLocator.getProxy(App.ModelName.CURRENCY_SYMBOLS);
this._interactiveButton = null;
this._buttonPool = new App.ObjectPool(App.CurrencyButton,4,buttonOptions);
this._buttonList = new App.VirtualList(this._buttonPool,App.Direction.Y,w,h,r);
this._pane = this.addChild(new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,w,h,r,false));
this._pane.setContent(this._buttonList);
this._initialized = false;
};
App.CurrencyScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.CurrencyScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.resetScroll();
this._pane.enable();
};
/**
* Disable
*/
App.CurrencyScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
};
/**
* Update
* @param {App.Collection} data
* @param {string} mode
* @private
*/
App.CurrencyScreen.prototype.update = function update(data,mode)
{
if (this._initialized)
{
this._pane.resetScroll();
this._buttonList.reset();
}
else
{
this._initialized = true;
this._buttonList.update(this._model.copySource());
this._pane.resize();
}
};
/**
* Click handler
* @private
*/
App.CurrencyScreen.prototype._onClick = function _onClick()
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button) button.onClick();
};
/**
* On Header click
* @param {number} action
* @private
*/
App.CurrencyScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
if (action === App.HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(
App.EventType.CHANGE_SCREEN,
App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK)
);
}
};
/**
* @class CurrencyPairButton
* @extends SwipeButton
* @param {number} poolIndex
* @param {Object} options
* @param {number} options.width
* @param {number} options.height
* @param {number} options.pixelRatio
* @param {PIXI.Texture} options.skin
* @param {{font:string,fill:string}} options.editLabelStyle
* @param {{font:string,fill:string}} options.pairLabelStyle
* @param {{font:string,fill:string}} options.rateLabelStyle
* @param {number} options.openOffset
* @constructor
*/
App.CurrencyPairButton = function CurrencyPairButton(poolIndex,options)
{
App.SwipeButton.call(this,options.width,options.openOffset);
this.allocated = false;
this.poolIndex = poolIndex;
this.boundingBox = new PIXI.Rectangle(0,0,options.width,options.height);
this._model = null;
//TODO add arrow to the right indicating Edit option
this._pixelRatio = options.pixelRatio;
this._background = this.addChild(new PIXI.Graphics());
this._editLabel = this.addChild(new PIXI.Text("Edit",options.editLabelStyle));
this._swipeSurface = this.addChild(new PIXI.DisplayObjectContainer());
this._skin = this._swipeSurface.addChild(new PIXI.Sprite(options.skin));
this._pairLabel = this._swipeSurface.addChild(new PIXI.Text("EUR/USD",options.pairLabelStyle));
this._rateLabel = this._swipeSurface.addChild(new PIXI.Text("@ 1.0",options.rateLabelStyle));
this._renderAll = true;
this._render();
};
App.CurrencyPairButton.prototype = Object.create(App.SwipeButton.prototype);
/**
* @method render
* @private
*/
App.CurrencyPairButton.prototype._render = function _render()
{
var w = this.boundingBox.width,
h = this.boundingBox.height,
r = this._pixelRatio,
offset = Math.round(15 * r);
App.GraphicUtils.drawRect(this._background,App.ColorTheme.RED,1,0,0,w,h);
this._editLabel.x = Math.round(w - 50 * this._pixelRatio);
this._editLabel.y = Math.round((h - this._editLabel.height) / 2);
this._pairLabel.x = offset;
this._pairLabel.y = Math.round((h - this._pairLabel.height) / 2);
this._rateLabel.x = Math.round(offset + this._pairLabel.width + 5 * r);
this._rateLabel.y = Math.round((h - this._rateLabel.height) / 2);
};
/**
* Set model
* @param {App.CurrencyPair} model
*/
App.CurrencyPairButton.prototype.setModel = function setModel(model)
{
this._model = model;
this._pairLabel.setText(model.base+"/"+model.symbol);
this._rateLabel.setText("@ "+model.rate);
};
/**
* Click handler
* @param {InteractionData} interactionData
*/
App.CurrencyPairButton.prototype.onClick = function onClick(interactionData)
{
if (this._isOpen && interactionData.getLocalPosition(this).x >= this._width - this._openOffset)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.EDIT_CURRENCY_RATE,
App.ScreenMode.EDIT,
this._model,
0,
0,
App.ScreenTitle.EDIT_CURRENCY_RATE
));
}
};
/**
* Update swipe position
* @param {number} position
* @private
*/
App.CurrencyPairButton.prototype._updateSwipePosition = function _updateSwipePosition(position)
{
this._swipeSurface.x = position;
};
/**
* Return swipe position
* @private
*/
App.CurrencyPairButton.prototype._getSwipePosition = function _getSwipePosition()
{
return this._swipeSurface.x;
};
/**
* @class CurrencyPairScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.CurrencyPairScreen = function CurrencyPairScreen(layout)
{
App.Screen.call(this,layout,0.4);
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
h = layout.contentHeight - Math.round(60 * r),
w = layout.width,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:w,
height:Math.round(50 * r),
pixelRatio:r,
skin:skin.GREY_50,
editLabelStyle:FontStyle.get(18,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
pairLabelStyle:FontStyle.get(18,FontStyle.BLUE),
rateLabelStyle:FontStyle.get(18,FontStyle.BLUE,null,FontStyle.LIGHT_CONDENSED),
openOffset:Math.round(80 * r)
};
this._model = App.ModelLocator.getProxy(App.ModelName.CURRENCY_PAIRS);
this._interactiveButton = null;
this._downloadButtonBackground = this.addChild(new PIXI.Sprite(skin.GREY_60));//TODO may not need this - I can use Screen BG
this._downloadButton = this.addChild(new App.Button("Update rates from internet",{
width:Math.round(w - 20 * r),
height:Math.round(40 * r),
pixelRatio:r,
style:FontStyle.get(18,FontStyle.BLACK_LIGHT,null,FontStyle.LIGHT_CONDENSED),
backgroundColor:App.ColorTheme.GREY_DARK
}));
this._buttonPool = new App.ObjectPool(App.CurrencyPairButton,4,buttonOptions);
this._buttonList = new App.VirtualList(this._buttonPool,App.Direction.Y,w,h,r);
this._pane = this.addChild(new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,w,h,r,true));
this._pane.setContent(this._buttonList);
this._swipeEnabled = true;
this._initialized = false;
};
App.CurrencyPairScreen.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.CurrencyPairScreen.prototype._render = function _render()
{
var padding = Math.round(10 * this._layout.pixelRatio),
buttonHeight = this._downloadButton.boundingBox.height + padding * 2;
this._downloadButton.x = padding;
this._downloadButton.y = padding;
this._pane.y = buttonHeight;
};
/**
* Enable
*/
App.CurrencyPairScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.resetScroll();
this._pane.enable();
};
/**
* Disable
*/
App.CurrencyPairScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
};
/**
* Update
* @param {App.Collection} data
* @param {string} mode
* @private
*/
App.CurrencyPairScreen.prototype.update = function update(data,mode)
{
if (this._initialized)
{
this._pane.resetScroll();
this._buttonList.reset();
}
else
{
this._initialized = true;
this._render();
this._buttonList.update(this._model.copySource());
this._pane.resize();
}
};
/**
* On tween complete
* @private
*/
App.CurrencyPairScreen.prototype._onTweenComplete = function _onTweenComplete()
{
App.Screen.prototype._onTweenComplete.call(this);
if (this._transitionState === App.TransitionState.HIDDEN) this._closeButtons(true);
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.CurrencyPairScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button)
{
if (!preferScroll) this._pane.cancelScroll();
this._interactiveButton = button;
this._interactiveButton.swipeStart(direction);
this._closeButtons(false);
}
};
/**
* Called when swipe ends
* @private
*/
App.CurrencyPairScreen.prototype._swipeEnd = function _swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.CurrencyPairScreen.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._buttonList.children.length,
button = null;
for (;i<l;)
{
button = this._buttonList.getChildAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
};
/**
* Click handler
* @private
*/
App.CurrencyPairScreen.prototype._onClick = function _onClick()
{
var data = this.stage.getTouchData(),
button = this._buttonList.getItemUnderPoint(data);
if (button) button.onClick(data);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.CurrencyPairScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate();
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(
App.ScreenName.MENU,
0,
null,
HeaderAction.NONE,
HeaderAction.CANCEL,
App.ScreenTitle.MENU
));
}
};
/**
* @class EditCurrencyPairScreen
* @param {Object} layout
* @constructor
*/
App.EditCurrencyPairScreen = function EditCurrencyPairScreen(layout)
{
App.Screen.call(this,layout,0.4);
var FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width;
this._background = this.addChild(new PIXI.Graphics());
this._pairLabel = this.addChild(new PIXI.Text("EUR / USD",App.FontStyle.get(24,App.FontStyle.BLUE)));
this._input = this.addChild(new App.Input("",20,Math.round(layout.width - this._pairLabel.width - Math.round(50 * r)),Math.round(40 * r),r));
this._downloadButton = this.addChild(new App.Button("Update rate from internet",{
width:Math.round(w - 20 * r),
height:Math.round(40 * r),
pixelRatio:r,
style:FontStyle.get(18,FontStyle.BLACK_LIGHT,null,FontStyle.LIGHT_CONDENSED),
backgroundColor:App.ColorTheme.GREY_DARK
}));
this._input.restrict(/\d{1,}(\.\d*){0,1}/g);
this._render();
};
App.EditCurrencyPairScreen.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.EditCurrencyPairScreen.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._layout.pixelRatio,
w = this._layout.width,
padding = Math.round(10 * r),
inputHeight = Math.round(60 * r);
this._pairLabel.x = padding * 2;
this._pairLabel.y = Math.round(22 * r);
this._input.x = Math.round(w - padding - this._input.width);
this._input.y = padding;
this._downloadButton.x = padding;
this._downloadButton.y = inputHeight + padding;
GraphicUtils.drawRects(this._background,ColorTheme.GREY,1,[0,0,w,inputHeight*2],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_DARK,1,[padding,inputHeight-1,w-padding*2,1],false,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_LIGHT,1,[padding,inputHeight,w-padding*2,1],false,true);
};
/**
* Enable
*/
App.EditCurrencyPairScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._input.enable();
};
/**
* Disable
*/
App.EditCurrencyPairScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._input.disable();
};
/**
* Update
* @param {App.CurrencyPair} model
* @param {string} mode
*/
App.EditCurrencyPairScreen.prototype.update = function update(model,mode)
{
this._model = model;
this._pairLabel.setText(this._model.base+" / "+this._model.symbol);
this._input.setValue(this._model.rate);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.EditCurrencyPairScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
changeScreenData.updateBackScreen = true;
this._input.blur();
//TODO check first if value is set
if (action === App.HeaderAction.CONFIRM)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_CURRENCY_PAIR,{
currencyPair:this._model,
rate:this._input.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else if (action === App.HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
};
/**
* @class MenuItem
* @extends Graphics
* @param {string} label
* @param {string} iconName
* @param {number} screenName
* @param {{width:number,height:number,pixelRatio:number,style:Object}} options
* @constructor
*/
App.MenuItem = function MenuItem(label,iconName,screenName,options)
{
PIXI.Graphics.call(this);
this.boundingBox = new App.Rectangle(0,0,options.width,options.height);
this._screenName = screenName;
this._pixelRatio = options.pixelRatio;
this._icon = PIXI.Sprite.fromFrame(iconName);
this._iconResizeRatio = Math.round(22 * options.pixelRatio) / this._icon.height;
this._labelField = new PIXI.Text(label,options.style);
this._render();
this.addChild(this._icon);
this.addChild(this._labelField);
};
App.MenuItem.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.MenuItem.prototype._render = function _render()
{
var ColorTheme = App.ColorTheme,
h = this.boundingBox.height;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round(15 * this._pixelRatio);
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = ColorTheme.WHITE;
this._labelField.x = Math.round(60 * this._pixelRatio);
this._labelField.y = Math.round((h - this._labelField.height) / 2);
App.GraphicUtils.drawRect(this,ColorTheme.BLUE,1.0,0,0,this.boundingBox.width,h);
};
/**
* Return associated screen name
* @returns {number}
*/
App.MenuItem.prototype.getScreenName = function getScreenName()
{
return this._screenName;
};
/**
* @class Menu
* @param {Object} layout
* @constructor
*/
App.Menu = function Menu(layout)
{
App.Screen.call(this,layout);
var MenuItem = App.MenuItem,
ScreenName = App.ScreenName,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width,
itemLabelStyle = FontStyle.get(20,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
itemOptions = {
width:w,
height:Math.round(40 * r),
pixelRatio:r,
style:itemLabelStyle
};
this._addTransactionItem = new MenuItem("Add Transaction","transactions",ScreenName.ADD_TRANSACTION,{width:w,height:Math.round(50*r),pixelRatio:r,style:itemLabelStyle});
this._transactionsItem = new MenuItem("Transactions","transactions",ScreenName.TRANSACTIONS,itemOptions);
this._reportItem = new MenuItem("Report","chart",ScreenName.REPORT,itemOptions);
this._accountsItem = new MenuItem("Accounts","account",ScreenName.ACCOUNT,itemOptions);
this._budgetItem = new MenuItem("Budgets","budget",-1,itemOptions);
this._currenciesItem = new MenuItem("Currency rates","currencies",ScreenName.CURRENCY_PAIRS,itemOptions);
this._settignsItem = new MenuItem("Settings","settings-app",ScreenName.SETTINGS,itemOptions);
this._container = new PIXI.Graphics();
this._pane = new App.Pane(App.ScrollPolicy.OFF,App.ScrollPolicy.AUTO,w,layout.contentHeight,r,false);
this._background = new PIXI.Graphics();
this._items = [];
this._render();
this.addChild(this._background);
this._items.push(this._container.addChild(this._addTransactionItem));
this._items.push(this._container.addChild(this._transactionsItem));
this._items.push(this._container.addChild(this._reportItem));
this._items.push(this._container.addChild(this._accountsItem));
this._items.push(this._container.addChild(this._budgetItem));
this._items.push(this._container.addChild(this._currenciesItem));
this._items.push(this._container.addChild(this._settignsItem));
this._pane.setContent(this._container);
this.addChild(this._pane);
};
App.Menu.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.Menu.prototype._render = function _render()
{
var r = this._layout.pixelRatio,
smallGap = Math.round(2 * r),
bigGap = Math.round(25 * r),
GraphicUtils = App.GraphicUtils,
bgColor = App.ColorTheme.BLUE_DARK;
this._transactionsItem.y = this._addTransactionItem.boundingBox.height + bigGap;
this._reportItem.y = this._transactionsItem.y + this._transactionsItem.boundingBox.height + smallGap;
this._accountsItem.y = this._reportItem.y + this._reportItem.boundingBox.height + smallGap;
this._budgetItem.y = this._accountsItem.y + this._accountsItem.boundingBox.height + smallGap;
this._currenciesItem.y = this._budgetItem.y + this._budgetItem.boundingBox.height + bigGap;
this._settignsItem.y = this._currenciesItem.y + this._currenciesItem.boundingBox.height + smallGap;
GraphicUtils.drawRect(this._container,bgColor,1,0,0,this._layout.width,this._settignsItem.y+this._settignsItem.boundingBox.height);
GraphicUtils.drawRect(this._background,bgColor,1,0,0,this._layout.width,this._layout.contentHeight);
};
/**
* Enable
*/
App.Menu.prototype.enable = function enable()
{
if (!this._enabled)
{
this._registerEventListeners(App.EventLevel.LEVEL_1);
this._registerEventListeners(App.EventLevel.LEVEL_2);
this._pane.resetScroll();
this._pane.enable();
this._enabled = true;
}
};
/**
* Disable
*/
App.Menu.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
};
/**
* Click handler
* @private
*/
App.Menu.prototype._onClick = function _onClick()
{
this._pane.cancelScroll();
var ScreenName = App.ScreenName,
ScreenTitle = App.ScreenTitle,
HeaderAction = App.HeaderAction,
item = this._getItemByPosition(this.stage.getTouchData().getLocalPosition(this._container).y),
screenName = item ? item.getScreenName() : ScreenName.BACK,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(screenName,0,null,HeaderAction.MENU,HeaderAction.ADD_TRANSACTION);
switch (screenName)
{
case ScreenName.ADD_TRANSACTION:
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
break;
case ScreenName.TRANSACTIONS:
changeScreenData.headerName = ScreenTitle.TRANSACTIONS;
changeScreenData.updateData = App.ModelLocator.getProxy(App.ModelName.TRANSACTIONS).copySource().reverse();
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.REPORT:
changeScreenData.headerName = ScreenTitle.REPORT;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.ACCOUNT:
changeScreenData.screenMode = App.ScreenMode.EDIT;
changeScreenData.headerName = ScreenTitle.ACCOUNTS;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.CURRENCY_PAIRS:
changeScreenData.screenMode = App.ScreenMode.EDIT;
changeScreenData.headerName = ScreenTitle.CURRENCY_RATES;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
case ScreenName.SETTINGS:
changeScreenData.headerName = ScreenTitle.SETTINGS;
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
break;
}
};
/**
* Return item by position passed in
* @param {number} position
* @return {MenuItem}
* @private
*/
App.Menu.prototype._getItemByPosition = function _getItemByPosition(position)
{
var i = 0,
l = this._items.length,
item = null;
for (;i<l;)
{
item = this._items[i++];
if (position >= item.y && position < item.y + item.boundingBox.height) return item;
}
return null;
};
/**
* @class SettingScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.SettingScreen = function SettingScreen(layout)
{
App.Screen.call(this,layout,0.4);
var TransactionOptionButton = App.TransactionOptionButton,//TODO refactor to 'OptionButton'?
FontStyle = App.FontStyle,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
r = layout.pixelRatio,
w = layout.width,
inputWidth = w - Math.round(10 * r) * 2,
options = {
pixelRatio:r,
width:w,
height:Math.round(50 * r),
skin:skin.GREY_50,
nameStyle:FontStyle.get(18,FontStyle.GREY_DARKER,null,FontStyle.LIGHT_CONDENSED),
valueStyle:FontStyle.get(18,FontStyle.BLUE,"right"),
valueDetailStyle:FontStyle.get(14,FontStyle.BLUE)
};
this._model = App.ModelLocator.getProxy(App.ModelName.SETTINGS);
this._container = new PIXI.DisplayObjectContainer();
this._list = this._container.addChild(new App.List(App.Direction.Y));
this._weekDayOption = this._list.add(new TransactionOptionButton("calendar","Start Of Week",options));
this._baseCurrencyOption = this._list.add(new TransactionOptionButton("currencies","Base Currency",options));
this._defaultCurrencyOption = this._list.add(new TransactionOptionButton("currencies","Default Currency",options));
this._defaultAccountOption = this._list.add(new TransactionOptionButton("account","Default Account",options));
this._defaultCategoryOption = this._list.add(new TransactionOptionButton("folder-app","Default Category",options));
this._defaultSubCategoryOption = this._list.add(new TransactionOptionButton("subcategory-app","Default SubCategory",options));
this._defaultMethodOption = this._list.add(new TransactionOptionButton("credit-card","Default Payment",options),true);
this._deleteBackground = this._container.addChild(new PIXI.Sprite(skin.GREY_60));
this._deleteButton = this._container.addChild(new App.PopUpButton("Delete All Transactions","Are you sure you want to\ndelete all transactions?",{
width:inputWidth,
height:Math.round(40 * r),
pixelRatio:r,
popUpLayout:{x:Math.round(10*r),y:0,width:Math.round(inputWidth-20*r),height:Math.round(layout.height/2),overlayWidth:w,overlayHeight:0}
}));
this._pane = this.addChild(new App.Pane(App.ScrollPolicy.OFF,App.ScrollPolicy.AUTO,w,layout.contentHeight,r,true));
this._pane.setContent(this._container);
this._updateLayout();
this._clickThreshold = 10 * r;
};
App.SettingScreen.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.SettingScreen.prototype._updateLayout = function _updateLayout()
{
var padding = Math.round(10 * this._layout.pixelRatio);
this._deleteBackground.y = this._list.y + this._list.boundingBox.height;
this._deleteButton.setPosition(padding,this._deleteBackground.y + padding);
this._pane.resize();
};
/**
* Update
* @private
*/
App.SettingScreen.prototype.update = function update()
{
this._weekDayOption.setValue(/*this._model.startOfWeek*/"Monday");
this._baseCurrencyOption.setValue(this._model.baseCurrency);
this._defaultCurrencyOption.setValue(this._model.defaultCurrencyQuote);
this._defaultAccountOption.setValue(this._model.defaultAccount.name);
this._defaultCategoryOption.setValue(this._model.defaultCategory.name);
this._defaultSubCategoryOption.setValue(this._model.defaultSubCategory.name);
this._defaultMethodOption.setValue(this._model.defaultPaymentMethod.name);
this._deleteButton.hidePopUp(true);
this._pane.resetScroll();
};
/**
* Hide
*/
App.SettingScreen.prototype.hide = function hide()
{
this._unRegisterDeleteButtonListeners();
App.Screen.prototype.hide.call(this);
};
/**
* Enable
*/
App.SettingScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.enable();
};
/**
* Disable
*/
App.SettingScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._pane.disable();
};
/**
* Register delete button event listeners
* @private
*/
App.SettingScreen.prototype._registerDeleteButtonListeners = function _registerDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.addEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.addEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.addEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* UnRegister delete button event listeners
* @private
*/
App.SettingScreen.prototype._unRegisterDeleteButtonListeners = function _unRegisterDeleteButtonListeners()
{
var EventType = App.EventType;
this._deleteButton.removeEventListener(EventType.CANCEL,this,this._onDeleteCancel);
this._deleteButton.removeEventListener(EventType.CONFIRM,this,this._onDeleteConfirm);
this._deleteButton.removeEventListener(EventType.COMPLETE,this,this._onHidePopUpComplete);
};
/**
* On delete cancel
* @private
*/
App.SettingScreen.prototype._onDeleteCancel = function _onDeleteCancel()
{
this._deleteButton.hidePopUp();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
};
/**
* On delete confirm
* @private
*/
App.SettingScreen.prototype._onDeleteConfirm = function _onDeleteConfirm()
{
// Just temporary for testing
localStorage.clear();
this._deleteButton.hidePopUp();
App.ViewLocator.getViewSegment(App.ViewName.HEADER).enableActions();
};
/**
* On Delete PopUp hide complete
* @private
*/
App.SettingScreen.prototype._onHidePopUpComplete = function _onHidePopUpComplete()
{
this._unRegisterDeleteButtonListeners();
this.enable();
this._registerEventListeners(App.EventLevel.LEVEL_2);
};
/**
* Click handler
* @private
*/
App.SettingScreen.prototype._onClick = function _onClick()
{
this._pane.cancelScroll();
var pointerData = this.stage.getTouchData(),
position = pointerData.getLocalPosition(this._container).y;
if (this._list.hitTest(position))
{
var button = this._list.getItemUnderPoint(pointerData);
if (button === this._weekDayOption) this._onAccountOptionClick();
else if (button === this._baseCurrencyOption) this._onCategoryOptionClick();
else if (button === this._defaultCurrencyOption) this._onTimeOptionClick();
else if (button === this._defaultAccountOption) this._onMethodOptionClick();
else if (button === this._defaultCategoryOption) this._onCurrencyOptionClick();
else if (button === this._defaultSubCategoryOption) this._onCurrencyOptionClick();
else if (button === this._defaultMethodOption) this._onCurrencyOptionClick();
}
else if (this._deleteButton.hitTest(position))
{
this.disable();
this._unRegisterEventListeners(App.EventLevel.LEVEL_1);
App.ViewLocator.getViewSegment(App.ViewName.HEADER).disableActions();
this._registerDeleteButtonListeners();
this._deleteButton.setPopUpLayout(0,this._container.y + this._layout.headerHeight,0,this._layout.contentHeight > this._container.height ? this._layout.contentHeight : this._container.height);
this._deleteButton.showPopUp();
}
};
/**
* On account option button click
* @private
*/
App.SettingScreen.prototype._onAccountOptionClick = function _onAccountOptionClick()
{
/*App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.ACCOUNT,
App.ScreenMode.SELECT,
null,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_ACCOUNT
));*/
};
/**
* On category option button click
* @private
*/
App.SettingScreen.prototype._onCategoryOptionClick = function _onCategoryOptionClick()
{
/*var account = this._model.account;
if (account && account.lifeCycleState !== App.LifeCycleState.DELETED)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.CATEGORY,
App.ScreenMode.SELECT,
account,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_CATEGORY
));
}
else
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.ACCOUNT,
App.ScreenMode.SELECT,
null,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_ACCOUNT
));
}*/
};
/**
* On time option button click
* @private
*/
App.SettingScreen.prototype._onTimeOptionClick = function _onTimeOptionClick()
{
/*App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.SELECT_TIME,
App.ScreenMode.SELECT,
this._model.date,
0,
0,
App.ScreenTitle.SELECT_TIME
));*/
};
/**
* On payment method option button click
* @private
*/
App.SettingScreen.prototype._onMethodOptionClick = function _onMethodOptionClick()
{
//this._methodOption.setValue(this._methodOption.getValue() === App.PaymentMethod.CASH ? App.PaymentMethod.CREDIT_CARD : App.PaymentMethod.CASH);
};
/**
* On currency option button click
* @private
*/
App.SettingScreen.prototype._onCurrencyOptionClick = function _onCurrencyOptionClick()
{
/*App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,this._getChangeTransactionData(
App.ScreenName.CURRENCIES,
App.ScreenMode.SELECT,
null,
0,
App.HeaderAction.NONE,
App.ScreenTitle.SELECT_CURRENCY
));*/
};
/**
* On Header click
* @param {number} action
* @private
*/
App.SettingScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate();
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(
App.ScreenName.MENU,
0,
null,
HeaderAction.NONE,
HeaderAction.CANCEL,
App.ScreenTitle.MENU
));
}
};
/**
* Construct and return change transaction data object
* @param {number} screenName
* @param {number} screenMode
* @param {*} updateData
* @param {number} headerLeftAction
* @param {number} headerRightAction
* @param {string} headerName
* @returns {{type:string,amount:string,transactionType:string,pending:boolean,repeat:boolean,method:string,note:string,nextCommand:App.ChangeScreen,nextCommandData:Object}}
* @private
*/
App.SettingScreen.prototype._getChangeTransactionData = function _getChangeTransactionData(screenName,screenMode,updateData,headerLeftAction,headerRightAction,headerName)
{
return {
type:App.EventType.CHANGE,
amount:this._transactionInput.getValue(),
transactionType:this._typeToggle.isSelected() ? App.TransactionType.INCOME : App.TransactionType.EXPENSE,
pending:this._pendingToggle.isSelected(),
repeat:this._repeatToggle.isSelected(),
method:this._methodOption.getValue(),
note:this._noteInput.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
screenName,
screenMode,
updateData,
headerLeftAction,
headerRightAction,
headerName
)
};
};
/**
* @class ApplicationView
* @extends DisplayObjectContainer
* @param {Stage} stage
* @param {CanvasRenderer} renderer
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.ApplicationView = function ApplicationView(stage,renderer,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
ViewLocator = App.ViewLocator,
ViewName = App.ViewName,
listenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
this._renderer = renderer;
this._stage = stage;
this._layout = {
originalWidth:width,
originalHeight:height,
width:Math.round(width * pixelRatio),
height:Math.round(height * pixelRatio),
headerHeight:Math.round(50 * pixelRatio),
contentHeight:Math.round((height - 50) * pixelRatio),
pixelRatio:pixelRatio
};
//TODO do I need event dispatcher here?
this._eventDispatcher = new App.EventDispatcher(listenerPool);
this._background = new PIXI.Graphics();
this._backgroundPattern = new PIXI.TilingSprite(App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_PATTERN,this._layout.width,this._layout.height);
//TODO use ScreenFactory for the screens?
//TODO deffer initiation and/or rendering of most of the screens?
this._screenStack = ViewLocator.addViewSegment(ViewName.SCREEN_STACK,new App.ViewStack([
new App.AccountScreen(this._layout),
new App.CategoryScreen(this._layout),
new App.SelectTimeScreen(this._layout),
new App.EditCategoryScreen(this._layout),
new App.TransactionScreen(this._layout),
new App.ReportScreen(this._layout),
new App.AddTransactionScreen(this._layout),
new App.EditScreen(this._layout),
new App.CurrencyPairScreen(this._layout),
new App.EditCurrencyPairScreen(this._layout),
new App.CurrencyScreen(this._layout),
new App.SettingScreen(this._layout),
new App.Menu(this._layout)
],false,listenerPool));
this._header = ViewLocator.addViewSegment(ViewName.HEADER,new App.Header(this._layout));
this._init();
this.addChild(this._background);
this.addChild(this._backgroundPattern);
this.addChild(this._screenStack);
this.addChild(this._header);
};
App.ApplicationView.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Init
* @private
*/
App.ApplicationView.prototype._init = function _init()
{
App.GraphicUtils.drawRect(this._background,App.ColorTheme.GREY,1,0,0,this._layout.width,this._layout.height);
this._backgroundPattern.alpha = 0.4;
this.scrollTo(0);
this._registerEventListeners();
this._screenStack.y = this._layout.headerHeight;
};
/**
* Register event listeners
*
* @method _registerEventListeners
* @private
*/
App.ApplicationView.prototype._registerEventListeners = function _registerEventListeners()
{
var EventType = App.EventType;
this._screenStack.addEventListener(EventType.CHANGE,this,this._onScreenChange);
App.ModelLocator.getProxy(App.ModelName.TICKER).addEventListener(EventType.TICK,this,this._onTick);
};
/**
* On screen change
* @private
*/
App.ApplicationView.prototype._onScreenChange = function _onScreenChange()
{
this._screenStack.show();
this._screenStack.hide();
};
/**
* Scroll to value passed in
* @param {number} value
*/
App.ApplicationView.prototype.scrollTo = function scrollTo(value)
{
if (document.documentElement && document.documentElement.scrollTop) document.documentElement.scrollTop = value;
else document.body.scrollTop = value;
};
/**
* On Ticker's Tick event
*
* @method _onTick
* @private
*/
App.ApplicationView.prototype._onTick = function _onTick()
{
//TODO do not render if nothing happens (prop 'dirty'?) - drains battery
this._renderer.render(this._stage);
};
/**
* On resize
* @private
*/
App.ApplicationView.prototype._onResize = function _onResize()
{
//this.scrollTo(0);
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ApplicationView.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ApplicationView.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
/**
* Easing functions
* @enum {Function}
* @type {{
* linear: Function,
* inQuad: Function,
* outQuad: Function,
* inOutQuad: Function,
* inCubic: Function,
* outCubic: Function,
* inOutCubic: Function,
* inExpo: Function,
* outExpo: Function,
* inOutExpo: Function,
* inElastic: Function,
* outElastic: Function,
* inOutElastic: Function}}
*/
App.Easing = {
linear: function(t) {
return t;
},
/**
* @property inQuad
* @static
*/
inQuad: function(t) {
return t*t;
},
/**
* @property outQuad
* @static
*/
outQuad: function(t) {
return -(t-=1)*t+1;
},
/**
* @property inOutQuad
* @static
*/
inOutQuad: function(t) {
if ((t/=.5) < 1) return .5*t*t;
return -.5*((--t)*(t-2) - 1);
},
/**
* @property inCubic
* @static
*/
inCubic: function(t) {
return t*t*t;
},
/**
* @property outCubic
* @static
*/
outCubic: function(t) {
return ((--t)*t*t + 1);
},
/**
* @property inOutCubic
* @static
*/
inOutCubic: function(t) {
if ((t/=.5) < 1) return .5*t*t*t;
return .5*((t-=2)*t*t + 2);
},
/**
* @property inExpo
* @static
*/
inExpo: function(t) {
return (t===0) ? 0.0 : Math.pow(2, 10 * (t - 1));
},
/**
* @property outExpo
* @static
*/
outExpo: function(t) {
return (t===1.0) ? 1.0 : (1-Math.pow(2, -10 * t));
},
/**
* @property inOutExpo
* @static
*/
inOutExpo: function(t) {
if (t===0) return 0.0;
if (t===1.0) return 1.0;
if ((t/=.5) < 1) return .5 * Math.pow(2, 10 * (t - 1));
return .5 * (-Math.pow(2, -10 * --t) + 2);
},
/**
* @property inElastic
* @static
*/
inElastic: function(t) {
var s=1.70158;var p=0;var a=1.0;
if (t===0) return 0.0; if (t===1) return 1.0; if (!p) p=.3;
s = p/(2*Math.PI) * Math.asin(1.0/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin((t-s)*(2*Math.PI)/ p));
},
/**
* @property outElastic
* @static
*/
outElastic: function(t) {
var s=1.70158;var p=0;var a=1.0;
if (t===0) return 0.0; if (t===1) return 1.0; if (!p) p=.3;
s = p/(2*Math.PI) * Math.asin(1.0/a);
return a*Math.pow(2,-10*t) * Math.sin((t-s)*(2*Math.PI)/p) + 1.0;
},
/**
* @property inOutElastic
* @static
*/
inOutElastic: function(t) {
var s=1.70158;var p=0;var a=1.0;
if (t===0) return 0.0; if ((t/=.5)===2) return 1.0; if (!p) p=(.3*1.5);
s = p/(2*Math.PI) * Math.asin(1.0/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin((t-s)*(2*Math.PI)/p));
return a*Math.pow(2,-10*(t-=1)) * Math.sin((t-s)*(2*Math.PI)/p)*.5 + 1.0;
}
};
/**
* @class TweenProxy
* @param {number} duration
* @param {Function} ease
* @param {number} defaultProgress
* @param {ObjectPool} eventListenerPool
* @extends {EventDispatcher}
* @constructor
*/
App.TweenProxy = function TweenProxy(duration,ease,defaultProgress,eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
this.progress = defaultProgress || 0.0;
this._interval = -1;
this._running = false;
this._reversed = false;
this._start = -1.0;
this._end = -1.0;
this._reversedEnd = -1.0;
this._now = -1.0;
this._duration = duration * 1000 || 1000;
this._ease = ease || App.Easing.linear;
this._timeStamp = window.performance && window.performance.now ? window.performance : Date;
this._intervalReference = this._tweenInterval.bind(this);
};
App.TweenProxy.prototype = Object.create(App.EventDispatcher.prototype);
/**
* Set easing function
* @method setEase
* @param {Function} value
*/
App.TweenProxy.prototype.setEase = function setEase(value)
{
this._ease = value;
};
/**
* Start
* @method start
* @param {boolean} [reverseIfRunning=false] - reverse the tween if the tween is currently running
* @param {Function} [ease=null] - set new ease
*/
App.TweenProxy.prototype.start = function start(reverseIfRunning,ease)
{
if (ease) this.setEase(ease);
if (!this._running)
{
this._running = true;
this._reversed = false;
this._tween();
}
else
{
if (reverseIfRunning)
{
if (this._reversed)
{
this._reversed = false;
}
else
{
this._reversed = true;
this._reversedEnd = this._start + (this._now - this._start) * 2;
}
}
}
};
/**
* Stop
* @method stop
*/
App.TweenProxy.prototype.stop = function stop()
{
this._running = false;
clearInterval(this._interval);
this._interval = -1;
};
/**
* Restart
* @method restart
*/
App.TweenProxy.prototype.restart = function restart()
{
if (this._running) this.stop();
this.start();
};
/**
* Is tween running?
* @method isRunning
* @returns {boolean}
*/
App.TweenProxy.prototype.isRunning = function isRunning()
{
return this._running;
};
/**
* Tween
* @method _tween
* @private
*/
App.TweenProxy.prototype._tween = function _tween()
{
if (this._interval > 0)
{
clearInterval(this._interval);
this._interval = -1.0;
}
this.progress = 0.0;
this._start = this._timeStamp.now();
this._end = this._start + this._duration;
this._interval = setInterval(this._intervalReference,1000/120);
};
/**
* Tween interval function
* @method _tweenInterval
* @private
*/
App.TweenProxy.prototype._tweenInterval = function _tweenInterval()
{
this._now = this._timeStamp.now();
var end = this._reversed ? this._reversedEnd : this._end;
var progress = (this._duration - (end - this._now)) / this._duration;
if (progress < 0) progress = 0.0;
else if (progress > 1) progress = 1.0;
this.progress = this._ease(progress);
if(this._now >= end)
{
this.progress = 1.0;
this.stop();
this.dispatchEvent(App.EventType.COMPLETE);
}
};
/**
* Destroy
*/
App.TweenProxy.prototype.destroy = function destroy()
{
App.EventDispatcher.prototype.destroy.call(this);
this.stop();
this._intervalReference = null;
this._timeStamp = null;
this._ease = null;
};
/**
* @class Ticker
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Ticker = function Ticker(eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
this._rafListener = this._raf.bind(this);
this._isRunning = false;
};
App.Ticker.prototype = Object.create(App.EventDispatcher.prototype);
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Ticker.prototype.addEventListener = function(eventType,scope,listener)
{
App.EventDispatcher.prototype.addEventListener.call(this,eventType,scope,listener);
if (!this._isRunning)
{
this._isRunning = true;
window.requestAnimationFrame(this._rafListener);
}
};
/**
* Remove event listeners
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Ticker.prototype.removeEventListener = function(eventType,scope,listener)
{
App.EventDispatcher.prototype.removeEventListener.call(this,eventType,scope,listener);
if (this._listeners.length === 0) this._isRunning = false;
};
/**
* Remove all listeners
*/
App.Ticker.prototype.removeAllListeners = function()
{
App.EventDispatcher.prototype.removeAllListeners.call(this);
this._isRunning = false;
};
/**
* Animation function
* @private
*/
App.Ticker.prototype._raf = function _raf()
{
if (this._isRunning)
{
window.requestAnimationFrame(this._rafListener);
this.dispatchEvent(App.EventType.TICK);
}
};
/**
* @class Controller
* @type {{_eventListenerPool:ObjectPool,_eventCommandMap: {}, _commands: Array, _init: Function, _onCommandComplete: Function, _destroyCommand: Function, dispatchEvent: Function}}
*/
App.Controller = {
_eventListenerPool:null,
_eventCommandMap:{},
/** @type {Array.<Command>} */
_commands:[],
/**
* Init
* @param {ObjectPool} eventListenerPool
* @param {Array.<>} eventMap
*/
init:function init(eventListenerPool,eventMap)
{
this._eventListenerPool = eventListenerPool;
var i = 0,
l = eventMap.length;
for (;i<l;) this._eventCommandMap[eventMap[i++]] = {constructor:eventMap[i++]};
},
/**
* On command complete
* @param {*} data
* @private
*/
_onCommandComplete:function _onCommandComplete(data)
{
this._destroyCommand(data);
},
/**
* Destroy command
* @param {Command} command
* @private
*/
_destroyCommand:function _destroyCommand(command)
{
var i = 0, l = this._commands.length, cmd = null;
for (;i<l;)
{
cmd = this._commands[i++];
if (cmd === command)
{
cmd.removeEventListener(App.EventType.COMPLETE,this,this._onCommandComplete);
cmd.destroy();
this._commands.splice(i,1);
break;
}
}
},
/**
* Dispatch event passed in
* @param {string} eventType
* @param {*} [data=null] Defaults to null
* @param {boolean} [checkRunningInstances=false] Defaults to false
*/
dispatchEvent:function dispatchEvent(eventType,data,checkRunningInstances)
{
/** @type {Function} */var commandConstructor = this._eventCommandMap[eventType].constructor;
if (commandConstructor)
{
/** @type {Command} */var cmd = null;
// First check, if multiple instances of this Command are allowed
// If not, destroy running instances, before executing new one
if (checkRunningInstances)
{
var i = 0, l = this._commands.length;
for (;i<l;)
{
cmd = this._commands[i++];
if (cmd instanceof commandConstructor && !cmd.allowMultipleInstances)
{
this._destroyCommand(cmd);
}
}
}
// Execute command
cmd = /** @type {Command} */new commandConstructor(this._eventListenerPool);
this._commands.push(cmd);
cmd.addEventListener(App.EventType.COMPLETE,this,this._onCommandComplete);
cmd.execute(data);
}
}
};
App.DefaultData = {
settings:[1,"CZK","CZK","1","1","1",1],
currencyPairs:[
[1,"EUR","AUD",1.3932],
[2,"EUR","CAD",1.3593],
[3,"EUR","CHF",1.066],
[4,"EUR","CZK",27.166],
[5,"EUR","DKK",7.4603],
[6,"EUR","GBP",0.7211],
[7,"EUR","HKD",8.2552],
[8,"EUR","HUF",304.04],
[9,"EUR","JPY",128.81],
[10,"EUR","MXN",16.41],
[11,"EUR","NOK",8.8013],
[12,"EUR","NZD",1.4461],
[13,"EUR","PLN",1.4461],
[14,"EUR","RON",4.4396],
[15,"EUR","SEK",9.1826],
[16,"EUR","SGD",1.4759],
[17,"EUR","THB",34.93],
[18,"EUR","TRY",2.7766],
[19,"EUR","USD",1.0628],
[20,"GBP","AUD",1.9293],
[21,"GBP","CAD",1.8825],
[22,"GBP","CHF",1.4777],
[23,"GBP","CZK",37.683],
[24,"GBP","DKK",10.3425],
[25,"GBP","HKD",11.4352],
[26,"GBP","HUF",421.46],
[27,"GBP","JPY",178.61],
[28,"GBP","MXN",22.5122],
[29,"GBP","NOK",12.196],
[30,"GBP","NZD",2.004],
[31,"GBP","PLN",5.7445],
[32,"GBP","RON",6.13249],
[33,"GBP","SEK",12.7325],
[34,"GBP","SGD",2.0465],
[35,"GBP","THB",48.45],
[36,"GBP","TRY",3.8482],
[37,"GBP","USD",1.4733],
[38,"USD","AUD",1.28526],
[39,"USD","CAD",1.2777],
[40,"USD","CHF",1.0028],
[41,"USD","CZK",25.58],
[42,"USD","DKK",7.0204],
[43,"USD","HKD",7.7631],
[44,"USD","HUF",286.11],
[45,"USD","JPY",121.26],
[46,"USD","MXN",15.424],
[47,"USD","NOK",8.2812],
[48,"USD","NZD",1.32162],
[49,"USD","PLN",3.8096],
[50,"USD","RON",4.1792],
[51,"USD","SEK",8.6418],
[52,"USD","SGD",1.3889],
[53,"USD","THB",32.86],
[54,"USD","TRY",2.611]
],
subCategories:[
["1","OSSZ"],
["2","ZP"],
["3","Taxes"],
["4","Invoice"],
["5","Other"],
["6","Rent"],
["7","Other"],
["8","Accounts"],
["9","Transfer"],
["10","ATM"],
["11","Exchange%20Rate"],
["12","Customs"],
["13","VAT"],
["14","Other"],
["15","Gym"],
["16","Swimming"],
["17","Other"],
["18","Groceries"],
["19","Drugs"],
["20","Clothing"],
["21","Pharmacy"],
["22","Shared%20Expenses"],
["23","Food"],
["24","Gift"],
["25","Flowers"],
["26","Other"],
["27","Breakfast"],
["28","Lunch"],
["29","Dinner"],
["30","Snack"],
["31","Coffee"],
["32","Other"],
["33","Public%20Transportation"],
["34","CR"],
["35","Abroad"],
["36","Taxi"],
["37","AirPlane"],
["38","Bus"],
["39","Train"],
["40","Ho%28s%29tel"],
["41","Gas"],
["42","Car%20Rental"],
["43","Other"],
["44","Club"],
["45","Bar"],
["46","Pub"],
["47","Coffee"],
["48","Concert"],
["49","Festival"],
["50","Cinema"],
["51","Theatre"],
["52","Gallery"],
["53","Sight%20Seeing"],
["54","Camp"],
["55","Paddle%20Boat"],
["56","Bowling"],
["57","Aqua%20Park"],
["58","Other"],
["59","Software"],
["60","Broker"],
["61","Credit"],
["62","Debit"],
["63","Forum"],
["64","Data"],
["65","Subscription"],
["66","Other"],
["67","Hairdresser"],
["68","Doctor"],
["69","Print"],
["70","Taxes"],
["71","Massage"],
["72","Post"],
["73","Moving"],
["74","Internet"],
["75","Phone"],
["76","Other"],
["77","Books"],
["78","Course"],
["79","Other"],
["80","Borrowing"],
["81","Interest"],
["82","Other"],
["83","Lending"],
["84","Interest"],
["85","Other"]
],
categories:[
["1","Freelance","80f320","currencies","1","1,2,3,4,5"],
["2","Living","9ae611","house","1","6,7",15000],
["3","Fees","b4d406","transactions","1","8,9,10,11,12,13,14"],
["4","Sport","cbbe01","ball","1","15,16,17",1500],
["5","Shopping","dea602","cart","1","18,19,20,21,22,23,24,25,26"],
["6","Eating","ee8c08","cutlery","1","27,28,29,30,31,32"],
["7","Travel","f97113","air-plane","1","33,34,35,36,37,38,39,40,41,42,43"],
["8","Leisure","fe5823","disco-ball","1","44,45,46,47,48,49,50,51,52,53,54,55,56,57,58"],
["9","Trading","fe3f37","chart","1","59,60,61,62,63,64,65,66"],
["10","Services","f92a4f","scissors","1","67,68,69,70,71,72,73,74,75,76"],
["11","Study","ee1868","book","1","77,78,79"],
["12","Income","de0b83","income","1","80,81,82"],
["13","Expense","cb049d","expense","1","83,84,85"]
],
accounts:[
["1","Private",1,"1,2,3,4,5,6,7,8,9,10,11,12,13"]
],
transactionsMeta:[]
};
/**
* Storage
* @param {string} workerUrl
* @constructor
*/
App.Storage = function Storage(workerUrl)
{
this._workerUrl = workerUrl;
this._worker = null;
this._initialized = false;
};
/**
* Init
* @private
*/
App.Storage.prototype._init = function _init()
{
if (!this._initialized)
{
this._initialized = true;
if (window.Worker)
{
this._worker = new Worker(this._workerUrl);
this._registerEventListeners();
this._worker.postMessage("init|"+JSON.stringify(App.StorageKey));
}
}
};
/**
* Register event listeners
* @private
*/
App.Storage.prototype._registerEventListeners = function _registerEventListeners()
{
this._worker.addEventListener("message",this._onWorkerMessage);
};
/**
* On worker message
* @param {Event} e
* @private
*/
App.Storage.prototype._onWorkerMessage = function _onWorkerMessage(e)
{
var components = e.data.split("|");
localStorage.setItem(components[0],components[1]);//TODO compress
};
/**
* Send data to worker to save under key passed in
* @param {string} key
* @param {Object} data
*/
App.Storage.prototype.setData = function setData(key,data/*,context? (CONFIRM|DELETE|...)*/)
{
if (!this._initialized) this._init();
this._worker.postMessage(key+"|"+JSON.stringify(data));
};
/**
* Query worker for data by key passed in
* @param {string} key
*/
App.Storage.prototype.getData = function getData(key)
{
if (!this._initialized) this._init();
var data = localStorage.getItem(key),
serialized = data;
if (data)
{
data = JSON.parse(data);
}
else
{
data = App.DefaultData[key];
serialized = JSON.stringify(data);
localStorage.setItem(key,serialized);//TODO save via worker ... and compress
}
this._worker.postMessage("save|"+key+"|"+serialized);
return data;
};
/**
* @class ServiceLocator
* @type {{_services:Object,addService:Function,hasService:Function,getService:Function}}
*/
App.ServiceLocator = {
_services:{},
/**
* Initialize with array of services passed in
* @param {Array.<>} services
*/
init:function init(services)
{
var i = 0,
l = services.length;
for (;i<l;) this._services[services[i++]] = services[i++];
},
/**
* @method addPoxy Add proxy to the locator
* @param {string} serviceName
* @param {*} proxy
*/
addService:function addService(serviceName,proxy)
{
if (this._services[serviceName]) throw Error("Service "+serviceName+" already exist");
this._services[serviceName] = proxy;
},
/**
* @method hasProxy Check if proxy already exist
* @param {string} serviceName
* @return {boolean}
*/
hasService:function hasService(serviceName)
{
return this._services[serviceName];
},
/**
* @method getProxy Returns proxy by name passed in
* @param {string} serviceName
* @return {*}
*/
getService:function getService(serviceName)
{
return this._services[serviceName];
}
};
/**
* The Command
* @class Command
* @extends {EventDispatcher}
* @param allowMultipleInstances {boolean}
* @param eventListenerPool {ObjectPool}
*/
App.Command = function Command(allowMultipleInstances,eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
this.allowMultipleInstances = allowMultipleInstances;
};
App.Command.prototype = Object.create(App.EventDispatcher.prototype);
/**
* Execute a command
* @param {*=} data Defaults to null
*/
App.Command.prototype.execute = function execute(data) {};
/**
* Destroy current instance
*
* @method destroy
*/
App.Command.prototype.destroy = function destroy()
{
App.EventDispatcher.prototype.destroy.call(this);
};
/**
* @class SequenceCommand
* @extends Command
* @param {boolean} allowMultipleInstances
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.SequenceCommand = function SequenceCommand(allowMultipleInstances,eventListenerPool)
{
App.Command.call(this,allowMultipleInstances,eventListenerPool);
this._nextCommand = null;
this._nextCommandData = null;
};
App.SequenceCommand.prototype = Object.create(App.Command.prototype);
/**
* Execute next command
* @param {*} [data=null]
* @private
*/
App.SequenceCommand.prototype._executeNextCommand = function _executeNextCommand(data)
{
this._nextCommand.addEventListener(App.EventType.COMPLETE,this,this._onNextCommandComplete);
this._nextCommand.execute(data);
};
/**
* On next command complete
* @private
*/
App.SequenceCommand.prototype._onNextCommandComplete = function _onNextCommandComplete()
{
this._nextCommand.removeEventListener(App.EventType.COMPLETE,this,this._onNextCommandComplete);
this.dispatchEvent(App.EventType.COMPLETE,this);
};
/**
* Destroy current instance
*
* @method destroy
*/
App.SequenceCommand.prototype.destroy = function destroy()
{
App.Command.prototype.destroy.call(this);
if (this._nextCommand)
{
this._nextCommand.destroy();
this._nextCommand = null;
}
this._nextCommandData = null;
};
/**
* @class LoadData
* @extends {Command}
* @param {ObjectPool} pool
* @param {Storage} storage
* @constructor
*/
App.LoadData = function LoadData(pool,storage)
{
App.Command.call(this,false,pool);
this._storage = storage;
this._jsonLoader = null;
this._fontLoadingInterval = -1;
this._fontInfoElement = null;
this._icons = null;
};
App.LoadData.prototype = Object.create(App.Command.prototype);
/**
* Execute the command
*
* @method execute
*/
App.LoadData.prototype.execute = function execute()
{
this._loadAssets();
};
/**
* Load image assets
*
* @method _loadAssets
* @private
*/
App.LoadData.prototype._loadAssets = function _loadAssets()
{
this._jsonLoader = new PIXI.JsonLoader("./data/icons-big.json");
this._jsonLoader.on("loaded",function()
{
this._icons = this._jsonLoader.json.frames;
this._jsonLoader.removeAllListeners("loaded");
this._jsonLoader = null;
this._loadFont();
}.bind(this));
this._jsonLoader.load();
};
/**
* Set app font and check if it is loaded
*
* @method _loadFont
* @private
*/
App.LoadData.prototype._loadFont = function _loadFont()
{
this._fontInfoElement = document.getElementById("fontInfo");
var FontStyle = App.FontStyle,
fontInfoWidth = this._fontInfoElement.offsetWidth,
fontName = "QW@HhsXJ",
fontsLoaded = 0;
this._fontLoadingInterval = setInterval(function()
{
if (this._fontInfoElement.offsetWidth !== fontInfoWidth && this._fontInfoElement.style.fontFamily === fontName)
{
fontsLoaded++;
if (fontsLoaded === 1)
{
fontInfoWidth = this._fontInfoElement.offsetWidth;
fontName = FontStyle.CONDENSED;
this._fontInfoElement.style.fontFamily = FontStyle.CONDENSED;
}
else if (fontsLoaded >= 2)
{
clearInterval(this._fontLoadingInterval);
document.body.removeChild(this._fontInfoElement);
this._loadData();
}
}
}.bind(this),100);
fontName = FontStyle.LIGHT_CONDENSED;
this._fontInfoElement.style.fontFamily = FontStyle.LIGHT_CONDENSED;
};
/**
* Load locally stored app data
*
* @method _loadData
* @private
*/
App.LoadData.prototype._loadData = function _loadData()
{
var StorageKey = App.StorageKey,
userData = Object.create(null),
timeStamp = window.performance && window.performance.now ? window.performance : Date,
start = timeStamp.now(),
transactions = Object.create(null),
transactionIds = null,
transactionKey = null,
i = 0,
l = 0;
// localStorage.clear();
userData[StorageKey.SETTINGS] = this._storage.getData(StorageKey.SETTINGS);
userData[StorageKey.CURRENCY_PAIRS] = this._storage.getData(StorageKey.CURRENCY_PAIRS);
userData[StorageKey.SUB_CATEGORIES] = this._storage.getData(StorageKey.SUB_CATEGORIES);
userData[StorageKey.CATEGORIES] = this._storage.getData(StorageKey.CATEGORIES);
userData[StorageKey.ACCOUNTS] = this._storage.getData(StorageKey.ACCOUNTS);
transactions[StorageKey.TRANSACTIONS_META] = this._storage.getData(StorageKey.TRANSACTIONS_META);
// Find and load two last segments of transactions
transactionIds = this._getMetaIds(transactions[StorageKey.TRANSACTIONS_META],2);
for (l=transactionIds.length;i<l;)
{
transactionKey = StorageKey.TRANSACTIONS+transactionIds[i++];
transactions[transactionKey] = this._storage.getData(transactionKey);
}
transactions.ids = transactionIds;
userData[StorageKey.TRANSACTIONS] = transactions;
// console.log("userData: ",timeStamp.now()-start,userData);
this.dispatchEvent(App.EventType.COMPLETE,{userData:userData,icons:this._icons});
};
/**
* Find and return IDs of transaction segments to load
* @param {Array.<Array>} metas
* @param {number} lookBack
* @private
*/
App.LoadData.prototype._getMetaIds = function _getMetaIds(metas,lookBack)
{
var i = metas.length > lookBack ? lookBack : metas.length - 1,
meta = null,
ids = [];
for (;i>-1;)
{
meta = metas[i--];
// Only return IDs of meta, that have more than zero transactions
if (meta[1]) ids.push(meta[0]);
}
return ids;
};
/**
* Destroy the command
*
* @method destroy
*/
App.LoadData.prototype.destroy = function destroy()
{
App.Command.prototype.destroy.call(this);
this._jsonLoader = null;
clearInterval(this._fontLoadingInterval);
this._storage = null;
this._fontInfoElement = null;
this._icons = null;
};
/**
* @class Initialize
* @extends {Command}
* @constructor
*/
App.Initialize = function Initialize()
{
this._eventListenerPool = new App.ObjectPool(App.EventListener,10);
App.Command.call(this,false,this._eventListenerPool);
this._storage = new App.Storage("./js/storage-worker.min.js");
this._loadDataCommand = new App.LoadData(this._eventListenerPool,this._storage);
};
App.Initialize.prototype = Object.create(App.Command.prototype);
/**
* Execute the command
*
* @method execute
*/
App.Initialize.prototype.execute = function execute()
{
this._loadDataCommand.addEventListener(App.EventType.COMPLETE,this,this._onLoadDataComplete);
this._loadDataCommand.execute();
};
/**
* Load data complete handler
*
* @method _onLoadDataComplete
* @param {string} data
* @private
*/
App.Initialize.prototype._onLoadDataComplete = function _onLoadDataComplete(data)
{
var HeaderAction = App.HeaderAction,
changeScreenDataPool = new App.ObjectPool(App.ChangeScreenData,5);
this._loadDataCommand.destroy();
this._loadDataCommand = null;
this._initServices();
this._initModel(data,changeScreenDataPool);
this._initController();
this._initView();
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenDataPool.allocate().update(
App.ScreenName.MENU,
0,
null,
HeaderAction.NONE,
HeaderAction.CANCEL,
App.ScreenTitle.MENU
));
this.dispatchEvent(App.EventType.COMPLETE);
};
/**
* Initialize services
* @private
*/
App.Initialize.prototype._initServices = function _initServices()
{
App.ServiceLocator.init([App.ServiceName.STORAGE,this._storage]);
};
/**
* Initialize application model
*
* @method _initModel
* @param {{userData:Object,icons:Object}} data
* @param {ObjectPool} changeScreenDataPool
* @private
*/
App.Initialize.prototype._initModel = function _initModel(data,changeScreenDataPool)
{
var ModelName = App.ModelName,
Collection = App.Collection,
PaymentMethod = App.PaymentMethod,
userData = data.userData,
currencyPairs = new App.CurrencyPairCollection(userData.currencyPairs,this._eventListenerPool);
App.ModelLocator.init([
ModelName.EVENT_LISTENER_POOL,this._eventListenerPool,
ModelName.TICKER,new App.Ticker(this._eventListenerPool),
ModelName.ICONS,Object.keys(data.icons).filter(function(element) {return element.indexOf("-app") === -1;}),
ModelName.PAYMENT_METHODS,new Collection([PaymentMethod.CASH,PaymentMethod.CREDIT_CARD],PaymentMethod,null,this._eventListenerPool),
ModelName.CURRENCY_PAIRS,currencyPairs,
ModelName.CURRENCY_SYMBOLS,new Collection(this._getCurrencySymbols(currencyPairs),App.CurrencySymbol,null,this._eventListenerPool),
ModelName.SETTINGS,new App.Settings(userData.settings),
ModelName.SUB_CATEGORIES,new Collection(userData.subCategories,App.SubCategory,null,this._eventListenerPool),
ModelName.CATEGORIES,new Collection(userData.categories,App.Category,null,this._eventListenerPool),
ModelName.ACCOUNTS,new Collection(userData.accounts,App.Account,null,this._eventListenerPool),
ModelName.TRANSACTIONS,new App.TransactionCollection(userData.transactions,this._eventListenerPool),
ModelName.CHANGE_SCREEN_DATA_POOL,changeScreenDataPool,
ModelName.SCREEN_HISTORY,new App.Stack()
]);
};
/**
* Goes through currencyPairs passed in and generate array of currency symbols
* @param {App.Collection} currencyPairs
* @returns {Array.<string>}
* @private
*/
App.Initialize.prototype._getCurrencySymbols = function _getCurrencySymbols(currencyPairs)
{
var symbols = [],
currencyPair = null,
i = 0,
l = currencyPairs.length();
for (;i<l;)
{
currencyPair = currencyPairs.getItemAt(i++);
if (symbols.indexOf(currencyPair.symbol) === -1) symbols.push(currencyPair.symbol);
if (symbols.indexOf(currencyPair.base) === -1) symbols.push(currencyPair.base);
}
return symbols;
};
/**
* Initialize commands
*
* @method _initController
* @private
*/
App.Initialize.prototype._initController = function _initController()
{
var EventType = App.EventType;
App.Controller.init(this._eventListenerPool,[
EventType.CHANGE_SCREEN,App.ChangeScreen,
EventType.CHANGE_TRANSACTION,App.ChangeTransaction,
EventType.CHANGE_ACCOUNT,App.ChangeAccount,
EventType.CHANGE_CATEGORY,App.ChangeCategory,
EventType.CHANGE_SUB_CATEGORY,App.ChangeSubCategory,
EventType.CHANGE_CURRENCY_PAIR,App.ChangeCurrencyPair
]);
};
/**
* Initialize view
*
* @method _initView
* @private
*/
App.Initialize.prototype._initView = function _initView()
{
var canvas = document.getElementsByTagName("canvas")[0],
context = canvas.getContext("2d"),
dpr = window.devicePixelRatio || 1,
bsr = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1,
pixelRatio = dpr / bsr > 2 ? 2 : dpr / bsr,
width = window.innerWidth,
height = window.innerHeight,
stage = new PIXI.Stage(0xffffff),
renderer = new PIXI.CanvasRenderer(width,height,{
view:canvas,
resolution:1,
transparent:false,
autoResize:false,
clearBeforeRender:false
}),
ViewLocator = App.ViewLocator,
ViewName = App.ViewName;
if (pixelRatio > 1)
{
canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.width = canvas.width * pixelRatio;
canvas.height = canvas.height * pixelRatio;
context.scale(pixelRatio,pixelRatio);
stage.interactionManager.setPixelRatio(pixelRatio);
}
App.FontStyle.init(pixelRatio);
PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.tintWithOverlay;
//context.webkitImageSmoothingEnabled = context.mozImageSmoothingEnabled = true;
context.lineCap = "square";
ViewLocator.addViewSegment(ViewName.SKIN,new App.Skin(Math.round(width * pixelRatio),pixelRatio));
ViewLocator.addViewSegment(ViewName.APPLICATION_VIEW,stage.addChild(new App.ApplicationView(stage,renderer,width,height,pixelRatio)));
};
/**
* Destroy the command
*
* @method destroy
*/
App.Initialize.prototype.destroy = function destroy()
{
App.Command.prototype.destroy.call(this);
if (this._loadDataCommand)
{
this._loadDataCommand.destroy();
this._loadDataCommand = null;
}
this._storage = null;
this._eventListenerPool = null;
};
/**
* @class ChangeScreen
* @extends {Command}
* @constructor
*/
App.ChangeScreen = function ChangeScreen()
{
App.Command.call(this,false,App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
};
App.ChangeScreen.prototype = Object.create(App.Command.prototype);
/**
* Execute the command
*
* @method execute
* @param {App.ChangeScreenData} data
*/
App.ChangeScreen.prototype.execute = function execute(data)
{
var ViewLocator = App.ViewLocator,
ViewName = App.ViewName,
ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
changeScreenDataPool = ModelLocator.getProxy(ModelName.CHANGE_SCREEN_DATA_POOL),
screenHistory = ModelLocator.getProxy(ModelName.SCREEN_HISTORY),
screenStack = ViewLocator.getViewSegment(ViewName.SCREEN_STACK),
screen = null;
if (data.screenName === App.ScreenName.BACK)
{
var updateBackScreen = data.updateBackScreen,
i = 0,
l = data.backSteps;
for (;i<l;i++) changeScreenDataPool.release(screenHistory.pop());
changeScreenDataPool.release(data);
data = screenHistory.peek();
screen = screenStack.getChildByIndex(data.screenName);
if (updateBackScreen) screen.update(data.updateData,data.screenMode);
}
else
{
if (data.headerLeftAction !== App.HeaderAction.CANCEL && data.headerRightAction !== App.HeaderAction.CANCEL && data.screenMode !== App.ScreenMode.SELECT)
{
this._clearHistory(screenHistory,changeScreenDataPool);
}
screen = screenStack.getChildByIndex(data.screenName);
screen.update(data.updateData,data.screenMode);
screenHistory.push(data);
}
// console.log("Stack: ",screenHistory._source);
// console.log("Pool: ",changeScreenDataPool._freeItems);
ViewLocator.getViewSegment(ViewName.HEADER).change(data.headerLeftAction,data.headerRightAction,data.headerName);
screenStack.selectChild(screen);
this.dispatchEvent(App.EventType.COMPLETE,this);
};
/**
* Clear history
* @param {App.Stack} screenHistory
* @param {App.ObjectPool} changeScreenDataPool
* @private
*/
App.ChangeScreen.prototype._clearHistory = function _clearHistory(screenHistory,changeScreenDataPool)
{
// console.log("Before clear: ------------------");
// console.log("Stack: ",screenHistory._source);
// console.log("Pool: ",changeScreenDataPool._freeItems);
var item = screenHistory.pop();
while (item)
{
changeScreenDataPool.release(item);
item = screenHistory.pop();
}
screenHistory.clear();
// console.log("After clear: ------------------");
// console.log("Stack: ",screenHistory._source);
// console.log("Pool: ",changeScreenDataPool._freeItems);
// console.log("---------------------------------");
};
/**
* @class ChangeTransaction
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeTransaction = function ChangeTransaction(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool);
};
App.ChangeTransaction.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {{nextCommand:Command,screenName:number}} data
*/
App.ChangeTransaction.prototype.execute = function execute(data)
{
var EventType = App.EventType,
ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
settings = ModelLocator.getProxy(ModelName.SETTINGS),
transactions = ModelLocator.getProxy(ModelName.TRANSACTIONS),
transaction = transactions.getCurrent(),
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
transaction = new App.Transaction();
transaction.id = transactions.getTransactionId();
transactions.addItem(transaction);
transactions.setCurrent(transaction);
data.nextCommandData.updateData = transaction;
}
else if (type === EventType.COPY)
{
transaction = data.transaction.copy();
transaction.id = transactions.getTransactionId();
transactions.addItem(transaction);
transactions.setCurrent(transaction);
data.nextCommandData.updateData = transaction;
}
else if (type === EventType.CHANGE)
{
this._setInputs(transaction,data,false);
this._setToggles(transaction,data);
this._setCategories(transaction,data,settings);
this._setTime(transaction,data);
this._setMethod(transaction,data,settings);
this._setCurrency(transaction,data,settings);
}
else if (type === EventType.CONFIRM)
{
// Update balances before saving
this._updateCategoryBalance(type,transaction,data,settings);
this._setToggles(transaction,data);
this._setInputs(transaction,data,true);
this._setMethod(transaction,data,settings);
transaction.currencyBase = settings.baseCurrency;
transaction.save();
transactions.setCurrent(null);
this._saveCollection(transaction,transactions);
}
else if (type === EventType.CANCEL)
{
if (transaction.isSaved())
{
transaction.revokeState();
transactions.setCurrent(null);
}
else
{
transactions.removeItem(transaction).destroy();
}
}
else if (type === EventType.DELETE)
{
// Update balances before deleting
this._updateCategoryBalance(type,transaction,data,settings);
transactions.removeItem(transaction).destroy();
data.nextCommandData.updateData = transactions.copySource().reverse();
this._saveCollection(transaction,transactions);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
/**
* Save input texts
* @param {App.Transaction} transaction
* @param {Object} data
* @param {boolean} setDefault
* @private
*/
App.ChangeTransaction.prototype._setInputs = function _setInputs(transaction,data,setDefault)
{
transaction.amount = isNaN(parseFloat(data.amount)) ? transaction.amount : parseFloat(data.amount);
transaction.note = data.note || transaction.note;
if (setDefault && !transaction.amount) transaction.amount = "0";
};
/**
* Save toggle button values
* @param {App.Transaction} transaction
* @param {Object} data
* @private
*/
App.ChangeTransaction.prototype._setToggles = function _setToggles(transaction,data)
{
transaction.type = data.transactionType || transaction.type;
if (typeof data.pending === "boolean") transaction.pending = data.pending;
if (typeof data.repeat === "boolean") transaction.repeat = data.repeat;
};
/**
* Save Account, Category, and SubCategory
* @param {App.Transaction} transaction
* @param {Object} data
* @param {App.Settings} settings
* @private
*/
App.ChangeTransaction.prototype._setCategories = function _setCategories(transaction,data,settings)
{
if (data.account && data.category && data.subCategory)
{
transaction.account = data.account;
transaction.category = data.category;
transaction.subCategory = data.subCategory;
//TODO move this into its own command!
settings.defaultAccount = data.account;
settings.defaultCategory = data.category;
settings.defaultSubCategory = data.subCategory;
}
};
/**
* Save time and data
* @param {App.Transaction} transaction
* @param {Object} data
* @private
*/
App.ChangeTransaction.prototype._setTime = function _setTime(transaction,data)
{
var date = data.date,
time = data.time;
if (date && time)
{
transaction.date.setFullYear(date.getFullYear(),date.getMonth(),date.getDate());
if (time.length > 0) transaction.date.setHours(parseInt(time.split(":")[0],10),parseInt(time.split(":")[1],10));
}
};
/**
* Save payment method
* @param {App.Transaction} transaction
* @param {Object} data
* @param {App.Settings} settings
* @private
*/
App.ChangeTransaction.prototype._setMethod = function _setMethod(transaction,data,settings)
{
if (data.method)
{
var method = App.ModelLocator.getProxy(App.ModelName.PAYMENT_METHODS).find("name",data.method);
transaction.method = method;
settings.defaultPaymentMethod = method;
}
};
/**
* Save currency quote
* @param {App.Transaction} transaction
* @param {Object} data
* @param {App.Settings} settings
* @private
*/
App.ChangeTransaction.prototype._setCurrency = function _setCurrency(transaction,data,settings)
{
if (data.currencyQuote)
{
transaction.currencyQuote = data.currencyQuote;
settings.defaultCurrencyQuote = data.currencyQuote;
}
};
/**
* Update subCategory balance
* @param {string} eventType
* @param {App.Transaction} transaction
* @param {Object} data
* @param {App.Settings} settings
* @private
*/
App.ChangeTransaction.prototype._updateCategoryBalance = function _updateCategoryBalance(eventType,transaction,data,settings)
{
var currencyPairCollection = App.ModelLocator.getProxy(App.ModelName.CURRENCY_PAIRS);
if (eventType === App.EventType.CONFIRM)
{
if (transaction.isSaved() && !transaction.savedPending) this._updateSavedBalance(transaction,currencyPairCollection);
if (!data.pending) this._updateCurrentBalance(transaction,currencyPairCollection,data,settings);
}
else if (eventType === App.EventType.DELETE)
{
this._updateSavedBalance(transaction,currencyPairCollection);
}
};
/**
* Update saved subCategory balance
* @param {App.Transaction} transaction
* @param {App.CurrencyPairCollection} currencyPairCollection
* @private
*/
App.ChangeTransaction.prototype._updateSavedBalance = function _updateSavedBalance(transaction,currencyPairCollection)
{
var TransactionType = App.TransactionType,
savedSubCategory = transaction.savedSubCategory,
rate = transaction.savedCurrencyRate ? transaction.savedCurrencyRate : currencyPairCollection.findRate(transaction.savedCurrencyBase,transaction.savedCurrencyQuote),
savedAmount = transaction.savedAmount / rate;
if (transaction.savedType === TransactionType.EXPENSE)
{
savedSubCategory.balance = savedSubCategory.balance + savedAmount;
}
else if (transaction.savedType === TransactionType.INCOME)
{
savedSubCategory.balance = savedSubCategory.balance - savedAmount;
}
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.SUB_CATEGORIES,
App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).serialize()
);
};
/**
* Update current subCategory balance
* @param {App.Transaction} transaction
* @param {App.CurrencyPairCollection} currencyPairCollection
* @param {Object} data
* @param {App.Settings} settings
* @private
*/
App.ChangeTransaction.prototype._updateCurrentBalance = function _updateCurrentBalance(transaction,currencyPairCollection,data,settings)
{
var TransactionType = App.TransactionType,
subCategory = transaction.subCategory,
currentAmount = parseFloat(data.amount) / currencyPairCollection.findRate(settings.baseCurrency,transaction.currencyQuote);
if (!isNaN(currentAmount))
{
if (data.transactionType === TransactionType.EXPENSE)
{
subCategory.balance = subCategory.balance - currentAmount;
}
else if (data.transactionType === TransactionType.INCOME)
{
subCategory.balance = subCategory.balance + currentAmount;
}
}
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.SUB_CATEGORIES,
App.ModelLocator.getProxy(App.ModelName.SUB_CATEGORIES).serialize()
);
};
/**
* Save transaction collection
* @param {App.Transaction} transaction
* @param {App.TransactionCollection} collection
* @private
*/
App.ChangeTransaction.prototype._saveCollection = function _saveCollection(transaction,collection)
{
var metaId = transaction.id.split(".")[0],
StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE);
Storage.setData(StorageKey.TRANSACTIONS+metaId,collection.serialize(metaId,false));
Storage.setData(StorageKey.TRANSACTIONS_META,collection.serializeMeta());
};
/**
* @class ChangeCategory
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeCategory = function ChangeCategory(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool || App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
};
App.ChangeCategory.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {Object} data
* @param {string} data.type
* @param {App.Category} data.category
* @param {string} data.name
* @param {string} data.color
* @param {string} data.icon
* @param {string} data.budget
* @param {App.Account} data.account
* @param {Command} data.nextCommand
* @param {Object} data.nextCommandData
*/
App.ChangeCategory.prototype.execute = function execute(data)
{
var EventType = App.EventType,
category = data.category,
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
category = new App.Category();
category.account = data.account.id;
this._nextCommandData.updateData = category;
}
else if (type === EventType.CHANGE)
{
category.name = data.name || category.name;
category.icon = data.icon || category.icon;
category.color = data.color || category.color;
category.budget = data.budget || category.budget;
this._registerSubCategories(category);
}
else if (type === EventType.CONFIRM)
{
category.name = data.name;
category.icon = data.icon;
category.color = data.color;
category.budget = data.budget;
this._registerCategory(category);
this._registerSubCategories(category);
}
else if (type === EventType.CANCEL)
{
this._cancelChanges(category);
}
else if (type === EventType.DELETE)
{
this._deleteCategory(category);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
/**
* Add category to collection
* @param category
* @private
*/
App.ChangeCategory.prototype._registerCategory = function _registerCategory(category)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
categories = ModelLocator.getProxy(ModelName.CATEGORIES);
if (categories.indexOf(category) === -1)
{
categories.addItem(category);
ModelLocator.getProxy(ModelName.ACCOUNTS).find("id",category.account).addCategory(category);
var StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE);
Storage.setData(StorageKey.ACCOUNTS,ModelLocator.getProxy(ModelName.ACCOUNTS).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.CATEGORIES,categories.serialize());//TODO do I need to serialize every time?
}
};
/**
* Add subCategories to collection
* @param category
* @private
*/
App.ChangeCategory.prototype._registerSubCategories = function _registerSubCategories(category)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE),
StorageKey = App.StorageKey,
subCategoryCollection = ModelLocator.getProxy(ModelName.SUB_CATEGORIES),
subCategories = category.subCategories,
subCategory = null,
i = 0,
l = subCategories.length;
for (;i<l;)
{
subCategory = subCategories[i++];
if (subCategoryCollection.indexOf(subCategory) === -1) subCategoryCollection.addItem(subCategory);
}
Storage.setData(StorageKey.CATEGORIES,ModelLocator.getProxy(ModelName.CATEGORIES).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.SUB_CATEGORIES,subCategoryCollection.serialize());//TODO do I need to serialize every time?
};
/**
* Cancel changes made to the category since last saved state
* @param {App.Category} category
* @private
*/
App.ChangeCategory.prototype._cancelChanges = function _cancelChanges(category)
{
var ModelName = App.ModelName,
ModelLocator = App.ModelLocator,
StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE),
subCategoryCollection = ModelLocator.getProxy(ModelName.SUB_CATEGORIES),
allSubCategories = category.subCategories,
i = 0,
l = allSubCategories.length;
category.revokeState();
var revokedSubCategories = category.subCategories;
for (;i<l;i++)
{
if (revokedSubCategories.indexOf(allSubCategories[i]) === -1 && subCategoryCollection.indexOf(allSubCategories[i]) > -1)
{
subCategoryCollection.removeItem(allSubCategories[i]);
}
}
i = 0;
l = revokedSubCategories.length;
for (;i<l;) revokedSubCategories[i++].revokeState();
//TODO destroy category if it was newly created and eventually cancelled?
Storage.setData(StorageKey.CATEGORIES,ModelLocator.getProxy(ModelName.CATEGORIES).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.SUB_CATEGORIES,subCategoryCollection.serialize());//TODO do I need to serialize every time?
};
/**
* Delete category
* @param {App.Category} category
* @private
*/
App.ChangeCategory.prototype._deleteCategory = function _deleteCategory(category)
{
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
StorageKey = App.StorageKey,
Storage = App.ServiceLocator.getService(App.ServiceName.STORAGE),
accounts = ModelLocator.getProxy(ModelName.ACCOUNTS);
accounts.find("id",category.account).removeCategory(category);
Storage.setData(StorageKey.ACCOUNTS,accounts.serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.CATEGORIES,ModelLocator.getProxy(ModelName.CATEGORIES).serialize());//TODO do I need to serialize every time?
Storage.setData(StorageKey.SUB_CATEGORIES,ModelLocator.getProxy(ModelName.SUB_CATEGORIES).serialize());//TODO do I need to serialize every time?
category.destroy();
};
/**
* @class ChangeSubCategory
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeSubCategory = function ChangeSubCategory(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool);//App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL)
};
App.ChangeSubCategory.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {{subCategory:App.SubCategory,name:string,category:App.Category,nextCommand:Command,nextCommandData:App.ChangeScreenData}} data
*/
App.ChangeSubCategory.prototype.execute = function execute(data)
{
var EventType = App.EventType,
subCategory = data.subCategory,
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
subCategory = new App.SubCategory();
// subCategory.category = data.category.id;
this._nextCommandData.updateData = {subCategory:subCategory,category:data.category};
}
else if (type === EventType.CHANGE)
{
subCategory.name = data.name;
data.category.addSubCategory(subCategory);
}
else if (type === EventType.DELETE)
{
data.category.removeSubCategory(subCategory);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
/**
* @class ChangeAccount
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeAccount = function ChangeAccount(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool);
};
App.ChangeAccount.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {{account:App.Account,name:string,nextCommand:Command,nextCommandData:App.ChangeScreenData}} data
*/
App.ChangeAccount.prototype.execute = function execute(data)
{
var EventType = App.EventType,
account = data.account,
type = data.type;
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
if (type === EventType.CREATE)
{
account = new App.Account();
this._nextCommandData.updateData = account;
}
else if (type === EventType.CHANGE)
{
account.name = data.name;
if (account.lifeCycleState === App.LifeCycleState.CREATED)
{
var collection = App.ModelLocator.getProxy(App.ModelName.ACCOUNTS);
if (collection.indexOf(account) === -1) collection.addItem(account);
account.lifeCycleState = App.LifeCycleState.ACTIVE;
// Save
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.ACCOUNTS,
App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).serialize()
);
}
}
else if (type === EventType.DELETE)
{
account.lifeCycleState = App.LifeCycleState.DELETED;
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.ACCOUNTS,
App.ModelLocator.getProxy(App.ModelName.ACCOUNTS).serialize()
);
}
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(EventType.COMPLETE,this);
};
/**
* @class ChangeCurrencyPair
* @extends SequenceCommand
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ChangeCurrencyPair = function ChangeCurrencyPair(eventListenerPool)
{
App.SequenceCommand.call(this,false,eventListenerPool);
};
App.ChangeCurrencyPair.prototype = Object.create(App.SequenceCommand.prototype);
/**
* Execute the command
*
* @method execute
* @param {{account:App.Account,name:string,nextCommand:Command,nextCommandData:App.ChangeScreenData}} data
*/
App.ChangeCurrencyPair.prototype.execute = function execute(data)
{
this._nextCommand = data.nextCommand;
this._nextCommandData = data.nextCommandData;
data.currencyPair.rate = parseFloat(data.rate);
// Save
App.ServiceLocator.getService(App.ServiceName.STORAGE).setData(
App.StorageKey.CURRENCY_PAIRS,
App.ModelLocator.getProxy(App.ModelName.CURRENCY_PAIRS).serialize()
);
if (this._nextCommand) this._executeNextCommand(this._nextCommandData);
else this.dispatchEvent(App.EventType.COMPLETE,this);
};
(function()
{
//TODO move to index.html and also build simple pre-preloader
function onInitComplete()
{
initCommand.destroy();
initCommand = null;
}
var initCommand = new App.Initialize();
initCommand.addEventListener(App.EventType.COMPLETE,this,onInitComplete);
initCommand.execute();
})();
<file_sep>/**
* @class HeaderTitle
* @extends HeaderSegment
* @param {string} value
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {{font:string,fill:string}} fontStyle
* @constructor
*/
App.HeaderTitle = function HeaderTitle(value,width,height,pixelRatio,fontStyle)
{
App.HeaderSegment.call(this,value,width,height,pixelRatio);
this._frontElement = new PIXI.Text(value,fontStyle);
this._backElement = new PIXI.Text(value,fontStyle);
this._render();
this.addChild(this._frontElement);
this.addChild(this._backElement);
};
App.HeaderTitle.prototype = Object.create(App.HeaderSegment.prototype);
/**
* Render
* @private
*/
App.HeaderTitle.prototype._render = function _render()
{
App.HeaderSegment.prototype._render.call(this);
this._middlePosition = Math.round(18 * this._pixelRatio);
this._frontElement.x = Math.round((this._width - this._frontElement.width) / 2);
this._frontElement.y = this._height;
this._frontElement.alpha = 0.0;
this._backElement.x = Math.round((this._width - this._backElement.width) / 2);
this._backElement.y = this._height;
this._backElement.alpha = 0.0;
};
/**
* Change
* @param {string} name
*/
App.HeaderTitle.prototype.change = function change(name)
{
App.HeaderSegment.prototype.change.call(this,name);
this._frontElement.setText(name);
this._frontElement.x = Math.round((this._width - this._frontElement.width) / 2);
this._frontElement.alpha = 1.0;
};
<file_sep>/**
* Scroll Policy
* @enum {string}
* @return {{ON:string,OFF:string,AUTO:string}}
*/
App.ScrollPolicy = {
ON:"ON",
OFF:"OFF",
AUTO:"AUTO"
};
<file_sep>/**
* StringUtils
* @type {{encode: Function}}
*/
App.StringUtils = {
_threeCharPattern:/.{1,3}/g,
/**
* Encode URI component
* @param {string} str
* @returns {string}
*/
encode:function encode(str)
{
//return encodeURIComponent(str).replace(/[!'()]/g,escape).replace(/\*/g,"%2A");// 'escape' is depreciated
return encodeURIComponent(str).replace(/[!'()*]/g,function(c) {return '%'+c.charCodeAt(0).toString(16);});
},
/**
* Add leading zero to number passed in
* @param {number} value
*/
pad:function pad(value)
{
if (value < 10) return '0' + value;
return value;
},
/**
* Format number passed in
* @param {number} value
* @param {number} decimal Fixed number of decimal places
* @param {string} separator
*/
formatNumber:function formatNumber(value,decimal,separator)
{
var num = String(value.toFixed(decimal)),
decimals = num.split("."),
integer = decimals[0],
reversed = integer.split("").reverse().join(""),
formatted = reversed.length > 3 ? reversed.match(this._threeCharPattern).join(separator) : reversed;
return formatted.split("").reverse().join("") + "." + decimals[1];
}
};
<file_sep>/**
* @class EditCurrencyPairScreen
* @param {Object} layout
* @constructor
*/
App.EditCurrencyPairScreen = function EditCurrencyPairScreen(layout)
{
App.Screen.call(this,layout,0.4);
var FontStyle = App.FontStyle,
r = layout.pixelRatio,
w = layout.width;
this._background = this.addChild(new PIXI.Graphics());
this._pairLabel = this.addChild(new PIXI.Text("EUR / USD",App.FontStyle.get(24,App.FontStyle.BLUE)));
this._input = this.addChild(new App.Input("",20,Math.round(layout.width - this._pairLabel.width - Math.round(50 * r)),Math.round(40 * r),r));
this._downloadButton = this.addChild(new App.Button("Update rate from internet",{
width:Math.round(w - 20 * r),
height:Math.round(40 * r),
pixelRatio:r,
style:FontStyle.get(18,FontStyle.BLACK_LIGHT,null,FontStyle.LIGHT_CONDENSED),
backgroundColor:App.ColorTheme.GREY_DARK
}));
this._input.restrict(/\d{1,}(\.\d*){0,1}/g);
this._render();
};
App.EditCurrencyPairScreen.prototype = Object.create(App.Screen.prototype);
/**
* Render
* @private
*/
App.EditCurrencyPairScreen.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._layout.pixelRatio,
w = this._layout.width,
padding = Math.round(10 * r),
inputHeight = Math.round(60 * r);
this._pairLabel.x = padding * 2;
this._pairLabel.y = Math.round(22 * r);
this._input.x = Math.round(w - padding - this._input.width);
this._input.y = padding;
this._downloadButton.x = padding;
this._downloadButton.y = inputHeight + padding;
GraphicUtils.drawRects(this._background,ColorTheme.GREY,1,[0,0,w,inputHeight*2],true,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_DARK,1,[padding,inputHeight-1,w-padding*2,1],false,false);
GraphicUtils.drawRects(this._background,ColorTheme.GREY_LIGHT,1,[padding,inputHeight,w-padding*2,1],false,true);
};
/**
* Enable
*/
App.EditCurrencyPairScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._input.enable();
};
/**
* Disable
*/
App.EditCurrencyPairScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._input.disable();
};
/**
* Update
* @param {App.CurrencyPair} model
* @param {string} mode
*/
App.EditCurrencyPairScreen.prototype.update = function update(model,mode)
{
this._model = model;
this._pairLabel.setText(this._model.base+" / "+this._model.symbol);
this._input.setValue(this._model.rate);
};
/**
* On Header click
* @param {number} action
* @private
*/
App.EditCurrencyPairScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.BACK);
changeScreenData.updateBackScreen = true;
this._input.blur();
//TODO check first if value is set
if (action === App.HeaderAction.CONFIRM)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_CURRENCY_PAIR,{
currencyPair:this._model,
rate:this._input.getValue(),
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else if (action === App.HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
};
<file_sep>/**
* @class Skin
* @param {number} width
* @param {number} pixelRatio
* @constructor
*/
App.Skin = function Skin(width,pixelRatio)
{
var ColorTheme = App.ColorTheme,
defaultScaleMode = PIXI.scaleModes.DEFAULT,
padding = Math.round(10 * pixelRatio),
graphics = new PIXI.Graphics(),
w = width - padding * 2,
h = Math.round(40 * pixelRatio),
draw = App.GraphicUtils.drawRects,
color = ColorTheme.GREY,
lightColor = ColorTheme.GREY_LIGHT,
darkColor = ColorTheme.GREY_DARK;
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_40 = graphics.generateTexture(1,defaultScaleMode);
draw(graphics,ColorTheme.WHITE,1,[0,0,width,h],true,false);
draw(graphics,color,1,[padding,h-1,w,1],false,true);
this.WHITE_40 = graphics.generateTexture(1,defaultScaleMode);
h = Math.round(50 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_50 = graphics.generateTexture(1,defaultScaleMode);
h = Math.round(60 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_60 = graphics.generateTexture(1,defaultScaleMode);
h = Math.round(70 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.GREY_70 = graphics.generateTexture(1,defaultScaleMode);
draw(graphics,ColorTheme.RED,1,[0,0,width,h],true,false);
draw(graphics,ColorTheme.RED_LIGHT,1,[padding,0,w,1],false,false);
draw(graphics,ColorTheme.RED_DARK,1,[padding,h-1,w,1],false,true);
this.RED_70 = graphics.generateTexture(1,defaultScaleMode);
w = Math.round(40 * pixelRatio);
h = w;
/*graphics.clear();
graphics.beginFill(ColorTheme.BLUE_DARK,1.0);
graphics.drawRect(0,0,w,h);
graphics.beginFill(ColorTheme.BLUE_LIGHT,1.0);
graphics.drawRect(0,h/2,w/2,h/2);
graphics.beginFill(ColorTheme.BLUE,1.0);
graphics.drawShape(new PIXI.Polygon([0,0,w,0,w,h,0,0]));
graphics.endFill();
this.BLUE_PATTERN = graphics.generateTexture(1,defaultScaleMode);*/
graphics.clear();
graphics.beginFill(ColorTheme.GREY_DARK,1.0);
graphics.drawRect(0,0,w,h);
graphics.beginFill(ColorTheme.GREY,1.0);
graphics.drawRect(0,h/2,w/2,h/2);
graphics.beginFill(0xdedede,1.0);
graphics.drawShape(new PIXI.Polygon([0,0,w,0,w,h,0,0]));
graphics.endFill();
this.GREY_PATTERN = graphics.generateTexture(1,defaultScaleMode);
w = width - padding * 4;
h = Math.round(40 * pixelRatio);
draw(graphics,color,1,[0,0,width,h],true,false);
draw(graphics,lightColor,1,[padding,0,w,1],false,false);
draw(graphics,darkColor,1,[padding,h-1,w,1],false,true);
this.NARROW_GREY_40 = graphics.generateTexture(1,defaultScaleMode);
draw(graphics,ColorTheme.WHITE,1,[0,0,width,h],true,false);
draw(graphics,color,1,[padding,h-1,w,1],false,true);
this.NARROW_WHITE_40 = graphics.generateTexture(1,defaultScaleMode);
};
<file_sep>/**
* @class AddNewButton
* @extends DisplayObjectContainer
* @param {string} label
* @param {{font:string,fill:string}} fontStyle
* @param {Texture} skin
* @param {number} pixelRatio
* @constructor
*/
App.AddNewButton = function AddNewButton(label,fontStyle,skin,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
this.boundingBox = new App.Rectangle(0,0,skin.width,skin.height);
this._label = label;
this._pixelRatio = pixelRatio;
this._skin = new PIXI.Sprite(skin);
this._icon = PIXI.Sprite.fromFrame("plus-app");
this._iconResizeRatio = Math.round(20 * pixelRatio) / this._icon.height;
this._labelField = new PIXI.Text(label,fontStyle);
this._render();
this.addChild(this._skin);
this.addChild(this._icon);
this.addChild(this._labelField);
};
App.AddNewButton.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.AddNewButton.prototype._render = function _render()
{
var gap = Math.round(10 * this._pixelRatio),
h = this.boundingBox.height,
position = 0;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
position = Math.round((this.boundingBox.width - (this._labelField.width + gap + this._icon.width)) / 2);
this._icon.x = position;
this._icon.y = Math.round((h - this._icon.height) / 2);
this._icon.tint = App.ColorTheme.GREY_DARK;
this._labelField.x = position + this._icon.width + gap;
this._labelField.y = Math.round((h - this._labelField.height) / 2);
};
<file_sep>/**
* @class Header
* @extends Graphics
* @param {Object} layout
* @constructor
*/
App.Header = function Header(layout)
{
PIXI.Graphics.call(this);
var ModelLocator = App.ModelLocator,
ModelName = App.ModelName,
HeaderIcon = App.HeaderIcon,
HeaderAction = App.HeaderAction,
FontStyle = App.FontStyle,
r = layout.pixelRatio,
listenerPool = ModelLocator.getProxy(ModelName.EVENT_LISTENER_POOL);
this._layout = layout;
this._iconSize = Math.round(50 * r);
this._leftIcon = new HeaderIcon(HeaderAction.ADD_TRANSACTION,this._iconSize,this._iconSize,r);
this._rightIcon = new HeaderIcon(HeaderAction.MENU,this._iconSize,this._iconSize,r);
this._title = new App.HeaderTitle("Cashius",this._layout.width-this._iconSize*2,this._iconSize,r,FontStyle.get(20,FontStyle.WHITE));
this._ticker = ModelLocator.getProxy(ModelName.TICKER);
this._tween = new App.TweenProxy(0.7,App.Easing.outExpo,0,listenerPool);
this._eventDispatcher = new App.EventDispatcher(listenerPool);
this._actionEnabled = true;
this._render();
this.addChild(this._leftIcon);
this.addChild(this._title);
this.addChild(this._rightIcon);
this._registerEventListeners();
};
App.Header.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Render
* @private
*/
App.Header.prototype._render = function _render()
{
var GraphicUtils = App.GraphicUtils,
ColorTheme = App.ColorTheme,
r = this._layout.pixelRatio,
w = this._layout.width,
h = this._layout.headerHeight,
offset = h - this._iconSize,
padding = Math.round(10 * r);
this._title.x = this._iconSize;
this._rightIcon.x = w - this._iconSize;
GraphicUtils.drawRects(this,ColorTheme.BLUE,1,[0,0,w,h],true,false);
GraphicUtils.drawRects(this,ColorTheme.BLUE_LIGHT,1,[
this._iconSize+1,offset+padding,1,this._iconSize-padding*2,
w-this._iconSize,offset+padding,1,this._iconSize-padding*2
],false,false);
GraphicUtils.drawRects(this,ColorTheme.BLUE_DARK,1,[
0,h-1,w,1,
this._iconSize,offset+padding,1,this._iconSize-padding*2,
w-this._iconSize-1,offset+padding,1,this._iconSize-padding*2
],false,true);
};
/**
* Register event listeners
* @private
*/
App.Header.prototype._registerEventListeners = function _registerEventListeners()
{
var EventType = App.EventType;
App.ViewLocator.getViewSegment(App.ViewName.SCREEN_STACK).addEventListener(EventType.CHANGE,this,this._onScreenChange);
if (App.Device.TOUCH_SUPPORTED) this.tap = this._onClick;
else this.click = this._onClick;
this._tween.addEventListener(EventType.COMPLETE,this,this._onTweenComplete);
this.interactive = true;
};
/**
* Enable actions
*/
App.Header.prototype.enableActions = function enableActions()
{
this._actionEnabled = true;
};
/**
* Disable actions
*/
App.Header.prototype.disableActions = function disableActions()
{
this._actionEnabled = false;
};
/**
* On screen change
* @private
*/
App.Header.prototype._onScreenChange = function _onScreenChange()
{
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
this._tween.restart();
};
/**
* Change
* @param {number} leftAction
* @param {number} rightAction
* @param {string} name
* @private
*/
App.Header.prototype.change = function change(leftAction,rightAction,name)
{
this._leftIcon.change(leftAction);
this._title.change(name);
this._rightIcon.change(rightAction);
};
/**
* On RAF Tick
* @private
*/
App.Header.prototype._onTick = function _onTick()
{
this._onTweenUpdate();
};
/**
* On tween update
* @private
*/
App.Header.prototype._onTweenUpdate = function _onTweenUpdate()
{
var progress = this._tween.progress;
//TODO offset each segment for effect
this._leftIcon.update(progress);
this._title.update(progress);
this._rightIcon.update(progress);
};
/**
* On tween complete
* @private
*/
App.Header.prototype._onTweenComplete = function _onTweenComplete()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
this._onTweenUpdate();
};
/**
* On click
* @param {InteractionData} data
* @private
*/
App.Header.prototype._onClick = function _onClick(data)
{
if (this._actionEnabled)
{
var position = data.getLocalPosition(this).x,
HeaderAction = App.HeaderAction,
action = HeaderAction.NONE;
if (position <= this._iconSize) action = this._leftIcon.getAction();
else if (position >= this._layout.width - this._iconSize) action = this._rightIcon.getAction();
if (action !== HeaderAction.NONE) this._eventDispatcher.dispatchEvent(App.EventType.CLICK,action);
}
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Header.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Header.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
<file_sep>App.ScreenFactory = function ScreenFactory()
{
//TODO implement 'initialize progress' as particular screens are initiated
};
<file_sep>/**
* @class IconSample
* @extends DisplayObjectContainer
* @param {number} modelIndex
* @param {string} model
* @param {number} pixelRatio
* @constructor
*/
App.IconSample = function IconSample(modelIndex,model,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var size = Math.round(64 * pixelRatio);
this.boundingBox = new App.Rectangle(0,0,size,size);
this._modelIndex = modelIndex;
this._model = model;
this._pixelRatio = pixelRatio;
this._icon = PIXI.Sprite.fromFrame(model);
this._iconResizeRatio = Math.round(32 * pixelRatio) / this._icon.height;
this._selected = false;
this._render();
this.addChild(this._icon);
};
App.IconSample.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Render
* @private
*/
App.IconSample.prototype._render = function _render()
{
var ColorTheme = App.ColorTheme,
size = this.boundingBox.width;
this._icon.scale.x = this._iconResizeRatio;
this._icon.scale.y = this._iconResizeRatio;
this._icon.x = Math.round((size - this._icon.width) / 2);
this._icon.y = Math.round((size - this._icon.height) / 2);
this._icon.tint = this._selected ? ColorTheme.BLUE : ColorTheme.GREY_DARK;
};
/**
* Set color
* @param {number} index
* @param {string} model
* @param {number} selectedIndex
*/
App.IconSample.prototype.setModel = function setModel(index,model,selectedIndex)
{
this._modelIndex = index;
this._model = model;
this._icon.setTexture(PIXI.TextureCache[model]);
this._selected = selectedIndex === this._modelIndex;
this._render();
};
/**
* Return model index
* @return {number}
*/
App.IconSample.prototype.getModelIndex = function getModelIndex()
{
return this._modelIndex;
};
/**
* Return value
* @returns {string}
*/
App.IconSample.prototype.getValue = function getValue()
{
return this._model;
};
/**
* Select
* @param {number} selectedIndex Index of selected item in the collection
*/
App.IconSample.prototype.select = function select(selectedIndex)
{
var selected = this._modelIndex === selectedIndex;
if (this._selected === selected) return;
this._selected = selected;
this._render();
};
<file_sep>/**
* @class CategoryScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.CategoryScreen = function CategoryScreen(layout)
{
App.Screen.call(this,layout,0.4);
var ScrollPolicy = App.ScrollPolicy,
FontStyle = App.FontStyle,
ObjectPool = App.ObjectPool,
r = layout.pixelRatio,
w = layout.width,
h = layout.contentHeight,
skin = App.ViewLocator.getViewSegment(App.ViewName.SKIN),
buttonOptions = {
width:w,
height:Math.round(50 * r),
pixelRatio:r,
skin:skin.GREY_50,
addButtonSkin:skin.WHITE_40,
nameLabelStyle:FontStyle.get(18,FontStyle.BLUE),
editLabelStyle:FontStyle.get(18,FontStyle.WHITE,null,FontStyle.LIGHT_CONDENSED),
addLabelStyle:FontStyle.get(14,FontStyle.GREY_DARK),
displayHeader:false
};
this._interactiveButton = null;
this._buttonsInTransition = [];
this._layoutDirty = false;
this._buttonExpandPool = new ObjectPool(App.CategoryButtonExpand,5,buttonOptions);
this._buttonEditPool = new ObjectPool(App.CategoryButtonEdit,5,buttonOptions);
this._buttonList = new App.TileList(App.Direction.Y,h);
this._addNewButton = new App.AddNewButton("ADD CATEGORY",FontStyle.get(14,FontStyle.GREY_DARK),App.ViewLocator.getViewSegment(App.ViewName.SKIN).GREY_50,r);
this._pane = new App.TilePane(ScrollPolicy.OFF,ScrollPolicy.AUTO,layout.width,h,r,false);
this._pane.setContent(this._buttonList);
this.addChild(this._pane);
};
App.CategoryScreen.prototype = Object.create(App.Screen.prototype);
/**
* Enable
*/
App.CategoryScreen.prototype.enable = function enable()
{
App.Screen.prototype.enable.call(this);
this._pane.resetScroll();
this._pane.enable();
};
/**
* Disable
*/
App.CategoryScreen.prototype.disable = function disable()
{
App.Screen.prototype.disable.call(this);
this._layoutDirty = false;
this._pane.disable();
};
/**
* Update
* @param {App.Account} data
* @param {string} mode
* @private
*/
App.CategoryScreen.prototype.update = function update(data,mode)
{
this._model = data;
this._buttonList.remove(this._addNewButton);
var ScreenMode = App.ScreenMode,
buttonPool = this._mode === ScreenMode.SELECT ? this._buttonExpandPool : this._buttonEditPool,
categories = this._model.categories,
i = 0,
l = this._buttonList.length,
button = null;
for (;i<l;i++) buttonPool.release(this._buttonList.removeItemAt(0));
buttonPool = mode === ScreenMode.SELECT ? this._buttonExpandPool : this._buttonEditPool;
for (i=0,l=categories.length;i<l;)
{
button = buttonPool.allocate();
button.update(categories[i++],mode);
this._buttonList.add(button,false);
}
this._buttonList.add(this._addNewButton);
this._updateLayout();
this._mode = mode;
this._swipeEnabled = mode === ScreenMode.EDIT;
};
/**
* On tick
* @private
*/
App.CategoryScreen.prototype._onTick = function _onTick()
{
App.Screen.prototype._onTick.call(this);
if (this._layoutDirty) this._updateLayout();
};
/**
* On tween complete
* @private
*/
App.CategoryScreen.prototype._onTweenComplete = function _onTweenComplete()
{
App.Screen.prototype._onTweenComplete.call(this);
if (this._transitionState === App.TransitionState.HIDDEN) this._closeButtons(true);
};
/**
* Called when swipe starts
* @param {boolean} [preferScroll=false]
* @param {string} direction
* @private
*/
App.CategoryScreen.prototype._swipeStart = function _swipeStart(preferScroll,direction)
{
var button = this._buttonList.getItemUnderPoint(this.stage.getTouchData());
if (button && !(button instanceof App.AddNewButton))
{
if (!preferScroll) this._pane.cancelScroll();
this._interactiveButton = button;
this._interactiveButton.swipeStart(direction);
this._closeButtons(false);
}
};
/**
* Called when swipe ends
* @private
*/
App.CategoryScreen.prototype._swipeEnd = function _swipeEnd()
{
if (this._interactiveButton)
{
this._interactiveButton.swipeEnd();
this._interactiveButton = null;
}
};
/**
* Close opened buttons
* @private
*/
App.CategoryScreen.prototype._closeButtons = function _closeButtons(immediate)
{
var i = 0,
l = this._buttonList.length - 1,// last button is 'AddNewButton'
button = null,
ScreenMode = App.ScreenMode,
EventType = App.EventType;
if (this._mode === ScreenMode.SELECT)
{
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton && button.isOpen())
{
if (this._buttonsInTransition.indexOf(button) === -1)
{
this._buttonsInTransition.push(button);
button.addEventListener(EventType.COMPLETE,this,this._onButtonTransitionComplete);
this._layoutDirty = true;
}
button.close(immediate);
}
}
}
else if (this._mode === ScreenMode.EDIT)
{
for (;i<l;)
{
button = this._buttonList.getItemAt(i++);
if (button !== this._interactiveButton) button.close(immediate);
}
}
};
/**
* Click handler
* @private
*/
App.CategoryScreen.prototype._onClick = function _onClick()
{
var data = this.stage.getTouchData(),
button = this._buttonList.getItemUnderPoint(data);
if (button)
{
if (button instanceof App.AddNewButton)
{
var changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(App.ScreenName.EDIT_CATEGORY);
changeScreenData.headerName = App.ScreenTitle.ADD_CATEGORY;
App.Controller.dispatchEvent(App.EventType.CHANGE_CATEGORY,{
type:App.EventType.CREATE,
account:this._model,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData
});
}
else
{
if (this._mode === App.ScreenMode.SELECT)
{
this._interactiveButton = button;
if (this._buttonsInTransition.indexOf(this._interactiveButton) === -1)
{
this._buttonsInTransition.push(this._interactiveButton);
this._interactiveButton.addEventListener(App.EventType.COMPLETE,this,this._onButtonTransitionComplete);
this._layoutDirty = true;
}
this._interactiveButton.onClick(data);
this._pane.cancelScroll();
}
else if (this._mode === App.ScreenMode.EDIT)
{
button.onClick(data);
}
}
}
};
/**
* On Header click
* @param {number} action
* @private
*/
App.CategoryScreen.prototype._onHeaderClick = function _onHeaderClick(action)
{
var HeaderAction = App.HeaderAction,
changeScreenData = App.ModelLocator.getProxy(App.ModelName.CHANGE_SCREEN_DATA_POOL).allocate().update(
App.ScreenName.MENU,
0,
null,
HeaderAction.NONE,
HeaderAction.CANCEL,
App.ScreenTitle.MENU
);
if (action === HeaderAction.ADD_TRANSACTION)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_TRANSACTION,{
type:App.EventType.CREATE,
nextCommand:new App.ChangeScreen(),
nextCommandData:changeScreenData.update()
});
}
else if (action === HeaderAction.MENU)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData);
}
else if (action === HeaderAction.CANCEL)
{
App.Controller.dispatchEvent(App.EventType.CHANGE_SCREEN,changeScreenData.update(App.ScreenName.BACK));
}
};
/**
* On button transition complete
* @param {App.ExpandButton} button
* @private
*/
App.CategoryScreen.prototype._onButtonTransitionComplete = function _onButtonTransitionComplete(button)
{
var i = 0,
l = this._buttonsInTransition.length,
EventType = App.EventType;
button.removeEventListener(EventType.COMPLETE,this,this._onButtonTransitionComplete);
for (;i<l;i++)
{
if (button === this._buttonsInTransition[i])
{
this._buttonsInTransition.splice(i,1);
break;
}
}
if (this._buttonsInTransition.length === 0)
{
this._interactiveButton = null;
this._layoutDirty = false;
this._updateLayout();
}
};
/**
* Update layout
* @private
*/
App.CategoryScreen.prototype._updateLayout = function _updateLayout()
{
this._buttonList.updateLayout(true);
this._pane.resize();
};
<file_sep>/**
* @class Rectangle
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @constructor
*/
App.Rectangle = function Rectangle(x,y,width,height)
{
//this.allocated = false;
//this.poolIndex = poolIndex;
this.x = x || 0;
this.y = y || 0;
this.width = width || 0;
this.height = height || 0;
};
/**
* @method reset Reset item returning to pool
*/
/*App.EventListener.prototype.reset = function reset()
{
this.allocated = false;
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
};*/<file_sep>/**
* @class InputScrollScreen
* @extends Screen
* @param {Object} layout
* @constructor
*/
App.InputScrollScreen = function InputScrollScreen(layout)
{
App.Screen.call(this,layout,0.4);
//TODO also disable header actions if input is focused and soft keyboard shown
//TODO add other 'scroll-' properties into TweenProxy?
this._scrollTween = new App.TweenProxy(0.5,App.Easing.outExpo,0,App.ModelLocator.getProxy(App.ModelName.EVENT_LISTENER_POOL));
this._scrollState = App.TransitionState.HIDDEN;
this._scrollInput = null;
this._scrollPosition = 0;
this._inputPadding = Math.round(10 * layout.pixelRatio);
};
App.InputScrollScreen.prototype = Object.create(App.Screen.prototype);
/**
* On tick
* @private
*/
App.InputScrollScreen.prototype._onTick = function _onTick()
{
App.Screen.prototype._onTick.call(this);
if (this._scrollTween.isRunning()) this._onScrollTweenUpdate();
};
/**
* On scroll tween update
* @private
*/
App.InputScrollScreen.prototype._onScrollTweenUpdate = function _onScrollTweenUpdate()
{
var TransitionState = App.TransitionState;
if (this._scrollState === TransitionState.SHOWING)
{
this._pane.y = -Math.round((this._scrollPosition + this._container.y) * this._scrollTween.progress);
}
else if (this._scrollState === TransitionState.HIDING)
{
this._pane.y = -Math.round((this._scrollPosition + this._container.y) * (1 - this._scrollTween.progress));
}
};
/**
* On scroll tween complete
* @private
*/
App.InputScrollScreen.prototype._onScrollTweenComplete = function _onScrollTweenComplete()
{
var TransitionState = App.TransitionState;
this._onScrollTweenUpdate();
if (this._scrollState === TransitionState.SHOWING)
{
this._scrollState = TransitionState.SHOWN;
this._scrollInput.enable();
this._scrollInput.focus();
}
else if (this._scrollState === TransitionState.HIDING)
{
this._scrollState = TransitionState.HIDDEN;
this._pane.enable();
App.ViewLocator.getViewSegment(App.ViewName.APPLICATION_VIEW).scrollTo(0);
}
};
/**
* Focus budget
* @param {boolean} [immediate=false] Flag if input should be focused immediately without tweening
* @private
*/
App.InputScrollScreen.prototype._focusInput = function _focusInput(immediate)
{
var TransitionState = App.TransitionState;
if (this._scrollState === TransitionState.HIDDEN || this._scrollState === TransitionState.HIDING)
{
this._scrollState = TransitionState.SHOWING;
this._pane.disable();
if (immediate)
{
this._scrollPosition = 0;
this._onScrollTweenComplete();
}
else
{
this._scrollPosition = this._scrollInput.y - this._inputPadding;
this._scrollTween.start();
}
}
};
/**
* On budget field blur
* @private
*/
App.InputScrollScreen.prototype._onInputBlur = function _onInputBlur()
{
var TransitionState = App.TransitionState;
if (this._scrollState === TransitionState.SHOWN || this._scrollState === TransitionState.SHOWING)
{
this._scrollState = TransitionState.HIDING;
this._scrollInput.disable();
if (this._scrollPosition > 0)
{
this._scrollTween.restart();
}
else
{
this._pane.resetScroll();
this._onScrollTweenComplete();
}
}
};
/**
* Reset screen scroll
*/
App.InputScrollScreen.prototype.resetScroll = function resetScroll()
{
if (this._scrollInput) this._scrollInput.blur();
this._scrollTween.stop();
this._pane.y = 0;
this._pane.resetScroll();
App.ViewLocator.getViewSegment(App.ViewName.APPLICATION_VIEW).scrollTo(0);
};
<file_sep>/**
* View Segment state
* @enum {number}
* @return {{
* APPLICATION_VIEW:number,
* HEADER:number,
* SCREEN_STACK:number,
* ACCOUNT_BUTTON_POOL:number,
* CATEGORY_BUTTON_EXPAND_POOL:number,
* CATEGORY_BUTTON_EDIT_POOL:number,
* SUB_CATEGORY_BUTTON_POOL:number,
* TRANSACTION_BUTTON_POOL:number,
* SKIN:number}}
*/
App.ViewName = {
APPLICATION_VIEW:0,
HEADER:1,
SCREEN_STACK:2,
ACCOUNT_BUTTON_POOL:3,
CATEGORY_BUTTON_EXPAND_POOL:4,
CATEGORY_BUTTON_EDIT_POOL:5,
SUB_CATEGORY_BUTTON_POOL:6,
TRANSACTION_BUTTON_POOL:7,
SKIN:8
};
<file_sep>/**
* @class ReportChartSegment
* @param {number} poolIndex
* @constructor
*/
App.ReportChartSegment = function ReportChartSegment(poolIndex)
{
PIXI.Graphics.call(this);
this.allocated = false;
this.poolIndex = poolIndex;
this._model = null;
this.color = 0;
this.fraction = 0.0;
this.startAngle = 0.0;
this.endAngle = 0.0;
this.steps = 10;
this.fullyRendered = false;
};
App.ReportChartSegment.prototype = Object.create(PIXI.Graphics.prototype);
/**
* Set model
* @param {App.Category} model
* @param {number} totalBalance
* @param {number} previousBalance
*/
App.ReportChartSegment.prototype.setModel = function setModel(model,totalBalance,previousBalance)
{
this._model = model;
this.color = this._model.color;
this.fraction = (this._model.balance / totalBalance) ;
this.startAngle = Math.abs(previousBalance / totalBalance) * 360;
this.endAngle = this.startAngle + this.fraction * 360;
this.steps = Math.ceil(this.fraction * 60);
this.fullyRendered = false;
this.clear();
};
/**
* Check if this segment renders model passed in
* @param {App.Category} model
* @returns {boolean}
*/
App.ReportChartSegment.prototype.rendersModel = function rendersModel(model)
{
return this._model === model;
};
<file_sep>/**
* @class InfiniteList
* @extends DisplayObjectContainer
* @param {Array} model
* @param {Function} itemClass
* @param {string} direction
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @constructor
*/
App.InfiniteList = function InfiniteList(model,itemClass,direction,width,height,pixelRatio)
{
PIXI.DisplayObjectContainer.call(this);
var Direction = App.Direction,
item = new itemClass(0,model[0],pixelRatio),
itemSize = direction === Direction.X ? item.boundingBox.width : item.boundingBox.height,
itemCount = direction === Direction.X ? Math.ceil(width / itemSize) + 1 : Math.ceil(height / itemSize) + 1,
modelLength = model.length - 1,
index = 0,
i = 0;
this.boundingBox = new PIXI.Rectangle(0,0,width,height);
this.hitArea = this.boundingBox;
this._ticker = App.ModelLocator.getProxy(App.ModelName.TICKER);
this._model = model;
this._itemClass = itemClass;//TODO use pool instead of classes?
this._direction = direction;
this._width = width;
this._height = height;
this._pixelRatio = pixelRatio;
this._items = new Array(itemCount);
this._itemSize = itemSize;
this._selectedModelIndex = -1;
this._enabled = false;
this._state = null;
this._mouseData = null;
this._virtualPosition = 0;
this._oldMousePosition = 0.0;
this._speed = 0.0;
this._offset = 0.0;
this._friction = 0.9;
for (;i<itemCount;i++,index++)
{
if(index > modelLength) index = 0;
if (i > 0) item = new itemClass(index,model[index],pixelRatio);
this._items[i] = item;
this.addChild(item);
}
this._updateLayout(false);
};
App.InfiniteList.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Enable
*/
App.InfiniteList.prototype.enable = function enable()
{
if (!this._enabled)
{
this._enabled = true;
this._registerEventListeners();
this.interactive = true;
}
};
/**
* Disable
*/
App.InfiniteList.prototype.disable = function disable()
{
this.interactive = false;
this._unRegisterEventListeners();
this._enabled = false;
};
/**
* Find and select item under position passed in
* @param {number} position
* @returns {*}
*/
App.InfiniteList.prototype.selectItemByPosition = function selectItemByPosition(position)
{
var i = 0,
l = this._items.length,
itemSize = this._itemSize,
itemProperty = this._direction === App.Direction.X ? "x" : "y",
item = null,
itemPosition = 0;
this._selectedModelIndex = -1;
for (;i<l;)
{
item = this._items[i++];
itemPosition = item[itemProperty];
if (itemPosition <= position && itemPosition + itemSize > position)
{
this._selectedModelIndex = item.getModelIndex();
break;
}
}
for (i=0;i<l;) this._items[i++].select(this._selectedModelIndex);
return item;
};
/**
* Find and select item under position passed in
* @param {string} value
*/
App.InfiniteList.prototype.selectItemByValue = function selectItemByValue(value)
{
var i = 0,
l = this._model.length;
this._selectedModelIndex = -1;
for (;i<l;i++)
{
if (this._model[i] === value)
{
this._selectedModelIndex = i;
break;
}
}
l = this._items.length;
for (i=0;i<l;) this._items[i++].select(this._selectedModelIndex);
};
/**
* Return selected model
* @returns {*}
*/
App.InfiniteList.prototype.getSelectedValue = function getSelectedValue()
{
return this._model[this._selectedModelIndex];
};
/**
* Cancel scroll
*/
App.InfiniteList.prototype.cancelScroll = function cancelScroll()
{
this._speed = 0.0;
this._state = null;
};
/**
* Register event listeners
* @private
*/
App.InfiniteList.prototype._registerEventListeners = function _registerEventListeners()
{
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = this._onPointerDown;
this.touchend = this._onPointerUp;
this.touchendoutside = this._onPointerUp;
}
else
{
this.mousedown = this._onPointerDown;
this.mouseup = this._onPointerUp;
this.mouseupoutside = this._onPointerUp;
}
this._ticker.addEventListener(App.EventType.TICK,this,this._onTick);
};
/**
* UnRegister event listeners
* @private
*/
App.InfiniteList.prototype._unRegisterEventListeners = function _unRegisterEventListeners()
{
this._ticker.removeEventListener(App.EventType.TICK,this,this._onTick);
if (App.Device.TOUCH_SUPPORTED)
{
this.touchstart = null;
this.touchend = null;
this.touchendoutside = null;
}
else
{
this.mousedown = null;
this.mouseup = null;
this.mouseupoutside = null;
}
};
/**
* REF Tick handler
* @private
*/
App.InfiniteList.prototype._onTick = function _onTick()
{
var InteractiveState = App.InteractiveState;
if (this._state === InteractiveState.DRAGGING) this._drag(App.Direction);
else if (this._state === InteractiveState.SCROLLING) this._scroll(App.Direction);
};
/**
* On pointer down
* @param {InteractionData} data
* @private
*/
App.InfiniteList.prototype._onPointerDown = function _onPointerDown(data)
{
this._mouseData = data;
var mousePosition = this._mouseData.getLocalPosition(this.stage).x;
if (this._direction === App.Direction.Y) mousePosition = this._mouseData.getLocalPosition(this.stage).y;
this._offset = mousePosition - this._virtualPosition;
this._speed = 0.0;
this._state = App.InteractiveState.DRAGGING;
};
/**
* On pointer up
* @param {InteractionData} data
* @private
*/
App.InfiniteList.prototype._onPointerUp = function _onPointerUp(data)
{
this._state = App.InteractiveState.SCROLLING;
this._mouseData = null;
};
/**
* Perform drag operation
* @param {{X:string,Y:string}} Direction
* @private
*/
App.InfiniteList.prototype._drag = function _drag(Direction)
{
if (this.stage)
{
if (this._direction === Direction.X)
{
var mousePosition = this._mouseData.getLocalPosition(this.stage).x;
if (mousePosition <= -10000) return;
this._updateX(mousePosition - this._offset);
}
else if (this._direction === Direction.Y)
{
mousePosition = this._mouseData.getLocalPosition(this.stage).y;
if (mousePosition <= -10000) return;
this._updateY(mousePosition - this._offset);
}
this._speed = mousePosition - this._oldMousePosition;
this._oldMousePosition = mousePosition;
}
};
/**
* Perform scroll operation
*
* @param {{X:string,Y:string}} Direction
* @private
*/
App.InfiniteList.prototype._scroll = function _scroll(Direction)
{
if (this._direction === Direction.X) this._updateX(this._virtualPosition + this._speed);
else if (this._direction === Direction.Y) this._updateY(this._virtualPosition + this._speed);
// If the speed is very low, stop it.
if (Math.abs(this._speed) < 0.1)
{
this._speed = 0.0;
this._state = null;
}
else
{
this._speed *= this._friction;
}
};
/**
* Update X position
* @param {number} position
* @private
*/
App.InfiniteList.prototype._updateX = function _updateX(position)
{
position = Math.round(position);
var i = 0,
l = this._items.length,
itemSize = this._itemSize,
width = this._width,
positionDifference = position - this._virtualPosition,
itemScreenIndex = 0,
virtualIndex = Math.floor(position / itemSize),
xIndex = 0,
modelIndex = 0,
modelLength = this._model.length,
x = 0,
item = null;
this._virtualPosition = position;
for (;i<l;)
{
item = this._items[i++];
x = item.x + positionDifference;
if (x + itemSize < 0 || x > width)
{
itemScreenIndex = -Math.floor(x / width);
x += itemScreenIndex * l * itemSize;
xIndex = Math.floor(x / itemSize);
if (virtualIndex >= 0) modelIndex = (xIndex - (virtualIndex % modelLength)) % modelLength;
else modelIndex = (xIndex - virtualIndex) % modelLength;
if (modelIndex < 0) modelIndex = modelLength + modelIndex;
else if (modelIndex >= modelLength) modelIndex = modelLength - 1;
//TODO check that I don't set the model way too many times!
item.setModel(modelIndex,this._model[modelIndex],this._selectedModelIndex);
}
item.x = x;
}
};
/**
* Update Y position
* @param {number} position
* @private
*/
App.InfiniteList.prototype._updateY = function _updateY(position)
{
position = Math.round(position);
var i = 0,
l = this._items.length,
itemSize = this._itemSize,
height = this._height,
positionDifference = position - this._virtualPosition,
itemScreenIndex = 0,
virtualIndex = Math.floor(position / itemSize),
yIndex = 0,
modelIndex = 0,
modelLength = this._model.length,
y = 0,
item = null;
this._virtualPosition = position;
for (;i<l;)
{
item = this._items[i++];
y = item.y + positionDifference;
if (y + itemSize < 0 || y > height)
{
itemScreenIndex = -Math.floor(y / height);
y += itemScreenIndex * l * itemSize;
yIndex = Math.floor(y / itemSize);
if (virtualIndex >= 0) modelIndex = (yIndex - (virtualIndex % modelLength)) % modelLength;
else modelIndex = (yIndex - virtualIndex) % modelLength;
if (modelIndex < 0) modelIndex = modelLength + modelIndex;
else if (modelIndex >= modelLength) modelIndex = modelLength - 1;
item.setModel(modelIndex,this._model[modelIndex],this._selectedModelIndex);
}
item.y = y;
}
};
/**
* Update layout
* @param {boolean} [updatePosition=false]
* @private
*/
App.InfiniteList.prototype._updateLayout = function _updateLayout(updatePosition)
{
var i = 0,
l = this._items.length,
child = null,
position = 0,
Direction = App.Direction;
if (this._direction === Direction.X)
{
for (;i<l;)
{
child = this._items[i++];
child.x = position;
position = Math.round(position + child.boundingBox.width);
}
if (updatePosition) this._updateX(this.x);
}
else if (this._direction === Direction.Y)
{
for (;i<l;)
{
child = this._items[i++];
child.y = position;
position = Math.round(position + child.boundingBox.height);
}
if (updatePosition) this._updateY(this.y);
}
};
/**
* Test if position passed in falls within this list boundaries
* @param {number} position
* @returns {boolean}
*/
App.InfiniteList.prototype.hitTest = function hitTest(position)
{
return position >= this.y && position < this.y + this.boundingBox.height;
};
<file_sep>/**
* Screen Name
* @enum {number}
* @return {{
* BACK:number,
* ACCOUNT:number,
* CATEGORY:number,
* SELECT_TIME:number,
* EDIT_CATEGORY:number,
* TRANSACTIONS:number,
* REPORT:number,
* ADD_TRANSACTION:number,
* EDIT:number,
* CURRENCY_PAIRS:number,
* EDIT_CURRENCY_RATE:number,
* CURRENCIES:number,
* SETTINGS:number,
* MENU:number
* }}
*/
App.ScreenName = {
BACK:-1,
ACCOUNT:0,
CATEGORY:1,
SELECT_TIME:2,
EDIT_CATEGORY:3,
TRANSACTIONS:4,
REPORT:5,
ADD_TRANSACTION:6,
EDIT:7,
CURRENCY_PAIRS:8,
EDIT_CURRENCY_RATE:9,
CURRENCIES:10,
SETTINGS:11,
MENU:12
};
<file_sep>/**
* @class Ticker
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.Ticker = function Ticker(eventListenerPool)
{
App.EventDispatcher.call(this,eventListenerPool);
this._rafListener = this._raf.bind(this);
this._isRunning = false;
};
App.Ticker.prototype = Object.create(App.EventDispatcher.prototype);
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Ticker.prototype.addEventListener = function(eventType,scope,listener)
{
App.EventDispatcher.prototype.addEventListener.call(this,eventType,scope,listener);
if (!this._isRunning)
{
this._isRunning = true;
window.requestAnimationFrame(this._rafListener);
}
};
/**
* Remove event listeners
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.Ticker.prototype.removeEventListener = function(eventType,scope,listener)
{
App.EventDispatcher.prototype.removeEventListener.call(this,eventType,scope,listener);
if (this._listeners.length === 0) this._isRunning = false;
};
/**
* Remove all listeners
*/
App.Ticker.prototype.removeAllListeners = function()
{
App.EventDispatcher.prototype.removeAllListeners.call(this);
this._isRunning = false;
};
/**
* Animation function
* @private
*/
App.Ticker.prototype._raf = function _raf()
{
if (this._isRunning)
{
window.requestAnimationFrame(this._rafListener);
this.dispatchEvent(App.EventType.TICK);
}
};
<file_sep>/**
* EventLevel
* @type {{NONE: number, LEVEL_1: number,LEVEL_2: number}}
*/
App.EventLevel = {
NONE:0,
LEVEL_1:1,
LEVEL_2:2
};
<file_sep>module.exports = function(grunt)
{
/**
* Construct and return banner
* @returns {string}
*/
function getBanner()
{
return "//<%= pkg.name %>, <%= grunt.template.today('dd-mm-yyyy, HH:MM:ss') %>\n";
}
// Configuration
grunt.initConfig({
pkg:grunt.file.readJSON("package.json"),
concat:{
dist:{
src:require(require("path").resolve("source.json")).source,
dest:"<%= pkg.destinationFolder %><%=pkg.destinationName%>.js"
}
},
uglify:{
options:{
banner:getBanner()/*,
mangle:{toplevel:true}*/
},
dist:{
files:{
'<%= pkg.destinationFolder %><%= pkg.destinationName %>.min.js':['<%= concat.dist.dest %>'],
'<%= pkg.destinationFolder %>storage-worker.min.js':['js/src/business/StorageWorker.js']
}
}
}
});
// Plugins
grunt.loadNpmTasks('grunt-contrib-concat'); //npm install grunt-contrib-concat --save-dev
grunt.loadNpmTasks('grunt-contrib-uglify'); //npm install grunt-contrib-uglify --save-dev
// Tasks
grunt.registerTask('default',['concat','uglify']); // this default task can be run just by typing "grunt" on the command line
};<file_sep>/**
* @class ViewStack
* @extends DisplayObjectContainer
* @param {Array} children
* @param {boolean} [addToStage=false]
* @param {ObjectPool} eventListenerPool
* @constructor
*/
App.ViewStack = function ViewStack(children,addToStage,eventListenerPool)
{
PIXI.DisplayObjectContainer.call(this);
this._children = [];
this._selectedChild = null;
this._selectedIndex = -1;
this._childrenToHide = [];
this._eventDispatcher = new App.EventDispatcher(eventListenerPool);
if (children)
{
var i = 0, l = children.length;
for (;i<l;) this.add(children[i++],addToStage);
}
};
App.ViewStack.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Add child to stack
*
* @param {Screen} child
* @param {boolean} [addToStage=false]
*/
App.ViewStack.prototype.add = function add(child,addToStage)
{
this._children[this._children.length] = child;
if (addToStage) this.addChild(child);
};
/**
* Select child
*
* @param {Screen} child
*/
App.ViewStack.prototype.selectChild = function selectChild(child)
{
if (this._selectedChild)
{
if (!child || this._selectedChild === child) return;
this._childrenToHide[this._childrenToHide.length] = this._selectedChild;
}
var i = 0, l = this._children.length;
for (;i<l;)
{
if (child === this._children[i++])
{
this._selectedChild = child;
this._selectedIndex = i - 1;
break;
}
}
this._eventDispatcher.dispatchEvent(App.EventType.CHANGE);
};
/**
* Select child by index passed in
*
* @param {number} index
*/
App.ViewStack.prototype.selectChildByIndex = function selectChildByIndex(index)
{
if (index < 0 || index >= this._children.length) return;
if (this._selectedChild)
{
if (this._selectedChild === this._children[index]) return;
this._childrenToHide[this._childrenToHide.length] = this._selectedChild;
}
this._selectedChild = this._children[index];
this._selectedIndex = index;
this._eventDispatcher.dispatchEvent(App.EventType.CHANGE);
};
/**
* Return selected child
* @returns {Screen}
*/
App.ViewStack.prototype.getSelectedChild = function getSelectedChild()
{
return this._selectedChild;
};
/**
* Return index of selected child
* @returns {number}
*/
App.ViewStack.prototype.getSelectedIndex = function getSelectedIndex()
{
return this._selectedIndex;
};
/**
* Return child by index passed in
* @param {number} index
* @returns {Screen|null}
*/
App.ViewStack.prototype.getChildByIndex = function getChildByIndex(index)
{
if (index < 0 || index >= this._children.length) return null;
return this._children[index];
};
/**
* Show
*/
App.ViewStack.prototype.show = function show()
{
if (this._selectedChild)
{
// First check if the child to show is not actually hiding
var i = 0, l = this._childrenToHide.length;
for (;i<l;i++)
{
if (this._selectedChild === this._childrenToHide[i])
{
this._selectedChild.removeEventListener(App.EventType.COMPLETE,this,this._onHideComplete);
this._childrenToHide.splice(i,1);
break;
}
}
if (!this.contains(this._selectedChild)) this.addChild(this._selectedChild);
this._selectedChild.show();
}
};
/**
* Hide
*/
App.ViewStack.prototype.hide = function hide()
{
var i = 0, l = this._childrenToHide.length, child = null, EventType = App.EventType;
for (;i<l;)
{
child = this._childrenToHide[i++];
child.addEventListener(EventType.COMPLETE,this,this._onHideComplete);
child.hide();
}
};
/**
* On hide complete
* @param {{target:Screen,state:string}} data
* @private
*/
App.ViewStack.prototype._onHideComplete = function _onHideComplete(data)
{
if (data.state === App.TransitionState.HIDDEN)
{
/**@type Screen */
var screen = data.target;
screen.removeEventListener(App.EventType.COMPLETE,this,this._onHideComplete);
if (this.contains(screen)) this.removeChild(screen);
var i = 0, l = this._childrenToHide.length;
for (;i<l;i++)
{
if (screen === this._childrenToHide[i])
{
this._childrenToHide.splice(i,1);
break;
}
}
}
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ViewStack.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
this._eventDispatcher.addEventListener(eventType,scope,listener);
};
/**
* Remove event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.ViewStack.prototype.removeEventListener = function removeEventListener(eventType,scope,listener)
{
this._eventDispatcher.removeEventListener(eventType,scope,listener);
};
<file_sep>/**
* @class TimeInput
* @extends Input
* @param {string} placeholder
* @param {number} fontSize
* @param {number} width
* @param {number} height
* @param {number} pixelRatio
* @param {boolean} displayIcon
* @constructor
*/
App.TimeInput = function TimeInput(placeholder,fontSize,width,height,pixelRatio,displayIcon)
{
App.Input.call(this,placeholder,fontSize,width,height,pixelRatio,displayIcon);
this._inputProxy = document.getElementById("timeInputProxy");
};
App.TimeInput.prototype = Object.create(App.Input.prototype);
/**
* Render
* @private
*/
App.TimeInput.prototype._render = function _render()
{
var r = this._pixelRatio;
this._renderBackground(false,r);
this._updateAlignment();
this._textField.y = Math.round(9 * r);
};
/**
* Update text
* @param {boolean} [finish=false]
* @private
*/
App.TimeInput.prototype._updateText = function _updateText(finish)
{
App.Input.prototype._updateText.call(this,finish);
this._updateAlignment();
};
/**
* Format the text input
* @param {boolean} [finish=false]
* @private
*/
App.TimeInput.prototype._format = function _format(finish)
{
if (this._inputProxy.value.length === 0) return "";
var value = this._inputProxy.value.replace(/\D/g,""),
hours = value.substr(0,2),
minutes = value.substr(2,2);
if (hours.length === 2 && parseInt(hours,10) > 24) hours = "24";
else if (minutes.length === 1 && parseInt(minutes,10) > 5) minutes = "5";
else if (minutes.length >= 2 && parseInt(minutes,10) > 59) minutes = "59";
if (finish)
{
if (hours.length === 1) hours = "0" + hours;
if (minutes.length === 0) minutes += "00";
else if (minutes.length === 1) minutes += "0";
}
if (minutes.length > 0) value = hours + ":" + minutes;
else value = hours;
this._inputProxy.value = value;
return value;
};
/**
* Update text's alignment
* @private
*/
App.TimeInput.prototype._updateAlignment = function _updateAlignment()
{
this._textField.x = Math.round((this._width - this._textField.width) / 2);
};
<file_sep>/**
* @class TransactionCollection
* @param {Object} data
* @param {App.ObjectPool} eventListenerPool
* @constructor
*/
App.TransactionCollection = function TransactionCollection(data,eventListenerPool)
{
var StorageKey = App.StorageKey,
ids = data.ids.sort(function(a,b){return a-b;}),
transactions = [],
i = 0,
l = ids.length;
for (;i<l;) transactions = transactions.concat(data[StorageKey.TRANSACTIONS+ids[i++]]);
App.Collection.call(this,transactions,App.Transaction,null,eventListenerPool);
this._maxSegmentSize = 3;
this._meta = [];
this._initMeta(data[StorageKey.TRANSACTIONS_META],ids);
};
App.TransactionCollection.prototype = Object.create(App.Collection.prototype);
/**
* Initialize meta information object
* @param {Array.<number>} meta
* @param {Array.<number>} ids
* @private
*/
App.TransactionCollection.prototype._initMeta = function _initMeta(meta,ids)
{
var i = 0,
l = meta.length,
item = null;
for (;i<l;i++)
{
item = meta[i];
// Initialize only meta objects with one or more transactions
if (item[1]) this._meta[i] = {metaId:item[0],length:item[1],transactionId:item[2],loaded:ids.indexOf(item[0]) > -1};
}
};
/**
* Serialize and return meta information
* @returns {Array}
*/
App.TransactionCollection.prototype.serializeMeta = function serializeMeta()
{
var i = 0,
l = this._meta.length,
data = [],
meta = null;
for (;i<l;)
{
meta = this._meta[i++];
data.push([meta.metaId,meta.length,meta.transactionId]);
}
return data;
};
/**
* Create and return new transaction ID
* @returns {string}
*/
App.TransactionCollection.prototype.getTransactionId = function getTransactionId()
{
var meta = this._meta[this._meta.length-1];
if (meta)
{
if (meta.length >= this._maxSegmentSize)
{
this._meta[this._meta.length] = {metaId:meta.metaId+1,length:0,transactionId:0,loaded:true};
meta = this._meta[this._meta.length-1];
}
}
else
{
meta = {metaId:0,length:0,transactionId:0,loaded:true};
this._meta[this._meta.length] = meta;
}
return meta.metaId + "." + meta.transactionId++;
};
/**
* Find and return meta object bu id passed in
* @param {number} id
* @returns {{metaId:number,length:number,transactionId:number,loaded:boolean}}
* @private
*/
App.TransactionCollection.prototype._getMetaById = function _getMetaById(id)
{
for (var i= 0,l=this._meta.length;i<l;i++)
{
if (this._meta[i].metaId === id) return this._meta[i];
}
return this._meta[this._meta.length-1];
};
/**
* @method addItem Add item into collection
* @param {*} item
*/
App.TransactionCollection.prototype.addItem = function addItem(item)
{
// Bump up length of meta object
this._getMetaById(parseInt(item.id.split(".")[0],10)).length++;
this._items[this._items.length] = item;
this.dispatchEvent(App.EventType.ADDED,item);
};
/**
* @method removeItem Remove item passed in
* @param {*} item
* @return {*} item
*/
App.TransactionCollection.prototype.removeItem = function removeItem(item)
{
// Decrease length of meta object
var meta = this._getMetaById(parseInt(item.id.split(".")[0],10));
if (meta.length > 0) meta.length--;
return this.removeItemAt(this.indexOf(item));
};
/**
* Serialize and return transaction data for segment specified by ID passed in
* @param {string} metaId
* @param {boolean} serializeData
* @returns {Array}
*/
App.TransactionCollection.prototype.serialize = function serialize(metaId,serializeData)
{
var transaction = null,
data = [],
i = 0,
l = this._items.length;
for (;i<l;)
{
transaction = this._items[i++];
if (metaId === transaction.id.split(".")[0]) data.push(transaction.getData(serializeData));
}
return data;
};
<file_sep>/**
* @class EventDispatcher
* @constructor
*/
App.EventDispatcher = function EventDispatcher(listenerPool)
{
this._listeners = [];
this._listenersPool = listenerPool;
};
/**
* Add event listener
* @param {string} eventType
* @param {Object} scope
* @param {Function} listener
*/
App.EventDispatcher.prototype.addEventListener = function addEventListener(eventType,scope,listener)
{
if (!this.hasEventListener(eventType,scope,listener))
{
var eventListener = this._listenersPool.allocate();
eventListener.type = eventType;
eventListener.scope = scope;
eventListener.handler = listener;
this._listeners[this._listeners.length] = eventListener;
}
};
/**
* @method hasEventListener
* @param {string} eventType
* @param {Object} scope
* @param {Function} handler
* @return {boolean}
*/
App.EventDispatcher.prototype.hasEventListener = function hasEventListener(eventType,scope,handler)
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;)
{
listener = this._listeners[i++];
if (listener.type === eventType && listener.scope === scope && listener.handler === handler)
{
listener = null;
return true;
}
}
listener = null;
return false;
};
/**
* Remove event listener
* @param {String} eventType
* @param {Object} scope
* @param {Function} handler
*/
App.EventDispatcher.prototype.removeEventListener = function removeEventListener(eventType,scope,handler)
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;i++)
{
listener = this._listeners[i];
if (listener.type === eventType && listener.scope === scope && listener.handler === handler)
{
this._listenersPool.release(listener);
listener.reset();
this._listeners.splice(i,1);
break;
}
}
listener = null;
};
/**
* Remove all listeners
*/
App.EventDispatcher.prototype.removeAllListeners = function removeAllListeners()
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;i++)
{
listener = this._listeners[i];
this._listenersPool.release(listener);
listener.reset();
this._listeners.splice(i,1);
}
listener = null;
this._listeners.length = 0;
};
/**
* Dispatch event
* @param {string} eventType
* @param {Object|null} data
*/
App.EventDispatcher.prototype.dispatchEvent = function dispatchEvent(eventType,data)
{
var i = 0, l = this._listeners.length, listener = null;
for (;i<l;)
{
listener = this._listeners[i++];
if (listener && listener.type === eventType)
{
listener.handler.call(listener.scope,data,eventType);
}
}
listener = null;
};
/**
* @method pipe Link incoming and outcoming events; dispatch incoming events further
* @param {Object} target
* @param {string} eventType
*/
App.EventDispatcher.prototype.pipe = function pipe(target,eventType)
{
target.addEventListener(eventType,this,this._pipeListener);
};
/**
* @method unpipe Remove event target from pipe
* @param {Object} target
* @param {string} eventType
*/
App.EventDispatcher.prototype.unPipe = function unPipe(target,eventType)
{
target.removeEventListener(eventType,this,this._pipeListener);
};
/**
* @method pipeListener Listens for events piped in, and dispatch them further
* @param {string} eventType
* @param {Object|null} data
* @private
*/
App.EventDispatcher.prototype._pipeListener = function _pipeListener(data,eventType)
{
this.dispatchEvent(eventType,data);
};
/**
* Destroy
*/
App.EventDispatcher.prototype.destroy = function destroy()
{
this.removeAllListeners();
this._listeners.length = 0;
this._listeners = null;
this._listenersPool = null;
};
| f56b0871ca1021211e2f6ca9f8a39f8ffc7580af | [
"JavaScript"
] | 82 | JavaScript | alesveselka/Hybrid | 082a0819a0ee86acf713b2ed6f63566645405b7d | e94ffed7d6f0e7d052d893f875f48d628cb6be67 |
refs/heads/master | <repo_name>redfern314/olinjs-3-hw<file_sep>/models/models.js
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/burgers');
var ingredientSchema = mongoose.Schema(
{name: String,
cost: Number
}
);
var orderSchema = mongoose.Schema(
{name: String,
ingredients: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient'}]
}
);
mongoose.model('Ingredient', ingredientSchema);
mongoose.model('Order', orderSchema);<file_sep>/routes/neworder.js
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/burgers');
var Ingredient = mongoose.model('Ingredient');
var Order = mongoose.model('Order');
exports.new = function(req, res){
console.log("loaded?");
Ingredient.find({}, function(err, docs) {
if (err) console.log(err); // ...
res.render('neworder', {title:"Add an Order",ingredients:docs});
})
};
exports.new_post = function(req, res){
console.log("posted");
var neworder = new Order({ name: req.body.name, ingredients: req.body.ingredients});
neworder.save(function (err) {
if (err) console.log(err); // ...
res.send("created new order");
});
};<file_sep>/public/javascripts/order.js
$(function () {
$('.orderform').on('submit', function () {
$.post("/order", {_id:this.id});
$('.'+this.id).html("");
return false;
});
});<file_sep>/routes/order.js
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/burgers');
var Ingredient = mongoose.model('Ingredient');
var Order = mongoose.model('Order');
exports.home = function(req, res){
console.log("loaded");
Order.find({}, function(err, orders) {
if (err) console.log(err); // ...
Ingredient.find({}, function(err, ingredients) {
if (err) console.log(err); // ...
res.render('order', {title:"Order List",orders:orders, ingredients:ingredients});
})
})
};
exports.home_post = function(req, res){
console.log("posted");
Order.remove({_id: req.body._id}, function(err) {
if (err) console.log(err); // ...
res.send("Order complete!");
});
};<file_sep>/public/javascripts/ingredient.js
$(function () {
$('#ingredientform').on('submit', function () {
$.post("/ingredient/new", $('#ingredientform').serialize());
$("#main").html("<p>Added successfully!</p>");
return false;
});
}); | 1b0a4fac45844037f7e8110fba1b6dfb2c3829a5 | [
"JavaScript"
] | 5 | JavaScript | redfern314/olinjs-3-hw | 9953f595d6f22a72ea9a0f5464beb89d05ef6121 | 98bbeff44b9465e7465c7694c04a69c1cfb084a4 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Testing;
namespace GalaSoft.MvvmLight.Test__WP8_
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Content = UnitTestSystem.CreateTestPage();
}
}
} | 5fe3c86cd316279cfc3d70a11fe47c0dc4ab8292 | [
"C#"
] | 1 | C# | wiyonoaten/MvvmLight2Mvx | 0500179c154939854ab1dc705b6892c0a5c80a9b | 46173882b665b80b17f2dd5e1af40549fda57af2 |
refs/heads/master | <repo_name>lwgray/feedr<file_sep>/app.py
import sys
import feedparser
from colorama import init
from colorama import Back, Style
init(autoreset=True)
# print(Fore.RED + 'some red text')
# print('automatically back to default color again')
url = sys.argv[1]
def latest():
d = feedparser.parse(url)
print (Back.RED + "Title:") + (Style.RESET_ALL + " " + d.entries[0].title)
print (Back.YELLOW + "Link:") + (Style.RESET_ALL + " " + d.entries[0].link)
def latest_five():
d = feedparser.parse(url)
i = 0
for i in range(0, 5):
# Prevent IndexError if less than five aricles in feed
try:
d.entries[i]
except IndexError:
break
print (Back.CYAN + "\t" + str(i + 1) + "\t")
print (Back.RED + "Title:") + \
(Style.RESET_ALL + " " + d.entries[i].title)
print (Back.YELLOW + "Link:") + \
(Style.RESET_ALL + " " + d.entries[i].link)
# print "Content: " + d.entries[i]['content']
def show(title, link, desc):
print str(title)
# print str(date)
print str(link)
print str(desc)
def menu():
print """What do you wish to do now? \n1. Read the latest issue.
\n2. Get the titles of the latest 5 issues."""
opt = int(raw_input('opt: '))
if opt == 1:
latest()
elif opt == 2:
latest_five()
else:
print "Not a valid choice"
exit(0)
if __name__ == "__main__":
# parse(sys.argv[1])
url = sys.argv[1]
menu()
<file_sep>/AUTHORS.md
<NAME> <<EMAIL>>
<NAME> <<EMAIL>>
| 6e128e9b1d00eb85487d524d9af24716ec752da9 | [
"Markdown",
"Python"
] | 2 | Python | lwgray/feedr | 770665fd63d0b310467c2ef8f5e797b6653efada | d2b038d52eef58021eb9e97976ff3c8ac2b741ed |
refs/heads/master | <file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var Order = sequelize.import(path.normalize(__dirname + "/../models/Order"));
var Orderitem = sequelize.import(path.normalize(__dirname + "/../models/Orderitem"));
exports.retrieveOrderhistroy = function(userId, callback) {
var productsArray = new Array();
var orderRecords = {};
Order.findAll({where: ["userid = ?", userId]}).on('success', function(order) {
for (var j = 0; j < order.length; j++) {
var product = {};
product.orderId = order[j].id ;
product.totalqty = order[j].od_totalqty;
product.totalPrice = order[j].od_totalprice;
var currentYear = new Date(order[j].od_date).getFullYear ();
var currentMonth = new Date(order[j].od_date).getMonth () + 1;
var currentDate = new Date(order[j].od_date).getDate ();
var orderdate = currentYear+'-'+currentMonth+'-'+currentDate;
product.orderDate = orderdate;
productsArray[j] = product;
}
}).on('success', function() {
orderRecords.product = productsArray;
callback(orderRecords);
})
};<file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var Order = sequelize.import(path.normalize(__dirname + "/../models/Order"));
var Orderitem = sequelize.import(path.normalize(__dirname + "/../models/Orderitem"));
exports.postOrder = function(products, firstName, lastName, address1, address2, city, postcode, comments, userId, totalPrice, totalItem, callback) {
if(userId == undefined){
var userId = 0;
}
//var phonenumber = data.billingAddress.phonenumber;
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var month = month < 10 ? "0" + month : month;
var day = currentTime.getDate()
var day = day < 10 ? "0" + day : day;
var year = currentTime.getFullYear()
now = year + "-" + month + "-" + day;
Order.build({od_date: now, od_last_update: now, userid: userId, od_shipping_first_name: firstName, od_shipping_last_name: lastName, od_shipping_address1: address1, od_shipping_address2:address2, od_shipping_city: city , od_shipping_postal_code: postcode, od_shipping_cost: 000,od_payment_first_name: firstName, od_payment_last_name: lastName, od_payment_address1: address1, od_payment_address2:address2, od_payment_city: city , od_payment_postal_code: postcode, od_comments: comments, od_totalqty: totalItem, od_totalprice: totalPrice })
.save().on('success', function() {
var chainer = new Sequelize.Utils.QueryChainer
chainer.add(
Order.findAll({order: 'id DESC', limit: 1}).on('success', function(orderdata) {
}).on('success', function(orderId) {
for (var i = 0; i < orderId.length; i++) {
var orderId = orderId[i].id;
}
for (var p = 0; p < products.length; p++) {
var productId = products[p].productId;
var quantity = products[p].quantity;
var price = products[p].totalPrice;
Orderitem.build({id: orderId, pd_id: productId, od_qty: quantity })
.save().on('success', function() {
})
}
var message = {};
message.message = "Inserted";
message.orderId = orderId;
message.successMessage = "Success";
callback(message);
})
)
chainer.run().on('success', function() {
})
})
.on('failure', function(err) {
//exception.executeException(0, '1000', err, res);
})
};<file_sep>module.exports = function(sequelize, DataTypes) {
return sequelize.define("eshop_categories", {
id: { type: sequelize.INTEGER, primaryKey: true, autoIncrement: true },
cat_name: { type: sequelize.STRING},
cat_image: { type: sequelize.STRING},
cat_details_image: { type: sequelize.STRING},
cat_parent_id: { type: sequelize.INTEGER},
cat_description: { type: sequelize.STRING}
}, {
classMethods: {
getProduct: function(){ return this.attributes.id }
},
instanceMethods: {
getProducts: function() { return this }
}
})
}<file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var User = sequelize.import(path.normalize(__dirname + "/../models/User"));
exports.addUser = function(firstname, lastname, email, password, phoneNumber, callback) {
var message = {};
User.count({ where: {email: email} }).on('success', function(user) {
}).on('success', function(user) {
if(user == 0){
User.build({first_name:firstname,last_name:lastname, email: email, password: <PASSWORD>, phone: phoneNumber })
.save().on('success', function() {
User.findAll({order: 'id DESC', limit: 1}).on('success', function(userid) {
for (var i = 0; i < userid.length; i++) {
var userId = userid[i].id;
}
message.message = "Inserted";
message.userId = userId;
message.successMessage = "Success";
callback(message);
})
})
}
else {
message.message = "Already exist";
message.userId = "0";
message.successMessage = "Failed";
callback(message);
}
})
}; <file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var Product = sequelize.import(path.normalize(__dirname + "/../models/Product"));
var Review = sequelize.import(path.normalize(__dirname + "/../models/Review"));
var User = sequelize.import(path.normalize(__dirname + "/../models/User"));
User.hasMany(Review,{foreignKey: 'user_id', as: "Reviews"});
exports.retrieveReviews = function(productId, callback) {
var reviewRecords = {};
var chainer = new Sequelize.Utils.QueryChainer
var ratingIdList = new Array();
var reviewsObjs = new Array();
var reviewArray = new Array();
var review = {};
review.productId = productId;
review.userId = 1;
Product.find({where: {id: productId}}).on('success', function(products) {
if(products != null) {
Review.findAll({where: ["pd_id = ? ", productId]}).on('success', function(reviews) {
if ( reviews.length > 0){
for (var i = 0; i < reviews.length; i++) {
var ratingId = reviews[i].rating;
ratingIdList[i] = ratingId;
reviewsObjs[i] = reviews[i];
}
} else {
var commentsArray = new Array();
var ratingArray = new Array();
for (var r = 0; r < 5; r++) {
var ratingSeries = {};
var ratingKeyValue = {};
ratingKeyValue.key = r + 1;
ratingKeyValue.value = 0;
ratingArray[r] = ratingKeyValue;
}
var ratings = {};
ratings.rating = ratingArray;
review.ratings = ratings;
review.average = 0;
review.comments = commentsArray;
reviewRecords.review = review;
callback(reviewRecords);
}
}).on('success', function() {
var ratingString;
var ratingrecordArray = new Array();
var j = 0;
var rating = {};
var totalCount = 0;
for (var i = 1; i <= 5; i++) {
var ratingId = i;
var k = 1;
var ratingCountString;
var ratingArray = new Array();
chainer.add(
Review.count({where: {rating: ratingId, pd_id: productId}}).on('success', function(ratingCount) {
var ratingSeries = {};
var ratingKeyValue = {};
ratingKeyValue.key = k;
ratingKeyValue.value = ratingCount;
//ratingSeries="{ keys :"+ k + ",values :" + ratingCount +"}";
totalCount += ratingCount;
ratingArray[j] = ratingKeyValue;
j++
k++// display rating id
})
)
chainer.run().on('success', function() {
var commentsChainer = new Sequelize.Utils.QueryChainer
var commentsArray = new Array();
var ratings = {};
ratings.rating = ratingArray;
review.ratings = ratings;
review.average = Math.round((totalCount / 5));
var usernameArray = new Array();
var userIdList = new Array();
var now = new Date();
commentsChainer.add(
Review.findAll({where: ["pd_id = ?", productId]}).on('success', function(reviewRecord) {
for(var m = 0; m < reviewRecord.length; m++){
var comment = {};
comment.rating = reviewRecord[m].rating;
comment.comment = reviewRecord[m].comment;
comment.userid = reviewRecord[m].user_id;
userIdList[m] = reviewRecord[m].user_id;
var commentDate = reviewRecord[m].comment_date;
var currentYear = new Date(commentDate).getFullYear ();
var currentMonth = new Date(commentDate).getMonth () + 1;
var currentDate = new Date(commentDate).getDate ();
var currentHours = commentDate.getHours ( );
var currentMinutes = commentDate.getMinutes ( );
var currentSeconds = commentDate.getSeconds ( );
currentHours = ( currentHours >= 10 ) ? currentHours : "0"+currentHours;
currentMinutes = ( currentMinutes >= 10) ? currentMinutes : "0"+ currentMinutes;
currentSeconds = ( currentSeconds >= 10) ? currentSeconds : "0"+ currentSeconds;
//console.info(currentYear+'-'+currentMonth+'-'+currentDate+' '+currentHours+':'+currentMinutes+':'+currentSeconds);
comment.commentDate = currentYear+'-'+currentMonth+'-'+currentDate+' '+currentHours+':'+currentMinutes+':'+currentSeconds;
//comment.commentDate = dateFormat(reviewRecord[m].comment_date, "yyyy-mm-dd HH:MM:ss")
commentsArray[m] = comment;
}
}).on('success', function(err) {
var userId = new Array();
for (var z = 0; z < userIdList.length; z++){
userId.push(userIdList[z]);
}
//var users = {};
User.findAll({where: {id: userId }}).on('success', function(usersdata) {
for (var u = 0; u < usersdata.length; u++){
var username = usersdata[u].first_name + ' ' + usersdata[u].last_name;
usernameArray[usersdata[u].id] = username;
}
for (var p1 = 0; p1 < commentsArray.length; p1++) {
var comment = commentsArray[p1];
comment.user = usernameArray[commentsArray[p1].userid];
commentsArray[p1] = comment;
}
var comments = {};
review.comments = commentsArray;
reviewRecords.review = review
callback(reviewRecords);
})
})
)
}).on('failure', function(err) {
//exception.executeException(0, '1000', err, res);
})
}
}).on('failure', function(err) {
//exception.executeException(0, '1000', err, res);
})
}
else {
var commentsArray = new Array();
var commentJson = {};
commentJson.comment = 'Not available...';
commentJson.user = 'Review';
commentsArray[0]= commentJson;
var comments = {};
review.comments = commentsArray;
reviewRecords.review = review;
//exception.executeException(0, '1001', 'Product reviews is not available', res);
callback(reviewRecords);
}
})
}<file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var EshopCategory = sequelize.import(path.normalize(__dirname + "/../models/Category"));
var Product = sequelize.import(path.normalize(__dirname + "/../models/Product"));
EshopCategory.hasMany(Product, { foreignKey: 'cat_id', as: "Products" });
var Review = sequelize.import(path.normalize(__dirname + "/../models/Review"));
exports.retrieveProducts = function(categoryId, callback) {
var productsArray = new Array();
var productsRecords = {};
if (isNaN(categoryId)) {
//exception.executeException(0, '1001', 'Category id invalid', res);
} else {
EshopCategory.find(parseInt(categoryId)).on('success', function(category) {
if (category != null) {
category.getProducts().on('success', function(products) {
for (var i = 0; i < products.length; i++) {
var product = {};
// TODO Rating hardcode
product.id = products[i].id;
product.name = products[i].pd_name;
product.category = products[i].cat_id;
product.model = products[i].pd_model;
product.specialProduct = products[i].pd_special;
product.listPrice = products[i].pd_list_price;
product.sellPrice = products[i].pd_sell_price;
product.description = products[i].pd_description;
product.image = products[i].pd_img;
product.detailImage = products[i].pd_det_img;
productsArray[i] = product;
}
}).on('success', function() {
var chainer = new Sequelize.Utils.QueryChainer
var ratingIdList = new Array();
var reviewsObjs = new Array();
var reviewArray = new Array();
var review = {};
var ratingString;
var ratingrecordArray = new Array();
var rating = {};
var totalCount = 0;
for (var p = 0; p < productsArray.length; p++) {
var j = 0;
var ratingCountString;
var ratingArray = new Array();
chainer.add(
Review.count({where: {rating: [1,2,3,4,5], pd_id: productsArray[p].id}}).on('success', function(ratingCount) {
totalCount = ratingCount;
totalCount = (totalCount > 25)? (totalCount /2) : totalCount;
var average = (totalCount / 5);
ratingArray[j] = Math.round(average);
j++
})
)
chainer.run().on('success', function() {
var avgRating = {};
avgRating.rating = ratingArray;
for (var p1 = 0; p1 < productsArray.length; p1++) {
var product = productsArray[p1];
product.rating = ratingArray[p1];
productsArray[p1] = product;
}
//console.info(productsArray);
productsRecords.product = productsArray
callback(productsRecords);
})
}
}).on('failure', function(err){
// exception.executeException(0, '1000', err, res);
})
} else {
//exception.executeException(0, '1001', 'Category id unavailable', res);
}
})
.on('failure', function(err){
//exception.executeException(0, '1000', err, res);
})
}
};<file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var Review = sequelize.import(path.normalize(__dirname + "/../models/Review"));
var Product = sequelize.import(path.normalize(__dirname + "/../models/Product"));
exports.retrieveProductdetails = function(productId, callback) {
var totalcount="";
var jsonStr = "";
var productsArray = new Array();
var productsRecords = {};
Product.findAll({where: ["id = ?", productId]}).on('success', function(products) {
try {
for (var i = 0; i < products.length; i++) {
var product = {};
product.id = products[i].id;
product.name = products[i].pd_name;
product.category = products[i].cat_id;
product.model = products[i].pd_model;
product.specialProduct = products[i].pd_special;
product.listPrice = products[i].pd_list_price;
product.sellPrice = products[i].pd_sell_price;
product.description = products[i].pd_description;
product.image = products[i].pd_img;
product.detailImage = products[i].pd_det_img;
productsArray[i] = product;
}
} catch (e) {
//exception.executeException(0, '1000', "failed during product details");
}
}).on('success', function() {
var chainer = new Sequelize.Utils.QueryChainer
var ratingIdList = new Array();
var reviewsObjs = new Array();
var reviewArray = new Array();
var review = {};
var ratingString;
var ratingrecordArray = new Array();
var totalCount = 0;
var j = 0;
var ratingCountString;
var rating;
chainer.add(
Review.count({where: {rating: [1,2,3,4,5], pd_id: productId}}).on('success', function(ratingCount) {
totalCount = ratingCount;
totalCount = (totalCount > 25)? (totalCount /2) : totalCount;
var average = (totalCount / 5);
rating = Math.round(average);
})
)
chainer.run().on('success', function() {
var product;
for (var p1 = 0; p1 < productsArray.length; p1++) {
product = productsArray[p1];
product.rating = rating;
productsArray[p1] = product;
}
if (product == undefined) {
exception.executeException(0, '1001', 'Product id unavailable');
} else {
var details = {"TV Type": "LCD", "Screen Size": "32' Inches", "Screen Ratio": "16:9", "TV Definition": "HDTV"};
product.details = details;
productsRecords.product = productsArray;
callback(productsRecords);
}
}).on('failure', function(err){
//exception.executeException(0, '1000', err);
})
}).on('failure', function(err) {
//exception.executeException(0, '1000', err);
})
};<file_sep>module.exports = function(sequelize, DataTypes) {
return sequelize.define("eshop_products", {
id: { type: sequelize.INTEGER, primaryKey: true, autoIncrement: true},
pd_name: { type: sequelize.STRING},
pd_description: { type: sequelize.STRING},
pd_manufacturer: { type: sequelize.STRING},
pd_qty: { type: sequelize.INTEGER},
cat_id: { type: sequelize.INTEGER},
pd_model: { type: sequelize.STRING},
pd_special: { type: sequelize.STRING},
pd_new: { type: sequelize.STRING},
pd_last_price: { type: sequelize.STRING},
pd_sell_price: { type: sequelize.STRING},
pd_img: { type: sequelize.STRING},
pd_det_img: { type: sequelize.STRING}
}, {
classMethods: {
getProd: function(){ return this.attributes.productId }
},
instanceMethods: {
getProducts: function() { return this }
}
})
}<file_sep>var dbconfigure = require('../lib/eshop/dbconfigure');
dbconfigure.configure('Production');
var register = require('../lib/eshop/service/register.js');
assert = require("assert");
/* describe("Testing Register Service", function() {
it("With New User Details", function(done){
var firstname = "Mohd";
var lastname = "Ibr";
var email = "<EMAIL>"
var password = "awc";
var phonenumber = 34235;
var registerjson = { "message":"Inserted", "userId":30, "successMessage":"Success" }
register.addUser(firstname, lastname, email, password, phonenumber, function(registerdata) {
assert.deepEqual(JSON.stringify(registerjson), JSON.stringify(registerdata), "Register Success");
done();
});
});
}); */
describe("Testing Register Service", function() {
it("With Existing User Details", function(done){
setTimeout(done, 100);
var firstname = "Mohamed";
var lastname = "Ibrahim";
var email = "<EMAIL>"
var password = "<PASSWORD>";
var phonenumber = 12345;
var registerjson = {"message":"Already exist","userId":"0","successMessage":"Failed"};
register.addUser(firstname, lastname, email, password, phonenumber, function(registerdata) {
assert.deepEqual(JSON.stringify(registerjson), JSON.stringify(registerdata), "Register Success");
});
});
}); <file_sep>var Sequelize = require("sequelize")
var utility = require("../utility")
var exception = require('../exception');
var sequelize = new Sequelize('dbs', utility.getDBUserName(), utility.getDBPassword(), {
// custom host; default: localhost
host: utility.getDBHost(),
// custom port; default: 3306
port: utility.getDBPort(),
// disable logging; default: true
logging: true,
// max concurrent database requests; default: 50
maxConcurrentQueries: 100,
// specify options, which are used when sequelize.define is called
// the following example is basically the same as:
// sequelize.define(name, attributes, { timestamps: false })
// so defining the timestamps for each model will be not necessary
define: { timestamps: false },
// similiar for sync: you can define this to always force sync for models
sync: { force: true }
})
var Project = sequelize.import(__dirname + "/models/Project")
var Task = sequelize.import(__dirname + "/models/Task")
var User = sequelize.import(__dirname + "/models/User")
var Person = sequelize.import(__dirname + "/models/Person")
/*
Project.sync().on('success', function() {
console.info('project sync');
}).on('failure', function(error) {
console.info('project failed = ', error);
})
Task.sync().on('success', function() {
console.info('task sync');
}).on('failure', function(error) {
console.info('task failed = ', error);
})
Project.drop();
Task.drop();
*/
/*
var project = Project.build({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
})
var task = Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
})
console.info('project = ', project);
console.info('task = ', task);
// now instantiate an object
//var task = Task.build({title: 'very important task'})
console.info('Title = ', task.title);
// ==> 'very important task'
console.info('Rating = ', task.rating);
// ==> 3
project.save().on('success', function() {
console.info('Project saved');
})
task.save().on('failure', function(error) {
console.info('task failed = ', error);
})
// you can also build, save and access the object with chaining:
Task.build({ title: 'foo', description: 'bar', deadline: new Date()})
.save().on('success', function(anotherTask) {
// you can now access the currently saved task with the variable anotherTask... nice!
})
task.updateAttributes({
title: 'a very different title now'
}).on('success', function() {})
var Foo = sequelize.import(__dirname + "/models/Foo")
console.info('Method1 = ', Foo.method1());
console.info('Method2 = ', Foo.build().method2());
var chainer = new Sequelize.Utils.QueryChainer
chainer
.add(Task.drop())
.add(Task.sync())
for(var i = 0; i < 2; i++)
chainer.add(Task.create({}))
chainer
.run()
.on('success', function(){})
.on('failure', function(errors){})
*/
//Project.hasOne(User)
//Project.hasOne(User, { foreignKey: 'p_id' })
//Project.hasOne(User, { as: 'Initiator' })
Project.hasMany(User, { foreignKey: 'p_id' });
//User.hasMany(Project);
//sequelize.sync();
Project.find(0).on('success', function(project) {
console.info('project = ', project);
project.getUsers().on('success', function(users) {
// associatedTasks is an array of tasks
for (var i = 0; i < users.length; i++) {
console.info('users = ', users[i].name);
}
})
})
/*
User.find(1).on('success', function(user) {
console.info('user = ', user.name);
}) */
//console.info(User.getIni());
//console.info(User.build().getInitiator());
exports.getProjects = function(req, res) {
}<file_sep><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.photon.phresco</groupId>
<artifactId>PHR_NodeJSWebService</artifactId>
<name>PHR_NodeJSWebService</name>
<version>4.0.0.1001-SNAPSHOT</version>
<inceptionYear>1999</inceptionYear>
<organization>
<name>Photon Infotech Inc.</name>
</organization>
<build>
<sourceDirectory>source/lib</sourceDirectory>
<testSourceDirectory>source/test</testSourceDirectory>
<directory>do_not_checkin/target</directory>
<plugins>
<!-- <plugin>
<groupId>com.photon.phresco.plugins</groupId>
<artifactId>nodejs-maven-plugin</artifactId>
<version>4.0.0.1001-SNAPSHOT</version>
<extensions>true</extensions>
</plugin> -->
</plugins>
</build>
<profiles>
<profile>
<id>windows</id>
<activation>
<os>
<family>Windows</family>
</os>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${basedir}/source/test.bat</executable>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>Unix</id>
<activation>
<os>
<family>unix</family>
</os>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<id>FilePermission</id>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>chmod</executable>
<arguments>
<argument>777</argument>
<argument>source/test.sh</argument>
</arguments>
</configuration>
</execution>
<execution>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${basedir}/source/test.sh</executable>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>Mac</id>
<activation>
<os>
<family>mac</family>
</os>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${basedir}/source/test.sh</executable>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>ci</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>default-clean</id>
<phase>pre-clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
<configuration>
<filesets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<fileset>
<directory>do_not_checkin/build</directory>
<includes>
<include>**/*</include>
</includes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<sonar.language xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">js</sonar.language>
<sonar.dynamicAnalysis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">true</sonar.dynamicAnalysis>
<sonar.exclusions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">**/node_modules/**</sonar.exclusions>
<sonar.javascript.testframework>jstestdriver</sonar.javascript.testframework>
<sonar.javascript.jstestdriver.reportsfolder>do_not_checkin/target/surefire</sonar.javascript.jstestdriver.reportsfolder>
<sonar.javascript.jstestdriver.coveragefile>coverage.dat</sonar.javascript.jstestdriver.coveragefile>
<sonar.dynamicAnalysis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">reuseReports</sonar.dynamicAnalysis>
</properties>
</project>
<file_sep>NodeJS WebService (E-Shop)
=======================
<b>E-Shop (Electronic Shopping)</b> is a pilot project included in Phresco. In order to show the Framework’s potential, the E-Shop
has been developed by encompassing all the facets offered by Phresco. As the name suggests, it is a project with
NodeJS WebService compatibility and has been created using NodeJS. Express, Sequelize and MySQL. It supports both json and jsonp Web Services
For more, visit http://nodejs.org/.
<file_sep>#
# PHR_NodeJSWebService
#
# Copyright (C) 1999-2014 Photon Infotech Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
cd source
pwd
jscoverage lib lib-cov
mv lib lib-orig
mv lib-cov lib
mkdir -p ../do_not_checkin/target/surefire
mocha -R xunit > ../do_not_checkin/target/surefire/TEST-AllTest.xml
mocha -R mocha-lcov-reporter > ../do_not_checkin/target/surefire/coverage.dat
rm -rf lib
mv lib-orig lib<file_sep>var dbconfigure = require('../lib/eshop/dbconfigure');
dbconfigure.configure('Production');
var productdetails = require('../lib/eshop/service/productDetails.js');
assert = require("assert");
describe("Testing Products Details Service", function() {
it("With ProductId", function(done){
var productId = 22;
var productdetailsJson = {"product":[{"id":22,"name":" BlackBerry Bold 9780 ","category":3,"model":"1022.0","specialProduct":0,"listPrice":387,"sellPrice":380,"description":"Cpu :\n 624 mhz processor\nPrimary :\n 5 mp, 2592x1944 pixels, autofocus, led flash, check quality\nWlan :\n Wi-fi 802.11 b/g, uma\nCard slot :\n Micro sd, up to 32gb, 2gb card included ","image":"product/bb_mobile_22.png","detailImage":"product/details/bb_mobile_22.png","rating":0,"details":{"TV Type":"LCD","Screen Size":"32' Inches","Screen Ratio":"16:9","TV Definition":"HDTV"}}]};
productdetails.retrieveProductdetails(productId, function(productdetailsdata){
assert.deepEqual(JSON.stringify(productdetailsJson), JSON.stringify(productdetailsdata), "ProductDetails Success");
});
setTimeout(done, 100);
});
});
describe("Testing Products Details Service", function() {
it("With Incorrect ProductId", function(done){
setTimeout(done, 100);
var productId = 2;
var productdetailsJson = {"product":[{"id":22,"name":" BlackBerry Bold 9780 ","category":3,"model":"1022.0","specialProduct":0,"listPrice":387,"sellPrice":380,"description":"Cpu :\n 624 mhz processor\nPrimary :\n 5 mp, 2592x1944 pixels, autofocus, led flash, check quality\nWlan :\n Wi-fi 802.11 b/g, uma\nCard slot :\n Micro sd, up to 32gb, 2gb card included ","image":"product/bb_mobile_22.png","detailImage":"product/details/bb_mobile_22.png","rating":0,"details":{"TV Type":"LCD","Screen Size":"32' Inches","Screen Ratio":"16:9","TV Definition":"HDTV"}}]};
productdetails.retrieveProductdetails(productId, function(productdetailsdata){
assert.notEqual(JSON.stringify(productdetailsJson), JSON.stringify(productdetailsdata), "ProductDetails Failure");
});
});
});<file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var Product = sequelize.import(path.normalize(__dirname + "/../models/Product"));
var EshopCategory = sequelize.import(path.normalize(__dirname + "/../models/Category"));
exports.retrieveCategories = function(callback) {
var categoriesArray = new Array();
var categoriesIdList = new Array();
var categoriesObjs = new Array();
var categoryRecords = {};
EshopCategory.findAll().on('success', function(categories) {
for (var i = 0; i < categories.length; i++) {
var categoryId = categories[i].cat_id;
categoriesIdList[i] = categoryId;
categoriesObjs[i] = categories[i];
}
}).on('success', function() {
var chainer = new Sequelize.Utils.QueryChainer
var productCountArrray = new Array()
for (var i = 0; i < categoriesIdList.length; i++) {
var categoryId = categoriesObjs[i].id;
var j = 0;
chainer.add(
Product.count({where: ["cat_id = ?", categoryId]}).on('success', function(productCount) {
var category = {};
category.id = categoriesObjs[j].id;
category.name = categoriesObjs[j].cat_name;
category.image = categoriesObjs[j].cat_image;
category.detailsImage = categoriesObjs[j].cat_image;
category.productCount = productCount;
categoriesArray[j] = category;
j++;
})
)
chainer.run().on('success', function(){
categoryRecords.category = categoriesArray;
callback(categoryRecords);
})
}
}).on('failure', function(err){
//exception.executeException(0, '1000', err, res);
})
}<file_sep>module.exports = function(sequelize, DataTypes) {
var order = sequelize.define("eshop_orders", {
id: { type: sequelize.INTEGER, primaryKey: true, autoIncrement: true},
od_date: { type: sequelize.DATE},
od_last_update: { type: sequelize.DATE},
userid: { type: sequelize.INTEGER},
od_status: { type: sequelize.STRING},
od_shipping_first_name: { type: sequelize.STRING},
od_shipping_last_name: { type: sequelize.STRING},
od_shipping_address1: { type: sequelize.STRING},
od_shipping_address2: { type: sequelize.STRING},
od_shipping_city: { type: sequelize.STRING},
od_shipping_postal_code: { type: sequelize.INTEGER},
od_shipping_cost: { type: sequelize.INTEGER},
od_payment_first_name: { type: sequelize.STRING},
od_payment_last_name: { type: sequelize.STRING},
od_payment_address1: { type: sequelize.STRING},
od_payment_address2: { type: sequelize.STRING},
od_payment_city: { type: sequelize.STRING},
od_payment_postal_code: { type: sequelize.INTEGER}
});
return order;
}
<file_sep>var exception = require('../../exception');
var dbconfigure = require('../dbconfigure');
var utility = require('../../utility');
var Sequelize = require("sequelize");
var sequelize = dbconfigure.getSequelize();
var path = require('path');
var User = sequelize.import(path.normalize(__dirname + "/../models/User"));
exports.getUserdetails = function(email, password, callback) {
var message = {};
User.count({ where: {email: email, password: password} }).on('success', function(user) {
}).on('success', function(user) {
User.find({ where: {email: email, password: password} }).on('success', function(userdata) {
if(user > 0){
message.message = "success";
message.userId = userdata.id;
message.userName = userdata.first_name + ' ' + userdata.last_name;
message.successMessage = "Login Success";
}
else{
message.message = "failure";
message.userId = "0";
message.userName = "";
message.successMessage = "Login failed";
}
callback(message);
})
})
};<file_sep>var memcache = require('memcache');
var port = 1030;
var host = 'localhost';
module.exports = function() {
var client = new memcache.Client(port, host);
client.port = '1030';
client.host = 'localhost';
client.on('connect', function(){
// no arguments - we've connected
console.info('connected');
});
client.on('close', function(){
// no arguments - connection has been closed
console.info('close');
});
client.on('timeout', function(){
// no arguments - socket timed out
console.info('timeout');
});
client.on('error', function(e){
// there was an error - exception is 1st argument
console.info('error');
});
// connect to the memcache server after subscribing to some or all of these events
client.connect();
return client;
}<file_sep>module.exports = function(sequelize, DataTypes) {
var user = sequelize.define("eshop_users", {
id: { type: sequelize.INTEGER, primaryKey: true, autoIncrement: true},
first_name: { type: sequelize.STRING},
last_name: { type: sequelize.STRING},
email: { type: sequelize.STRING},
password: { type: sequelize.STRING},
phone: { type: sequelize.STRING}
});
return user;
}
<file_sep>module.exports = function(sequelize, DataTypes) {
var review = sequelize.define('eshop_reviews', {
id: { type: sequelize.INTEGER, primaryKey: true, autoIncrement: true},
pd_id: { type: sequelize.INTEGER},
user_id: { type: sequelize.INTEGER},
rating: { type: sequelize.INTEGER},
comment: { type: sequelize.STRING},
comment_date: { type: sequelize.DATE}
});
return review;
}
<file_sep>/**
* PHR_NodeJSWebService
*
* Copyright (C) 1999-2014 Photon Infotech Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.photon.phresco.Screens;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class SearchResponse implements Serializable {
private final long serialVersionUID = 1L;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrlValue() {
return urlValue;
}
private String featureIcon;
private String name;
private String urlValue;
public JSONObject getCategoryJSONObject(String url) throws IOException {
// Log.i("getCategoryJSONObject","");
JSONObject categoryJSONResponseObj = null;
categoryJSONResponseObj = JSONHelper.getJSONObjectFromURL(url);
// System.out.println(" in side search Response---->");
return categoryJSONResponseObj;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getCategoryGSONObject(JSONObject categoryJSONObj) {
List<SearchResponse> categoryList = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
categoryList = (List<SearchResponse>) jsonObj.fromJson(
categoryJSONObj.getJSONArray("category").toString(),
listType);
} catch (JSONException ex) {
}
return categoryList;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getCategoryList1GSONObject(JSONObject categoryList1JSONObj) {
List<SearchResponse> categoryList1 = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
categoryList1 = (List<SearchResponse>) jsonObj.fromJson(categoryList1JSONObj.getJSONArray("product").toString(),
listType);
} catch (JSONException ex) {
}
return categoryList1;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getCategoryList2GSONObject(JSONObject categoryList2JSONObj) {
List<SearchResponse> categoryList2 = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
categoryList2 = (List<SearchResponse>) jsonObj.fromJson(categoryList2JSONObj.getJSONArray("product").toString(),
listType);
} catch (JSONException ex) {
}
return categoryList2;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getCategoryList3GSONObject(JSONObject categoryList3JSONObj) {
List<SearchResponse> categoryList3 = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
categoryList3 = (List<SearchResponse>) jsonObj.fromJson(categoryList3JSONObj.getJSONArray("product").toString(),
listType);
} catch (JSONException ex) {
}
return categoryList3;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getNewProductListGSONObject(JSONObject NewProductListJSONObj) {
List<SearchResponse> NewProductList = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
NewProductList = (List<SearchResponse>) jsonObj.fromJson(NewProductListJSONObj.getJSONArray("product").toString(),
listType);
} catch (JSONException ex) {
}
return NewProductList;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getproductGSONObject(JSONObject productJSONObj) {
List<SearchResponse> productList = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
productList = (List<SearchResponse>) jsonObj.fromJson(productJSONObj.getJSONArray("product").toString(), listType);
} catch (JSONException ex) {
}
return productList;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getcomputerListGSONObject(JSONObject computerListJSONObj) {
List<SearchResponse> computerList = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
computerList = (List<SearchResponse>) jsonObj.fromJson( computerListJSONObj.getJSONArray("product").toString(), listType);
} catch (JSONException ex) {
}
return computerList;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getMobileListGSONObject(JSONObject MobileListJSONObj) {
List<SearchResponse> MobileList = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
MobileList = (List<SearchResponse>) jsonObj.fromJson(MobileListJSONObj.getJSONArray("product").toString(), listType);
} catch (JSONException ex) {
}
return MobileList;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getProductsListGSONObject(JSONObject ProductsListJSONObj) {
List<SearchResponse> ProductsList = null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
ProductsList = (List<SearchResponse>) jsonObj.fromJson( ProductsListJSONObj.getJSONArray("product").toString(), listType);
} catch (JSONException ex) {
}
return ProductsList;
}
@SuppressWarnings("unchecked")
public List<SearchResponse> getSpecialProductsListGSONObject(JSONObject SpecialProductsListJSONObj) {
List<SearchResponse> SpecialProductsList= null;
try {
Gson jsonObj = new Gson();
Type listType = new TypeToken<List<SearchResponse>>() {
}.getType();
SpecialProductsList= (List<SearchResponse>) jsonObj.fromJson( SpecialProductsListJSONObj.getJSONArray("product").toString(), listType);
} catch (JSONException ex) {
}
return SpecialProductsList;
}
}
| 25f1285957f81b52079ceb01142e76947bb5114f | [
"JavaScript",
"Markdown",
"Maven POM",
"Java",
"Shell"
] | 21 | JavaScript | namu2018/nodejs-webservice-eshop | ea439022bad4eb01533ee20007c0a088dab32614 | cb72cd57430ea5103c97b7e90742769cf7eb6f11 |
refs/heads/master | <repo_name>daniltirsk/-<file_sep>/exercise 1.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
setlocale(0,"Rus");
int f,a;
bool c;
cout << "Select function: (1) y=x^4 (2) y=e^x (3) y=tg(x)"<< endl;
cin >> f;
cout << "Enter the interval -a<=x<=a, enter a"<< endl;
cin >> a;
c = false;
if (f==1){
for (double i = -a; i <= a; i+=0.1) {
if (i*i*i*i==-i*-i*-i*-i) {
c = true;
} else {
c = false;
break;
}
}
} else if (f==2) {
for (double i = -a; i <= a; i+=0.1) {
if (exp(i)==exp(-i)) {
c = true;
} else {
c = false;
break;
}
}
} else if (f==3) {
for (double i = -a; i <= a; i+=0.1) {
if (tan(M_PI/2) == tan(i)) {
continue;
} else {
if (tan(i)==tan(-i)) {
c = true;
} else {
c = false;
break;
}
}
}
} else {
cout << "Incorrect input"<< endl;
return 0;
}
if (c==true) {
cout << "четная"<< endl;
} else {
cout << "нечетная или общего вида"<< endl;
}
return 0;
}
<file_sep>/exercise 2.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
setlocale(0,"Rus");
int f,a;
bool c;
double n;
cout << "Select function: (1) y=sin(x)^2 (2) y=tg(x) (3) y=1/x * sin(x)"<< endl;
cin >> f;
c = false;
if (f==1){
for (int i = 0; i <= 5*180; i+=45) {
cout << sin(i*M_PI/180)*sin(i*M_PI/180) << endl;
}
} else if (f==2) {
for (int i = 0; i <= 5*180; i+=45) {
if (i%180==90){
continue;
} else {
cout << tan(i*M_PI/180) << endl;
}
}
} else if (f==3) {
for (double i = 0; i <= 5*360; i+=45) {
if (i==0){
continue;
} else {
cout << (1/i) * sin(i*M_PI/180) << endl;
}
}
} else {
cout << "Incorrect input"<< endl;
return 0;
}
return 0;
}
<file_sep>/exercise 4.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double k,p,r;
int y;
cout << "Enter k"<< endl;
cin >> k;
cout << "Enter p"<< endl;
cin >> p;
cout << "Enter r"<< endl;
cin >> r;
y=0;
if ((k/100 * p) < r) {
while (k > 0) {
k = (k + k/100*p)- r;
y++;
}
} else {
cout << "no" << endl;
return 0;
}
cout << "yes "<< y<< " years" <<endl;
}
<file_sep>/exercise 6.cpp
#include <iostream>
#include <cmath>
using namespace std;
int fact(int n){
int res;
res = 1;
for (int i = 1; i <= n; i++) {
res = res * i;
}
return res;
}
int main(){
setlocale(0,"Rus");
int m;
float x, b, c, b1, b2;
cout << "Задайте x и m" << endl;
cin >>x>>m;
b=1+x;
b1=1+x;
b2=1;
for (int i=2; i<=m; i++) {
b1*=b;
}
cout<<b1<<" "<< fact(m-1)<<endl;
for (int i=1; i<=m; i++) {
b2+= (fact(m)/(fact(i)*fact(m-i)))*pow(x,i);
}
cout <<b2;
}
<file_sep>/exercise 9.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
setlocale(0,"Rus");
double row,p,e,n,fract;
int s, cr, cf;
row=2;
n=2;
e=exp(1);
s=3;
fract=0;
cf=0;
cout << "Задайте погрешность" << endl;
cin >> p;
while (row <= e-p) {
row = row + 1/n;
n*=s;
s++;
}
cr = s-1; // кол-во итераций для ряда
cout << "кол-во итераций для ряда = " << cr<< endl;
while (true) {
for (int i=cf; i>=1; i--) {
if (i%2 == 0){
fract=1/(2+fract);
}
else {
fract=1/(i-fract);
}
}
if (abs(e - (fract + 1))<p)
{
break;
}
cf++; // кол-во итераций для дроби
}
cout << "кол-во итераций для дроби = " << cf<< endl;
if (cr > cf) {
cout << cr<< " > "<<cf<< " Дробь быстрее ряда" << endl;
} else if (cr = cf) {
cout << cr<< " = "<<cf<< " Ряд и дробь одинакого быстры" << endl;
} else {
cout << cr<< " < "<<cf<< " Ряд быстрее дроби" << endl;
}
}
<file_sep>/exercise 3.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a,b;
cout << "Enter a, b"<< endl;
cin >> a>>b;
for (float i=-a; i<=a; i++) {
for (float j=-b; j<=b; j++) {
if (((i*i)/(a*a) + (j*j)/(b*b)) <= 1) {
cout << "x="<<i<<" y="<<j<<endl;
} else {
continue;
}
}
}
return 0;
}
<file_sep>/exercise 7.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
setlocale(0,"Rus");
double x, p;
x=1;
cout << "Задайте погрешность" << endl;
cin >> p;
while (sin(x)/x <= 1-p) {
cout<< sin(x)/x<< " " << x<< endl;
x=x/2;
}
}
<file_sep>/exercise 8.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(){
setlocale(0,"Rus");
double x, y, e, p;
x=1;
y = 1+1/x;
e=exp(1);
cout << "Задайте погрешность" << endl;
cin >> p;
while (y <= e-p) {
x++;
y=1+1/x;
y=pow(y,x);
}
cout<< "Число e="<<e<<" Заданная погрешность: "<<p<<" Итоговое число: "<<y <<" Конечное отличие: "<<e-y<<" При n= " << x<< endl;
}
<file_sep>/exercise 5.cpp
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
int main(){
float k, mile,m1,k1,m2,z;
int m;
cout << "Enter k"<< endl;
cin >>k;
mile=1.609344;
m=1;
z=0;
cout << "MILES "<< "KILOMETERS"<< endl;
for (float i=1; i<=k; i++) {
m1=i/mile;
m2=int(m1)+z;
k1=m2*mile;
if (m2 == m) {
printf("%.4f %.4f", m2, k1);
cout<<endl;
m++;
}
printf("%.4f %.4f", m1,i);
cout << endl;
}
return 0;
}
| 7720dfca4635e7bf1256451121756296ca58dd58 | [
"C++"
] | 9 | C++ | daniltirsk/- | 2e948f894329b633c16623bf8ad9dff6dbb3ffb8 | 46108d8ccd503e48ed684023d8af5a0c001f5a03 |
refs/heads/master | <file_sep># remoteSudo
Alllows use of sudo commands on remote hosts
## Usage<br>
` remoteSudo.sh <user> <command> <host file||comma delimited list>`<br>
## Requirement
Requires sshpass
Install with<br>
` yum install sshpass -y`
## Testing results
<pre>userid@y0319t11229:~$ ./remoteSudo.sh userid 'ls /etc/audit' ./hosts
Password: *<PASSWORD>*
Warning: Permanently added 'y0319t12479,10.19.216.52' (RSA) to the list of known hosts.
Enter your password on host <PASSWORD>12479:auditd.conf
audit.rules
rules.d
Warning: Permanently added 'y0319t12480,10.19.216.54' (RSA) to the list of known hosts.
Enter your password on host y0319t12480:auditd.conf
audit.rules
rules.d
Warning: Permanently added 'y0319t12481,10.19.216.56' (RSA) to the list of known hosts.
Enter your password on host <PASSWORD>t12481:auditd.conf
audit.rules
rules.d
Warning: Permanently added 'y0319t12484,10.19.216.55' (RSA) to the list of known hosts.
Enter your password on host y0319t12484:auditd.conf
audit.rules
rules.d
Warning: Permanently added 'y0319t12485,10.19.216.53' (RSA) to the list of known hosts.
Enter your password on host <PASSWORD>2485:auditd.conf
audit.rules
rules.d</pre>
## Additional Info
The bash script will split commands on semicolon if it exists in the command string and run each of the commands with sudo. This results as each command being a separate ssh session to the host.
The PowerShell script can use the same session to run multiple commands.
## Inspired by
PowerShell Posh-SSH
(also included in the repo)
<file_sep>#!/bin/bash
user=$1
cmd=$2
host=$3
read -p 'Password: ' -s PWD
function usage {
echo "Usage remoteSudo.sh <user> <command> <host file||comma delimited list>"
exit
}
# Check number of arguments
if [ "$#" -ne 3 ]; then
usage
fi
# Check for comma delimited list or filename
if [[ $host == *[,]* ]]; then
IFS=',' read -r -a hosts <<< "$host"
elif [[ $host == *"/"* ]]; then
IFS=$'\n' read -d '' -r -a hosts < $host
else
usage
fi
# install sshpass if not already installed
if [ ! $(echo $PWD | sudo -S yum list sshpass | grep 'Installed Packages') ]; then
echo $PWD | sudo -S yum install sshpass -y
fi
# Check if command is has semicolon separators
if [[ $cmd == *";"* ]]; then
IFS=';' read -a arrCMD <<<$cmd
# Run remote sudo commands on list of hosts
for h in "${hosts[@]}"
do
echo ""
echo $h
for cmd1 in "${arrCMD[@]}"
do
sshpass -p $PWD ssh -o StrictHostKeyChecking=no $user@$h "echo $PWD | sudo -S $cmd1"
done
done
else
# Run remote sudo command on list of hosts
for h in "${hosts[@]}"
do
echo $h
sshpass -p $PWD ssh -o StrictHostKeyChecking=no $user@$h "echo $PWD | sudo -S $cmd"
done
fi
| b35c22c73ccac57d2728a7eb91e7485b6fb27f2e | [
"Markdown",
"Shell"
] | 2 | Markdown | rossKayHe/remoteSudo | 4ac0ffeddbf0f17fbb112fa4ae979e7d6393a49a | 122b5894e19dc42aa1ab26eb4f0cc11a4c80bf87 |
refs/heads/master | <file_sep>export const state = () => ({
subCategories: [],
})
export const getters = {
getSubCategoiresOfCategory: (state) => (payload) => {
return state.subCategories.filter(item => {
return item.category.title.toLowerCase() == payload.category.toLowerCase();
})
},
getSubCategory: (state) => (payload) => {
return state.subCategories.find(item => {
return item.title.toLowerCase() == payload.subCategory.toLowerCase();
})
}
}
export const mutations = {
initalizeSubCategories(state, payload) {
state.subCategories = payload.subCategories;
}
}
<file_sep>const validator = require('validator');
const isEmpty = require('../../validation/isEmpty');
module.exports.validFeebackPost = (data) => {
let errors = {};
data.name = isEmpty(data.name) ? '' : data.name;
data.phone = isEmpty(data.phone) ? '' : data.phone;
data.feedback = isEmpty(data.feedback) ? '' : data.feedback;
if(validator.isEmpty(data.name)) errors.name = "Name field is required";
if(!validator.isLength(data.phone, {min: 10, max: 10})) errors.phone = "Phone Number should be of 10 digit";
if(!validator.isNumeric(data.phone)) errors.phone = "Phone field must be numeric";
if(validator.isEmpty(data.phone)) errors.phone = "Phone field is required";
if(validator.isEmpty(data.feedback)) errors.feedback = "Feedback field is required";
return {
errors,
isValid: isEmpty(errors)
}
}<file_sep>export default function ({
store
}) {
if (!process.server) {
store.commit('ui/changeSkletonLoading', {
skeltonLoading: true
})
}
}
<file_sep>export const state = () => ({})
export const getters = {
}
export const mutations = {}
export const actions = {
async nuxtServerInit({
dispatch
}) {
await dispatch('public/getPublicData', null, {
root: true
});
}
}
<file_sep>const mongoose = require('mongoose');
const { dbUrl } = require('../../config/index');
const connect = async () => {
try {
let uri = dbUrl;
await mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
console.log('mongodb Connected......');
} catch(err) {
console.log(err.message);
process.exit(1);
}
}
module.exports = connect;<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
let publicSchema = new Schema({
name: {
type: String,
required: true,
unique: true,
lowercase: true
},
slug: {
type: String,
required: true,
},
main_categories: [{
type: Schema.Types.ObjectId,
ref: 'main_category'
}]
}, {
timestamps: true
});
module.exports = mongoose.model('public', publicSchema);<file_sep>const config = {
reqHost: "https://all-formula.herokuapp.com"
}
export default config; <file_sep>const router = require('express').Router();
var { verifyUser, signin } = require('./authController')
router.post('/singin', verifyUser(), signin);
module.exports = router;<file_sep>const router = require('express').Router();
const controller = require('./mainCategoryController');
router.param('slug', controller.params);
router.route('/')
.get(controller.get)
.post(controller.post);
router.route('/:slug')
.get(controller.getOne)
module.exports = router;<file_sep>const validator = require('validator');
const isEmpty = require('../isEmpty');
module.exports.validPublicPut = (data) => {
let errors = {};
data.mainCategories = isEmpty(data.mainCategory) ? [] : data.mainCategory;
data.subCategories = isEmpty(data.subCategories) ? [] : data.subCategories;
data.categories = isEmpty(data.categories) ? [] : data.categories;
data.products = isEmpty(data.products) ? [] : data.products;
return {
errors,
isValid: isEmpty(errors)
}
}<file_sep>const validator = require('validator');
const isEmpty = require('../isEmpty');
module.exports.validateCollectionPut = (data) => {
let errors = {};
data.name = isEmpty(data.name) ? '' : data.name;
if (validator.isEmpty(data.name)) errors.name = "Kindly provide the name of the collection";
return {
errors,
isValid: isEmpty(errors)
}
}
<file_sep>let Product = require('./productModel');
let SubCategory = require('../subCategory/subCategoryModel');
let { validateProductPost } = require('../../validation/product/post');
const slugify = require('slug-generator');
module.exports.get = async function (req, resp, next) {
try {
let product = await Product.find({}).exec();
resp.json(product);
} catch (err) {
console.log(err.message);
next(err);
}
}
module.exports.post = async function (req, resp, next) {
let {
errors,
isValid
} = validateProductPost(req.body);
if (!isValid) {
return resp.status(400).json(errors);
}
try {
let product = new Product();
product.title = req.body.title;
product.slug = slugify(req.body.title);
product.description = req.body.description;
product.equation = req.body.equation;
product.sub_category = req.body.subCategory;
product = await product.save();
let subCategory = await SubCategory.findById(req.body.subCategory).exec();
subCategory.products.push(product._id);
await subCategory.save();
resp.json(product);
} catch (err) {
console.log(err);
next(err);
}
}
<file_sep>module.exports = Object.freeze({
dbUrl: 'mongodb+srv://mgpokra:Mongo@27607@cluster0-dqzy6.mongodb.net/formula?retryWrites=true&w=majority',
reqHost: "https://all-formula.herokuapp.com/",
email: {
user: '<EMAIL>',
password: '<PASSWORD>'
}
})
<file_sep>import devConfig from './dev';
import prodConfig from './prod';
let env = process.env.NODE_ENV || 'development';
let basiConfig = {
}
let envConfig = {};
switch (env) {
case 'dev':
case 'development':
envConfig = devConfig;
break;
case 'prod':
case 'production':
envConfig = prodConfig;
break;
default:
envConfig = devConfig;
}
const frontConfig = {
...basiConfig,
...envConfig
}
export default frontConfig;
<file_sep>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
let collectionSchema = new Schema({
name: {
type: String,
required: true,
unique: true,
lowercase: true
},
slug: {
type: String,
required: true,
},
main_categories: [{
type: Schema.Types.ObjectId,
ref: 'main_category'
}]
}, {
timestamps: true
});
module.exports = mongoose.model('collection', collectionSchema);<file_sep>const Category = require('./categoryModel');
let { validateCategoryPost } = require('../../validation/category/post');
const slugify = require('slug-generator');
let MainCategory = require('../mainCategory/mainCategoryModel');
module.exports.params = async function(req, res, next, slug) {
try {
let category = await Category.findOne({slug: slug}).populate({
path: 'sub_categories',
select: 'title slug description image'
}).select('title slug description image').exec();
req.category = category;
next();
} catch (err) {
next(err);
}
}
module.exports.get = async function (req, resp, next) {
try {
let categories = await Category.find({}).populate({
path: 'sub_categories',
select: 'title slug description products, image'
}).select('title slug description image').exec();
resp.json(categories);
} catch (err) {
console.log(err.message);
next(err);
}
}
module.exports.getOne = function(req, resp, next) {
return resp.json(req.category);
}
module.exports.post = async function (req, resp, next) {
const {errors, isValid} = validateCategoryPost(req.body);
if(!isValid) {
return resp.status(400).json(errors);
}
try {
let category = new Category();
category.title = req.body.title;
category.slug = slugify(req.body.title);
category.description = req.body.description;
category.main_category = req.body.mainCategory;
category = await category.save();
let mainCategory = await MainCategory.findById(req.body.mainCategory).exec();
mainCategory.categories.push(category._id);
mainCategory = await mainCategory.save();
resp.json(category);
} catch (err) {
console.log(err.message);
next(err);
}
}
<file_sep>const SubCategory = require('./subCategoryModel');
let { validateSubCategoryPost } = require('../../validation/subCategory/post');
let Category = require('../category/categoryModel');
const slugify = require('slug-generator');
module.exports.params = async function(req, resp, next, slug) {
try {
let subCategory = await SubCategory.findOne({slug: slug}).populate({
path: 'products',
select: '_id title description equation image'
}).select('_id description title').exec();
if(!subCategory) {
return resp.status(404).json({msg: "Not found"});
}
req.subCategory = subCategory;
next();
} catch(err) {
}
}
module.exports.get = async function (req, resp, next) {
try {
let subCategories = await SubCategory.find({}).exec();
resp.json(subCategories);
} catch (err) {
console.log(err.message);
next(err);
}
}
module.exports.getOne = function(req, resp, next) {
return resp.json(req.subCategory);
}
module.exports.post = async function (req, resp, next) {
const {errors, isValid} = validateSubCategoryPost(req.body);
if(!isValid) {
return resp.status(400).json(errors);
}
try {
let subCategory = new SubCategory();
subCategory.title = req.body.title;
subCategory.slug = slugify(req.body.title);
subCategory.description = req.body.description;
subCategory.category = req.body.category;
subCategory = await subCategory.save();
let category = await Category.findById(req.body.category).exec();
category.sub_categories.push(subCategory._id);
category = await category.save();
resp.json(subCategory);
} catch (err) {
console.log(err.message);
next(err);
}
}
<file_sep>import {
frontConfig
} from '../config/frontend/index';
import config from '../config/frontend/dev';
export const state = () => ({
mainCategories: [],
currentMainCategory: null,
test: 'this it the test msg'
})
export const getters = {}
export const mutations = {
initalizeMainCategories(state, payload) {
state.mainCategories = payload.mainCategories;
}
}
export const actions = {
getMainCategories({
commit
}) {
return this.$axios.$get(`${config.reqHost}/api/public`).then(data => {
commit('initalizeMainCategories', {
mainCategories: data.main_categories
})
commit('category/initalizeCategories', {
categories: data.categories
}, {
root: true
});
commit('subCategory/initalizeSubCategories', {
subCategories: data.sub_categories
}, {
root: true
})
commit('formula/initalizeFormulas', {
formulas: data.products
}, {
root: true
})
}).catch(err => {
console.log(err);
})
}
}
<file_sep>process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const env = process.env.NODE_ENV;
let baseConfig = {
env: process.env.NODE_ENV,
secrets: {
jwt: '<PASSWORD>'
},
// 10 days in minutes
expireTime: 24 * 60 * 10,
}
let envConfig = {};
switch (env) {
case 'dev':
case 'development':
envConfig = require('./dev');
break;
case 'prod':
case 'production':
envConfig = require('./prod');
break;
default:
envConfig = require('./dev');
}
module.exports = Object.freeze({
...envConfig,
...baseConfig
})<file_sep>const router = require('express').Router();
router.use('/category', require('./category/categoryRoute'));
router.use('/product', require('./product/productRoute'));
router.use('/main_category', require('./mainCategory/mainCategoryRoute'));
router.use('/sub_category', require('./subCategory/subCategoryRoute'));
router.use('/user', require('./user/userRoute'));
router.use('/auth', require('./auth/authRoute'));
router.use('/public', require('./public/publicRoute'));
router.use('/collection', require('./collection/collecionRoute'));
router.use('/feedback', require('./feedback/route'));
module.exports = router;<file_sep>var User = require('./userModel');
var {
validateSingUp
} = require('../../validation/user/signup');
var { signToken } = require('../auth/authController');
module.exports.params = async function (req, resp, next, id) {
try {
let user = await User.findById(id).exec();
if (!user) {
return resp.status(400).json({
msg: 'User with this id not found'
})
} else {
req.user = user;
next();
}
} catch (err) {
console.log(err);
next(err);
}
}
module.exports.get = async function (req, resp, next) {
try {
let users = await User.find({}).exec();
return resp.json(users);
} catch (err) {
console.log(err);
next(err);
}
}
module.exports.getOne = function (req, resp, next) {
var user = req.user;
return resp.json(user);
}
module.exports.post = async function (req, resp, next) {
const {errors, isValid} = validateSingUp(req.body);
if (!isValid) {
return resp.status(400).json(errors);
}
try {
let user = await User.findOne({email: req.body.email}, 'email').exec();
if(user) {
return resp.json("User with this email is already exits");
}
user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.phone = req.body.phone;
user.password = <PASSWORD>;
user = await user.save();
var token = signToken(user._id);
return resp.json({token: token});
} catch(err) {
console.log(err);
next(err);
}
}
<file_sep>const router = require('express').Router();
const controller = require('./subCategoryController');
router.param('slug', controller.params)
router.route('/')
.get(controller.get)
.post(controller.post)
router.get('/:slug', controller.getOne);
module.exports = router;<file_sep>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const {
capatalize
} = require('../commonModelMethod');
let subCategorySchema = new Schema({
title: {
type: String,
required: true,
set: capatalize
},
slug: {
type: String,
required: true
},
description: {
type: String,
set: capatalize
},
products: [{
type: Schema.Types.ObjectId,
ref: 'product'
}],
category: {
type: Schema.Types.ObjectId,
ref: 'category',
required: true
},
image: {
type: Schema.Types.ObjectId,
ref: 'image'
}
}, {
timestamps: true
})
module.exports = mongoose.model('sub_category', subCategorySchema);
<file_sep>export const state = () => ({
navBarTitle: "Formulas",
skeltonLoading: false,
darkTheme: false,
bottomNav: 0 // Bottom Nav active button
})
export const getters = {
}
export const mutations = {
setNavbarTitle(state, payload) {
state.navBarTitle = payload.title
},
changeSkletonLoading(state, payload) {
state.skeltonLoading = payload.skeltonLoading;
},
setBottomNav(state, payload) {
state.bottomNav = payload.number;
},
changeTheme(state) {
state.darkTheme = !state.darkTheme
}
}<file_sep>var Collection = require('./collectionModel');
var {
validateCollectionPost
} = require('../../validation/collection/post');
var isEmpty = require('../../validation/isEmpty');
var slugify = require('slug-generator');
module.exports.params = async function (req, resp, next, slug) {
try {
let collection = await Collection.findOne({
slug: slug
}).exec();
if (!collection) {
return resp.status(400).json({
msg: 'Collection with this email does not exist'
});
}
req.collection = collection;
next();
} catch (err) {
next(err);
}
}
module.exports.get = async function (req, res, next) {
try {
let collection = await Collection.findOne().populate({
path: 'main_categories',
select: 'title slug description',
populate: {
path: 'categories',
select: 'title slug description',
options: {
limit: 5
}
}
}).exec();
return res.json(collection);
} catch (err) {
next(err);
}
}
module.exports.post = async function (req, res, next) {
try {
let {
errors,
isValid
} = validateCollectionPost(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
let collection = new Collection();
collection.name = req.body.name;
collection.slug = slugify(req.body.name);
collection = await collection.save();
return res.json(collection);
} catch (err) {
next(err);
}
}
/**
* push main, sub, category, porduct only single not in bulk
*/
module.exports.put = async function (req, res, next) {
req.body.mainCategory = isEmpty(req.body.mainCategory) ? "" : req.body.mainCategory;
try {
let collection = req.collection;
if (req.body.mainCategory) collection.main_categories.push(req.body.mainCategory);
collection = await collection.save();
return res.json(collection);
} catch (err) {
next(err);
}
}
module.exports.mainCategory = async function (req, resp, next) {
try {
let data = await Collection.findOne().populate({
path: 'main_categories',
select: "slug title description",
match: {
slug: {
$eq: req.params.mainCategory
}
},
populate: {
path: 'categories',
select: "slug title description",
}
})
if (!data || !data.main_categories || !data.main_categories.length) {
return resp.status(404).json({
msg: 'Not Found'
});
}
return resp.json(data.main_categories[0]);
} catch (err) {
next(err);
}
}
module.exports.categoryInMainCategory = async function (req, resp, next) {
try {
let data = await Collection.findOne().populate({
path: 'main_categories',
select: "slug title description",
match: {
slug: {
$eq: req.params.mainCategory
}
},
populate: {
path: 'categories',
select: "slug title description",
match: {
slug: {
$eq: req.params.category
}
},
options: {
limit: 1
},
populate: {
path: 'sub_categories',
select: "slug title description",
}
}
})
if (!data || !data.main_categories || !data.main_categories.length || !data.main_categories[0].categories || !data.main_categories[0].categories.length) {
return resp.status(404).json({
msg: 'Not found'
})
}
return resp.json(data.main_categories[0].categories[0]);
} catch (err) {
}
}
module.exports.subCategoryInMainCategory = async function (req, resp, next) {
try {
console.log("here");
let data = await Collection.findOne().populate({
path: 'main_categories',
select: "slug",
match: {
slug: {
$eq: req.params.mainCategory
}
},
populate: {
path: 'categories',
select: "slug",
match: {
slug: {
$eq: req.params.category
}
},
populate: {
path: 'sub_categories',
select: "title description",
match: {
slug: {
$eq: req.params.subCategory
}
},
populate: {
path: 'products',
select: 'title equation description'
}
}
}
});
if (!data || !data.main_categories || !data.main_categories.length || !data.main_categories[0].categories || !data.main_categories[0].categories.length || !data.main_categories[0].categories[0].sub_categories || !data.main_categories[0].categories[0].sub_categories.length) {
return resp.status(404).json({
msg: 'Not found'
})
}
return resp.json(data.main_categories[0].categories[0].sub_categories[0]);
} catch (err) {
}
}
module.exports.delete = function (req, res, next) {
}
<file_sep>var validator = require('validator');
var isEmpty = require('../isEmpty');
var User = require('../../api/user/userModel')
module.exports.validateSingUp = (data) => {
let errors = {};
data.name = isEmpty(data.name) ? '' : data.name;
data.email = isEmpty(data.email) ? '' : data.email;
data.password= isEmpty(data.password) ? '' : data.password;
data.confirmPassword = isEmpty(data.confirmPassword) ? '' : data.confirmPassword;
if(!validator.isEmail(data.email)) errors.email = "kindly enter right email address";
if(validator.isEmpty(data.email)) errors.email = "kindly enter email address";
if(validator.isEmpty(data.name)) errors.name = "kindly enter name field";
if(validator.isEmpty(data.password)) errors.password = "kindly enter password field";
if(validator.isEmpty(data.confirmPassword)) errors.confirmPassword = "kindly enter confirm password field";
if(data.password != data.confirmPassword) errors.confirmPassword = "<PASSWORD> with confirm password";
return {
errors,
isValid: isEmpty(errors)
}
}<file_sep>var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var config = require('../../../config/index');
var checkToken = expressJwt({
secret: config.secrets.jwt
});
var User = require('../user/userModel');
var {
validateLogin
} = require('../../validation/user/login');
module.exports.decodeToken = function () {
return function (req, res, next) {
// make it optional to place token on query string
// if it is, place it on the headers where it should be
// so checkToken can see it. See follow the 'Bearer 034930493' format
// so checkToken can see it and decode it
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer' + req.query.access_token;
}
// this will call next if token is valid
// and send error if its not. It will attached
// the decoded token to req.user
checkToken(req, res, next);
}
}
module.exports.getFreshUser = function () {
return async function (req, res, next) {
try {
let user = await User.findById(req.user._id).exec();
if (!user) {
// if no user is found it was not
// it was a valid JWT but didn't decode
// to a real user in our DB. Either the user was deleted
// since the client got the JWT, or
// it was a JWT from some other source
res.status(401).send('Unauthorized');
} else {
// update req.user with fresh user from
// stale token data
req.user = user;
next();
}
} catch (err) {
Console(err);
next(err);
}
}
}
module.exports.verifyUser = function () {
return async function (req, res, next) {
const {
errors,
isValid
} = validateLogin(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
try {
let user = await User.findOne({
email: req.body.email
}).exec();
if (!user) {
return res.status(401).send('No user with the given email');
} else {
// checking the passowords here
if (!user.authenticate(req.body.password)) {
res.status(401).send('Wrong password');
} else {
// if everything is good,
// then attach to req.user
// and call next so the controller
// can sign a token from the req.user._id
req.user = user;
next();
}
}
} catch (err) {
console.log(err);
next(err);
}
}
}
// util method to sign tokens on signup
const signToken = function(id) {
return jwt.sign(
{_id: id},
config.secrets.jwt,
{expiresIn: config.expireTime}
);
};
module.exports.signToken = signToken;
module.exports.signin = function(req, res, next) {
// req.user will be there from the middleware
// verify user. Then we can just create a token
// and send it back for the client to consume
var token = signToken(req.user._id);
return res.json({token: token});
}
<file_sep>module.exports = Object.freeze({
dbUrl: 'mongodb://localhost:27017/test',
reqHost: "http://127.0.0.1:3000/",
email: {
user: '<EMAIL>',
password: '<PASSWORD>'
}
})<file_sep>const validator = require('validator');
const isEmpty = require('../../validation/isEmpty');
module.exports.validateCategoryPost = (data) => {
let errors = {};
data.title = isEmpty(data.title) ? '' : data.title;
data.mainCategory = isEmpty(data.mainCategory) ? '' : data.mainCategory;
if(validator.isEmpty(data.title)) errors.title = "Category title is required";
if(validator.isEmpty(data.mainCategory)) errors.mainCategory = "Kindly select main category field";
return {
errors,
isValid: isEmpty(errors)
}
}<file_sep>const router = require('express').Router();
const publicController = require('./publicController');
router.param('slug', publicController.params);
router.route('/')
.get(publicController.get)
.post(publicController.post);
router.route("/:slug")
.put(publicController.put);
router.route('/category/:mainCategory/:category')
.get(publicController.categoryInMainCategory);
router.route('/sub_category/:mainCategory/:category/:subCategory')
.get(publicController.subCategoryInMainCategory);
router.route('/main_category/:mainCategory').get(publicController.mainCategory);
router.get('/nexted', publicController.getNexted);
module.exports = router;
<file_sep>const config = {
reqHost: "http://127.0.0.1:3000"
}
export default config;
<file_sep>const validator = require('validator');
const isEmpty = require('../isEmpty');
module.exports.validPublicPost = (data) => {
let errors = {};
data.name = isEmpty(data.name) ? '' : data.name;
if(validator.isEmpty(data.name)) errors.name = "Kindly Enter public name";
return {
errors,
isValid: isEmpty(errors)
}
}<file_sep>const validator = require('validator');
const isEmpty = require('../isEmpty');
module.exports.validateLogin = (data) => {
let errors = {};
data.email = isEmpty(data.email) ? '' : data.email;
data.password = isEmpty(data.password) ? '' : data.password;
if(!validator.isEmail(data.email)) errors.email = "Kindly enter right email address";
if(validator.isEmpty(data.email)) errors.email = "Kindly enter email address";
if(validator.isEmpty(data.password)) errors.password= "<PASSWORD> enter password";
return {
errors,
isValid: isEmpty(errors)
}
} | 62680b90b4a56d23b8761558b26a8b26e67a6c6c | [
"JavaScript"
] | 33 | JavaScript | Mohitpokra/formula | 9df3ea114dd066697f5ee4300786f2f54519a6ed | 9298d77c77a76bf3733019c666e964b007b60e34 |
refs/heads/master | <repo_name>AnnaSu/vue-base-demo<file_sep>/README.md
# vue-base-demo
## Start Server for Website
### Install http-server:
npm install http-server -g
### Usage http-server:
http-server
*Now you can visit http://localhost:8080 to view your server*
***
## Start Server for API
### Install JSON Server
npm install -g json-server
### Start JSON Server
json-server --watch db.json
<file_sep>/05 - Counter for like&unlike/js/5.js
// Data 1
var app = new Vue({
el: '#app',
data: {
logoName: 'Anna Studio',
logoImg: 'img/sun.png',
subMessage: 'Welcome To Anna Studio.',
helloMessage: 'Nice To Meet You.',
buttonText: 'More',
coverImg: 'url(img/header-bg.jpg)',
teamMembers: [{
avatar: 'img/team/1.jpg',
name: 'Rulin',
jobTitle: '明日之星冰霸王'
},
{
avatar: 'img/team/2.jpg',
name: '<NAME>',
jobTitle: '天生傲嬌小柯南'
},
{
avatar: 'http://placekitten.com/g/225/225',
name: '<NAME>',
jobTitle: '全端打雜碼農'
}
],
customerName: '',
customerEmail: '',
customerPhone: '',
likeCounter: 896,
unlikeCounter: 9,
islike: false,
isunlike: false
},
methods: {
like: function (islike) {
// this.islike = !islike;
// if (this.isunlike) { this.isunlike = false; }
this.likeCounter = (this.islike) ? this.likeCounter - 1 : this.likeCounter + 1;
this.islike = !islike;
if (this.isunlike) { this.isunlike = false; this.unlikeCounter = this.unlikeCounter - 1; }
},
unlike: function (isunlike) {
// this.isunlike = !isunlike;
// if (this.islike) { this.islike = false;}
this.unlikeCounter = (this.isunlike) ? this.unlikeCounter - 1 : this.unlikeCounter + 1;
this.isunlike = !isunlike;
if (this.islike) { this.islike = false; this.likeCounter = this.likeCounter - 1; }
}
}
})
// Data 2
// var app = new Vue({
// el: '#app',
// data: {
// logoName: 'Cat Coffee',
// logoImg: 'img/hot-drink.png',
// subMessage: 'Welcome To Cat Coffee.',
// helloMessage: 'Cat Coffee With You.',
// buttonText: 'Love',
// coverImg: 'url(http://b.blog.xuite.net/b/8/5/6/11151381/blog_442951/txt/15327151/4.jpg)',
// teamMembers: [{
// avatar: 'img/team/1.jpg',
// name: 'Rulin',
// jobTitle: '明日之星冰霸王'
// },
// {
// avatar: 'img/team/2.jpg',
// name: '<NAME>',
// jobTitle: '天生傲嬌小柯南'
// },
// {
// avatar: 'http://placekitten.com/g/225/225',
// name: '<NAME>',
// jobTitle: '全端打雜碼農'
// }
// ],
// customerName: '',
// customerEmail: '',
// customerPhone: '',
// likeCounter: 896,
// unlikeCounter: 9,
// islike: false,
// isunlike: false
// },
// methods: {
// like: function (islike) {
// // this.islike = !islike;
// // if (this.isunlike) { this.isunlike = false; }
// this.likeCounter = (this.islike) ? this.likeCounter - 1 : this.likeCounter + 1;
// this.islike = !islike;
// if (this.isunlike) { this.isunlike = false; this.unlikeCounter = this.unlikeCounter - 1; }
// },
// unlike: function (isunlike) {
// // this.isunlike = !isunlike;
// // if (this.islike) { this.islike = false;}
// this.unlikeCounter = (this.isunlike) ? this.unlikeCounter - 1 : this.unlikeCounter + 1;
// this.isunlike = !isunlike;
// if (this.islike) { this.islike = false; this.likeCounter = this.likeCounter - 1; }
// }
// }
// })
| f3f5517cfa8182cdaef28357da7fe1e5f85e173e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | AnnaSu/vue-base-demo | d6e638b549217e2742e5b058616065d15b4cfe24 | 53ea5a0798dfbc743b3864aede61d811ca2ec4b7 |
refs/heads/master | <file_sep>exports.notFound = function(req, res){
res.status(404);
res.json({
error: 'Recurso não encontrado :('
});
};
exports.serverError = function(err, req, res){
res.status(err.status || 500);
res.json({
error: err.message
});
};<file_sep>module.exports = function(app){
var userRepository = app.repositories.user;
var userController = {
login: function(req, res){
var user = req.headers["user"];
var password = req.headers["password"];
var response = userRepository.login(user, password);
console.log(response);
res.json(response);
}
}
return userController;
} | 8ab74038ee562d419a0f698401614b84e7db9da6 | [
"JavaScript"
] | 2 | JavaScript | vmussak/programaEstagio | b9e6bd557952e3a5a7fbedd27ffe171d421450e1 | 6beb887a8055ef22e04ebe1702b6f6d83654db13 |
refs/heads/master | <repo_name>andreyselin/tmp_dis<file_sep>/src/frontend/env.ts
export const env = {
logger: {
batchSize: 85,
intervalMs: 2000,
},
baseUrl: 'not-used-as-url-base-yet',
};
<file_sep>/src/frontend/api.ts
import axios from "axios";
const apiAddress = path => `http://localhost:8080${ path }`;
export const api = {
join: async () => (await axios.post(apiAddress('/join'))).data
};
<file_sep>/src/backend/server.js
const AWS = require('aws-sdk');
const { v4: uuidv4 } = require('uuid');
const express = require ('express');
const path = require('path');
const bodyParser = require('body-parser');
const chime = new AWS.Chime({ region: 'us-east-1' });
// Set the AWS SDK Chime endpoint. The global endpoint is https://service.chime.aws.amazon.com.
chime.endpoint = new AWS.Endpoint(process.env.ENDPOINT || 'https://service.chime.aws.amazon.com');
const meetingTable = {};
const title = 'm1', region = 'eu-central-1', name = 'a1';
// Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
/////////////
// //
// API //
// //
/////////////
const app = express();
const port = 8080;
app.use(bodyParser.json());
app.use('/scripts', express.static(path.join(__dirname, '..', '..', 'dist/')));
app.get('/', (req, res, next) => {
const thePath = path.join(__dirname, '..', '..', 'public/index.html');
res.sendFile(thePath);
});
app.post('/join', async (req, res) => {
if (!meetingTable[title]) {
meetingTable[title] = await chime.createMeeting({
ClientRequestToken: uuidv4(),
MediaRegion: region,
ExternalMeetingId: title.substring(0, 64),
}).promise();
}
const meeting = meetingTable[title];
const attendee = await chime.createAttendee({
MeetingId: meeting.Meeting.MeetingId,
ExternalUserId: `${uuidv4().substring(0, 8)}#${name}`.substring(0, 64),
}).promise();
res.json({
JoinInfo: {
Meeting: meeting,
Attendee: attendee,
}
});
});
app.post('/end', async (req, res) => {
await chime.deleteMeeting({
MeetingId: meetingTable[title].Meeting.MeetingId,
}).promise();
res.json({});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
<file_sep>/src/frontend/Meeting.ts
import DefaultMeetingSession from "amazon-chime-sdk-js/build/meetingsession/DefaultMeetingSession";
import AudioVideoFacade from "amazon-chime-sdk-js/build/audiovideofacade/AudioVideoFacade";
import MeetingSession from "amazon-chime-sdk-js/build/meetingsession/MeetingSession";
import MeetingSessionConfiguration from "amazon-chime-sdk-js/build/meetingsession/MeetingSessionConfiguration";
import {api} from "./api";
import {createLogger, MyDeviceChangeObserver} from "./logger";
import DefaultDeviceController from "amazon-chime-sdk-js/build/devicecontroller/DefaultDeviceController";
import {AVObserver} from "./AVObserver";
import DefaultModality from "amazon-chime-sdk-js/build/modality/DefaultModality";
import DefaultActiveSpeakerPolicy from "amazon-chime-sdk-js/build/activespeakerpolicy/DefaultActiveSpeakerPolicy";
import VideoTile from "amazon-chime-sdk-js/build/videotile/VideoTile";
import VideoTileState from "amazon-chime-sdk-js/build/videotile/VideoTileState";
import {tileOrganizer} from "./TileOrganizer";
export class Meeting extends AVObserver {
roster = {};
meetingSession: MeetingSession | null = null;
audioVideo: AudioVideoFacade | null = null;
async initialize () {
try {
const joinInfo = (await api.join()).JoinInfo;
console.log({ joinInfo });
const configuration = new MeetingSessionConfiguration(joinInfo.Meeting, joinInfo.Attendee);
this.supplementConfig(configuration);
// original: initializeMeetingSession
const logger = createLogger(configuration);
const deviceController = new DefaultDeviceController(logger);
this.meetingSession = new DefaultMeetingSession(configuration, logger, deviceController);
this.audioVideo = this.meetingSession.audioVideo;
this.audioVideo.addDeviceChangeObserver(new MyDeviceChangeObserver());
this.setupDeviceLabelTrigger();
// await this.populateAllDeviceLists();
this.setupSubscribeToAttendeeIdPresenceHandler();
this.audioVideo.addObserver(this);
// Mute me and turn off speaker connections (not sure if it is connected initially)
// this.audioVideo.realtimeMuteLocalAudio();
// this.audioVideo.unbindAudioElement();
this.audioVideo.start();
await this.turnVideo(true);
} catch (e) {
console.log('error ==>', e);
}
}
videoTileDidUpdate(tileState: VideoTileState): void {
this.log(`video tile updated: ${JSON.stringify(tileState, null, ' ')}`);
if (!tileState.boundAttendeeId) {
return;
}
const tileIndex = tileOrganizer.acquireTileIndex(tileState.tileId as number, tileState.localTile) ;
const tileElement = document.getElementById(`tile-${tileIndex}`) as HTMLDivElement;
const videoElement = document.getElementById(`video-${tileIndex}`) as HTMLVideoElement;
console.log('tileIndex-tileIndex', tileIndex);
this.log(`binding video tile ${tileState.tileId} to ${videoElement.id}`);
this.audioVideo?.bindVideoElement(tileState.tileId as number, videoElement);
// this.tileIndexToTileId[tileIndex] = tileState.tileId;
// this.tileIdToTileIndex[tileState.tileId] = tileIndex;
tileElement.style.display = 'block';
this.layoutVideoTiles();
}
async turnVideo (mode) {
if (mode === true) {
const cameras = await (this.audioVideo as AudioVideoFacade).listVideoInputDevices();
await this.audioVideo?.chooseVideoInputDevice(cameras[0]);
}
}
setupSubscribeToAttendeeIdPresenceHandler(): void {
const handler = (
attendeeId: string,
present: boolean,
externalUserId?: string,
dropped?: boolean
): void => {
this.log(`${attendeeId} present = ${present} (${externalUserId})`);
if (!present) {
delete this.roster[attendeeId];
this.log(`${attendeeId} dropped = ${dropped} (${externalUserId})`);
return;
}
if (!this.roster[attendeeId]) {
this.roster[attendeeId] = {
name: externalUserId?.split('#').slice(-1)[0]
};
}
this.audioVideo?.realtimeSubscribeToVolumeIndicator(
attendeeId,
async (attendeeId: string, volume: number | null, muted: boolean | null, signalStrength: number | null) => {
if (!this.roster[attendeeId]) {
return;
}
if (volume !== null) {
this.roster[attendeeId].volume = Math.round(volume * 100);
}
if (muted !== null) {
this.roster[attendeeId].muted = muted;
}
if (signalStrength !== null) {
this.roster[attendeeId].signalStrength = Math.round(signalStrength * 100);
}
}
);
};
this.audioVideo?.realtimeSubscribeToAttendeeIdPresence(handler);
}
layoutVideoTiles(): void {
// @ts-ignore
// document.getElementById('console').innerHTML = document.getElementById('console').innerHTML + '<div>layoutVideoTiles called</div>'
}
////////////////////////
// //
// //
// Misc below //
// //
// //
////////////////////////
setupDeviceLabelTrigger(): void {
this.audioVideo?.setDeviceLabelTrigger(
async (): Promise<MediaStream> =>
await navigator.mediaDevices.getUserMedia({ audio: true, video: true })
);
}
log(str: string): void {
console.log(`[DEMO] ${str}`);
}
supplementConfig(configuration) {
configuration.enableWebAudio = false;
configuration.enableUnifiedPlanForChromiumBasedBrowsers = true;
configuration.attendeePresenceTimeoutMs = 5000;
configuration.enableSimulcastForUnifiedPlanChromiumBasedBrowsers = false;
}
}
<file_sep>/src/frontend/AVObserver.ts
import AudioVideoObserver from "amazon-chime-sdk-js/build/audiovideoobserver/AudioVideoObserver";
import MeetingSessionStatus from "amazon-chime-sdk-js/build/meetingsession/MeetingSessionStatus";
import MeetingSessionStatusCode from "amazon-chime-sdk-js/build/meetingsession/MeetingSessionStatusCode";
import VideoTileState from "amazon-chime-sdk-js/build/videotile/VideoTileState";
import MeetingSessionVideoAvailability from "amazon-chime-sdk-js/build/meetingsession/MeetingSessionVideoAvailability";
import ClientVideoStreamReceivingReport
from "amazon-chime-sdk-js/build/clientmetricreport/ClientVideoStreamReceivingReport";
import ClientMetricReport from "amazon-chime-sdk-js/build/clientmetricreport/ClientMetricReport";
import {tileOrganizer} from "./TileOrganizer";
const log = (...args) => console.log(args);
export class AVObserver implements AudioVideoObserver {
audioVideoDidStartConnecting(reconnecting: boolean): void {
log(`--AVObserver-1--- ${reconnecting}`);
}
audioVideoDidStart(): void {
log('--AVObserver-2--- session started');
}
audioVideoDidStop(sessionStatus: MeetingSessionStatus): void {
log(`--AVObserver-3--- session stopped from ${JSON.stringify(sessionStatus)}`);
}
videoTileDidUpdate(tileState: VideoTileState): void {
log(`--AVObserver-4--- video tile updated: ${JSON.stringify(tileState, null, ' ')}`);
}
videoTileWasRemoved(tileId: number): void {
log(`--AVObserver-5--- : ${ tileId }`);
}
videoAvailabilityDidChange(availability: MeetingSessionVideoAvailability): void {
log(`--AVObserver-6--- : ${ JSON.stringify(availability) }`);
}
estimatedDownlinkBandwidthLessThanRequired(estimatedDownlinkBandwidthKbps: number, requiredVideoDownlinkBandwidthKbps: number ): void {
log(`--AVObserver-7--- : Estimated downlink bandwidth is ${estimatedDownlinkBandwidthKbps} is less than required bandwidth for video ${requiredVideoDownlinkBandwidthKbps}`);
}
videoNotReceivingEnoughData(videoReceivingReports: ClientVideoStreamReceivingReport[]): void {
log(`--AVObserver-8--- : One or more video streams are not receiving expected amounts of data ${JSON.stringify(videoReceivingReports)}`);
}
metricsDidReceive(clientMetricReport: ClientMetricReport): void {
log(`--AVObserver-9--- : ${ JSON.stringify(clientMetricReport) } `);
}
connectionDidBecomePoor(): void {
log('--AVObserver-10--- : connection is poor');
}
connectionDidSuggestStopVideo(): void {
log('--AVObserver-11--- : suggest turning the video off');
}
connectionDidBecomeGood(): void {
log('--AVObserver-12--- : suggest turning the video off');
}
videoSendDidBecomeUnavailable(): void {
log('--AVObserver-13--- : sending video is not available');
}
}
<file_sep>/src/frontend/TileOrganizer.ts
class TileOrganizer {
// this is index instead of length
static MAX_TILES = 3;
static LOCAL_VIDEO_INDEX = 2;
private tiles: { [id: number]: number } = {};
public tileStates: {[id: number]: boolean } = {};
acquireTileIndex(tileId: number, isLocalTile: boolean): number {
for (let index = 0; index <= TileOrganizer.MAX_TILES; index++) {
if (this.tiles[index] === tileId) {
return index;
}
}
for (let index = 0; index <= TileOrganizer.MAX_TILES; index++) {
if (!(index in this.tiles)) {
if (isLocalTile) {
this.tiles[TileOrganizer.LOCAL_VIDEO_INDEX] = tileId;
return TileOrganizer.LOCAL_VIDEO_INDEX;
}
this.tiles[index] = tileId;
return index;
}
}
throw new Error('no tiles are available');
}
releaseTileIndex(tileId: number): number {
for (let index = 0; index <= TileOrganizer.MAX_TILES; index++) {
if (this.tiles[index] === tileId) {
delete this.tiles[index];
return index;
}
}
return TileOrganizer.MAX_TILES;
}
}
export const tileOrganizer = new TileOrganizer();
<file_sep>/src/frontend/index.ts
// declare const window: any;
import {Meeting} from "./Meeting";
window.onload = async () => {
const meeting = new Meeting();
(window as any).meeting = meeting;
meeting.initialize();
(window as any).showTiles = () => {
meeting.audioVideo?.startLocalVideoTile();
};
};
<file_sep>/src/frontend/logger.ts
import {
Logger,
ConsoleLogger,
LogLevel,
MeetingSessionPOSTLogger
} from "amazon-chime-sdk-js";
import MultiLogger from "amazon-chime-sdk-js/build/logger/MultiLogger";
import {env} from "./env";
import DeviceChangeObserver from "amazon-chime-sdk-js/build/devicechangeobserver/DeviceChangeObserver";
export const createLogger = (configuration) => {
let logger: Logger;
const logLevel = LogLevel.INFO;
const consoleLogger = logger = new ConsoleLogger('SDK', logLevel);
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
logger = consoleLogger;
} else {
logger = new MultiLogger(
consoleLogger,
new MeetingSessionPOSTLogger(
'SDK',
configuration,
env.logger.batchSize,
env.logger.intervalMs,
`${env.baseUrl}logs`,
logLevel
),
);
}
return logger;
};
export class MyDeviceChangeObserver implements DeviceChangeObserver {
audioInputsChanged(_freshAudioInputDeviceList: MediaDeviceInfo[]): void {
console.log('--myDeviceChangeObserver-1--');
}
videoInputsChanged(_freshVideoInputDeviceList: MediaDeviceInfo[]): void {
console.log('--myDeviceChangeObserver-2--');
}
audioOutputsChanged(_freshAudioOutputDeviceList: MediaDeviceInfo[]): void {
console.log('--myDeviceChangeObserver-3--');
}
audioInputStreamEnded(deviceId: string): void {
console.log('--myDeviceChangeObserver-4--');
}
videoInputStreamEnded(deviceId: string): void {
console.log('--myDeviceChangeObserver-5--');
}
}
| d6e0e31045e2d3e8e74974061451f99a56db9a7a | [
"JavaScript",
"TypeScript"
] | 8 | TypeScript | andreyselin/tmp_dis | 9774bbc23d1504ba0c9086db6f404648b718cfc5 | 59b81f3d3ab889c5bbe474da70b6cff87cef964c |
refs/heads/master | <repo_name>lovefeier/python1<file_sep>/python1-1
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print('hello world')
#python 3.0 使用('')
#2.0使用""
| 69522a8d36b4fb0b94c6dad1d4338cc0f13ffc4a | [
"Python"
] | 1 | Python | lovefeier/python1 | 56ded630d84e9825f25eed10cf5e5d24b4cd9551 | d57aab2c3730123232f2e7e4d3079456a69360a9 |
refs/heads/master | <file_sep>(function($){
$(function(){
var DrawTool = {} || DrawTool;
DrawTool.loadsvg = function(svgurl){
var d = new $.Deferred;
$('#dom').load(svgurl,function(){
d.resolve();
})
return d.promise();
}
alert('test');
});
})(jQuery);
<file_sep>
(function($){
$(function(){
var DrawTool = {} || DrawTool;
DrawTool.loadsvg = function(svgurl){
var d = new $.Deferred;
$('#dom').load(svgurl,function(){
$(window).on('resize orientationchange',function(){
DrawTool.resetItemsize();
});
$(window).trigger('resize');
d.resolve();
})
return d.promise();
}
DrawTool.makebtn = function(){
var items = [{"btnsrc":"img/btn01.png","svgdata":"svg/01.svg"},
{"btnsrc":"img/btn02.png","svgdata":"svg/02.svg"},
{"btnsrc":"img/btn03.png","svgdata":"svg/03.svg"},
{"btnsrc":"img/btn04.png","svgdata":"svg/04.svg"},
{"btnsrc":"img/btn05.png","svgdata":"svg/05.svg"},
{"btnsrc":"img/btn06.png","svgdata":"svg/06.svg"}
];
var colors = [
{'color':'#a7dbd1'},
{'color':'#c4e6be'},
{'color':'#b5cfe0'},
{'color':'#cebed4'},
{'color':'#d9d0c9'},
{'color':'#efd25c'},
{'color':'#62afa0'},
{'color':'#50946c'},
{'color':'#3d6c8b'},
{'color':'#906d9f'},
{'color':'#5f4f43'},
{'color':'#e59b27'},
{'color':'#42746a'},
{'color':'#225c3a'},
{'color':'#1c4057'},
{'color':'#553562'},
{'color':'#412e1f'},
{'color':'#7d5d2b'},
{'color':'#e0b173'},
{'color':'#eaa1ba'},
{'color':'#ec9f97'},
{'color':'#FFFFFF'},
{'color':''},
{'color':''},
{'color':'#d68148'},
{'color':'#ce547f'},
{'color':'#c1554a'},
{'color':'#d4d5d5'},
{'color':''},
{'color':''},
{'color':'#a6541e'},
{'color':'#923455'},
{'color':'#923c33'},
{'color':'#4d5556'},
{'color':''},
{'color':''}
];
var items_len = items.length,colors_len = colors.length,compiled = _.map(items,function(json,key){ json.key =key;json.max = items_len;json.setnum = 4; return _.template($('#itembtn').html())(json);});
$('#itemArea').html(compiled.join(''));
compiled = _.map(colors,function(json,key){ json.key = key;json.max = colors_len;json.setnum = 18;return _.template($('#colorbtn').html())(json);});
$('#colorBtnArea').html(compiled.join(''));
$('#colorBtnArea li span').each(function(){
var col = $(this).data('color');
$(this).css('background',col);
});
$('#itemArea').owlCarousel({
loop:false,
margin:0,
items:1,
autoHeight:false,
nav:false});
var colors_num = Math.ceil(colors.length / 20),
Controller = function(o){
this.startX = null;
this.startY = null;
this.movedX = null;
this.movedY = null;
this.counter = 0;
this.flgx = null;
this.max = o.max;
this.movespan = $(window).width();
this.target = o.target;
};
Controller.prototype = {
'init':function(){
var _self = this;
$(window).on('load resize',function(){
_self.setMoveSpan = $(window).width();
})
},
'handler':function(e,target){
var touch = e.originalEvent.changedTouches[0],
_self = this;
if(e.type=='touchstart'){
_self.startX = parseInt(target.get(0).scrollLeft);
}
if(e.type == 'touchend'){
var flg = parseInt(target.get(0).scrollLeft - _self.startX);
if(Math.abs(flg) < 10) return;
_self.flgx = (flg > 0) ? 1 : -1;
_self.target.animate({'scrollLeft':(_self.CounterCheck(_self.flgx) * _self.movespan)},400);
}
},
'CounterCheck':function(n){
var _self = this;
if(_self.max < n){
_self.counter = _self.max;
}else if(n < 0){
_self.counter = 0;
}else{
_self.counter = _self.counter + n;
}
return _self.counter;
},
'setMoveSpan':function(n){
var _self = this;
_self.moveSpan = n;
}
}
if(colors_num > 0){
$(window).on('resize',function(){
var single_wid = $(window).width(),wid = colors_num * $(window).width();
$('#colorBtnArea').width(wid);
$('#colorBtnArea').find('ul').width(single_wid);
});
$(window).trigger('resize');
}
var controller = new Controller({max:colors_num,target:$('#colorbox')});
controller.init();
$('#colorbox').bind('touchstart touchend',function(e){
controller.handler(e,$(this));
});
}
DrawTool.loaddata = function(){
var itembox = $('#itembox'),
step1 = $('.step1'),
step2 = $('.step2');
itembox.find('li .item').on('click',function(){
var parent = $(this).parent(),
loadtarget = $(this).data('svg');
//step1.hide();
itembox.find('li').removeClass('selectedItem');
parent.addClass('selectedItem');
step2.show();
DrawTool.loadsvg(loadtarget).then(function(){
DrawTool.init();
});
return false;
});
}
DrawTool.resetItemsize = function(){
$('#dom svg').height($(window).width());
$('#dom').css('min-height',$('#dom').width());
}
DrawTool.resize = function(){
var svg = $('svg'),
pathobj = $('path,circle,polygon'),
rect = svg.find('rect'),
scale = .8,
size = 740,
posi = (size - (size * scale)) / 2;
svg.attr('viewBox','0 0 740 740');
rect.attr('width',740);
rect.attr('height',740);
pathobj.attr('transform','matrix(.8,0,0,.8,' + posi + ',' +posi +')');
}
DrawTool.init = function(){
var WIDTH = 640,
HEIGHT = 640,
//id = $('#dom').data('id'),
id=$.cookie('sid'),
downloadBtn = $('#download'),
make = $('#make'),
colorbox = $('#colorbox'),
makebox = $('#makebox'),
itembox = $('#itembox'),
step1 = $('.step1'),
step2 = $('.step2'),
step3 = $('.step3'),
ImageToBase64 = function(img, mime_type) {
// New Canvas
var canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
// Draw Image
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0,WIDTH,HEIGHT);
// To Base64
return canvas.toDataURL(mime_type);
},
color = '',
selectObj = '',
pathobj = $('path,rect,circle,polygon'),
color = '',
picker = $('.jscolor'),
bgcolor;
var edit = {} || edit;
edit.wrap = function($target){
var selectPath = $('<rect>',{'id':'selectedPath'});
$target.wrap(selectPath);
}
edit.rebuild = function (){
if($('#selectedPath').size()) $('#selectedPath').replaceWith($('#selectedPath').html());
}
make.off().on('click', function() {
$('#dom').css('opacity',0);
//DrawTool.resize();
var svg = $('svg').get(0),
data = new XMLSerializer().serializeToString(svg),
url = "data:image/svg+xml;charset=utf-8;base64," + btoa(unescape(encodeURIComponent(data))),
img = $('<img>',{'class':'dlsvg',width:WIDTH,height:HEIGHT});
background = $('rect').eq(0).css('fill');
img.on('load',function(){
var src = ImageToBase64($(this).get(0),'image/png');
//var src = $(this).attr('src');
var Render = {
'response':function(res){
//var $img = $('<img>',{'src':res.data,width:WIDTH,height:HEIGHT,'class':'makeimg','crossOrigin':'Anonymous'});
var $img = $('<img>',{'src':res.data,width:WIDTH,height:HEIGHT,'class':'makeimg'});
$('#dom').html($img);
if(navigator.userAgent.indexOf('Android 4.0') > -1 || navigator.userAgent.indexOf('Android 4.1') > -1 || navigator.userAgent.indexOf('Android 4.2') > -1 || navigator.userAgent.indexOf('Android 4.3') > -1){
var a = $('<a>',{'class':'attention','href':res.data,'text':'※保存できない場合はこちらをクリックして、リンク先画像を保存してください'});
$('#dom').append(a);
}
$('#dom').css('opacity',1);
setTimeout(function(){$('.makeimg').addClass('bounceIn animated');},400);
setTimeout(function(){$('.fukidashi').show().addClass('bounceIn animated');},800);
make.remove();
itembox.remove();
colorbox.remove();
step1.hide();
step2.hide();
step3.show();
$(window).off().on('resize orientationchange',function(){
DrawTool.resetItemsize();
});
}},
request = {
'url':document.URL,
'type':'POST',
'data':{
image:src,
width:WIDTH,
height:HEIGHT,
id:id,
background:background
},
'dataType':'json',
'success':function(res){
Render.response(res);
},
'error':function(jqXHR,textStatus,errorThrown){
console.log('------render error----');
console.log(jqXHR, textStatus, errorThrown);
make.remove();
}
}
$.ajax(request);
});
//img.get(0).setAttribute('crossOrigin','Anonymous')
img.get(0).setAttribute('src', url);
return false;
});
pathobj.off().on('click', function() {
selectObj = $(this);
//pathobj.css('opacity', 1);
//selectObj.css('opacity', .5);
pathobj.removeAttr('class');
selectObj.attr('class','selectedpath');
//edit.rebuild();
//edit.wrap($(this));
//selectedObj = String(selectObj.attr('class')).replace('pathobj ', '');
//$('.selectedObj').text('Selected:' + selectedObj);
//if(color) selectObj.css('fill', color);
});
/*ピッカーでテスト
picker.on('change', function() {
if (!selectObj) return;
color = '#' + $(this).val();
//$('.' + selectedObj).css('fill', color);
selectObj.css('fill', color);
pathobj.css('opacity', 1);
});
*/
//itembox.removeClass('active');
makebox.addClass('active');
colorbox.addClass('active');
colorbox.find('li span').off().on('click',function(){
color = $(this).data('color');
if(!color) return false;
if(selectObj) selectObj.css('fill', color);
if(pathobj) pathobj.css('opacity', 1);
colorbox.find('li span').removeClass('selected');
$(this).addClass('selected');
return false;
});
}
DrawTool.makebtn();
DrawTool.loaddata();
});
})(jQuery);
<file_sep><?php
function isAjax()
{
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
return true;
}
return false;
}
$response = array();
//---------------セッションスタート
session_start();
$session_id = sha1(session_id());
//---------------ajax通信でトークンが不一致の場合
if(isAjax() && $_SERVER["REQUEST_METHOD"] != "POST" && $_POST['id'] != sha1(session_id())){
$response["data"] = 'error token number';
header("Content-Type: application/json; charset=utf-8");
echo json_encode($response);
exit;
}
//---------------ajax通信
if(isAjax() && $_POST['id'] == sha1(session_id())){
try{
$img_data = $_POST['image'];
$img_data = preg_replace('/data:[^,]+,/i','', $img_data);
$img_data = base64_decode($img_data);
$image = imagecreatefromstring($img_data);
imagesavealpha($image, TRUE);
$path = date('Y/m');
$upload_dir = './upload/';
$dir = $upload_dir . $path;
if(!file_exists($dir)){
clearstatcache();
mkdir($dir, 0777, TRUE);
}
do{
$filename = $dir . '/' . mt_rand() . '.png';
} while(file_exists($filename));
$filename = str_replace("\r\n", '', htmlspecialchars($filename));
if(isset($filename)){
imagepng($image,$filename,9);
$response["data"] = $filename;
}else{
$response["response_error"] = "error";
}
}catch(Exception $e){
$response['response_error'] = $e->getMessage();
}
header("Content-Type: application/json; charset=utf-8");
echo json_encode($response);
exit;
}
?>
<file_sep><?php
class Makeimg {
public static $response = array();
public static $source = '';
public static function isAjax(){
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
return true;
}
return false;
}
public static function sessionStart(){
session_start();
setcookie('sid',self::getSessionId());
}
public static function getSessionId(){
return sha1(session_id());
}
public static function sessionEnd(){
setcookie('sid', '', time() - 1800);
$_SESSION = array();
session_destroy();
}
public static function getDirList($dir) {
$files = scandir($dir);
$files = array_filter($files, function ($file) { // 注(1)
return !in_array($file, array('.', '..'));
});
return $files;
}
public function __construct(){
}
public static function rmfile($dir){
if ($handle = opendir("$dir")) :
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..") {
if (is_dir("$dir/$item")) {
Makeimg::rmfile("$dir/$item");
} else {
unlink("$dir/$item");
}
}
}
closedir($handle);
rmdir($dir);
endif;
}
public static function create_svg_and_png($filename,$img_data = ''){
if(empty($img_data)):
$img_data = self::$source;
endif;
$tmpsvg_filename = str_replace(".png",".svg",$filename);
file_put_contents($tmpsvg_filename,$img_data);
//ImageMagick
//$cmd = '/usr/bin/convert '.$tmpsvg_filename.' '.$filename;
//system($cmd);
//Imagick
$im = new Imagick();
$im->readImageBlob($tmpsvg_filename);
$im->setImageFormat("png24");
unlink($tmpsvg_filename);
}
public static function run(){
//---------------ajax通信でトークンが不一致の場合
if(Makeimg::isAjax() && ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST['id'] != sha1(session_id()))){
Makeimg::$response["data"] = 'error token number';
header("Content-Type: application/json; charset=utf-8");
echo json_encode(Makeimg::$response);
Makeimg::sessionEnd();
exit;
}
if(Makeimg::isAjax() && $_POST['id'] == sha1(session_id())){
//---------------ajax通信
try{
$img_data = $_POST['image'];
$img_data = preg_replace('/data:[^,]+,/i','', $img_data);
$img_data = base64_decode($img_data);
Makeimg::$source = $img_data;
/*canvasでpngにデコード済の場合は以下で対応可能
$image = imagecreatefromstring($img_data);
imagesavealpha($image, TRUE);
*/
$path = date('Ymd');
$pastpath = date('Ymd',strtotime("-1 day"));
$upload_dir = './upload/';
$dirlist = Makeimg::getDirList($upload_dir);
$dir = $upload_dir . $path;
if(!empty($dirlist)):
//1日前のディレクトリを削除
foreach($dirlist as $d):
if($d <= $pastpath){
if(file_exists($upload_dir . $d)):
//rmdir($upload_dir . $d);
Makeimg::rmfile($upload_dir . $d);
endif;
}
endforeach;
endif;
if(!file_exists($dir)){
clearstatcache();
mkdir($dir, 0777, TRUE);
}
do{
$filename = $dir . '/' . mt_rand() . '.png';
} while(file_exists($filename));
$filename = str_replace("\r\n", '', htmlspecialchars($filename));
if(isset($filename)){
/*ファイル生成処理*/
Makeimg::create_svg_and_png($filename);
/*CANVASでPNGデータにデコード済の場合は以下でOK
imagepng($image,$filename,9);
*/
Makeimg::$response["data"] = $filename;
}else{
Makeimg::$response["response_error"] = "error";
}
}catch(Exception $e){
Makeimg::$response['response_error'] = $e->getMessage();
}
Makeimg::sessionEnd();
header("Content-Type: application/json; charset=utf-8");
echo json_encode(Makeimg::$response);
exit;
}
}
}
Makeimg::sessionStart();
Makeimg::run();
?>
<file_sep><?php
include_once(dirname(__FILE__) . '/app/functions.inc' );
?>
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>塗り絵アプリ</title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="js/owlcarousel/assets/owl.carousel.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/animate.css">
<!--[if lt IE 9]>
<script src="js/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="wrapper row">
<div class="colorpicker">
<span class="row">
<input class="jscolor col-12" value="ab2567">
</span>
</div>
<article>
<header class="headerArea">
<h1>
<img src="img/thankyou_img01.png" alt="">
</h1>
<div class="txArea Area-01 fireworks">
<p>好きな色でキャラクターを塗って画像を保存しましょう。</p>
</div>
</header>
<p class="nuriettl">
<img src="img/thankyou_img03.png" alt="" id="mask">
</p>
<div class="txArea Area-02">
<div class="exTextArea">
<p class="tx-01">スマホで遊べるぬりえです。好きな色にぬってオリジナルの動物を作ることができます。作ったぬりえはLINEやFacebookのアイコンにもすることができます。</p>
</div>
<p class="step1 tx-02">
<img src="img/thankyou_img04_ttl.png" alt="1,ぬるキャラを選ぶ">
</p>
</p>
<div class="active step1" id="itembox">
<div id="itemArea" class="cf"></div>
<ul class="arr">
<li class="left-arr"><img src="img/arr_left.png" alt=""></li>
<li class="right-arr"><img src="img/arr_right.png" alt=""></li>
</ul>
</div>
<div class="drawArea">
<div class="fukidashi">
<img src="img/think_fukidashi.png" alt="画像を長押しして保存してください">
</div>
<div id='dom' class="domArea col-12"></div>
</div>
<div class="step2">
<img src="img/thankyou_img05.png" alt="2,エリアをタップして塗る">
</div>
<div class="colorboxWrap step2">
<div class="" id="colorbox">
<div id="colorBtnArea" ></div>
</div>
<ul class="arr">
<li class="left-arr"><img src="img/arr_left.png" alt=""></li>
<li class="right-arr"><img src="img/arr_right.png" alt=""></li>
</ul>
</div>
<div id="makebox">
<span id="make" class="btn">
<img src="img/thankyou_saveBtn.png" alt="決定する">
</span>
</div>
<div class="step3">
<a href="/">
<img src="img/btn_return.png" alt="">
</a>
</div>
</article>
<footer>
<small>2019 Example. All Rights Reserved.</small>
</footer>
</div>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>-->
<script src="js/jquery.js"></script>
<script src="js/jscolor.min.js"></script>
<!--<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>-->
<script src="js/underscore.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/owlcarousel/owl.carousel.min.js"></script>
<script src="js/functions.js"></script>
<script type="text/template" id="itembtn">
<% if(key==0){ %>
<ul class="cf">
<%}%>
<% if(key==max){ %>
</ul>
<%}%>
<% if(key%setnum==0&&key!=0&&key!=max){ %>
</ul><ul class="cf">
<%}%>
<li><span class="border"></span><span class="item" data-svg="<%= svgdata %>"><img src="<%= btnsrc %>"></span></li>
</script>
<script type="text/template" id="colorbtn">
<% if(key==0){ %>
<ul class="cf">
<%}%>
<% if(key==max){ %>
</ul>
<%}%>
<% if(key%setnum==0&&key!=0&&key!=max){ %>
</ul><ul class="cf">
<%}%>
<li>
<% if(color!=''){ %>
<span data-color="<%= color %>" ></span>
<% }else{ %>
<span></span>
<% } %>
</li>
</script>
</body>
</html>
| efdbad497213a4ba1aa0958a60b3b435f4eef1b7 | [
"JavaScript",
"PHP"
] | 5 | JavaScript | dev-fukushima/app-nurie | f5e4ef257ba79f86717f0f2343a571e9a4fd1c7a | 0c8507772532ad5608eb2c48a163e84f2f141e74 |
refs/heads/master | <repo_name>mastenl/Capstone-mleonard14<file_sep>/TicTacToe.cpp
#include "TicTacToe.h"
#include <string>
#include <iostream>
#include <fstream>
//TicTacToe::TicTacToe()
void TicTacToe::boardReset()
{
char posNumber='0';
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
posNumber++;
board[i][j]=posNumber;
}
}
}
bool TicTacToe::welcome()
{
std::string answer;
bool play;
bool valid=false;
std::ifstream file("welcome.txt");
if (file.is_open())
std::cout << file.rdbuf();
file.close();
while(valid==false)
{
std::cin>>answer;
if(answer == "y")
{
play = true;
valid=true;
}
else if(answer == "n")
{
std::cout << ":( ok, Goodbye."<<std::endl;
play= false;
valid=true;
}
else
{
std::cout << "Please input a proper answer. (y/n)" << std::endl;
continue;
}
}
return play;
}
void TicTacToe::drawBoard()
{
std::cout << " | | " << std::endl;
std::cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << std::endl;
std::cout << "____|_____|____" << std::endl;
std::cout << " | | " << std::endl;
std::cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << std::endl;
std::cout << "____|_____|____" << std::endl;
std::cout << " | | " << std::endl;
std::cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << std::endl;
std::cout << " | | " << std::endl;
}
void TicTacToe::place(char &player)
{
std::string move;
bool validMove=false;
std::cout <<"Enter the position you would like to mark."<<std::endl;
while(validMove==false)
{
std::cin >> move;
if( move == "1" && board[0][0]!='X' && board[0][0]!='O')//checks if valid move
{
board[0][0] = player;//place marker
validMove=true;
}
else if(move == "2" && board[0][1]!='X' && board[0][1]!='O')
{
board[0][1] = player;
validMove=true;
}
else if(move == "3" && board[0][2]!='X' && board[0][2]!='O')
{
board[0][2] = player;
validMove=true;
}
else if(move == "4" && board[1][0]!='X' && board[1][0]!='O')
{
board[1][0] = player;
validMove=true;
}
else if(move == "5" && board[1][1]!='X' && board[1][1]!='O')
{
board[1][1] = player;
validMove=true;
}
else if(move == "6" && board[1][2]!='X' && board[1][2]!='O')
{
board[1][2] = player;
validMove=true;
}
else if(move == "7" && board[2][0]!='X' && board[2][0]!='O')
{
board[2][0] = player;
validMove=true;
}
else if(move == "8" && board[2][1]!='X' && board[2][1]!='O')
{
board[2][1] = player;
validMove=true;
}
else if(move == "9" && board[2][2]!='X' && board[2][2]!='O')
{
board[2][2] = player;
validMove=true;
}
else
{
std::cout<<"Invalid move"<<std::endl;
continue;
}
}
}
char TicTacToe::switchTurns(int turns)
{
if (turns==1||turns==3||turns==5||turns==7||turns==9)
{
player = 'X';
}
else
{
player = 'O';
}
return(player);
}
bool TicTacToe::checkWinner(int turns)
{
bool winner=false;
bool tieGame=false;
if(board[0][0] == board[0][1] && board[0][1] == board[0][2])
{
winner=true;
}
else if(board[1][0] == board[1][1] && board[1][1] == board[1][2])
{
winner=true;
}
else if(board[2][0] == board[2][1] && board[2][1] == board[2][2])
{
winner=true;
}
else if(board[0][0] == board[1][0] && board[1][0] == board[2][0])
{
winner=true;
}
else if(board[0][1] == board[1][1] && board[1][1] == board[2][1])
{
winner=true;
}
else if(board[0][2] == board[1][2] && board[1][2] == board[2][2])
{
winner=true;
}
else if(board[0][0] == board[1][1] && board[1][1] == board[2][2])
{
winner=true;
}
else if(board[0][2] == board[1][1] && board[1][1] == board[2][0])
{
winner=true;
}
else if(turns>9 && winner==false)
{
std::cout<<"Tie Game!"<<std::endl;
tieGame=true;
return(tieGame);
}
if(winner==true)
{
if(player == 'X')
{
std::cout << std::endl << "Congratulations Player 1! You Win!" << std::endl;
}
else
{
std::cout << std::endl << "Congratulations Player 2! You Win!" << std::endl;
}
}
return(winner);
}
<file_sep>/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "TicTacToe.h"
using namespace std;
int main()
{
bool initiate=false;
TicTacToe game;
int turns=1;
char player;
initiate = game.welcome();
while(initiate==true)
{
game.boardReset();
turns=1;
while(game.checkWinner(turns)==false)
{
player=game.switchTurns(turns);
game.drawBoard();
game.place(player);
turns++;
continue;
}
game.drawBoard();
initiate = game.welcome();
}
return 0;
}
<file_sep>/TicTacToe.h
#ifndef _TicTacToe_H_
#define _TicTacToe_H_
#include <string>
#include <vector>
class TicTacToe
{
private:
char board[3][3];
public:
char player;
void boardReset();
bool welcome();
void drawBoard();
char switchTurns(int);
void place(char &player);//move
bool checkWinner(int);
};
#endif
<file_sep>/README.md
# Capstone-mleonard14
# Input/Output
I needed to know where the player wanted to put their piece so I outputted a simple message asking them.
Then I had them input the position that they wanted to put it in.
[TicTacToe.cpp lines 81,86](/TicTacToe.cpp))
#Control Flow
Here I used if and its counter part else if in order to set up conditions to tell if the user can mark in that position or not. I also used an else in order to call any inputs that are not a position "invalid".
[TicTacToe.cpp lines 87-136](/TicTacToe.cpp))
#Iteration
##while
I put a while loop here so I could run the game in a loop until the game is finished.
[main.cpp lines 23-31](/main.cpp))
##for
put a nested for loop in for my array. This will allow each square to have a sequential number.
[TicTacToe.cpp lines 10-17](/TicTacToe.cpp))
#Data Structure
##Array
I declare an array here so I can reference it throughout my code and I only need 3x3 square.
[TicTacToe.h line 9](/TicTacToe.h))
#Function
##void function
I have a function that prints out the Tic-Tac-Toe board. Does not need to return anything so it is a void.
[TicTacToe.cpp lines 58-73](/TicTacToe.cpp))
##pass-by-reference
Player is passed by reference so that we can tell if it is 'X'or 'O' that is being placed down in a
position chosen by the player.
[TicTacToe.cpp lines 77-139](/TicTacToe.cpp))
#non-void type function
I have a function that switches the character of 'X' to 'O' and vice versa. Because it switched what player was equal too I needed the function to return a char.
[TicTacToe.cpp lines 141-153](/TicTacToe.cpp))
#File IO
I have it open a file called "welcome.txt" and it prints out the entire file as a greeting. It is a roundabout way of doing it but it has the correct effect.
[TicTacToe.cpp lines 25-28](/TicTacToe.cpp))
#Class
Here I declare a class called TicTacToe so that I am able to easily pass information between files.
[TicTacToe.h lines 1-20](/TicTacToe.h))
| f4547af2242cf13d98e2bf74f0be6fa92ca0b9a7 | [
"Markdown",
"C++"
] | 4 | C++ | mastenl/Capstone-mleonard14 | 48a81a22f35f5e26b3be3347fffe056efcc641bb | f77b64ed752f484089a8a47eb504490a96d74c2c |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
namespace PerceptronVisualisation
{
public partial class MainForm : Form
{
Perceptron perceptron;
List<Point> points;
float LINE_A = 1;
float LINE_B = 0;
Func<float, float> function;
int trainings = 0;
int wrongPoints = 0;
bool autoTrain = false;
public MainForm()
{
InitializeComponent();
perceptron = new Perceptron();
InfoLabel.Text = perceptron.getWeights();
points = new List<Point>();
function = new Func<float, float>(x => (LINE_A)*x + LINE_B);
UpdateInfo();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Draw();
}
protected void GetLineValues()
{
var form = new LineEnterForm();
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
LINE_A = form.a;
LINE_B = form.b;
function = new Func<float, float>(x => (LINE_A) * x + LINE_B);
points = new List<Point>();
perceptron.ReInit();
trainings = 0;
}
}
protected void Draw()
{
Bitmap bm = new Bitmap(pictureBox.Width, pictureBox.Height);
Graphics formGraphics = Graphics.FromImage(bm);
Pen blackPen = new Pen(Color.Black);
Pen redPen = new Pen(Color.Red);
wrongPoints = 0;
foreach (Point p in points)
{
float[] inputs = { p.x, p.y, p.bias};
int target = p.label;
int guess = perceptron.Guess(inputs);
Brush brush;
if (target == guess)
{
brush = new SolidBrush(Color.Green);
}
else
{
brush = new SolidBrush(Color.Red);
wrongPoints++;
}
formGraphics.DrawEllipse(blackPen, pictureBox.Width/2 + p.x, pictureBox.Height / 2 - p.y, 10, 10);
formGraphics.FillEllipse(brush, pictureBox.Width / 2 + p.x, pictureBox.Height / 2 - p.y, 10, 10);
brush.Dispose();
}
if (autoTrain)
{
DoTraining();
}
formGraphics.DrawLine(blackPen, pictureBox.Width / 2, 0, pictureBox.Width / 2, pictureBox.Width);
formGraphics.DrawLine(blackPen, 0, pictureBox.Height / 2, pictureBox.Width, pictureBox.Height / 2);
formGraphics.DrawLine(redPen, 0, pictureBox.Height/2 - function(- pictureBox.Width / 2), pictureBox.Width, pictureBox.Height / 2 - function(pictureBox.Width/2));
var pfunction = perceptron.GetPrediction();
formGraphics.DrawLine(blackPen, 0, pictureBox.Height / 2 - pfunction(-pictureBox.Width / 2), pictureBox.Width, pictureBox.Height / 2 - pfunction(pictureBox.Width / 2));
pictureBox.Image = bm;
blackPen.Dispose();
redPen.Dispose();
formGraphics.Dispose();
}
protected void UpdateInfo()
{
var sb = new StringBuilder();
float pr_a = 0, pr_b = 0;
perceptron.GetPredictedValues(out pr_a, out pr_b);
sb.AppendFormat("Actual line: {0}x + ({1})\n\nPredictedLine: {2}x + ({3})\n\nError:\n\tA: {4}\n\tB: {5}\n\n", LINE_A, LINE_B, pr_a, pr_b, Math.Abs(LINE_A-pr_a), Math.Abs(LINE_B-pr_b));
sb.AppendFormat("Number of trainings: {0}\n", trainings);
sb.AppendFormat("Number of circles: {0} (errors: {1})", points.ToArray().Length, wrongPoints);
CurrentStatusLabel.Text = sb.ToString();
ModeLabel.Text = String.Format("AUTO MODE: {0}", autoTrain ? "ON" : "OFF");
}
protected void DoTraining()
{
foreach (Point p in points)
{
float[] inputs = { p.x, p.y, p.bias };
perceptron.Train(inputs, p.label);
}
if (wrongPoints != 0)
{
trainings += 1;
}
UpdateInfo();
}
private void pictureBox_MouseClick(object sender, MouseEventArgs e)
{
DoTraining();
}
private void pictureBox_Paint(object sender, PaintEventArgs e)
{
Draw();
InfoLabel.Text = perceptron.getWeights();
}
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.Enter: case Keys.A:
points.Add(new Point(function));
UpdateInfo();
break;
case Keys.R:
points = new List<Point>();
UpdateInfo();
break;
case Keys.Q:
perceptron.ReInit();
trainings = 0;
InfoLabel.Text = perceptron.getWeights();
UpdateInfo();
break;
case Keys.U:
points = new List<Point>();
for(int i = 0; i<200; i++)
{
points.Add(new Point(function));
Thread.Sleep(1);
}
Draw();
UpdateInfo();
break;
case Keys.T:
DoTraining();
break;
case Keys.B:
autoTrain = autoTrain ? false : true;
UpdateInfo();
break;
case Keys.L:
Task t = new Task(() => { GetLineValues(); });
t.Start();
break;
default:
break;
}
}
}
}
<file_sep># Perceptron-visualization
Visualization of single perceptron written on C# and inspired by <NAME>'s video (https://youtu.be/ntKn5TPHHAk)
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PerceptronVisualisation
{
class Point
{
public float x { get; }
public float y { get; }
public float bias { get; }
public int label { get; }
public Point(Func<float, float> f)
{
bias = 1;
Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
x = rand.Next(-3000, 3000)/10;
y = rand.Next(-3000, 3000)/10;
label = y > f(x) ? 1 : -1;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PerceptronVisualisation
{
public partial class LineEnterForm : Form
{
public float a = 1;
public float b = 0;
public LineEnterForm()
{
InitializeComponent();
}
private void OKbtn_Click(object sender, EventArgs e)
{
try
{
string eq = eqTextBox.Text;
string str_b = eq.Substring(eq.IndexOf('x') + 1);
string str_a = eq.Substring(0, eq.IndexOf('x') - 1);
double _a = 0;
double _b = 0;
if (Double.TryParse(str_a, out _a) && Double.TryParse(str_b, out _b))
{
a = FloatConverter.DoubleToFloat(_a);
b = FloatConverter.DoubleToFloat(_b);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("Incorrect equation of line! Try again!", "Error");
eqTextBox.Text = "";
}
} catch
{
MessageBox.Show("Incorrect equation of line! Try again!", "Error");
eqTextBox.Text = "";
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PerceptronVisualisation
{
class Perceptron
{
const float LEARNING_RATE = 0.01f;
const float BIAS_RATE = 3f;
float[] weights = new float[3];
public Perceptron()
{
Random rand = new Random(DateTime.Now.Millisecond);
for(int i = 0; i<weights.Length; i++)
{
weights[i] = FloatConverter.DoubleToFloat(rand.NextDouble()*2-1);
}
}
public int Guess(float[] inputs)
{
double sum = 0;
for(int i = 0; i < weights.Length; i++)
{
sum += weights[i] * inputs[i];
}
return sum < 0 ? -1 : 1;
}
public void Train(float[] inputs, int target)
{
int guess = Guess(inputs);
int error = target - guess;
for(int i = 0; i<weights.Length; i++)
{
weights[i] += error * inputs[i] *( i ==2 ? BIAS_RATE : LEARNING_RATE);
}
}
public void ReInit()
{
Random rand = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < weights.Length; i++)
{
weights[i] = FloatConverter.DoubleToFloat(rand.NextDouble() * 2 - 1);
}
}
public string getWeights()
{
var sb = new StringBuilder();
for(int i = 0; i < weights.Length; i++)
{
sb.AppendFormat("w{0}: {1} ", i, weights[i]);
}
return sb.ToString();
}
public Func<float, float> GetPrediction()
{
for(int i = 0; i<weights.Length; i++)
{
if(weights[i] == 0)
{
weights[i] += 0.0001f;
}
}
return new Func<float, float>(x => -(weights[2] / weights[1]) - (weights[0] / weights[1]) * x);
}
public void GetPredictedValues(out float a, out float b)
{
for (int i = 0; i < weights.Length; i++)
{
if (weights[i] == 0)
{
weights[i] += 0.0001f;
}
}
a = -(weights[0] / weights[1]);
b = -(weights[2] / weights[1]);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PerceptronVisualisation
{
class FloatConverter
{
public static float DoubleToFloat(double dValue)
{
if (float.IsPositiveInfinity(Convert.ToSingle(dValue)))
{
return float.MaxValue;
}
if (float.IsNegativeInfinity(Convert.ToSingle(dValue)))
{
return float.MinValue;
}
return Convert.ToSingle(dValue);
}
}
}
| 2c4c48a1d994301517a4d135fd1a41e3573eea6f | [
"Markdown",
"C#"
] | 6 | C# | AntonSvystunov/Perceptron-visualization | 1106c3cbe904c11df5c8991aca8c06d9b2b9ee63 | bf556345b1646dda043056b653dbf24a306fa0ab |
refs/heads/master | <file_sep># iArduinoWo —— node.js and mongodb blog website
iArduinoWo是利用node.js和mongodb搭建的轻博客站点,这里是此站点的源文件
##项目演示网址:http://wo.iArduino.cn
本项目是基于node.js框架rrestjs开发构成的
##rrestjs框架:http://www.rrestjs.com
##在线PS网站:http://www.uupoop.com/
##安装方法:
目前没有对windows环境下做任何测试和支持,请使用linux系统
1、请先安装node.js的6.X以上版本
2、npm install rrestjs
3、从github上打包iArduinoWo源码下载
4、安装mongodb2.0以上数据库
5、修改config文件夹下的配置文件,进行数据库连接
##联系方式
email: <EMAIL>
QQ: <EMAIL>
<file_sep>#!/bin/bash
REV=`svn up | grep "At revision" | cut -d " " -f 3`
REV1=`ps -ef | grep "iArduinoWo" | grep -v grep | awk '{print $2}' | head -1`
if [ ! -z $REV ] && [ ! -z $REV1 ]; then
echo "BYE!BYE! ^_^ "
exit 0
fi
if [ -z $REV ] && [ ! -z $REV1 ]; then
forever stop /opt/node_js/iArduinoWo/app.js
fi
if [ -z $REV ] || [ -z $REV1 ]; then
forever start /opt/node_js/iArduinoWo/app.js
fi<file_sep>var path = require('path'), processPath = path.dirname(process.argv[1]);// 运行node的目录,这里可以方便替换下面baseDir的__dirname,方便用户自己搭建目录,利用node_modules加载rrestjs
// 自定义配置
// 通用配置
/*
* 注意,所有的路径配置的前面请加‘/’而后面不要加'/'!
*/
module.exports = {
server : 'iArduinoWo',
poweredBy : 'node.js',
listenPort : 3000,// 监听端口,如果配合clusterplus监听多个端口,这里也可以使用[3000, 3001, 3002, 3003]数组形式,rrestjs会智能分析
baseDir : path.join(__dirname, '/..'), // 绝对目录地址,下面的目录配置都是根据这个目录的相对地址,这里是根据config文件进行配置地址 baseDir:processPath,//这里是根据启动nodejs的命令目录来设置baseDir
autoCreateFolders : true,// 如果想要以node_modules加载rrestjs,则此项最好选择true,rrestjs会根据config自动创建静态文件目录和缓存目录等目录
favicon : '/favicon.ico', // favicon存放地址
charset : 'utf-8',
autoStatic : '/static', // 自动响应静态文件的uri,比如 // http://rrestjs.com/static/rrest.jpg 将会自动响应给客户端,为了加速这里只能设置一级目录
staticFolder : '/view/static', // 自动响应静态文件的根目录,比如 // http://rrestjs.com/static/rrest.jpg 将返回 baseDir+'/example/static/rrest.jpg'
staticParse : true,// 是否开启静态文件压缩整合功能
staticParseName : 'parse',// 压缩整合功能的名称,例如用户可以'/static/?parse=/index.body.css|/index.user.css|/user.face.css'压缩整合成一个css响应给客户端
staticParseCacheTime : 1000 * 60 * 60,// 压缩整合缓存时间,1小时
staticParseCacheFolder : '/tmp/static',// 缓存整合功能的缓存文件夹
staticParseMaxNumber : 10,// 整合压缩css或js文件的最大上限,建议不要超过15
uploadFolder : '/tmp/upload', // 文件上传的临时目录
postLimit : 1024 * 1024 * 1,// 限制上传的postbody大小,单位byte
// cluster配置
isCluster : true, // 是否开启多进程集群
isClusterAdmin : false,// 进程监听管理功能是否开启
CLusterLog : false,// 是否打开cluster自带的控制台信息,生产环境建议关闭
adminListenPort : 20910,// 管理员监听端口号
adminAuthorIp : /^10.1.49.223$/,// 允许访问管理的IP地址
ClusterNum : 1, // 开启的进程数
ClusterReload : '/controller',// 只有当进程数为1时,进入开发模式,可以监听此文件夹下的改动,包括子文件夹,不用重复
// ctrl+c 和 上键+enter
// 静态文件配置
staticGetOnly : true, // 静态是否只能通过get获取
staticLv2MaxAge : 1000 * 60 * 60, // 静态文件2级缓存更新周期,建议设置为1小时
staticLv2Number : 10000,// 静态文件2级缓存数量,可以根据内存的大小适当调整
// session配置
isSession : true, // 是否开启session,开启会影响性能。
syncSession : false,// 当多进程时是否开启session同步,开启会影响性能。
sessionName : 'rrSid', // 保存session id 的cookie 的name
sessionExpire : false, // false表示会话session,否则填入1000*60,表示session有效1分钟
clearSessionSetInteval : 1000 * 60 * 60, // 自动清理垃圾session时间,建设设置为1小时
clearSessionTime : 1000 * 60 * 60 * 24 * 7,// 会话session超时,建议设置为1天
// session内存存储
sessionDbStore : true,// 是否使用mongodb数据库存储session,如果设置为true,则不需要同步session
// deflate和gzip配置
isZlib : true, // 是否开启delate和gizp压缩,大并发压缩虽然可以减少传输字节数,但是会影响性能
ZlibArray : [ 'text/plain', 'application/javascript', 'text/css',
'application/xml', 'text/html' ], // 只压缩数组中的content-type响应
// logger log4js 配置
isLog : false, // 是否开启日志,过多的记录日志会影响性能,但是能记录系统运行情况
logLevel : 'debug',// ['trace','debug','info','warn','error', 'fatal'] 日志等级
logPath : '/mylogs/console.log', // "/mylogs/console.log" 日志存放目录
logMaxSize : 1024 * 1024 * 10, // 单个日志文件大小
logFileNum : 10, // 当单个日志文件大小达标时,自动切分,这里设置最多切分多少个日志文件
// Template
tempSet : 'jade', // 使用哪种页面模版:jade或者ejs
tempFolder : '/view/template', // 默认读取模版的根目录
tempHtmlCache : false, // 是否开启模版的html缓存,当输出模版需要大量数据库或缓存I/O操作,且实时性要求不高时可以使用
tempCacheTime : 1000 * 60 * 60,// 模版缓存时间
tempCacheFolder : '/tmp/template', // 模版缓存 存放目录
// mongodb 配置
isMongodb : true, // 是否开启mongodb支持,注意:如果使用数据库存储session,这里必须开启
MongodbIp : '127.0.0.1', // mongodb地址
MongodbPort : 27017, // mongodb端口
MongodbConnectString : false, // 是否使用字符串连接,日入nae的连接方法,这个优先级高于地址+端口
MongodbConnectTimeout : 1000 * 30,// 连接超时
MongodbMaxConnect : 50,// 连接池连接数
MongodbDefaultDbName : 'iArduinoWo',// 默认使用的数据库名
poolLogger : false,// 是否记录连接池的日志,建议关闭
// 自动加载模块 配置
AutoRequire : true, // 是否开启模块自动加载,加载只有的模块可以使用 rrest.mod.模块名 来进行调用
ModulesFloder : '/modules', // 自动加载模块的存放目录,只读一层目录
ModulesExcept : [ 'captcha' ], // 自动加载模块目录中例外不加载的模块
// ip地址访问过滤
IPfirewall : false, // 是否开启IP过滤,开启会影响性能。
BlackList : true,// 如果是true,表示下面这些是黑名单,如果是false,表示下面这些是白名单,路径设置优先级大于IP
ExceptIP : /^10.1.49.223$/, // 正则表达式,匹配成功表示此IP可以正常访问,白名单
ExceptPath : [ '/user' ],// 例外的路径,如果用户访问这个路径,无论在不在ip过滤列表中,都可以正常使用,白名单才能使用
NotAllow : 'No permission!', // 禁止访问响应给客户端的信息
}
| ed765470c1b4f429ede04fe4133a9cdf346d1116 | [
"Markdown",
"JavaScript",
"Shell"
] | 3 | Markdown | schidler/iArduinoWo | ad675a1ba1ff39c08625b6fbb503b6e24ce766ca | a1fdd8b3c1859760c2f786bdc78a67b7d22245ea |
refs/heads/main | <repo_name>peramilo/ML-Pong<file_sep>/README.md
# ML-Pong
An implementation of Deep Q-learning on simple 1 player pong game.
The goal is using machine learning to create and train an agent that will choose best action to perform based on
the state of the game.
Agents decisions are based on expected discounted long-term reward for executing an action in a given state, value
which is called "Q-value". The object of Q-learning is estimating Q-values for optimal decision making policy that
maximizes future rewards.
In the game we have a paddle and a moving ball, the goal being to prevent the ball getting past the paddle and touch
the bottom wall. Only possible actions are moving the paddle either left or right.
Model used consists of 1 hidden layer, together with an input and output layer.
Input consists of position of paddle's center and x and y coordinates of the ball.
Reward is given when the ball bounces of the paddle, and negative points are given
on lost game.
Small reward is also given for each frame we are moving towards the ball.
This drastically improved learning process, but isn't really ideal since it rewards
behaviour that isn't necessarily optimal, since there is no need for paddle to constantly be under the ball.
TensorFlow and Keras modules were used to create and train deep learning model.
pygame module is used to display the attempts on the screen.
<file_sep>/envir.py
import numpy as np
import pygame
class Game:
def __init__(self):
self.WHITE = (255, 255, 255)
self.BLACK = (0, 0, 0)
self.screenWidth = 800
self.screenHeight = 600
self.padWidth = 100
self.padHeight = 15
self.ballRad = 12
self.padPosX = 0
self.padPosY = self.screenHeight - 10
self.padPosX = int(self.screenWidth / 2 - self.padWidth / 2)
self.ballPosX = int(self.screenWidth / 2 - self.ballRad / 2)
self.ballPosY = int(self.screenHeight / 6)
self.padVel = 0
self.ballVelX = int(np.random.choice((-5, -4, -3, 3, 4, 5), 1))
self.ballVelY = 4
self.point = 0
self.reward = 0
self.done = False
# For displaying attempts we need to uncomment screen and allow draw_screen in main_loop
# Using Clock we can limit the fps and make it easier to see model's actions
# self.fps = pygame.time.Clock()
# self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight))
def draw_screen(self):
self.screen.fill(self.BLACK)
self.draw_ball()
self.draw_pad()
pygame.display.flip()
def draw_ball(self):
pygame.draw.circle(self.screen, self.WHITE, (self.ballPosX, self.ballPosY), self.ballRad, 0)
def draw_pad(self):
pygame.draw.rect(self.screen, self.WHITE, (self.padPosX, self.padPosY, self.padWidth, self.padHeight))
def move_ball(self):
self.ballPosX += self.ballVelX
self.ballPosY += self.ballVelY
def move_pad(self):
if 0 <= self.padPosX <= self.screenWidth - self.padWidth:
self.padPosX += self.padVel
else:
if self.padPosX <= 0:
self.padPosX = 1
else:
self.padPosX = self.screenWidth - self.padWidth - 1
self.padVel = 0
def action(self, x):
if x == 1:
self.padVel += 4
elif x == 0:
self.padVel -= 4
# Registers and handles collisions
def coll(self):
if self.ballPosY - self.ballRad <= 0:
self.ballPosY = self.ballRad
self.ballVelY *= -1
if self.ballPosX + self.ballRad >= self.screenWidth or self.ballPosX - self.ballRad <= 0:
self.ballVelX *= -1
if self.ballPosY + self.ballRad >= self.screenHeight:
if self.ballPosX + self.ballRad >= self.padPosX and self.ballPosX - self.ballRad <= self.padPosX + self.padWidth:
self.pad_coll()
else:
self.reward = -1000
self.done = True
if self.ballPosX + self.ballRad >= self.padPosX and self.ballPosX - self.ballRad <= self.padPosX + self.padWidth:
if self.ballPosY + self.ballRad >= self.padPosY:
self.pad_coll()
# Gives reward of 1 for each frame where we are moving towards the ball
if abs(self.padPosX + self.padWidth / 2 + self.padVel - self.ballPosX) <= abs(
self.padPosX + self.padWidth / 2 - self.ballPosX):
if self.reward == 0:
self.reward = 1
# Handles pad collisions
def pad_coll(self):
self.ballVelY *= -1
self.point += 1
self.reward = 200
self.ballPosY = self.padPosY - self.ballRad
# Returns state of the game
def state(self):
x = (self.ballPosX / self.screenWidth, self.ballPosY / self.screenHeight,
(self.padPosX + self.padWidth / 2) / self.screenWidth)
return x
def reset(self):
self.__init__()
# Initial X velocity is choosen from 4 possible values
self.ballVelX = int(np.random.choice((-4, -3, 3, 4), 1))
self.ballVelY = 4
self.done = False
self.point = 0
def get_reward(self):
x = self.reward
self.reward = 0
return x
def is_done(self):
return self.done
def main_loop(self):
self.coll()
self.move_ball()
# Uncomment for limiting fps
# self.fps.tick(30)
self.move_pad()
# Uncomment for displaying attempts
# self.draw_screen()
<file_sep>/main.py
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from envir import Game
a = 1
x = Game()
max_steps = 4000
max_history = 20000
gamma = 0.99
epsilon = 1.0
epsilon_min = 0.01
epsilon_decay = 0.995
batch_size = 32
episode_reward = 0
episode_reward_history = []
# Histories hold information from previous frames, decisions
point_history = []
action_history = []
state_history = []
state_next_history = []
done_history = []
reward_history = []
# Specifies how often to update our model.
update_after_actions = 5
update_target_model = 10000
def create_model():
# 1 hidden layer, 128 nodes in size
inputs = layers.Input(shape=(3,))
layer1 = layers.Dense(128, activation="relu")(inputs)
action = layers.Dense(2, activation="softmax")(layer1)
return keras.Model(inputs=inputs, outputs=action)
model = create_model() # This is the main, decision making model
model.summary()
model_target = create_model() # Target model, helps with learning
# Adam will be optimizer used, with Huber as a loss function
optimizer = keras.optimizers.Adam(learning_rate=0.00025, clipnorm=1.0)
loss_function = keras.losses.Huber()
episode_number = 0
while True:
x.reset()
state = x.state()
frame = 0
episode_reward = 0
for step in range(1, max_steps):
frame += 1
if np.random.rand() < epsilon:
action = np.random.choice(2)
else:
stateTensor = tf.convert_to_tensor(state)
stateTensor = tf.expand_dims(stateTensor, 0)
action_probs = model(stateTensor, training=False)
action = tf.argmax(action_probs[0]).numpy()
if epsilon > epsilon_min:
epsilon *= epsilon_decay
x.main_loop()
x.action(action)
done = x.is_done()
reward = x.get_reward()
state_next = x.state()
episode_reward += reward
action_history.append(action)
state_history.append(state)
state_next_history.append(state_next)
reward_history.append(reward)
done_history.append(done)
state = state_next
if frame % update_after_actions == 0 and len(done_history) > batch_size:
# Chooses random samples from our history:
indices = np.random.choice(range(len(done_history)), size=batch_size)
state_sample = np.array([state_history[i] for i in indices])
state_next_sample = np.array([state_next_history[i] for i in indices])
action_sample = np.array([action_history[i] for i in indices])
reward_sample = np.array([reward_history[i] for i in indices])
done_sample = tf.convert_to_tensor([float(done_history[i]) for i in indices])
future_rewards = model_target.predict(state_next_sample)
updated_q_values = reward_sample + gamma * tf.reduce_max(future_rewards, axis=1)
updated_q_values = updated_q_values * (1 - done_sample) - done_sample
masks = tf.one_hot(action_sample, 2)
with tf.GradientTape() as tape:
q_values = model(state_sample)
q_action = tf.reduce_sum(tf.multiply(q_values, masks), axis=1)
loss = loss_function(updated_q_values, q_action)
# Backpropagation
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
# Updating target model with main model weights
if frame % update_target_model == 0:
model_target.set_weights(model.get_weights)
# Deletes a row if we step over history limit
if len(reward_history) > max_history:
del reward_history[:1]
del state_history[:1]
del state_next_history[:1]
del action_history[:1]
del done_history[:1]
if x.is_done():
break
episode_number += 1
episode_reward_history.append(episode_reward)
point_history.append(x.point)
if len(episode_reward_history) > 10:
del episode_reward_history[:1]
del point_history[:1]
mean_reward = np.mean(episode_reward_history)
mean_point = np.mean(point_history)
if episode_number % 5 == 0:
print(episode_number, mean_reward, mean_point)
| 67c3931c1b448b5783c984f7b67ba8cbe0119bb6 | [
"Markdown",
"Python"
] | 3 | Markdown | peramilo/ML-Pong | 8a8f05978a6f8675f02d42647b33163dcb15ed80 | 5ef131b0d26e1c8ac00041b47f32c775ad4bb228 |
refs/heads/master | <file_sep>// ====================================================================================================
//
// Text Analyzer
//
// ====================================================================================================
// --------------------------------------------------
// Initialize when the DOM is ready
// --------------------------------------------------
$(function() {
// Cache Elements
// -----------------------------
var textarea = $('#js-text'),
submitBtn = $('#js-submit'),
countElem = $('.js-wordcount'),
uniqueElem = $('.js-unique'),
avgElem = $('.js-average'),
report = $('.text-report');
// Add analysis to the DOM
// -----------------------------
var updateDom = function(wordCount, uniques, average) {
countElem.text(wordCount);
uniqueElem.text(uniques);
avgElem.text(average);
report.removeClass('hidden');
};
// Submit button handler
// -----------------------------
submitBtn.click(function(e) {
e.preventDefault();
var wordList = textarea.val().split(' '),
wordCount = wordList.length,
uniques = $.unique(wordList).length,
sum = 0,
average;
$.each(wordList, function(index, item) {
sum += item.length;
});
average = Math.round(sum / wordCount);
updateDom(wordCount, uniques, average);
});
});
<file_sep>// ====================================================================================================
//
// Text Analyzer
//
// ====================================================================================================
// --------------------------------------------------
// Initialize when the DOM is ready
// --------------------------------------------------
document.addEventListener('DOMContentLoaded', () => {
var textarea = document.getElementById('js-text'),
submitBtn = document.getElementById('js-submit'),
countElem = document.querySelector('.js-wordcount'),
uniqueElem = document.querySelector('.js-unique'),
avgElem = document.querySelector('.js-average'),
report = document.querySelector('.text-report');
});
| 821da391f55cf6dbc8130c69da296d377076d553 | [
"JavaScript"
] | 2 | JavaScript | SheenaVasani/text-analyzer-starter-files | 8fd7a9599c9ba4e7fcc14ef640121c3583cc65b0 | 3c64b879e32372bc1f49b76fc469d7d0bcb731c8 |
refs/heads/master | <repo_name>fredlawl/playground-graph-visitor<file_sep>/GraphVisitor/LabelGraph.cs
using GraphLib;
namespace GraphVisitor
{
public class LabelGraph : BaseGraph<LabelGraph, Label>
{
public string Title { get; protected set; }
public LabelGraph(string title)
{
Title = title;
}
public override void Accept(IGraphVisitor<LabelGraph, Label> visitor)
{
visitor.Visit(this);
}
protected override BaseGraph<LabelGraph, Label> Clone()
{
return new LabelGraph(this.Title);
}
}
}<file_sep>/GraphVisitor/DotGraphPrinter.cs
using System.Text;
using GraphLib;
namespace GraphVisitor
{
public class DotGraphPrinter : IGraphVisitor<LabelGraph, Label>
{
private StringBuilder _sb;
private IVertexVisitor<Label> _vertexVisitor;
public IVertexVisitor<Label> VertexVisitor => _vertexVisitor;
public DotGraphPrinter()
{
_sb = new StringBuilder();
_vertexVisitor = new DotVertexPrinter(_sb);
}
public void Visit(LabelGraph graph)
{
_sb.AppendLine($"digraph \"{graph.Title}\" {{");
_sb.AppendLine("\trankdir=LR;");
_sb.AppendLine("\tsize=\"8,5\"");
_sb.AppendLine("\tnode [shape = circle];");
foreach (var pair in graph.AdjacencyList)
{
foreach (var edge in pair.Value)
{
_sb.Append("\t");
pair.Key.Accept(_vertexVisitor);
edge.Accept(_vertexVisitor);
_sb.AppendLine();
}
}
_sb.AppendLine("}");
}
public string Output()
{
return _sb.ToString();
}
}
}<file_sep>/GraphVisitor/DotVertexPrinter.cs
using System.Text;
using GraphLib;
namespace GraphVisitor
{
public class DotVertexPrinter : IVertexVisitor<Label>
{
private StringBuilder _sb;
public DotVertexPrinter(StringBuilder sb)
{
_sb = sb;
}
public void Visit(Label vertex)
{
_sb.Append($"\"{vertex.Value}\"");
}
public void Visit(Edge<Label> edge)
{
_sb.Append(" -> ");
edge.Vertex.Accept(this);
_sb.Append($" [ label = \"{edge.Label}\" ];");
}
}
}<file_sep>/README.md
# Playground Graph Visitor
Small test application that has a generic adjacency list graph class and a visitor to print out the graph in [Graphviz](http://www.graphviz.org/)'s dot language. <file_sep>/GraphLib/IGraphVisitor.cs
namespace GraphLib
{
public interface IGraphVisitor<TGraph, TVertex> where TGraph : BaseGraph<TGraph, TVertex> where TVertex : Vertex<TVertex>
{
IVertexVisitor<TVertex> VertexVisitor { get; }
void Visit(TGraph graph);
}
}<file_sep>/GraphVisitor/Program.cs
using System;
using GraphLib;
namespace GraphVisitor
{
class Program
{
static void Main(string[] args)
{
var printer = new DotGraphPrinter();
var graph = new LabelGraph("My Label Graph");
graph.AddEdge(new Label("test1"), new Edge<Label>(new Label("test2"), "0"));
graph.AddEdge(new Label("test1"), new Edge<Label>(new Label("test3"), "1"));
graph.AddEdge(new Label("test2"), new Edge<Label>(new Label("test1"), "2"));
graph.Accept(printer);
Console.WriteLine(printer.Output());
}
}
}
<file_sep>/GraphLib/Vertex.cs
using System;
namespace GraphLib
{
public abstract class Vertex<T> : IEquatable<T> where T : Vertex<T>
{
public abstract bool EqualsCore(T other);
public abstract int GetHashCodeCore();
public virtual bool Equals(T other)
{
if (other == null)
return false;
if (ReferenceEquals(this, other))
return true;
return EqualsCore(other);
}
public override bool Equals(object other)
{
var casted = other as T;
if (casted == null)
return false;
if (ReferenceEquals(this, casted))
return true;
return EqualsCore(casted);
}
public override int GetHashCode()
{
return GetHashCodeCore();
}
public abstract void Accept(IVertexVisitor<T> visitor);
}
}<file_sep>/GraphVisitor/Label.cs
using System;
using GraphLib;
namespace GraphVisitor
{
public class Label : Vertex<Label>
{
public string Value { get; protected set; }
public Label(string label)
{
Value = label;
}
public override bool EqualsCore(Label other)
{
return Value.Equals(other.Value, StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCodeCore()
{
return Value.GetHashCode();
}
public override void Accept(IVertexVisitor<Label> visitor)
{
visitor.Visit(this);
}
}
}<file_sep>/GraphLib/IVertexVisitor.cs
namespace GraphLib
{
public interface IVertexVisitor<TVertex> where TVertex : Vertex<TVertex>
{
void Visit(TVertex vertex);
void Visit(Edge<TVertex> edge);
}
}<file_sep>/GraphLib/BaseGraph.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace GraphLib
{
public abstract class BaseGraph<TGraph, TVertex> where TGraph : BaseGraph<TGraph, TVertex> where TVertex : Vertex<TVertex>
{
protected IDictionary<TVertex, IList<Edge<TVertex>>> _adjacencyList = new Dictionary<TVertex, IList<Edge<TVertex>>>();
public IReadOnlyDictionary<TVertex, IList<Edge<TVertex>>> AdjacencyList => new ReadOnlyDictionary<TVertex, IList<Edge<TVertex>>>(_adjacencyList);
public void AddVertex(TVertex vertex)
{
if (vertex == null)
throw new ArgumentNullException(nameof(vertex));
if (_adjacencyList.ContainsKey(vertex))
return;
_adjacencyList.Add(vertex, new List<Edge<TVertex>>());
}
public void AddEdge(TVertex from, Edge<TVertex> to)
{
AddVertex(from);
AddVertex(to.Vertex);
_adjacencyList[from].Add(to);
}
public BaseGraph<TGraph, TVertex> GetTranspose()
{
var graph = Clone();
if (graph == null)
throw new InvalidOperationException("Call to Clone() returned null.");
// todo: Write this function
throw new NotImplementedException();
return graph;
}
public abstract void Accept(IGraphVisitor<TGraph, TVertex> visitor);
protected abstract BaseGraph<TGraph, TVertex> Clone();
}
}<file_sep>/GraphLib/Edge.cs
using System;
namespace GraphLib
{
public class Edge<T> where T : Vertex<T>
{
public T Vertex { get; protected set; }
public string Label { get; protected set; }
public Edge(T to, string label = null)
{
if (to == null)
throw new ArgumentNullException(nameof(to));
Vertex = to;
Label = label ?? string.Empty;
}
public void Accept(IVertexVisitor<T> visitor)
{
visitor.Visit(this);
}
}
} | f38529b49cc66db1fc046910b36ef2b2a8e71498 | [
"Markdown",
"C#"
] | 11 | C# | fredlawl/playground-graph-visitor | 849b9bfabe5a129a7ad9ed524a5411fa5a1664be | e4710b7b58c285b80b099f494ebe63e1c1e42ed4 |
refs/heads/master | <file_sep>#!/bin/bash
#author lll
dbName=test
fileName=`date +%Y%m%d.%H%M`
backupPath=/root/data
dbuser=root
dbpassword=<PASSWORD>
if [ ! -n "$1" ] ;then
echo -e "---请输入需要备份数据库名称---"
exit
fi
if [ "${dbName}" == "$1" ];then
if [ ! -e $backupPath ];then
echo "---正在创建备份路径---"
mkdir -p $backupPath
fi
mysqldump -u$dbuser -p$dbpassword $1>$backupPath/$fileName.sql
echo "---$1数据库备份完成---"
echo "---备份路径为$backupPath/$fileName.sql---"
else
echo "---please input correct database name---"
exit
fi
| fe6317d7d27ddcdda9bbf4858eec85294398ef32 | [
"Shell"
] | 1 | Shell | lfengsw/hello-world | 2207b3a8db22a7d72043578ec93e022da3cc9499 | 8bd949ceb325d7b8cd8bfdf64451c117678e60a0 |
refs/heads/master | <repo_name>claireedanaher/DS501<file_sep>/CaseStudy2/previous/CaseStudy2_DataTags.py
###CASE STUDY 2####
import sys
import pandas as pd
import json
import pymongo
from pymongo import MongoClient
###################################################################################################################################
# IMPORT 1M Data
###################################################################################################################################
ratings=pd.read_table("C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/ratings.dat", sep='::', names=['user_id', 'movie_id', 'rating','timestamp'])
ratings
users=pd.read_table('C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/users.dat', sep='::', names=['user_id', 'gender', 'age', 'occupation', 'zipcode'])
users
movies=pd.read_table('C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/movies.dat', sep='::', names=['movie_id', 'title', 'genre'])
users
# AGGREGATE INTO ONE FLAT FILE NAMES data_agg_1M
data_agg_1M=pd.merge(ratings, movies, on='movie_id')
data_agg_1M=pd.merge(data_agg_1M, users ,on='user_id')
###################################################################################################################################
###################################################################################################################################
# IMPORT TAG AND MOVIE TITLE INFO FROM 20M data
###################################################################################################################################
movies_tags=pd.read_csv("C:/WPI/DS501/CaseStudy/CaseStudy2/Data/20M/movies.csv", names=['movie_id', 'title', 'genre'])
movies_tags=movies_tags.drop(0)
movies_tags
tags=pd.read_csv("C:/WPI/DS501/CaseStudy/CaseStudy2/Data/20M/tags.csv", names=['user_id', 'movie_id', 'tag', 'timestamp'])
tags=tags.drop(0)
tags
# AGGREGATE INTO ONE FLAT FILE NAMES tagg_agg
tag_agg=pd.merge(tags,movies_tags,on='movie_id')
###################################################################################################################################
###################################################################################################################################
#CONSISTENCY CHECK
#PURPOSE: Determine differences in movie titles with 1M and 20M data sets
###################################################################################################################################
#RETURNS TRUE/FALSE with counts of matching titles from 1M to 20M
movies['title'].isin(movies_tags['title']).value_counts()
#True 3361
#False 522
#RETURNS TRUE/FALSE with counts of matching titles from 20M to 10M
movies_tags['title'].isin(movies['title']).value_counts()
#False 23914
#True 3364
###################################################################################################################################
#OUTCOME1: NUMBERS PROVE TO BE CONSISTANT WITH MERGE
#OUTCOME2: 522 out of 3883 movies are in 1M but not 20M accounting for approx 13% of the movies
###################################################################################################################################
movielens=pd.merge(data_agg_1M,tag_agg,how='left', on='title')
movielens.drop('user_id_y', axis=1)
movielens.drop('movie_id_y', axis=1)
movielens.drop('timestamp_y', axis=1)
movielens.drop('genre_y', axis=1)
<file_sep>/CaseStudy4/Previous/testing maps.py
import plotly
import pandas as pd
df = pd.read_csv('city_summary.csv')
for col in df.columns:
df[col] = df[col].astype(str)
scl = [[0.0, 'rgb(255,237,221)'],[0.2, 'rgb(255,174,104)'],[0.4, 'rgb(255,162,81)'],\
[0.6, 'rgb(255,157,71)'],[0.8, 'rgb(255,139,38)'],[1.0, 'rgb(255,119,0)']]
df['text'] = df['state'] + '<br>' + 'Top City: ' +df['City'] + '<br>' + 'Top Genre: ' + df['Top Genre'] + '<br>' + 'Tags: ' + df['Tags']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['ranking_value'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
) ),
colorbar = dict(
title = "Ranking Value")
) ]
layout = dict(
title = '2017 Aggregated Soundcloud Listening Data by State<br>(Hover for breakdown)',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)'),
)
fig = dict( data=data, layout=layout )
plotly.offline.plot( fig, filename='d3-cloropleth-map' )<file_sep>/CaseStudy2/previous/QueryMongoDB.py
###CASE STUDY 2####
import sys
import pandas as pd
import json
import pymongo
from pymongo import MongoClient
###################################################################################################################################
# CONNECT TO MONGODB ATLAS
###################################################################################################################################
#Connects with the mongodb client
client = pymongo.MongoClient("mongodb://admin:ds501@casestudy2-shard-00-00-z2tsj.mongodb.net:27017,casestudy2-shard-00-01-z2tsj.mongodb.net:27017,casestudy2-shard-00-02-z2tsj.mongodb.net:27017/test?ssl=true&replicaSet=CaseStudy2-shard-0&authSource=admin")
#Connects to collection in mondgo db
#Likely would make sense to rename this but I didn't have time
db=client['data_agg_1M']
#Connects to the table in mongodb
dbmovielens=db['data_agg_1M']
#The variable cursor is used to identify what you would like to search for
cursor=dbmovielens.find({'title':"<NAME> (2000)"})
#Creates a dict for the dataframe
fields=['user_id','movie_id','rating','timestamp','title', 'genre', 'gender', 'age', 'occupation', 'zipcode' ]
#creates a dataframe containing all of the records associated with the term queried for via the cursor
movielens=pd.DataFrame(list(cursor),columns=fields)
#Prints the results
print(movielens)
client.close()
###################################################################################################################################
###################################################################################################################################
# CONNECT TO MONGODB ATLAS
###################################################################################################################################
#Connects with the mongodb client
client = pymongo.MongoClient("mongodb://admin:ds501@casestudy2-shard-00-00-z2tsj.mongodb.net:27017,casestudy2-shard-00-01-z2tsj.mongodb.net:27017,casestudy2-shard-00-02-z2tsj.mongodb.net:27017/test?ssl=true&replicaSet=CaseStudy2-shard-0&authSource=admin")
#Connects to collection in mondgo db
#Likely would make sense to rename this but I didn't have time
db=client['data_agg_1M']
#Connects to the table in mongodb with the tag info
dbmovielens=db['tag_data']
#The variable cursor is used to identify what you would like to search for
cursor=dbmovielens.find({'tag':'Mark Waters'})
#Creates a dict for the dataframe
fields=['user_id','movie_id','tag','timestamp','title', 'genre' ]
#creates a dataframe containing all of the records associated with the term queried for via the cursor
movielens=pd.DataFrame(list(cursor),columns=fields)
#Prints the results
print(movielens)
client.close()
###################################################################################################################################
<file_sep>/CaseStudy2/previous/CaseStudy2_Q1.py
###CASE STUDY 2####
import sys
import pandas as pd
import json
import pymongo
import numpy as np
from pymongo import MongoClient
###################################################################################################################################
# CONNECT TO MONGODB ATLAS
###################################################################################################################################
#Connects with the mongodb client
client = pymongo.MongoClient("mongodb://admin:ds501@casestudy2-shard-00-00-z2tsj.mongodb.net:27017,casestudy2-shard-00-01-z2tsj.mongodb.net:27017,casestudy2-shard-00-02-z2tsj.mongodb.net:27017/test?ssl=true&replicaSet=CaseStudy2-shard-0&authSource=admin")
#Connects to collection in mondgo db
#Likely would make sense to rename this but I didn't have time
db=client['data_agg_1M']
#Connects to the table in mongodb
dbmovielens=db['data_agg_1M']
#Connects to the table in mongodb with the tag info
#dbTagData=db['tag_data']
###################################################################################################################################
# PULLS ALL DATA FROM MONGO DB AND CREATES A DATA FRAME CALLED movielensDF
###################################################################################################################################
allfields=['user_id','movie_id','rating','timestamp','title', 'genre', 'gender', 'age', 'occupation', 'zipcode' ]
cursor = dbmovielens.find({})
movielensDF = pd.DataFrame(list(cursor), columns = allfields)
movielensDF[:5]
movielensDF.dtypes()
movielensDF[:100]
###################################################################################################################################
# CALCULATES HIGH AVERAGE MOVIES
###################################################################################################################################
movie_avgrating=movielensDF.pivot_table('rating',index='title',aggfunc='mean')
highavg_movie=movie_avgrating[movie_avgrating['rating']>=4.5]
high_avgcnt=len(highavg)
print('The total number of movies with an average rating of at least 4.5 is '+str(high_avgcnt))
###################################################################################################################################
# CREATES GENDER SPECIFIC DFs
###################################################################################################################################
fem_reviews=movielensDF
#REMOVE= CRITERIA FOR REMOVAL
remove=['M']
#REMOVES RECORDS FROM DATA FRAME BASED ON CRITIA
fem_reviews=fem_reviews.query('gender not in @remove')
fem_movies=fem_reviews.pivot_table('rating',index='title',aggfunc='mean')
highavg=fem_movies[fem_movies['rating']>=4.5]
high_avgcnt=len(highavg)
print('The total number of movies with an average rating of at least 4.5 among women is '+str(high_avgcnt))
male_reviews=movielensDF
remove=['F']
male_reviews=male_reviews.query('gender not in @remove')
male_reviews=male_reviews.pivot_table('rating',index='title',aggfunc='mean')
highavg=male_reviews[male_reviews['rating']>=4.5]
high_avgcnt=len(highavg)
print('The total number of movies with an average rating of at least 4.5 among men is '+str(high_avgcnt))
<file_sep>/CaseStudy4/Previous/CaseeStudy4_Prelim.py
###CASE STUDY 2####
import sys
import pandas as pd
import json
import pymongo
from pymongo import MongoClient
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_files
from sklearn.model_selection import train_test_split
from sklearn import metrics
df = pd.read_csv('C:/WPI/DS501/CaseStudy/CaseStudy4/soundcloud.csv')
df.head()
#####################################################################
#EXPORT JSON FILE
#invar=variable containing data to be converted to json
#filename=file name for the json data to be save to
################## START ############################################
def json_export(invar,filename):
data=invar.reset_index().to_json(orient='records')
file = open(filename,'w')
file.write(data)
file.close()
return(data)
################### END ##################################################
#####################################################################
#Extract info from raw file
################## START ############################################
def explode(df, lst_cols, fill_value=''):
# make sure `lst_cols` is a list
if lst_cols and not isinstance(lst_cols, list):
lst_cols = [lst_cols]
# all columns except `lst_cols`
idx_cols = df.columns.difference(lst_cols)
# calculate lengths of lists
lens = df[lst_cols[0]].str.len()
if (lens > 0).all():
# ALL lists in cells aren't empty
return pd.DataFrame({
col:np.repeat(df[col].values, df[lst_cols[0]].str.len())
for col in idx_cols
}).assign(**{col:np.concatenate(df[col].values) for col in lst_cols}) \
.loc[:, df.columns]
else:
# at least one list in cells is empty
return pd.DataFrame({
col:np.repeat(df[col].values, df[lst_cols[0]].str.len())
for col in idx_cols
}).assign(**{col:np.concatenate(df[col].values) for col in lst_cols}) \
.append(df.loc[lens==0, idx_cols]).fillna(fill_value) \
.loc[:, df.columns]
################### END ##################################################
def vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range):
vectorizor=TfidfVectorizer(doc,max_features=val_max_feature,
min_df=val_min_df,max_df=val_max_df,
stop_words='english',
ngram_range=val_ngram_range)
tfid_result=vectorizor.fit_transform(doc)
display_scores(vectorizor,tfid_result)
def display_scores(vectorizer, tfidf_result):
# http://stackoverflow.com/questions/16078015/
scores = zip(vectorizer.get_feature_names(),
np.asarray(tfidf_result.sum(axis=0)).ravel())
sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True)
# end=len(sorted_scores)
for item in sorted_scores[:20]:
print ("{0:20} Score: {1}".format(item[0], item[1]))
################################################################################################
#NYC
################################################################################################
ny_cities = ['New York','New York City','NYC','new york city','New York & Philadelphia','New York, NY','NEW YORK','New York/ L.A.','NY']
df_newyork = df.loc[df['city'].isin(ny_cities)]
df_newyork.shape
df_newyork.loc[df_newyork['city'].isin(ny_cities), 'city'] = 'New York City'
df_newyork.head()
df_newyork['city'].value_counts()
df_nyc =explode(df_newyork.assign(var1=df_newyork.genres_list.str.split(',')), 'var1')
df_nyc_csv = explode(df_nyc.assign(var2 = df_nyc.tags_list.str.split(',')),'var2')
df_city=df_nyc_csv*1
del df_city['genres_list']
del df_city['tags_list']
del df_city['city']
df_city=df_city.rename(columns={'var1':'genre','var2':'tag'})
df_city["genre"] = df_city["genre"].str.replace("[", "")
df_city["genre"] = df_city["genre"].str.replace("]", "")
df_city["genre"] = df_city["genre"].str.replace("'", "")
df_city["tag"] = df_city["tag"].str.replace("[", "")
df_city["tag"] = df_city["tag"].str.replace("]", "")
df_city["tag"] = df_city["tag"].str.replace("'", "")
df_city["tag"] = df_city["tag"].str.replace('"', "")
df_city['City']="New York City"
df_city['State']="NY"
df_city[1:5]
df_agg=df_city*1
city_genre=df_city['genre'].value_counts()
city_genre[1:5]
genres_pivot = df_city.pivot_table('tag',index='genre',aggfunc='count')
genres_pivot = genres_pivot.sort_values('tag', ascending= False)
genres_pivot
top_genres = genres_pivot[0:1]
top_genres
top_genres =top_genres.index.tolist() # list of straight up movie_id of the worst movies
top_genres
genre=top_genres[:1]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
genre=top_genres[1:2]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
genre=top_genres[2:3]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
################################################################################################
#Boston
################################################################################################
boston_cities = ['Boston','Boston, Texas','Boston MA ,United states','Boston, Massachusetts - Austin, Texas','Boston, Massachusetts ','BOSTON','Boston, Massachusetts']
df_boston = df.loc[df['city'].isin(boston_cities)]
df_boston.shape
df_boston.loc[df_boston['city'].isin(boston_cities), 'city'] = 'Boston'
df_boston.head()
df_boston['city'].value_counts()
df_boston =explode(df_boston.assign(var1=df_boston.genres_list.str.split(',')), 'var1')
df_boston_csv = explode(df_boston.assign(var2 = df_boston.tags_list.str.split(',')),'var2')
df_boston[1:5]
df_city=df_boston_csv*1
del df_city['genres_list']
del df_city['tags_list']
del df_city['city']
df_city=df_city.rename(columns={'var1':'genre','var2':'tag'})
df_city["genre"] = df_city["genre"].str.replace("[", "")
df_city["genre"] = df_city["genre"].str.replace("]", "")
df_city["genre"] = df_city["genre"].str.replace("'", "")
df_city["tag"] = df_city["tag"].str.replace("[", "")
df_city["tag"] = df_city["tag"].str.replace("]", "")
df_city["tag"] = df_city["tag"].str.replace("'", "")
df_city["tag"] = df_city["tag"].str.replace('"', "")
df_city[1:5]
df_city['City']="Boston"
df_city['State']="MA"
df_city[1:5]
city_genre=df_city['genre'].value_counts()
city_genre[1:5]
genres_pivot = df_city.pivot_table('tag',index='genre',aggfunc='count')
genres_pivot = genres_pivot.sort_values('tag', ascending= False)
genres_pivot
top_genres = genres_pivot[1:4]
top_genres
top_genres =top_genres.index.tolist() # list of straight up movie_id of the worst movies
top_genres
genre=top_genres[:1]
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
genre=top_genres[1:2]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
genre=top_genres[2:3]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
################################################################################################
la_cities = ['Los Angeles, CA','Los Angeles','L.A','Los Angeles Area','Los Angeles, California','Los Angeles // Santa Barbara','los angeles','Los Angeles, California','LOS ANGELES','LosAngeles','Los Angeles, CA + Phoenix, AZ']
df_la = df.loc[df['city'].isin(la_cities)]
df_la.shape
df_la.loc[df_la['city'].isin(la_cities), 'city'] = 'Los Angeles'
df_la.head()
df_la['city'].value_counts()
df_la =explode(df_la.assign(var1=df_la.genres_list.str.split(',')), 'var1')
df_la_csv = explode(df_la.assign(var2 = df_la.tags_list.str.split(',')),'var2')
df_la[1:5]
df_city=df_la_csv*1
del df_city['genres_list']
del df_city['tags_list']
del df_city['city']
df_city=df_city.rename(columns={'var1':'genre','var2':'tag'})
df_city["genre"] = df_city["genre"].str.replace("[", "")
df_city["genre"] = df_city["genre"].str.replace("]", "")
df_city["genre"] = df_city["genre"].str.replace("'", "")
df_city["tag"] = df_city["tag"].str.replace("[", "")
df_city["tag"] = df_city["tag"].str.replace("]", "")
df_city["tag"] = df_city["tag"].str.replace("'", "")
df_city["tag"] = df_city["tag"].str.replace('"', "")
df_city[1:5]
df_city['City']="Los Angeles"
df_city['State']="CA"
df_city[1:5]
df_city['genre'].value_counts()
city_genre=df_city['genre'].value_counts()
city_genre[1:5]
genres_pivot = df_city.pivot_table('tag',index='genre',aggfunc='count')
genres_pivot = genres_pivot.sort_values('tag', ascending= False)
genres_pivot
top_genres = genres_pivot[1:4]
top_genres
top_genres =top_genres.index.tolist() # list of straight up movie_id of the worst movies
top_genres
genre=top_genres[:1]
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
genre=top_genres[1:2]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
genre=top_genres[2:3]
genre
tags_top_genre=df_city.query('genre in @genre')
doc = tags_top_genre['tag'].tolist()
val_max_feature=200
val_min_df=1
val_max_df=0.98
val_ngram_range=(1,3)
vector(doc,val_max_feature,val_min_df,val_max_df,val_ngram_range)
<file_sep>/CaseStudy1/README.md
# DS501
DS501 Repository
<file_sep>/CaseStudy2/previous/best and worst.py
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 16:25:06 2017
@author: Jonny
"""
import pandas as pd
import pymongo
#Connects with the mongodb client
client = pymongo.MongoClient("mongodb://admin:ds501@casestudy2-shard-00-00-z2tsj.mongodb.net:27017,casestudy2-shard-00-01-z2tsj.mongodb.net:27017,casestudy2-shard-00-02-z2tsj.mongodb.net:27017/test?ssl=true&replicaSet=CaseStudy2-shard-0&authSource=admin")
#Connects to collection in mondgo db
#Likely would make sense to rename this but I didn't have time
db=client['data_agg_1M']
#Connects to the table in mongodb
dbmovielens=db['data_agg_1M']
allfields=['movie_id','rating']
cursor = dbmovielens.find({})
movielensDF = pd.DataFrame(list(cursor), columns = allfields)
movie_rate_freq = movielensDF['movie_id'].value_counts()
seen_IDs = movie_rate_freq.index.tolist()
seen_IDs = seen_IDs[:int(len(seen_IDs)/2)]
seen_movies = movielensDF.query('movie_id not in @seen_IDs')
seen_movies_pivot = seen_movies.pivot_table('rating',index='movie_id',aggfunc='mean')
seen_movies_pivot = seen_movies_pivot.sort_values('rating', ascending= False)
bottom_percentile = 5 # can change this to whatever percentile you want
top_percentile = 5 # can change this to whatever percentile you want
num_movies = len(seen_IDs)
bottom_position = int((bottom_percentile/100)*(num_movies + 1))
top_position = int((top_percentile/100)*(num_movies + 1))
worst_movies = seen_movies_pivot[-bottom_position:] # dataFrame that has the worst movies and their average rating
worst_movies_list = worst_movies.index.tolist() # list of straight up movie_id of the worst movies
best_movies = seen_movies_pivot[:top_position] # dataFrame that has the best movies and their average rating
best_movies_list = best_movies.index.tolist() # list of straight up movie_id of the best movies
client.close()
<file_sep>/CaseStudy2/previous/CaseStudy2_Prelim.py
###CASE STUDY 2####
import sys
import pandas as pd
import json
import pymongo
from pymongo import MongoClient
###################################################################################################################################
# IMPORT 1M Data
###################################################################################################################################
ratings=pd.read_table("C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/ratings.dat", sep='::', names=['user_id', 'movie_id', 'rating','timestamp'])
ratings
users=pd.read_table('C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/users.dat', sep='::', names=['user_id', 'gender', 'age', 'occupation', 'zipcode'])
users
movies=pd.read_table('C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/movies.dat', sep='::', names=['movie_id', 'title', 'genre'])
users
# AGGREGATE INTO ONE FLAT FILE NAMES data_agg_1M
data_agg_1M=pd.merge(ratings, movies, on='movie_id')
data_agg_1M=pd.merge(data_agg_1M, users ,on='user_id')
###################################################################################################################################
#####################################################################
#EXPORT JSON FILE
#invar=variable containing data to be converted to json
#filename=file name for the json data to be save to
################## START ############################################
def json_export(invar,filename):
data=invar.reset_index().to_json(orient='records')
file = open(filename,'w')
file.write(data)
file.close()
return(data)
################### END ##################################################
def main():
outfile='C:/WPI/DS501/CaseStudy/CaseStudy2/Data/1M/data_agg_1M.json'
obj_json=json_export(data_agg_1M,outfile)
main()
###################################################################################################################################
# CONNECT TO MONGODB ATLAS
###################################################################################################################################
client = pymongo.MongoClient("mongodb://admin:ds501@ds502casestudy2-shard-00-00-z2tsj.mongodb.net:27017,ds502casestudy2-shard-00-01-z2tsj.mongodb.net:27017,ds502casestudy2-shard-00-02-z2tsj.mongodb.net:27017/test?ssl=true&replicaSet=DS502CaseStudy2-shard-0&authSource=admin")
###################################################################################################################################
<file_sep>/CaseStudy2/previous/PullAllDataFromMongo.py
###CASE STUDY 2####
import sys
import pandas as pd
import json
import pymongo
from pymongo import MongoClient
###################################################################################################################################
# CONNECT TO MONGODB ATLAS
###################################################################################################################################
#Connects with the mongodb client
client = pymongo.MongoClient("mongodb://admin:ds501@casestudy2-shard-00-00-z2tsj.mongodb.net:27017,casestudy2-shard-00-01-z2tsj.mongodb.net:27017,casestudy2-shard-00-02-z2tsj.mongodb.net:27017/test?ssl=true&replicaSet=CaseStudy2-shard-0&authSource=admin")
#Connects to collection in mondgo db
#Likely would make sense to rename this but I didn't have time
db=client['data_agg_1M']
#Connects to the table in mongodb
dbmovielens=db['data_agg_1M']
###################################################################################################################################
# PULLS ALL DATA FROM MONGO DB AND CREATES A DATA FRAME CALLED movielensDF
###################################################################################################################################
allfields=['user_id','movie_id','rating','timestamp','title', 'genre', 'gender', 'age', 'occupation', 'zipcode' ]
cursor = dbmovielens.find({})
movielensDF = pd.DataFrame(list(cursor), columns = allfields)
movielensDF[:5]
| 327fbdd0ba7b1343c765086b9f46425d6153528d | [
"Markdown",
"Python"
] | 9 | Python | claireedanaher/DS501 | d8cf2248ea2e8aad1d4c98b3c3d9ae879bbda74a | ec8b6ac314ceeb37ab9cb4b3840e3f71dad2bf70 |
refs/heads/master | <file_sep>let active = document.getElementsByClassName("tab"),
dws_form = document.getElementsByClassName("dws-form")[0].children,
tab_form = document.querySelectorAll(".tab-form");
for (let key of active) {
key.addEventListener("click", function () {
for (let key of dws_form) {
key.classList.remove("active")
}
this.classList.add("active");
let index = [].indexOf.call(active, this);
tab_form.item(index).classList.add("active")
});
}
class User {
constructor(name, email, password) {
this.name = name;
this.email = email;
this.password = <PASSWORD>;
}
}
let options = {
name: {
minLength: 3,
maxLength: 10,
regExp: /^[a-zA-Z]+$/
},
email: {
regExp: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
},
pass: {
minLength: 8,
maxLength: 16,
regExp: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/
}
};
let formRegistration = document.forms["registration"],
formEnter = document.forms["enter"],
userName = formRegistration["name"],
mailRegist = formRegistration["email"],
passworRegist = formRegistration["password"],
mailEnt = formEnter["email"],
passwordEnt = formEnter["password"],
buttons = document.querySelectorAll(".button"),
enterIndicator = [false, false],
registIndicator = [false, false, false];
function checkValidationBasedPattern(str, regEx) {
return str.match(regEx) instanceof Array;
}
function checkMinLength(num, count) {
return num.length >= count;
}
function checkMaxLength(num, count) {
return num.length <= count;
}
function addClass() {
if (registIndicator.every((elem) => elem === true) && formRegistration.classList.contains("pointer") === false) {
formRegistration.classList.add("pointer");
}else if (enterIndicator.every((elem) => elem === true) && formEnter.classList.contains("pointer") === false) {
formEnter.classList.add("pointer");
}
}
function removeClass() {
if (formRegistration.classList.contains("pointer")) {
formRegistration.classList.remove("pointer");
}
if (formEnter.classList.contains("pointer")) {
formEnter.classList.remove("pointer");
}
}
userName.addEventListener("keyup", function () {
if (checkValidationBasedPattern(this.value, options.name.regExp) && checkMinLength(this.value, options.name.minLength) && checkMaxLength(this.value, options.name.maxLength)) {
this.style.border = '1px solid #00d813';
this.style.borderTopColor = "#fff";
this.style.borderLeftColor = "#fff";
registIndicator[0] = true;
if (registIndicator.every((elem) => elem === true) && formRegistration.classList.contains("pointer") === false) {
formRegistration.classList.add("pointer");
}
} else {
this.style.border = '1px solid #ff0013';
this.style.borderTopColor = "#fff";
this.style.borderLeftColor = "#fff";
registIndicator[0] = false;
if (formRegistration.classList.contains("pointer")) {
formRegistration.classList.remove("pointer");
}
}
});
function checkEmail() {
if (checkValidationBasedPattern(this.value, options.email.regExp)) {
console.log(this.forms);
this.style.border = '1px solid #00d813';
this.style.borderTopColor = "#fff";
this.style.borderLeftColor = "#fff";
if (this.form.name === 'enter') {
enterIndicator[0] = true;
} else {
registIndicator[1] = true;
}
addClass();
} else {
this.style.border = '1px solid #ff0013';
this.style.borderTopColor = "#fff";
this.style.borderLeftColor = "#fff";
if (this.form.name === 'enter') {
enterIndicator[0] = false;
} else {
registIndicator[1] = false;
}
removeClass();
}
}
function checkPassword() {
if (checkValidationBasedPattern(this.value, options.pass.regExp) && checkMinLength(this.value, options.pass.minLength) && checkMaxLength(this.value, options.pass.maxLength)) {
this.style.border = '1px solid #00d813';
this.style.borderTopColor = "#fff";
this.style.borderLeftColor = "#fff";
if (this.form.name === 'enter') {
enterIndicator[1] = true;
} else {
registIndicator[2] = true;
}
addClass();
} else {
this.style.border = '1px solid #ff0013';
this.style.borderTopColor = "#fff";
this.style.borderLeftColor = "#fff";
if (this.form.name === 'enter') {
enterIndicator[1] = false;
} else {
registIndicator[2] = false;
}
removeClass();
}
}
formRegistration.classList.add("pointer");
mailRegist.addEventListener("keyup", checkEmail);
mailEnt.addEventListener("keyup", checkEmail);
passworRegist.addEventListener("keyup", checkPassword);
passwordEnt.addEventListener("keyup", checkPassword);
buttons[0].addEventListener('click', function () {
console.log('yes');
});
buttons[1].addEventListener('click', function () {
console.log('yes');
});
| 31cbd8311fe9e560b7de004065b55aa684917234 | [
"JavaScript"
] | 1 | JavaScript | Garo150390/registration | 320692b069b990b4ca5813b1c76d60afbacfd023 | 23ddb1ccbbfd4162c5762bd2eb62fe21d1a62838 |
refs/heads/master | <repo_name>maoyunan/test<file_sep>/lib/connect_db/sqlite_connect.py
# coding=utf-8
from sqlalchemy import Table, Column, Integer, String, MetaData, create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
# import live_seeds
Base = declarative_base()
class MysqlORM(object):
def __init__(self):
self.engine = create_engine('sqlite:///test.database', echo=True)
session_factory = sessionmaker(bind=self.engine)
self.session = scoped_session(session_factory)
def create_table(self):
Base.metadata.create_all(self.engine)
def drop_table(self):
Base.metadata.drop_all(self.engine)
if __name__ == '__main__':
orm = MysqlORM()
orm.create_table()
<file_sep>/README.md
快手爬虫
-----
#### 开发日志
2018-3-23
数据库模块
2018-3-26
base版本完成
2018-5-22
将系统架构改成爬虫架构,目标支持爬链家网,javbus
2018-5-23
链家爬虫只需要支持上海地区
<file_sep>/lib/db/tables/demo_tables/live_seeds.py
from lib.connect_db.sqlite_connect import Column, Base, Integer, String, MysqlORM
class LiveSeed(Base):
__tablename__ = "live_seed"
id = Column(Integer, primary_key=True)
peer_id = Column(Integer, primary_key=False)
def __init__(
self,
peer_id=None,
):
self.peer_id = peer_id
if __name__ == '__main__':
orm = MysqlORM()
orm.session.query(LiveSeed)
# li = LiveSeed(1)
# orm.session.execute('show databases;')
# orm.session.add(li)
# results = orm.session.query(LiveSeed).all()
<file_sep>/ks_main.py
import os
import re
import requests
import time
from const.ks_const import *
def live_state_explorer(live_address):
response = requests.get(live_address, stream=True)
return response.status_code, response
def live_recorder(
storage_address,
live_stream_data,
storage_method='wb',
chunk_size=1024):
with open(storage_address, storage_method) as file:
for chunk in live_stream_data.iter_content(chunk_size):
file.write(chunk)
def storage_path(live_address):
path = 'live_show_data/{path}'.format(path=live_address)
if os.path.exists(path) is False:
os.makedirs(path)
return path + '/' + str(int(time.time())) + '.mp4'
else:
return path + '/' + str(int(time.time())) + '.mp4'
if __name__ == '__main__':
while True:
state, response_data = live_state_explorer(rg_sister_live_address)
if state != 200:
print('error, status_code = {state}'.format(state=state))
time.sleep(15)
else:
data = re.match(rule, response_data).group()
live_recorder(storage_path('rg_sister_live_address'), data)
print('success storage!')
# a = 'http://xy.pull.yximgs.com/gifshow/O08rSP0tzow.flv?sign=1522218122-8a3383e940028d7fb1ff0070565edde5'
# z = re.match(r'http://xy.pull.yximgs.com/gifshow/[0-9a-zA-Z]*.flv\?sign=\d*-[0-9a-zA-Z]*', a)
# print(z.group())
<file_sep>/const/ks_const/ks_const.py
# coding=utf-8
# Live Address---------
rabbit_live_address = 'http://ws.pull.yximgs.com/' \
'gifshow/p9PQhI9-qLc.flv?wsTime=5ab66b22&wsSecret=ef5be10d8fe442d587b0319d9089a6c0'
rg_sister_live_address = 'https://xy.pull.yximgs.com/' \
'gifshow/3HDpLWbmBjA.flv?sign=1522136610-dcaac8cc56305df3d1216377c40128fe'
headers = {
'User-Agent': 'test'}
# -----------------------------
# 连接数据库配置
USER_NAME = 'root'
PASS_WD = '<PASSWORD>'
IP = 'localhost'
PORT = '3306'
DATABASE_NAME = 'test'
# -------
rule = r'http://xy.pull.yximgs.com/gifshow/[0-9a-zA-Z]*.flv\?sign=\d*-[0-9a-zA-Z]*'
<file_sep>/lj_main.py
from optparse import OptionParser
import requests
from lxml import etree
from const.lj_const.lj_const import NEW_HOUSE, NH_REGION_XPATH, NH_LOUPAN_XPATH
def get_city_region():
parser = OptionParser()
parser.add_option("-c", "--city", dest="city",
help="请输入你的城市", metavar="city | sh")
parser.add_option("-r", "--region", dest="region",
help="请输入你需要查询的区(县)", metavar="region| yangpu")
(options, args) = parser.parse_args()
if options.city is None:
input_city = input("请输入你的城市(拼音首字母):")
else:
input_city = options.city
if options.region is None:
input_region = input("请输入你需要查询的区(县)(区县拼音):")
else:
input_region = options.region
return input_city, input_region
if __name__ == '__main__':
# city, region = get_city_region()
city = 'sh'
region = 'yangpu'
url = NEW_HOUSE.format(city=city)
try:
response = requests.get(url)
html = response.content
region_list = list()
elements = etree.HTML(html).xpath(NH_REGION_XPATH)
for element in elements:
link = element.attrib['data-district-spell']
region_list.append(link)
except BaseException:
print('请检查你的输入')
exit(1)
region_info = "{region}/#{region}".format(region=region)
url_region = ''.join([url, region_info])
print(url_region)
loupan_infos = dict()
elements = etree.HTML(requests.get(url_region).content).xpath(NH_LOUPAN_XPATH)
for element in elements:
link_url = element.attrib['href'].split('/')[2]
link_name = element.attrib['title']
loupan_infos[link_name] = link_url
# print(loupan_infos)
for loupan_n, loupan_u in loupan_infos.items():
url_l = ''.join([url, loupan_u])
elements = etree.HTML(requests.get(url_l).content).xpath(
'/html/body/div[2]/div[2]/div[4]/div[2]/div[1]/p[1]/span[1]/text()')
elements2 = etree.HTML(requests.get(url_l).content).xpath(
'/html/body/div[2]/div[2]/div[4]/div[2]/div[1]/p[1]/span[@class="yuan"]/text()')
print(elements2)
elements1 = etree.HTML(requests.get(url_l).content).xpath(
'/html/body/div[2]/div[2]/div[4]/div[2]/div[1]/p[1]/span[@class="junjia"]/text()')
# print(elements1)
# if elements[0] == '均价':
# print('{0}均价是{1}'.format(loupan_n, elements[0]))
# else:
# pass
<file_sep>/lib/connect_db/mysql.py
from sqlalchemy import create_engine, Table, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from const.ks_const import *
Base = declarative_base()
class MysqlORM(object):
def __init__(self):
self.engine = create_engine(
'connect_db+mysqldb://{user_name}:{pass_wd}@{ip}:{port}/{database_name}'.format(
user_name=USER_NAME,
pass_wd=<PASSWORD>,
ip=IP,
port=PORT,
database_name=DATABASE_NAME),
echo=False)
session_factory = sessionmaker(bind=self.engine)
self.session = scoped_session(session_factory)
def create_table(self):
Base.metadata.create_all(self.engine)
def drop_table(self):
Base.metadata.drop_all(self.engine)
if __name__ == '__main__':
orm = MysqlORM()
user = Table('user', Base.metadata,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
Column('fullname', String(40)))
orm.create_table()
<file_sep>/const/lj_const/lj_const.py
NEW_HOUSE = "https://{city}.fang.lianjia.com/loupan/"
NH_REGION_XPATH = "/html/body/div[2]/div[2]/ul/li"
NH_LOUPAN_XPATH = "/html/body/div[4]/ul[2]/li/a"
| 10e306552051b260e733ae46b23a9ca998f1d2fb | [
"Markdown",
"Python"
] | 8 | Python | maoyunan/test | 4c51450f023fa3c4a88b86e85786cd3a4948da3a | 694d2433af1909b88eee3eb2ee6cd327c3504a42 |
refs/heads/master | <file_sep>using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IS4CCRedirectUriIssue {
public class Config {
protected static ApiResource API_RESOURCE = new ApiResource("test-api", "My API");
public static IEnumerable<ApiResource> GetApiResources() {
return new List<ApiResource>
{
API_RESOURCE
};
}
public static IEnumerable<IdentityResource> GetIdentityResources() => new List<IdentityResource>();
public static IEnumerable<Client> GetClients() {
return new List<Client>
{
new Client {
ClientId = "Broken-Client",
AllowedGrantTypes = { GrantType.ClientCredentials, GrantType.AuthorizationCode },
ClientSecrets = { new Secret("Broken-Client-Secret".Sha256()) },
AllowedScopes = { API_RESOURCE.Name }
},
new Client {
ClientId = "Working-Client",
AllowedGrantTypes = { GrantType.ClientCredentials },
ClientSecrets = { new Secret("Working-Client-Secret".Sha256()) },
AllowedScopes = { API_RESOURCE.Name }
}
};
}
public static List<TestUser> GetTestUsers() => new List<TestUser>();
}
}
<file_sep>Allowing a client to grant both authorization code and client credentials will result in only authorization code being validated. Identity Server will complain that no redirect URI has been specified even though it should not be necessary for Client Credentials Flow.<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
namespace IS4CCRedirectUriIssue.Client {
[Route("Issue")]
public class IssueController : Controller {
[HttpGet]
public async Task<string> Index() {
var disco = await DiscoveryClient.GetAsync("https://localhost:5001");
if (disco.IsError) {
return disco.Error;
}
var response = new StringBuilder();
//Broken client
response.AppendLine("Client Credentials + Authorization Code:");
var brokenTokenClient = new TokenClient(disco.TokenEndpoint, "Broken-Client", "Broken-Client-Secret");
var brokenTokenResponse = await brokenTokenClient.RequestClientCredentialsAsync("test-api");
if (brokenTokenResponse.IsError) {
response.AppendLine(brokenTokenResponse.Error);
} else {
response.AppendLine(brokenTokenResponse.Json.ToString());
}
response.AppendLine();
response.AppendLine("Only Client Credentials:");
//Working client, only difference being this one doesn't allow Authorization Code
var workingTokenClient = new TokenClient(disco.TokenEndpoint, "Working-Client", "Working-Client-Secret");
var workingTokenResponse = await workingTokenClient.RequestClientCredentialsAsync("test-api");
if (workingTokenResponse.IsError) {
response.AppendLine(workingTokenResponse.Error);
} else {
response.AppendLine(workingTokenResponse.Json.ToString());
}
return response.ToString(); ;
}
}
}
| 508ba8e8dddeba56e341142f4ba82075e8eab2b1 | [
"Markdown",
"C#"
] | 3 | C# | tedchirvasiu/identity-server-4-client-credentials-issue | d89d0604ad237e482a8c6a172e85317c2a2163b7 | e41d57cb2d045550c8fab88359802a18ba670338 |
refs/heads/master | <repo_name>adelrodriguez/wikipedia-viewer<file_sep>/viewer.js
$(document).ready(function() {
$("form").submit(function(event) {
// prevent page from reloading
event.preventDefault();
// clear old results
$(".card-columns").empty();
// search results
search();
});
});
function search() {
var query = $("input[type='text']").val();
$("input[type='text']").val("");
var url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + query + "&utf8=&srlimit=25&format=json&callback=?";
getResults(url);
}
function getResults(url) {
$.getJSON(url, function(data) {
data.query.search.forEach(displayResults);
});
}
function displayResults(result) {
var articleLink = "https://en.wikipedia.org/wiki/" + result.title;
var card = '<div class="card">' +
'<a class="article" target="_blank" href="' + articleLink + '">' +
'<div class="card-block">' +
'<h4 class="card-title">' + result.title + '</h4>' +
'<p class="card-text">' + result.snippet +
'</p></div></a></div>';
$(card).appendTo(".card-columns").hide().fadeIn(1000);
}<file_sep>/README.md
# Wikipedia Viewer
This is was made for freeCodeCamp's "Build a Wikipedia Viewer" project. It uses the [MediaWiki API](https://www.mediawiki.org/wiki/API:Main_page) and Bootstrap 4. | 618e65019cd9be690d9d61601db835c769f23c54 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | adelrodriguez/wikipedia-viewer | 5b5e3a7b3f0021a3473e575f6329b9a5454e6bb4 | 3250abd77f8d4a3a087f77cb96022fa1be6d5a72 |
refs/heads/master | <file_sep>
# Polyseer.io SDK for Node.js
The official Polyseer.io SDK for Node.js. Detailed API information can be found at (https://polyseer.io/documentation).
## About
Polyseer.io is an Integrated Development Platform that instantly
provides teams with the resources needed to build, support, and maintain world
class software products.
## Requirements
- Node.js (see package.json for supported versions)
- NPM
## Installation
To install inside a project, run:
npm install polyseerio --save
## Example
Be sure to check out the examples in /example.
## Environment Variables
Certain values can be set in environment variables:
* POLYSEERIO_TOKEN access-token used for API calls
* NODE_ENV the current environment
* POLYSEERIO_LOG_LEVEL SDK logging level default error
## Usage
This SDK provides direct platform interactions as well as a
configurable agent that can be used for immediate integration.
Example: (Quick start agent)
return require('polyseerio').start().then(client ⇒ { console.log('ok') });
Example: (Configured quick start)
const polyseerio = require('polyseerio');
return polyseerio.start({
env: 'APP_ENV',
environment: 'testing',
agent: {
id: 'my-instance-id',
attach_strategy: polyseerio.Strategy.ID
}
}).
then(client ⇒ {
console.log('ok');
});
Example: (SDK only)
const polyseerio = require('polyseerio'),
client = polyseerio({ token: 'my-access-token' }),
{ Event,
Alert,
Instance } = client;
return Instance.attach({
name: 'my-example-instance',
strategy: Instance.attach.Strategy.FALLBACK
}).then(instance ⇒ {
console.log(`Manual instance attached as: ${instance.get('id')}.`);
return Event.create({
name: `Attached ${instance.get('name')}.`,
color: polyseerio.Color.GREEN,
icon: polyseerio.Icon.CHECK,
description: `ID: ${instance.get('id')}`
});
}).then(event ⇒ {
console.log(`Event: ${event.get('id')}, was triggered.`);
return Alert.findByName('instance-attached');
}).then(alert ⇒ {
return alert.trigger({
meta: {
notice: 'Just wanted to alert you to this.'
}
});
}).catch(console.log);
## Design
* Provides direct platform calls via client a well as a Polyseer.io Node.JS agent.
* All client SDK calls return a Promise.
* Supports object-oriented style programming.
* ORM style instances. E.g. environment.save(), alert.trigger(), instance.gauge();
* A resources environment can be deduced or explicitly passed to SDK calls through the options param.
* Missing environment's will be upserted by default.
* API calls are made using the https:// protocol.
## SDK Resources
Use of the SDK begins with construction of a client. To construct a client
instance, call the required polyseerio module.
### polyseerio
* polyseerio
* `(options = {}) ⇒ Client`
* `options (Object)`
- `.deduce (Boolean)` if the environment should be deduced from the environment when not supplied
- `.env (String)` environment variable holding current environment
- `.timeout (Number)` integer containing number of ms to wait for server responses
- `.token (String)` environment variable holding current environment
- `.token_env (String)` if no token is provided this environment variable will be checked for one
- `.upsert_env (Boolean)` if an environment should be created when it cannot be found
- `.version (String)` api version to use
* `.start(options = {}) ⇒ Client` generate a client and start an agent
* `options (Object)` see () options, plus the additional below can be passed
- `.agent (Object)` agent options (see client.startAgent options)
* `.Color (Object)` platform color types
* `.Determiner (Object)` expectation determiner types
* `.Direction (Object)` instance direction types
* `.Icon (Object)` platform icon types
* `.Protocol (Object)` alert protocol types
* `.Strategy (Object)` instance attachment strategies
* `.Subtype (Object)` instance subtypes
* `.Type (Object)` resource types
### client
* client
* `.getCurrentEnvironment() ⇒ client.Environment` Resolves the current environment **IF** it has been deduced.
* `.startAgent(options = {}) ⇒ client` Starts the Polyseer.io agent.
* `options`
- `.attach (Boolean)`
- `.attach_strategy (Symbol)`
- `.name (String)` instance name (will be used as a unique id)
- `.description (String)` a description of this instance
- `.group (String)` what group this instance belongs to
- `.agent_retry (Number)` number of ms to retry agent attach when initial attach fails
- `.direction (polyseerio.Direction)` the monitoring direction (inbound) // force this
- `.subtype (polyseerio.Subtype)` the instance subtype: periodic or long_running.
- `.expectation` will be upserted for this instance
- `.is_alive (Boolean)` create an expectation that this process is alive
- `.fact`
- `.architecture (Boolean)` the operating system architecture
- `.cpu_count (Boolean)` the number of cores
- `.endianess (Boolean)` if the architecture if little or big endian
- `.free_memory (Boolean)` the current free memory
- `.gid (Boolean)` the group if othe process is running under
- `.home_directory (Boolean)` current user's home directory
- `.hostname (Boolean)` the system hostname
- `.launch_arguments (Boolean)` command used to launch the instance
- `.node_version (Boolean)` the version of node being used
- `.pid (Boolean)` the id of the process
- `.platform (Boolean)` the operating platform of
- `.title (Boolean)` the title of the process
- `.uid (Boolean)` user id the process is running as
- `.uptime (Boolean)` the uptime of the process
- `.v8_version (Boolean)` the version of v8
- `.metric`
- `.cpu (Boolean)` track user and system cpu usage
- `.memory (Boolean)` track memory usage
- `.uptime (Boolean)` track process uptime
- `.event`
- `.start (Boolean)` event notice when agent starts
- `.stop (Boolean)` event notice when agent stops
- `.process`
- `.SIGHUP (Boolean)` event notice when process receives SIGHUP
- `.SIGINT (Boolean)` event notice when process receives SIGINT
- `.SIGTERM (Boolean)` event notice when process receives SIGTERM
- `.exit (Boolean)` event notice on process exit
- `.uncaughtException (Boolean)` event notice on uncaught execptions
- `.unhandledRejection (Boolean)` event notice on unhandled promise rejections
- `.warning (Boolean)` event notice on process warning
* Contains all of the enum values exported on polyseerio as well.
### Alert
* .Alert
* `.create(attributes = {}, options = {}) ⇒ client.Alert`
* `.find(query = {}, options = {}) ⇒ client.Alert`
* `.findById(id, options = {}) ⇒ [client.Alert]`
* `.findByName(name, options = {}) ⇒ client.Alert`
* `.remove(id, options = {})`
* `.trigger(id, payload = {}, options = {}) ⇒ client.Alert`
* `.update(id, updates = {}, options = {}) ⇒ client.Alert`
* new **Alert**(attributes = {})
* `.get(key) ⇒ Mixed`
* `.remove() ⇒ this`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
* `.trigger(payload = {}) ⇒ this`
### Channel
* .Channel
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.findByName(name, options = {})`
* `.message(id, content, options = {})`
* `.remove(id, options = {})`
* `.update(id, updates = {}, options = {})`
* new **Channel**(attributes = {})
* `.get(key) ⇒ Mixed`
* `.message(content)`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Environment
* .Environment
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.findByName(name, options = {})`
* `.message(id, content, options = {})`
* `.remove(id, options = {})`
* `.update(id, payload = {}, options = {})`
* new **Environment**(attributes = {})
* `.get(key) ⇒ Mixed`
* `.message(content)`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Event
* .Event
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* new **Event**(attributes = {})
* `.get(key) ⇒ Mixed`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Expectation
* .Expectation
* `.check(id, options = {})`
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.findByName(name, options = {})`
* `.remove(id, options = {})`
* `.update(id, updates = {}, options = {})`
* new **Expectation**(attributes = {})
* `.check()`
* `.get(key) ⇒ Mixed`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Instance
* .Instance
* `.attach(options = {})`
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.findByName(name, options = {})`
* `.remove(id, options = {})`
* `.update(id, updates = {}, options = {})`
* new **Instance**(attributes = {})
* `.addFact()`
* `.addGauge()`
* `.attach()`
* `.fact()`
* `.gauge()`
* `.get(key) ⇒ Mixed`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Logic Block
* .LogicBlock
* `.create(attributes = {}, options = {})`
* `.execute(id, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.findByName(name, options = {})`
* `.remove(id, options = {})`
* `.update(id, updates = {}, options = {})`
* new **LogicBlock**(attributes = {})
* `.execute()`
* `.get(key) ⇒ Mixed`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Member
* .Member
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.remove(id, options = {})`
* `.update(id, updates = {}, options = {})`
* new **Member**(attributes = {})
* `.get(key) ⇒ Mixed`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
### Settings
* .Settings
* `.retrieve()`
* `.update(updates = {})`
### Task
* .Task
* `.create(attributes = {}, options = {})`
* `.find(query = {}, options = {})`
* `.findById(id, options = {})`
* `.remove(id, options = {})`
* `.update(id, updates = {}, options = {})`
* new **Task**(attributes = {})
* `.get(key) ⇒ Mixed`
* `.remove()`
* `.save() ⇒ this`
* `.set(key, value, default = undefined) ⇒ this`
* `.setProperties(object = {}) ⇒ this`
## Contributing
Always welcome to add, just open a PR.
## Testing
Testing requires:
- Make
- Grunt
- nvm (if doing version testing)
Install node modules locally by running:
npm install
Then run a command below based on what test suite you need to run.
### Lint
make lint
### Unit
make unit-test
### Integration
make integration-test
### Validation
Requires the environment to have a root level access-token defined as:
export ROOT_KEY=a-test-root-key
make validation-test
### Version testing
make version-testing
To test specific versions:
make version-testing SUPPORTED=4.0.0 5.0.0 5.2.0
### All
make test
## Debugging
In order to debug an issue is can be helpful to enable debug logging. To do
so set the environment variable: POLYSEERIO_LOG_LEVEL to debug.
<file_sep>'use strict';
const should = require('should'),
lodash = require('lodash'),
sinon = require('sinon'),
proxyquire = require('proxyquire'),
{ createRequestMock } = require('./helper');
/**
* Returns an Agent mock.
*
* @return {sinon.stub}
*/
function createAgentMock () {
return {
start: sinon.stub(),
on: sinon.stub()
};
}
/**
* Agent double used as standin through proxyquire.
*/
class AgentDouble {
constructor (...args) {
this.args = args;
}
start (...args) {
return global.Promise.resolve(args);
}
on (...args) {
return args;
}
}
describe('Client', () => {
const Client = proxyquire('../../lib/client', {
'./agent': AgentDouble
});
describe('constructor', () => {
it('throws a TypeError if a cid is not passed', () => {
(function () {
new Client(undefined, {});
}).should.throw('Cannot create a Client instance without passing a unique client id (cid).');
});
it('throws a TypeError if an instance of request is not passed', () => {
(function () {
new Client(1, {});
}).should.throw('Cannot create an instance of Client without passing an instance of request to the options.');
});
it('defaults the agent to null', () => {
const client =new Client(1, {
request: createRequestMock()
});
lodash.isNull(client._agent).should.eql(true);
});
});
describe('Event', () => {
const { Event } = Client;
it('defines AGENT_START', () => {
Event.AGENT_START.should.eql('agent-start');
});
it('defines AGENT_STOP', () => {
Event.AGENT_STOP.should.eql('agent-stop');
});
});
it('is eventable', () => {
const client = new Client(0, {
request: createRequestMock()
});
client.should.have.property('on');
client.should.have.property('once');
client.should.have.property('emit');
});
describe('startAgent', () => {
it('throws if agent has already been started', () => {
const client = new Client(0, {
request: createRequestMock()
});
client._agent = createAgentMock();
return client.startAgent().should.be.
rejectedWith('Agent has already been started for this client.');
});
it('creates an Agent instance, calls start and forwards arguments', () => {
const client = new Client(0, {
request: createRequestMock()
});
const agentArgs = ['a', 'foo', 'b'];
return client.startAgent(...agentArgs).should.be.fulfilled().
then(result => {
client._agent.args.should.eql([client]);
result.should.eql(agentArgs);
});
});
});
});
<file_sep>'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var lodash = require('lodash'),
co = require('co'),
DefaultConfig = require('./default_config'),
HandlerMap = require('./handler'),
logger = require('../logger'),
_require = require('../enum'),
Strategy = _require.Strategy,
logAndReject = logger.logAndReject,
_require2 = require('../resource/routine'),
upsert = _require2.upsert,
_require3 = require('./helper'),
filterHandlers = _require3.filterHandlers,
resolveName = _require3.resolveName,
teardownWithHandler = _require3.teardownWithHandler,
setupWithHandler = _require3.setupWithHandler;
/**
* Fulfills an agent configuration.
*
* @param {Client}
* @param {object}
* @return {Promise}
*/
function setup(client, options) {
return co(regeneratorRuntime.mark(function _callee2() {
var _this = this;
var _ret;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
logger.log('debug', 'Setting up agent for client: ' + client._cid + '.');
if (!options.attach) {
_context2.next = 6;
break;
}
return _context2.delegateYield(regeneratorRuntime.mark(function _callee() {
var instance, name, setupHandler, setups;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// resolve the instance
instance = null;
_context.t0 = options.attach_strategy;
_context.next = _context.t0 === Strategy.FALLBACK ? 4 : _context.t0 === Strategy.ID ? 10 : 15;
break;
case 4:
logger.log('debug', 'Resolving instance using fallback.');
name = resolveName(options);
_context.next = 8;
return upsert(client.Instance, { name: name });
case 8:
instance = _context.sent;
return _context.abrupt('break', 15);
case 10:
logger.log('debug', 'Resolving instance using primary id.', {
id: options.id
});
_context.next = 13;
return client.Instance.find_by_id(options.id);
case 13:
instance = _context.sent;
return _context.abrupt('break', 15);
case 15:
client.instance = instance;
// create a setup handler.
setupHandler = setupWithHandler(HandlerMap, client, options.handlers);
// gather and perform work.
setups = lodash.map(options.handlers, function (_, key) {
return setupHandler(key);
});
_context.next = 20;
return global.Promise.all(setups);
case 20:
logger.log('debug', 'Attempting to attach instance to polyseerio.', {
id: instance.id,
strategy: options.attach_strategy
});
// start monitoring.
_context.next = 23;
return instance.attach();
case 23:
return _context.abrupt('return', {
v: instance
});
case 24:
case 'end':
return _context.stop();
}
}
}, _callee, _this);
})(), 't0', 3);
case 3:
_ret = _context2.t0;
if (!((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object")) {
_context2.next = 6;
break;
}
return _context2.abrupt('return', _ret.v);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
})).catch(logAndReject);
}
/**
* Tearsdown an client's agent.
*
* @param {Client}
* @return {Promise}
*/
function teardown(client, handlerOptions) {
return co(regeneratorRuntime.mark(function _callee3() {
var teardownHandler, teardowns;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
logger.log('debug', 'Tearing down agent for client: ' + client._cid + '.');
teardownHandler = teardownWithHandler(HandlerMap, client, handlerOptions);
// gather and perform work.
teardowns = lodash.map(handlerOptions, function (_, key) {
return teardownHandler(key);
});
_context3.next = 5;
return global.Promise.all(teardowns);
case 5:
_context3.next = 7;
return client.instance.detach();
case 7:
return _context3.abrupt('return', client);
case 8:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
})).catch(logAndReject);
}
module.exports = {
setup: setup,
teardown: teardown
};<file_sep>'use strict';
const lodash = require('lodash'),
{ resolveEid } = require('../helper');
/**
* Base resource class.
*/
class Base {
constructor (attributes = {}) {
if (lodash.has(attributes, 'eid')) {
this.eid = attributes.eid;
} else {
this.eid = resolveEid(this.copts || {});
}
this._attributes = attributes;
}
}
module.exports = Base;
<file_sep>'use strict';
const should = require('should'),
co = require('co'),
{ DEFAULT_TIMEOUT } = require('./config'),
{ setup,
teardown } = require('./helper');
describe('Upsert Environment', function () {
this.timeout(DEFAULT_TIMEOUT);
before(function () {
return setup(this, {
upsert_env: true
}).
then(_ => {
this.Event = this.client.Event;
});
});
after(function () { teardown(this); });
it('when upsert_env is on and a resource is created in a non-existent environment it will create the environment and the resource', function() {
const client = this.client,
Event = this.Event,
name = 'zoozoo';
return co(function* () {
const event = yield Event.create({ name: 'foofoo' }, {
environment: name
});
event.get('name').should.eql('foofoo');
const foundEvent = yield Event.findById(event.get('id'), {
environment: name
});
const environment = yield client.Environment.findByName(name);
const result = yield client.Environment.remove(environment.get('id'));
});
});
});
<file_sep>'use strict';
const should = require('should'),
lodash = require('lodash');
describe('Base', () => {
const Base = require('../../../lib/resource/base');
describe('constructor', () => {
it('can construct with no arguments', () => {
(function () {
new Base();
}).should.not.throw();
});
it('sets the attributes passed as _attributes', () => {
const attributes = {
foo: 'bar'
};
const instance = new Base(attributes);
instance._attributes.should.eql(attributes);
});
it('will set passed eid', () => {
const attributes = {
eid: 'alpha'
};
const instance = new Base(attributes);
instance.eid.should.eql('alpha');
});
it('correct default eid', () => {
const instance = new Base();
instance.eid.should.eql('development');
});
});
});
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon'),
helper = require('./helper');
describe('Static: findById', () => {
const method = require('../../../../lib/sdk/static/findById');
const id = 100,
options = {};
it('makes the correct call to get', () => {
const context = helper.getContext();
context.request.get.returns(global.Promise.resolve());
return method(id, options, context).
then(_ => {
context.request.get.called.should.eql(true);
context.request.get.calledWithExactly({
uri: context.uri
}).should.eql(true);
});
});
it('resolves when get resolves', () => {
const context = helper.getContext(),
result = sinon.stub();
context.request.get.returns(global.Promise.resolve(result));
return method(id, options, context).should.be.fulfilled(result);
});
it('rejects when get rejects', () => {
const context = helper.getContext(),
error = new Error('foo');
context.request.get.returns(global.Promise.reject(error));
return method(id, options, context).should.be.rejectedWith(error);
});
});
<file_sep>'use strict';
const fs = require('fs'),
path = require('path'),
lodash = require('lodash'),
inflection = require('inflection'),
{ DEFAULT_ENVIRONMENT } = require('./constant');
const DEFAULT_LOOP_PROMISE_OPTIONS = {
delay: 1000
};
/**
* Converts a resource (URL section) to resource type.
*
* @param {string}
* @return {string}
*/
function resourceToType (resource) {
return inflection.singularize(resource);
}
/**
* Used in instance methods to forward context to function as the
* first argument.
*
* @param {function}
* @return {function}
*/
function forwardThis (func) {
return function (...args) {
/*jshint validthis:true */
return func(this, ...args);
};
}
/**
* Clear a promise loop.
*
* @param {number}
*/
function clearLoop (loopId) {
if (!lodash.isNumber(loopId)) {
throw new Error(`clearLoop expects a number to be passed, got: ${loopId}.`);
}
const loop = loopPromise.map.get(loopId);
if (loop.tid) {
clearTimeout(loop.tid);
}
return global.Promise.resolve();
}
/**
* Used for each loop created by the loopPromise.
*/
class LoopObject {
constructor (id) {
this.id = id;
this.clear = false;
this.loop = null;
this.resolve = null;
this.reject = null;
}
}
/**
* Loop a promise returning function.
*
* @param {promise}
* @return {number}
*/
function loopPromise (promise, options = {}) {
options = Object.assign({}, DEFAULT_LOOP_PROMISE_OPTIONS, options);
const { delay } = options;
loopPromise._id = loopPromise._id++ || 0;
const loopObject = new LoopObject(loopPromise._id);
loopPromise.map.set(loopObject.id, loopObject);
/**
* Returns a delayed promise if the the delay has not yet been met.
*
* @param {number}
* @param {number}
* @param {Mixed}
*/
function delayLoop (start, delay, result) {
const remaining = (delay - (Date.now() - start)),
amount = (remaining > 0) ? remaining : 0;
return delayPromise(amount, loopObject, result);
}
/**
* Takes a start time and a delay amount, returns a higher order
* function that will pass the result of a promise through but first
* delay the resolution by the remaining delay if it exists.
*
* @param {number}
* @param {number}
*/
function delayIdentity (start, delay) {
return result => {
return delayLoop(start, delay, result);
};
}
function loop (local) {
const start = Date.now();
return promise().
then(delayIdentity(start, delay)).
catch(delayIdentity(start, delay)).
then(result => {
if (loopObject.clear) {
loopPromise.map.delete(loopObject.id);
return global.Promise.reject();
}
return result;
}).
then(loop);
}
loop(promise);
return loopObject.id;
}
loopPromise.map = new Map();
/**
* Delay a promise by some amount.
*
* @param {number}
* @param {Mixed}
* @return {function}
*/
function delayPromise (amount, loopObject, result) {
return new global.Promise((resolve, reject) => {
loopObject.tid = setTimeout(_ => resolve(result), amount);
loopObject.resolve = resolve;
loopObject.reject = reject;
});
}
/**
* Returns default options given defaults and passed options.
*
* @param {object}
* @param {object}
* @return {object}
*/
function createOptions (options, defaults = {}) {
return Object.assign({}, defaults, options);
}
/**
* Forward object based arguments with an override.
*
* @param {request} options
* @param {string} resource type
* @param {object} query params
*/
function forward (args, adjustments) {
return lodash.zipWith(args, adjustments, (left, right) => {
return Object.assign({}, left, right);
});
}
// Default options for the wrapRequest middleware parameter.
const DEFAULT_WRAP_REQUEST_MIDDLEWARE = {
pre: lodash.identity,
post: lodash.identity,
reject: function (error) {
return global.Promise.reject(error);
}
};
/**
* Wrap a request instance with some option middleware.
*
* @param {request}
* @param {function}
* @param {function}
* @return {object}
*/
function wrapRequest (request, middleware) {
middleware = lodash.defaults(middleware, DEFAULT_WRAP_REQUEST_MIDDLEWARE);
const { pre, post, reject } = middleware;
const wrapper = options => request(pre(options)).then(post, reject);
['del',
'delete',
'get',
'patch',
'post',
'put'
].forEach(method => {
wrapper[method] = options => {
return request[method](pre(options)).then(post, reject);
};
});
return wrapper;
}
/**
* Requires an entire directory.
*
* @param {string}
* @param {function}
* @param {function}
* @return {object}
*/
function requireDirectory (directory, predicate, iteratee) {
const requireObjects = _getRequireObjects(...arguments);
return _requireRequireObjects(requireObjects);
}
/**
* Given an array of export objects, a reduced object is returned.
*
* @param {array[object]}
* @return {object}
*/
function _requireRequireObjects (requireObjects) {
return requireObjects.reduce((result, requireObject) => {
result[requireObject.name] = require(requireObject.require);
return result;
}, {});
}
/**
* Creates a loadable directory object given a predicate and iteratee.
*
* @param {string}
* @param {function}
* @param {function}
* @return {object}
*/
function _getRequireObjects (directory, predicate, iteratee) {
return fs.readdirSync(directory).reduce((result, file) => {
const pathObject = path.parse(file);
if (predicate(pathObject)) {
result.push(iteratee(pathObject));
}
return result;
}, []);
}
/**
* Format a payload before sending.
*
* @param {object}
* @return {object}
*/
function formatPayload (payload) {
return {
data: {
attributes: Object.assign({}, payload)
}
};
}
/**
* Remap an object based on a path mapping.
*
* TODO: name rekey see if there is a single liner lodash
*
* @param {object} the object to remap paths for
* @param {object} the mapping of current paths
* @return {object} the remapped object
*/
function remapObjectPaths (object, paths = {}) {
return lodash.reduce(object, (result, value, key) => {
if (!(key in paths)) {
result[key] = value;
} else {
result[paths[key]] = value;
}
return result;
}, {});
}
/**
* Create an environment mapping.
*
* @param {string} the environment variable that holds the current environment
* @param {object} the environments that should be defined
* @param {object} current process.env variables
* @return {object} map
* @return {object} map.current
* @return {object} map.environments
* @throws {Error} when no environment key exists
*/
function _createEnvironmentMap (key, environments, env) {
if (lodash.has(env, key)) {
const current = env[key];
return { current, environments: Object.assign({}, environments) };
} else {
throw new Error(`Could not create an environment map, no environment variable named: ${key} could be found.`);
}
}
/**
* Will attempt to resolve the API token.
*
* Returns undefined if one cannot be resolved.
*
* @param {string} token as passed by client constructor
* @param {object} where to look in the environment for a token
* @return {string|undefined}
*/
function resolveToken (options) {
if (!lodash.isNil(options.token)) {
return options.token;
}
if (lodash.has(process.env, options.token_env)) {
const value = lodash.get(process.env, options.token_env);
if (!lodash.isNil(value)) {
return value;
}
}
return null;
}
/**
* Attempt to resolve the current environment EID from the
* options.
*
* @param {object}
* @return {object}
*/
function resolveEid (options) {
if ('environment' in options && !lodash.isNil(options.environment)) {
return options.environment;
}
if (options.deduce) {
const env = options.env;
if (env in process.env) {
return process.env[env];
}
}
return DEFAULT_ENVIRONMENT;
}
/**
* Given an environment map, the current environment will be returned.
*
* @param {string} the environment variable that holds the current environment
* @param {object} the environments that should be defined
* @param {object} current process.env variables
* @return {string} the current environment id
*/
function deduceEid (key, environments, env) {
const map = _createEnvironmentMap(key, environments, env);
if (lodash.has(map.environments, map.current)) {
return map.environments[map.current];
} else {
throw new Error(`Could not find the current environment: ${map.current} in the environments passed.`);
}
}
module.exports = {
clearLoop,
createOptions,
deduceEid,
formatPayload,
forward,
forwardThis,
loopPromise,
remapObjectPaths,
requireDirectory,
resolveEid,
resolveToken,
resourceToType,
wrapRequest
};
<file_sep>'use strict';
var lodash = require('lodash');
/**
* Set multiple attribute.
*
* @param {Resoure}
* @param {string}
* @param {mixed}
* @return {mixed}
*/
function setProperties(instance) {
var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
lodash.forEach(properties, function (value, key) {
instance.set(key, value);
});
return instance;
}
module.exports = setProperties;<file_sep>'use strict';
var winston = require('winston'),
lodash = require('lodash');
/**
* SDK logger.
*/
var logger = new winston.Logger({
level: process.env.POLYSEERIO_LOG_LEVEL || 'error',
transports: [new winston.transports.Console()]
});
/**
* Log an error.
*
* @param {winston}
* @param {Error}
*/
function _logErrorWithLogger(logger, error) {
var meta = { stack: error.stack };
logger.log('error', error.name + ': ' + error.message, meta);
}
var logErrorWithLogger = lodash.curry(_logErrorWithLogger);
/**
* Log an error and continue to reject.
*
* @param {winston}
* @param {Error}
*/
function _logAndRejectWithLogger(logger, error) {
logErrorWithLogger(logger, error);
return global.Promise.reject(error);
}
var logAndRejectWithLogger = lodash.curry(_logAndRejectWithLogger);
/**
* Create helper methods.
*/
var logError = logErrorWithLogger(logger);
var logAndReject = logAndRejectWithLogger(logger);
// A little bit dangerous. Maybe there is a way to be nicer.
Object.assign(logger, {
logError: logError,
logAndReject: logAndReject
});
module.exports = logger;<file_sep>'use strict';
/**
* Trigger a resource.
*
* @param {string}
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function trigger (id, meta, options, context = {}) {
meta = meta || {};
return context.request.post({
uri: `${context.uri}/trigger`,
body: { meta }
});
}
module.exports = trigger;
<file_sep>'use strict';
const should = require('should'),
lodash = require('lodash');
describe('Factory', () => {
const factory = require('../../lib');
describe('RequiredResources', () => {
const { RequiredResources } = factory;
it('includes the correct required resource sdks', () => {
RequiredResources.should.containDeep([
'alerts',
'channels',
'environments',
'events',
'expectations',
'instances',
'logic-blocks',
'members',
'settings',
'tasks'
]);
});
});
describe('ClientResourcePaths', () => {
const { ClientResourcePaths } = factory;
it('correctly defines alerts path', () => {
const path = ClientResourcePaths.alerts;
path.should.eql('Alert');
});
it('correctly defines channels path', () => {
const path = ClientResourcePaths.channels;
path.should.eql('Channel');
});
it('correctly defines environements path', () => {
const path = ClientResourcePaths.environments;
path.should.eql('Environment');
});
it('correctly defines events path', () => {
const path = ClientResourcePaths.events;
path.should.eql('Event');
});
it('correctly defines expectations path', () => {
const path = ClientResourcePaths.expectations;
path.should.eql('Expectation');
});
it('correctly defines instances path', () => {
const path = ClientResourcePaths.instances;
path.should.eql('Instance');
});
it('correctly defines logic-blocks path', () => {
const path = ClientResourcePaths['logic-blocks'];
path.should.eql('LogicBlock');
});
it('correctly defines members path', () => {
const path = ClientResourcePaths.members;
path.should.eql('Member');
});
it('correctly defines settings path', () => {
const path = ClientResourcePaths.settings;
path.should.eql('Settings');
});
it('correctly defines tasks path', () => {
const path = ClientResourcePaths.tasks;
path.should.eql('Task');
});
});
it('throws a TypeError without a token', () => {
(function () {
factory({ token_env: 'ZINGZANG' });
}).should.throw('Could not find an access token. None was passed and none could be found in the environment variable: ZINGZANG.');
});
});
<file_sep>'use strict';
/**
* Remove a resource.
*
* @param {string}
* @param {object}
* @param {object}
* @return {Promise}
*/
function remove (id, options, context = {}) {
return context.request.del({ uri: context.uri });
}
module.exports = remove;
<file_sep>'use strict';
const Fact = {
ARCHITECTURE: 'architecture',
CPU_COUNT: 'cpu_count',
ENDIANNESS: 'endianness',
FREE_MEMORY: 'free_memory',
GID: 'gid',
HOME_DIRECTORY: 'home_directory',
HOSTNAME: 'hostname',
LAUNCH_ARGUMENTS: 'launch_arguments',
NODE_VERSION: 'node_version',
PID: 'pid',
PLATFORM: 'platform',
TITLE: 'title',
UID: 'uid',
UPTIME: 'uptime',
V8_VERSION: 'v8_version'
};
const Expectation = {
IS_ALIVE: 'is_alive'
};
const Event = {
START: 'start',
STOP: 'stop'
};
const Process = {
EXIT: 'exit',
UNCAUGHT_EXCEPTION: 'uncaughtException',
UNHANDLED_REJECTION: 'unhandledRejection',
WARNING: 'warning',
SIGHUP: 'SIGHUP',
SIGINT: 'SIGINT',
SIGTERM: 'SIGTERM'
};
const Metric = {
MEMORY: 'memory',
CPU: 'cpu',
UPTIME: 'uptime'
};
module.exports = {
Event,
Expectation,
Fact,
Metric,
Process
};
<file_sep>'use strict';
const Logic = require('../logic.json'),
{ Expectation } = require('../enum');
module.exports = {
[Expectation.IS_ALIVE] (_config, client) {
return client.Expectation.create({
name: `${client.instance.get('name')} instance is alive.`,
description: `Agent created expectation.`,
is_on: true,
determiner: client.Determiner.ONE,
subject: client.Type.INSTANCE,
subjects: [client.instance.get('id')],
is_expected: true,
logic: Logic[Expectation.IS_ALIVE]
});
}
};
<file_sep>'use strict';
var checkStatic = require('../static/check');
/**
* Create a check instance method for a resource.
*
* @param {request}
* @param {string}
* @return {function}
*/
function check(instance) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return checkStatic.apply(undefined, [instance.id].concat(args));
}
module.exports = check;<file_sep>'use strict';
const should = require('should');
describe('get', () => {
const method = require('../../../../lib/sdk/method/get');
it('returns the attribute', () => {
const result = method({
_attributes: {
foo: 'bar'
}
}, 'foo');
result.should.eql('bar');
});
it('defaults to undefined', () => {
const result = method({
_attributes: {
foo: 'bar'
}
}, 'alpha');
(result === undefined).should.eql(true);
});
it('allows for a default', () => {
const result = method({
_attributes: {
foo: 'bar'
}
}, 'alpha', 'zoomie');
result.should.eql('zoomie');
});
});
<file_sep>'use strict';
var messageStatic = require('../static/message');
/**
* Create a message instance method for a resource.
*
* @param {Resource}
* @param {...}
* @return {Promise}
*/
function message(instance) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return messageStatic.apply(undefined, [instance.id].concat(args));
}
module.exports = message;<file_sep>'use strict';
var lodash = require('lodash'),
_require = require('./enum'),
Resource = _require.Resource,
_require2 = require('./constant'),
DEFAULT_API_BASE_URL = _require2.DEFAULT_API_BASE_URL,
DEFAULT_API_VERSION = _require2.DEFAULT_API_VERSION,
DEFAULT_API_PROTOCOL = _require2.DEFAULT_API_PROTOCOL;
/**
* Resources that are routable by environment.
*/
var RoutableResources = [Resource.ALERT, Resource.ENVIRONMENT_MESSAGE, Resource.EVENT, Resource.EXPECTATION, Resource.INSTANCE, Resource.TASK];
/**
* Determines if a resource is routable by environment.
*
* @param {string}
* @return {boolean}
*/
function _isRoutableResource(resource) {
return RoutableResources.indexOf(resource) !== -1;
}
// Use memoized version.
var isRoutableResource = lodash.memoize(_isRoutableResource);
/**
* Returns the path for a given resource.
*
* @param {string}
* @param {options}
* @return {string}
*/
function _getResourcePath(resource) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var environment = '';
if (isRoutableResource(resource)) {
if (!lodash.has(options, 'eid')) {
throw new TypeError('Cannot get routable resource path for ' + resource + ', without passing an eid to the options.');
}
// convert into a message resource
if (resource === Resource.ENVIRONMENT_MESSAGE) {
resource = Resource.MESSAGE;
}
environment = 'environments/' + options.eid + '/';
}
var id = 'id' in options && !lodash.isNil(options.id) ? '/' + options.id : '';
return '/' + environment + resource + id;
}
// Export memoized version.
var getResourcePath = lodash.memoize(_getResourcePath, function (resource) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return resource + '.' + options.id + '.' + options.eid;
});
/**
* Construct a usable polyseer API base url.
*
* @param {string} base url
* @param {string} version
* @return {string}
*/
function getBaseUrl() {
var base = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_API_BASE_URL;
var protocol = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_API_PROTOCOL;
var version = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_API_VERSION;
return '' + protocol + base + '/' + version;
}
module.exports = {
getResourcePath: getResourcePath,
getBaseUrl: getBaseUrl,
RoutableResources: RoutableResources
};<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon');
describe('Agent ExpectationHandler', () => {
const Handler = require('../../../../lib/agent/handler/expectation');
describe('is_alive', () => {
const { is_alive } = Handler;
it('ensures that there is an expectation that checks this instance is alive', () => {
const client = {
Expectation: {
create: sinon.stub()
},
instance: {
get: sinon.stub()
},
Type: {
INSTANCE: 'instance'
},
Determiner: {
ONE: 'one'
}
};
client.Expectation.create.returns(global.Promise.resolve('result_double'));
client.instance.get.withArgs('id').returns(100);
client.instance.get.withArgs('name').returns('foo');
return is_alive({}, client).should.be.fulfilled().
then(result => {
const data = client.Expectation.create.args[0][0];
data.name.should.eql('foo instance is alive.');
data.description.should.eql('Agent created expectation.');
data.is_on.should.eql(true);
data.determiner.should.eql('one');
data.subject.should.eql('instance');
data.subjects.should.eql([100]);
data.is_expected.should.eql(true);
data.logic.should.eql({
"===": [
{
"pointer": "heartbeat_status"
},
"beating"
]
});
result.should.eql('result_double');
});
});
});
});
<file_sep>'use strict';
const should = require('should');
describe('Definition', () => {
const Definition = require('../../../lib/resource/definition');
});
<file_sep>'use strict';
const should = require('should'),
polyseerio = require('../../'),
{ getClient } = require('./helper');
describe('Client instantiation testing', () => {
const Client = require('../../lib/client');
it('can be created', () => {
const client = getClient();
client.should.be.an.instanceOf(Client);
});
it('will configure without a token if one can be found in the environment', () => {
const value = process.env.POLYSEERIO_TOKEN;
process.env.POLYSEERIO_TOKEN = '<PASSWORD>';
(function () {
const client = polyseerio();
client.should.be.an.instanceOf(Client);
}).should.not.throw();
process.env.POLYSEERIO_TOKEN = value;
});
it('will not configure if a token cannot be found in the environment', () => {
const value = process.env.POLYSEERIO_TOKEN;
delete process.env.POLYSEERIO_TOKEN;
(function () {
const client = polyseerio();
client.should.be.an.instanceOf(Client);
}).should.throw();
process.env.POLYSEERIO_TOKEN = value;
});
});
<file_sep>'use strict';
var STATIC = Symbol('static'),
METHOD = Symbol('method');
module.exports = {
STATIC: STATIC,
METHOD: METHOD
};<file_sep>'use strict';
const should = require('should');
describe('DefinitionConstant', () => {
const DefinitionConstant = require('../../../lib/resource/definition_constant');
it('correctly defines STATIC ', () => {
const { STATIC } = DefinitionConstant;
(typeof STATIC === 'symbol').should.eql(true);
});
it('correctly defines METHOD ', () => {
const { METHOD } = DefinitionConstant;
(typeof METHOD === 'symbol').should.eql(true);
});
});
<file_sep>'use strict';
const logger = require('../../logger'),
{ attachToProcess } = require('../helper'),
{ Process } = require('../enum');
const Listener = {
[Process.EXIT]: function (_config, client) {
return function (code) {
return client.Event.create({
name: `${client.instance.get('name')} exited with code: ${code}.`,
color: client.Color.RED,
icon: client.Icon.ERROR
});
};
},
[Process.UNCAUGHT_EXCEPTION]: function (_config, client) {
return function (error) {
return client.Event.create({
name: `${client.instance.get('name')} experienced an uncaught exception.`,
description: `${error.name}: ${error.message}.`,
color: client.Color.RED,
icon: client.Icon.ERROR
});
};
},
[Process.UNHANDLED_REJECTION]: function (_config, client) {
return function (reason, promise) {
return client.Event.create({
name: `${client.instance.get('name')} experienced an unhandled rejection.`,
description: `Reason: ${reason}.`,
color: client.Color.RED,
icon: client.Icon.ERROR
});
};
},
[Process.WARNING]: function (_config, client) {
return function () {
return global.Promise.reoslve();
};
},
/**
* Fired when the process receives SIGHUP.
*
* @param {Client}
* @param {Instance}
* @return {Promise}
*/
[Process.SIGHUP]: function (_config, client) {
return function () {
logger.log('debug', `Process received ${Process.SIGHUP}.`);
return client.Event.create({
name: `${client.instance.get('name')} received ${Process.SIGHUP}.`,
color: client.Color.PURPLE,
icon: client.Icon.SIGNAL
});
};
},
/**
* Fired when the process receives SIGINT.
*
* @param {Client}
* @param {Instance}
* @return {Promise}
*/
[Process.SIGINT]: function (_config, client) {
return function () {
logger.log('debug', `Process received ${Process.SIGINT}.`);
return client.Event.create({
name: `${client.instance.get('name')} received ${Process.SIGINT}.`,
color: client.Color.PURPLE,
icon: client.Icon.SIGNAL
}).then(_ => {
return client._agent.stop();
}).then(_ => {
logger.log('debug', `Agent has been stopped.`);
});
};
},
/**
* Fired when the process receives SIGTERM.
*
* @param {Client}
* @param {Instance}
* @return {Promise}
*/
[Process.SIGTERM]: function (_config, client) {
return function () {
logger.log('debug', `Process received ${Process.SIGTERM}.`);
return client.Event.create({
name: `${client.instance.get('name')} received ${Process.SIGTERM}.`,
color: client.Color.PURPLE,
icon: client.Icon.SIGNAL
}).then(_ => {
return client._agent.stop();
}).then(_ => {
logger.log('debug', `Agent has been stopped.`);
});
};
}
};
const attach = attachToProcess(Listener, process);
module.exports = {
[Process.EXIT]: attach(Process.EXIT),
[Process.UNCAUGHT_EXCEPTION]: attach(Process.UNCAUGHT_EXCEPTION),
[Process.UNHANDLED_REJECTION]: attach(Process.UNHANDLED_REJECTION),
[Process.WARNING]: attach(Process.WARNING),
[Process.SIGHUP]: attach(Process.SIGHUP),
[Process.SIGINT]: attach(Process.SIGINT),
[Process.SIGTERM]: attach(Process.SIGTERM)
};
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon'),
proxyquire = require('proxyquire'),
{ STATIC,
METHOD } = require('../../../lib/resource/definition_constant');
describe('Resource Factory', () => {
const DefinitionDouble = {
foo: {
[STATIC]: [
'pong'
],
[METHOD]: [
'ping'
]
},
bar: {
[STATIC]: [
'pong'
],
[METHOD]: [
'ping'
]
},
singleton: {
[STATIC]: [
'pong'
]
}
},
factoryDouble = {
staticFactory: sinon.stub(),
methodFactory: sinon.stub()
};
const factory = proxyquire('../../../lib/resource/factory', {
'./definition': DefinitionDouble,
'../sdk/factory': factoryDouble
});
let memoizeId = 0;
beforeEach(() => {
factoryDouble.staticFactory.reset();
factoryDouble.methodFactory.reset();
});
function createResourceDouble () {
return class ResourceDouble {
constructor () {
this.one = 'alpha';
}
};
}
describe('function', () => {
it('throws if there is no defintion', () => {
const resource = 'undef',
request = sinon.spy();
(function () {
factory(resource, request);
}).should.throw(/Could not find definition for resource: undef./);
});
it('returns a non constructable object when resource is defined as a singleton', () => {
const resource = 'singleton',
request = sinon.spy();
factoryDouble.staticFactory.returns([]);
factoryDouble.methodFactory.returns([]);
const Result = factory(resource, request);
(function () {
new Result();
}).should.throw('Result is not a constructor');
});
it('memoizes between calls based on resource and request', () => {
const resourceOne = 'foo',
resourceTwo = 'bar',
request = sinon.spy();
factoryDouble.staticFactory.returns([]);
factoryDouble.methodFactory.returns([]);
const firstResult = factory(resourceOne, request),
secondResult = factory(resourceTwo, request),
thirdResult = factory(resourceOne, request);
// we should not be regenerating.
factoryDouble.staticFactory.callCount.should.eql(2);
factoryDouble.methodFactory.callCount.should.eql(2);
});
it('adds static methods to resource', () => {
const resource = 'foo',
options = sinon.spy(),
request = sinon.spy();
factoryDouble.staticFactory.
withArgs(request, resource, DefinitionDouble.foo[STATIC], options).
returns({
'ping': 'pong'
});
factoryDouble.methodFactory.returns([]);
const result = factory(resource, request, options, memoizeId++);
result.should.have.property('ping');
result.ping.should.eql('pong');
});
it('adds methods to prototype', () => {
const resource = 'foo',
options = sinon.spy(),
request = sinon.spy();
factoryDouble.staticFactory.returns([]);
factoryDouble.methodFactory.
withArgs(request, resource, DefinitionDouble.foo[METHOD]).
returns({
'ping': function (_, a) { return a; }
});
const Result = factory(resource, request, options, memoizeId++);
const instance = new Result();
Result.should.not.have.property('ping');
instance.should.have.property('ping');
instance.ping('a').should.eql('a');
});
});
describe('addMethod', () => {
const { addMethod } = factory;
it('attaches the method to the prototype with the given name', () => {
const Resource = createResourceDouble(),
method = function () {
return this.one;
},
name = 'alpha';
addMethod(Resource, method, name);
Resource.prototype.should.have.property(name);
});
it('binds correct context to method attached to prototype', () => {
const Resource = createResourceDouble(),
method = function (intance) {
return intance.one;
},
name = 'alpha';
addMethod(Resource, method, name);
const resource = new Resource();
const result = resource.alpha().should.eql('alpha');
});
it('returns the Resource', () => {
const Resource = {
prototype: {}
},
method = sinon.stub(),
name = 'alpha';
const result = addMethod(Resource, method, name);
result.should.eql(Resource);
});
});
describe('addStatic', () => {
const { addStatic } = factory;
it('attaches method directly to object', () => {
const Resource = {},
method = sinon.stub(),
name = 'alpha';
addStatic(Resource, method, name);
Resource.alpha.should.eql(method);
});
it('returns the Resource', () => {
const Resource = {},
method = sinon.stub(),
name = 'alpha';
const result = addStatic(Resource, method, name);
result.should.eql(Resource);
});
});
describe('addStatics', () => {
const { addStatics } = factory;
it('attaches a collection of statics to the object', () => {
const Resource = {},
statics = {
alpha: sinon.stub(),
beta: sinon.stub()
};
addStatics(Resource, statics);
Resource.should.have.property('alpha');
Resource.alpha.should.eql(statics.alpha);
Resource.should.have.property('alpha');
Resource.beta.should.eql(statics.beta);
});
it('returns the Resource', () => {
const Resource = {},
statics = {
alpha: sinon.stub(),
beta: sinon.stub()
};
const result = addStatics(Resource, statics);
result.should.eql(Resource);
});
});
describe('addMethods', () => {
const { addMethods } = factory;
it('returns the Resource if methods are empty and does not throw', () => {
const Resource = {}, // no prototype
request = sinon.stub(),
methods = {};
(function () {
const result = addMethods(Resource, request, methods);
result.should.eql(Resource);
}).should.not.throw();
});
it('attaches a collection of instance methods to the object', () => {
const Resource = {
prototype: {}
},
request = sinon.stub(),
methods = {
alpha: function (instance, ...args) {
return 'alpha';
},
beta: function (instance, ...args) {
return 'beta';
}
};
addMethods(Resource, request, methods);
Resource.should.have.propertyByPath('prototype', 'alpha');
Resource.prototype.alpha().should.eql('alpha');
Resource.should.have.propertyByPath('prototype', 'beta');
Resource.prototype.beta().should.eql('beta');
});
it('attaches the request to the Resource prototype', () => {
const Resource = {
prototype: {}
},
request = sinon.stub(),
methods = {
alpha: sinon.stub(),
beta: sinon.stub()
};
addMethods(Resource, request, methods);
Resource.should.have.propertyByPath('prototype', '_request');
Resource.prototype._request.should.eql(request);
});
it('returns the Resource', () => {
const Resource = {
prototype: {}
},
request = sinon.stub(),
methods = {
alpha: sinon.stub(),
beta: sinon.stub()
};
const result = addMethods(Resource, request, methods);
result.should.eql(Resource);
});
});
describe('getMemoizeKey', () => {
const { getMemoizeKey } = factory;
it('returns the correct memoize complex key', () => {
const resource = 'alpha',
cid = 33;
const result = getMemoizeKey(resource, undefined, undefined, cid);
result.should.eql('alpha.33');
});
});
describe('definesSingleton', () => {
const { definesSingleton } = factory;
it('returns true if Symbol("method") is not defined', () => {
const definition = {
[STATIC]: ['alpha']
};
const result = definesSingleton(definition);
result.should.eql(true);
});
it('returns true if Symbol("method") is empty', () => {
const definition = {
[STATIC]: ['alpha'],
[METHOD]: []
};
const result = definesSingleton(definition);
result.should.eql(true);
});
it('returns false is Symbol("method") is defined and has items', () => {
const definition = {
[STATIC]: ['alpha'],
[METHOD]: ['bar']
};
const result = definesSingleton(definition);
result.should.eql(false);
});
});
describe('createResource', () => {
const { createResource } = factory;
it('returns a function that is newable', () => {
const resource = 'foo',
Resource = createResource(resource);
(function () {
new Resource();
}).should.not.throw();
});
it('sets the passed resource name on the instance', () => {
const resource = 'foo',
Resource = createResource(resource);
const instance = new Resource();
instance.resource.should.eql(resource);
});
it('defaults .eid to development', () => {
const resource = 'foo',
Resource = createResource(resource);
const instance = new Resource({});
instance.eid.should.eql('development');
});
it('sets .eid if passed in attributes', () => {
const resource = 'foo',
Resource = createResource(resource);
const instance = new Resource({ eid: 'lala' });
instance.eid.should.eql('lala');
});
it('assigns attributes to _attributes', () => {
const resource = 'foo',
Resource = createResource(resource);
const instance = new Resource({
ding: 'dong',
eid: 'foo'
});
instance.should.have.property('_attributes');
instance.eid.should.eql('foo');
instance._attributes.should.containEql({
ding: 'dong'
});
});
it('will not assign reserved keywords', () => {
const resource = 'foo',
Resource = createResource(resource);
const instance = new Resource({
meta: 'alpha',
relationships: 'alpha',
eid: 'foo'
});
if ('meta' in instance) {
instance.meta.should.not.eql('alpha');
}
if ('relationships' in instance) {
instance.relationships.should.not.eql('alpha');
}
});
});
});
<file_sep>'use strict';
/**
* Find a resource by primary id.
*
* @param {object}
* @param {string}
* @param {object}
* @return {Promise}
*/
function findById (id, options, context = {}) {
return context.request.get({
uri: context.uri
});
}
module.exports = findById;
<file_sep>'use strict';
/**
* Check a resource.
*
* Used for expecations.
*
* @param {object}
* @param {object}
* @return {Promise}
*/
function check(options) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return context.request.get({
uri: context.uri + '/check'
});
}
module.exports = check;<file_sep>'use strict';
/**
* Message a resource.
*
* @param {request} options
* @param {string} resource type
* @return {function}
*/
function message(id, content, options) {
var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return context.request.post({
uri: context.uri + '/messages',
body: {
content: content
}
});
}
module.exports = message;<file_sep>'use strict';
var gaugeStatic = require('../static/gauge'),
_require = require('../helper'),
instanceToContext = _require.instanceToContext;
/**
* Send gauge metrics to an instance.
*
* @param {Resource}
* @param {object}
* @param {object}
* @return {Promise}
*/
function gauge(instance, gauges, options) {
return gaugeStatic(instance.get('id'), gauges, options, instanceToContext(instance));
}
module.exports = gauge;<file_sep>'use strict';
const should = require('should');
describe('toJSON', () => {
const method = require('../../../../lib/sdk/method/toJSON');
it('returns attributes', () => {
const instance = {
_attributes: {
foo: 'bar',
ping: 'pong'
}
};
const result = method(instance);
result.should.eql({
foo: 'bar',
ping: 'pong'
});
});
it('returns a copy of attributes', () => {
const instance = {
_attributes: {
foo: 'bar',
ping: 'pong'
}
};
const result = method(instance);
result.foo = 'ninja';
instance._attributes.foo.should.eql('bar');
});
});
<file_sep>'use strict';
const jshintReporter = require('jshint-junit-reporter'),
lintableFiles = ['example/**/*.js', 'example/**/*.json', 'test/**/*.js', 'src/**/*.js'],
unitTestFiles = ['test-dist/unit/**/*_test.js'],
integrationTestFiles = ['test-dist/integration/**/*_test.js'],
validationTestFiles = ['test-dist/validation/**/*_test.js'];
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
babel: {
options: {
sourceMap: true
},
dist: {
files: {
'dist/s': 'lib/**/*.js'
}
}
},
mochaTest: {
integration_stdout: {
options: {
reporter: 'spec'
},
src: integrationTestFiles
},
validation_stdout: {
options: {
reporter: 'spec'
},
src: validationTestFiles
},
unit_stdout: {
options: {
reporter: 'spec'
},
src: unitTestFiles
},
unit_file: {
options: {
reporter: 'xunit',
quiet: true,
captureFile: './unit_test_results.xml'
},
src: unitTestFiles
}
},
jshint: {
options: {
esnext: true,
node: true,
globals: {
describe: false,
it: false,
before: false,
beforeEach: false,
after: false,
afterEach: false
}
},
stdout: {
files: { src: lintableFiles }
},
file: {
files: { src: lintableFiles },
options: {
reporterOutput: 'lint_test_results.xml',
reporter: jshintReporter
}
}
}
});
grunt.registerTask('compile', ['babel']);
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
};
<file_sep>'use strict';
/**
* Message a resource.
*
* @param {request} options
* @param {string} resource type
* @return {function}
*/
function message (id, content, options, context = {}) {
return context.request.post({
uri: `${context.uri}/messages`,
body: {
content
}
});
}
module.exports = message;
<file_sep>'use strict';
/**
* Trigger a resource.
*
* @param {string}
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function trigger(id, meta, options) {
var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
meta = meta || {};
return context.request.post({
uri: context.uri + '/trigger',
body: { meta: meta }
});
}
module.exports = trigger;<file_sep>const polyseerio = require('../'),
co = require('co');
const client = polyseerio();
return client.startAgent().
then(_ => {
console.log('Agent has started.');
return client.Event.create({
name: 'User signed up.',
color: 'green',
icon: 'check'
});
}).catch(console.log);
<file_sep>'use strict';
const Handler = require('./enum'),
{ Strategy,
Direction,
Subtype } = require('../enum');
module.exports = {
attach: true,
attach_strategy: Strategy.FALLBACK,
id: null,
name: null,
description: 'Created by the Polyseer.io Node.JS agent.',
group: 'agent',
direction: Direction.INBOUND,
subtype: Subtype.LONG_RUNNING,
agent_retry: 60000, // 1 minute
// disabled until better discovery pattern
expectation: {
[Handler.Expectation.IS_ALIVE]: false
},
fact: {
[Handler.Fact.ARCHITECTURE]: true,
[Handler.Fact.CPU_COUNT]: true,
[Handler.Fact.ENDIANNESS]: true,
[Handler.Fact.FREE_MEMORY]: true,
[Handler.Fact.GID]: true,
[Handler.Fact.HOME_DIRECTORY]: true,
[Handler.Fact.HOSTNAME]: true,
[Handler.Fact.LAUNCH_ARGUMENTS]: true,
[Handler.Fact.NODE_VERSION]: true,
[Handler.Fact.PID]: true,
[Handler.Fact.PLATFORM]: true,
[Handler.Fact.TITLE]: true,
[Handler.Fact.UID]: true,
[Handler.Fact.UPTIME]: true,
[Handler.Fact.V8_VERSION]: true
},
metric: {
[Handler.Metric.MEMORY]: true,
[Handler.Metric.CPU]: true,
[Handler.Metric.UPTIME]: true
},
event: {
[Handler.Event.START]: true,
[Handler.Event.STOP]: true
},
process: {
[Handler.Process.EXIT]: true,
[Handler.Process.WARNING]: true,
[Handler.Process.UNCAUGHT_EXCEPTION]: true,
[Handler.Process.UNHANDLED_REJECTION]: true,
[Handler.Process.SIGHUP]: true,
[Handler.Process.SIGINT]: true,
[Handler.Process.SIGTERM]: true
}
};
<file_sep>'use strict';
var lodash = require('lodash');
/**
* Add a gauge to the instance that will be sent with each heartbeat.
*
* @param {Resource}
* @param {string}
* @param {function}
* @return {Promise}
*/
function addGauge(instance, key, resolver) {
if (!lodash.has(instance, '_heartbeatGauges')) {
instance._heartbeatGauges = new Map();
}
instance._heartbeatGauges.set(key, resolver);
return global.Promise.resolve();
}
module.exports = addGauge;<file_sep>'use strict';
const sinon = require('sinon'),
lodash = require('lodash');
/**
* Returns a request mock.
*
* @return {sinon.stub}
*/
function createRequestMock () {
return {
post: sinon.stub(),
put: sinon.stub(),
del: sinon.stub(),
delete: sinon.stub(),
get: sinon.stub()
};
}
/**
* Create a mock instance.
*
* @param {object}
* @return {object}
*/
function createInstance (attributes = {}) {
const mock = {
_attributes: Object.assign({}, attributes),
get: sinon.stub(),
set: sinon.stub()
};
lodash.forEach(attributes, (value, key) => {
mock.get.withArgs(key).returns(value);
});
return mock;
}
module.exports = {
createInstance,
createRequestMock
};
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon'),
helper = require('./helper');
describe('Static: find', () => {
const method = require('../../../../lib/sdk/static/find');
const query = {
foo: 'bar'
},
options = {};
it('makes the correct call to get', () => {
const context = helper.getContext();
context.request.get.returns(global.Promise.resolve());
return method(query, options, context).
then(_ => {
context.request.get.called.should.eql(true);
context.request.get.calledWithExactly({
uri: context.uri,
qs: query
}).should.eql(true);
});
});
it('defaults query to an empty object', () => {
const context = helper.getContext();
context.request.get.returns(global.Promise.resolve());
return method({}, options, context).
then(_ => {
context.request.get.args[0][0].qs.should.eql({});
});
});
it('resolves when get resolves', () => {
const context = helper.getContext(),
result = sinon.stub();
context.request.get.returns(global.Promise.resolve(result));
return method(query, options, context).should.be.fulfilled(result);
});
it('rejects when get rejects', () => {
const context = helper.getContext(),
error = new Error('foo');
context.request.get.returns(global.Promise.reject(error));
return method(query, options, context).should.be.rejectedWith(error);
});
});
<file_sep>'use strict';
/**
* Convert an instance to a plain JSON object.
*
* @param {Resoure}
* @return {object}
*/
function toJSON (instance) {
return Object.assign({}, instance._attributes);
}
module.exports = toJSON;
<file_sep>'use strict';
const sinon = require('sinon');
function createRequestMock () {
return {
post: sinon.stub(),
del: sinon.stub(),
get: sinon.stub(),
put: sinon.stub(),
patch: sinon.stub()
};
}
module.exports = {
createRequestMock
};
<file_sep>'use strict';
/**
* Create a resource.
*
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function create (attributes, options, context = {}) {
attributes = attributes || {};
return context.request.post({
uri: context.uri,
body: attributes
});
}
module.exports = create;
<file_sep>'use strict';
var _module$exports;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var Interface = require('./interface'),
_require = require('../helper'),
attachToProcess = _require.attachToProcess,
_require2 = require('../enum'),
Event = _require2.Event;
module.exports = (_module$exports = {}, _defineProperty(_module$exports, Event.START, function (_config, client) {
return client.Event.create({
name: client.instance.get('name') + ' agent has started.',
color: client.Color.GREEN,
icon: client.Icon.CHAIN
});
}), _defineProperty(_module$exports, Event.STOP, _defineProperty({}, Interface.TEARDOWN, function (_config, client) {
return client.Event.create({
name: client.instance.get('name') + ' agent has stopped.',
color: client.Color.ORANGE,
icon: client.Icon.CHAIN_BROKEN
});
})), _module$exports);<file_sep>'use strict';
const lodash = require('lodash'),
Static = require('./static'),
Method = require('./method'),
{ getResourcePath } = require('../url_builder'),
{ curry } = require('lodash'),
{ reduceOptions } = require('./helper');
const STATIC_ARITY = 4;
const ID_REGEX = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i;
function isId (id) {
return (lodash.isNumber(id) || ID_REGEX.test(id));
}
/**
*/
function preProcessMethodCall (instance, copts, method) {
}
/**
* Preprocesses a static call.
*
* @param {Request}
* @param {string}
* @param {object}
* @param {function}
* @return {function}
*/
function preprocessStaticCall (request, resource, copts, method) {
return function (...args) {
let callOptions = {};
// we have call site overrides.
if (args.length === method.length) {
callOptions = args.pop();
}
const options = reduceOptions(callOptions, copts);
let id = null;
if (isId(lodash.first(args))) {
id = lodash.first(args);
}
const uri = getResourcePath(resource, {
eid: options.environment, id
});
const context = {
resource,
request,
uri
};
return method(...args, options, context);
};
}
/**
* Create a static function for a given resource.
*
* @param {request} options
* @param {string} resource type
* @param {object} query params
*/
function staticFactory (request, resource, statics = [], options = {}) {
return statics.reduce((result, method) => {
if (!(method in Static)) {
throw new Error(`SDK factory was asked to generate a '${method}' static method; however, a method of that name has not been defined.`);
}
result[method] = preprocessStaticCall(request, resource, options, Static[method]);
return result;
}, {});
}
/**
* Create an instance function for a given resource.
*
* @param {request} options
* @param {string} resource type
* @param {object} query params
*/
function methodFactory (request, resource, statics = [], options = {}) {
return statics.reduce((result, method) => {
if (!(method in Method)) {
throw new Error(`SDK factory was asked to generate a '${method}' instance method; however, a method of that name has not been defined.`);
}
result[method] = Method[method];
return result;
}, {});
}
module.exports = {
staticFactory,
methodFactory
};
<file_sep>'use strict';
const should = require('should'),
co = require('co'),
{ DEFAULT_TIMEOUT } = require('./config');
describe('Alert', function () {
const polyseerio = require('../../');
this.timeout(DEFAULT_TIMEOUT);
it('can perform a quick start', () => {
return co(function* () {
const client = yield polyseerio.start({
token_env: 'ROOT_KEY'
}).should.be.fulfilled();
// go and assert quick start is working...
});
});
/*
it('long form', () => {
return co(function* () {
const client = polyseerio({
token_env: 'ROOT_KEY'
});
yield client.startAgent({
name: 'foo'
}).should.be.fulfilled();
// go and assert quick start is working...
});
});
*/
});
<file_sep>'use strict';
var _Listener, _module$exports;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var logger = require('../../logger'),
_require = require('../helper'),
attachToProcess = _require.attachToProcess,
_require2 = require('../enum'),
Process = _require2.Process;
var Listener = (_Listener = {}, _defineProperty(_Listener, Process.EXIT, function (_config, client) {
return function (code) {
return client.Event.create({
name: client.instance.get('name') + ' exited with code: ' + code + '.',
color: client.Color.RED,
icon: client.Icon.ERROR
});
};
}), _defineProperty(_Listener, Process.UNCAUGHT_EXCEPTION, function (_config, client) {
return function (error) {
return client.Event.create({
name: client.instance.get('name') + ' experienced an uncaught exception.',
description: error.name + ': ' + error.message + '.',
color: client.Color.RED,
icon: client.Icon.ERROR
});
};
}), _defineProperty(_Listener, Process.UNHANDLED_REJECTION, function (_config, client) {
return function (reason, promise) {
return client.Event.create({
name: client.instance.get('name') + ' experienced an unhandled rejection.',
description: 'Reason: ' + reason + '.',
color: client.Color.RED,
icon: client.Icon.ERROR
});
};
}), _defineProperty(_Listener, Process.WARNING, function (_config, client) {
return function () {
return global.Promise.reoslve();
};
}), _defineProperty(_Listener, Process.SIGHUP, function (_config, client) {
return function () {
logger.log('debug', 'Process received ' + Process.SIGHUP + '.');
return client.Event.create({
name: client.instance.get('name') + ' received ' + Process.SIGHUP + '.',
color: client.Color.PURPLE,
icon: client.Icon.SIGNAL
});
};
}), _defineProperty(_Listener, Process.SIGINT, function (_config, client) {
return function () {
logger.log('debug', 'Process received ' + Process.SIGINT + '.');
return client.Event.create({
name: client.instance.get('name') + ' received ' + Process.SIGINT + '.',
color: client.Color.PURPLE,
icon: client.Icon.SIGNAL
}).then(function (_) {
return client._agent.stop();
}).then(function (_) {
logger.log('debug', 'Agent has been stopped.');
});
};
}), _defineProperty(_Listener, Process.SIGTERM, function (_config, client) {
return function () {
logger.log('debug', 'Process received ' + Process.SIGTERM + '.');
return client.Event.create({
name: client.instance.get('name') + ' received ' + Process.SIGTERM + '.',
color: client.Color.PURPLE,
icon: client.Icon.SIGNAL
}).then(function (_) {
return client._agent.stop();
}).then(function (_) {
logger.log('debug', 'Agent has been stopped.');
});
};
}), _Listener);
var attach = attachToProcess(Listener, process);
module.exports = (_module$exports = {}, _defineProperty(_module$exports, Process.EXIT, attach(Process.EXIT)), _defineProperty(_module$exports, Process.UNCAUGHT_EXCEPTION, attach(Process.UNCAUGHT_EXCEPTION)), _defineProperty(_module$exports, Process.UNHANDLED_REJECTION, attach(Process.UNHANDLED_REJECTION)), _defineProperty(_module$exports, Process.WARNING, attach(Process.WARNING)), _defineProperty(_module$exports, Process.SIGHUP, attach(Process.SIGHUP)), _defineProperty(_module$exports, Process.SIGINT, attach(Process.SIGINT)), _defineProperty(_module$exports, Process.SIGTERM, attach(Process.SIGTERM)), _module$exports);<file_sep>'use strict';
var _module$exports;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var os = require('os'),
_require = require('../enum'),
Fact = _require.Fact;
module.exports = (_module$exports = {}, _defineProperty(_module$exports, Fact.ARCHITECTURE, function (_config, client) {
client.instance.addFact('architecture', process.arch);
}), _defineProperty(_module$exports, Fact.CPU_COUNT, function (_config, client) {
client.instance.addFact('cpu_count', os.cpus().length);
}), _defineProperty(_module$exports, Fact.ENDIANNESS, function (_config, client) {
client.instance.addFact('endianness', os.endianness());
}), _defineProperty(_module$exports, Fact.FREE_MEMORY, function (_config, client) {
client.instance.addFact('free_memory', function () {
return os.freemem();
});
}), _defineProperty(_module$exports, Fact.HOME_DIRECTORY, function (_config, client) {
client.instance.addFact('home_directory', os.homedir());
}), _defineProperty(_module$exports, Fact.HOSTNAME, function (_config, client) {
client.instance.addFact('hostname', os.hostname());
}), _defineProperty(_module$exports, Fact.GID, function (_config, client) {
client.instance.addFact('gid', process.getgid());
}), _defineProperty(_module$exports, Fact.LAUNCH_ARGUMENTS, function (_config, client) {
var value = process.argv.join(' ');
client.instance.addFact('launch_arguments', value);
}), _defineProperty(_module$exports, Fact.UPTIME, function (_config, client) {
client.instance.addFact('uptime', function () {
return process.uptime();
});
}), _defineProperty(_module$exports, Fact.NODE_VERSION, function (_config, client) {
client.instance.addFact('node_version', process.versions.node);
}), _defineProperty(_module$exports, Fact.PID, function (_config, client) {
client.instance.addFact('pid', process.pid);
}), _defineProperty(_module$exports, Fact.PLATFORM, function (_config, client) {
client.instance.addFact('platform', process.platform);
}), _defineProperty(_module$exports, Fact.TITLE, function (_config, client) {
client.instance.addFact('title', process.title);
}), _defineProperty(_module$exports, Fact.UID, function (_config, client) {
client.instance.addFact('uid', process.getuid());
}), _defineProperty(_module$exports, Fact.V8_VERSION, function (_config, client) {
client.instance.addFact('v8_version', process.versions.v8);
}), _module$exports);<file_sep>'use strict';
const executeStatic = require('../static/execute');
/**
* Create an execute instance method for a resource.
*
* @param {request}
* @param {string}
* @return {function}
*/
function execute (instance, ...args) {
return executeStatic(instance.id, ...args);
}
module.exports = execute;
<file_sep>const polyseerio = require('../'),
co = require('co'),
client = polyseerio();
return co(function* () {
yield client.getCurrentEnvironment().message('Hello deduced environment.');
const testing = yield client.Environment.findByName('testing');
testing.message('Hello testing environment.');
}).
catch(console.log);
<file_sep>'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var lodash = require('lodash'),
_require = require('../helper'),
resolveEid = _require.resolveEid;
/**
* Base resource class.
*/
var Base = function Base() {
var attributes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Base);
if (lodash.has(attributes, 'eid')) {
this.eid = attributes.eid;
} else {
this.eid = resolveEid(this.copts || {});
}
this._attributes = attributes;
};
module.exports = Base;<file_sep>'use strict';
/**
* Create a resource.
*
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function create(attributes, options) {
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
attributes = attributes || {};
return context.request.post({
uri: context.uri,
body: attributes
});
}
module.exports = create;<file_sep>const polyseerio = require('../');
/**
* The fastest way to integrate Polyseer.io.
*
* Requires a POLYSEERIO_TOKEN variable in the environment.
* Defaults environment to production or what was found in NODE_ENV.
*/
return polyseerio.start().
then(client => {
console.log('ok, agent started.');
});
<file_sep>'use strict';
const should = require('should'),
proxyquire = require('proxyquire'),
sinon = require('sinon');
describe('Middleware', () => {
const formatPayloadDouble = sinon.stub(),
parseResponseDouble = sinon.stub();
const Middleware = proxyquire('../../lib/middleware', {
'./helper': {
formatPayload: formatPayloadDouble
},
'./resource/helper': {
parseResponse: parseResponseDouble
}
});
beforeEach(() => {
formatPayloadDouble.reset();
});
describe('forwardCurry', () => {
const { forwardCurry } = Middleware;
it('can curry one argument to passed function', () => {
const func = function (a) { return arguments; };
const curry = forwardCurry(func, 'dos'),
result = curry('uno');
result[0].should.eql('uno');
result[1].should.eql('dos');
});
it('can curry two arguments to passed function', () => {
const func = function (a) { return arguments; };
const curry = forwardCurry(func, 'dos', 'tres'),
result = curry('uno');
result[0].should.eql('uno');
result[1].should.eql('dos');
result[2].should.eql('tres');
});
});
describe('preRequest', () => {
const { preRequest } = Middleware;
it('returns identity if no body', () => {
const options = {
foo: 'bar'
};
const result = preRequest(options);
result.should.eql(options);
});
it('calls formatPayload if body in optinos', () => {
const options = {
body: {
alpha: 'beta'
},
ding: 'dong'
};
formatPayloadDouble.returns('result');
const result = preRequest(options);
result.should.eql({
body: 'result',
ding: 'dong'
});
});
});
describe('postRequest', () => {
const { postRequest } = Middleware;
it('returns the result of parseResponse', () => {
parseResponseDouble.returns('foo');
const result = postRequest('alpha');
parseResponseDouble.calledWithExactly('alpha');
result.should.eql('foo');
});
});
describe('postReject', () => {
const { postReject } = Middleware;
it('simply rejects original error when there is no response in error', () => {
const error = new Error('foo'),
cid = 1,
request = sinon.stub();
return postReject(error, cid, request).should.be.rejectedWith(error);
});
it('simply rejects original error when error.response is nil', () => {
const error = {
a: 'b',
response: undefined
},
cid = 1,
request = sinon.stub();
return postReject(error, cid, request).should.be.rejectedWith(error);
});
});
});
<file_sep>'use strict';
const lodash = require('lodash'),
requestPromise = require('request-promise'),
{ formatPayload } = require('./helper'),
{ getEidFromRequestPath,
parseResponse } = require('./resource/helper');
/**
* Retrty a failed request.
*
* @return {Promise}
*/
function retryRequest (request, failed, cid, payload = {}) {
const uri = failed.path.split('polyseer/v1/')[1];
return request({
method: failed.method,
uri,
body: payload
}).then(response => {
return parseResponse(response, cid);
});
}
/**
* Creates the missing environment.
*
* @param {request}
* @return {Promise}
*/
function upsertEnvironment (request, name) {
return request.post({
uri: '/environments',
body: formatPayload({
name,
description: 'Environment created by agent upsert.'
})
});
}
/**
* Determine if a request was rejected due to a missing
* environment.
*
* @param {request}
* @return {Promise}
*/
function rejectedDueToMissingEnvironment (error) {
if (error.name !== 'StatusCodeError') {
return false;
}
if (error.statusCode !== 404) {
return false;
}
if (!lodash.has(error.error, 'errors') || !lodash.isArray(error.error.errors)) {
return false;
}
return lodash.some(error.error.errors, err => {
return (
err.status === 404 &&
err.detail.indexOf('Could not find') !== -1 &&
err.detail.indexOf('environment') !== -1);
});
}
/**
* Used to curry client options along to middleware.
*
* @param {function}
* @param {object}
* @return {function}
*/
function forwardCurry () {
const params = Array.prototype.slice.call(arguments),
func = params.shift();
return function () {
return func(...arguments, ...params);
};
}
/**
* Called before a request is made.
*
* @param {object}
* @param {number}
* @return {object}
*/
function preRequest (options, cid) {
if ('body' in options) {
options.body = formatPayload(options.body);
}
return options;
}
/**
* Called after a request is made.
*
* @param {object}
* @param {number}
* @return {Mixed}
*/
function postRequest (response, cid) {
return parseResponse(response, cid);
}
/**
* Called after a request is rejected.
*
* @param {object}
* @param {number}
* @return {Mixed}
*/
function postReject (error, cid, request, copts = {}) {
// if we have an error with a response that is not nil.
if (lodash.has(error, 'response') && !lodash.isNil(error.response)) {
if (copts.upsert_env) {
let originalPayload = {};
if (error.response.request.body) {
originalPayload = JSON.parse(error.response.request.body); // becomes undefined (tick issue)
}
const isMissingEnvironment = rejectedDueToMissingEnvironment(error);
if (isMissingEnvironment) {
const failedRequest = error.response.req,
name = getEidFromRequestPath(failedRequest.path);
return upsertEnvironment(request, name).
then(_ => {
return retryRequest(request, failedRequest, cid, originalPayload);
});
}
}
}
return global.Promise.reject(error);
}
module.exports = {
forwardCurry,
preRequest,
postRequest,
postReject
};
<file_sep>'use strict';
const lodash = require('lodash'),
co = require('co'),
DefaultConfig = require('./default_config'),
HandlerMap = require('./handler'),
logger = require('../logger'),
{ Strategy } = require('../enum'),
{ logAndReject } = logger,
{ upsert } = require('../resource/routine'),
{ filterHandlers,
resolveName,
teardownWithHandler,
setupWithHandler } = require('./helper');
/**
* Fulfills an agent configuration.
*
* @param {Client}
* @param {object}
* @return {Promise}
*/
function setup (client, options) {
return co(function* () {
logger.log('debug', `Setting up agent for client: ${client._cid}.`);
if (options.attach) {
// resolve the instance
let instance = null;
switch (options.attach_strategy) {
case Strategy.FALLBACK:
logger.log('debug', 'Resolving instance using fallback.');
const name = resolveName(options);
instance = yield upsert(client.Instance, { name });
break;
case Strategy.ID:
logger.log('debug', 'Resolving instance using primary id.', {
id: options.id
});
instance = yield client.Instance.find_by_id(options.id);
break;
default:
// raise
}
client.instance = instance;
// create a setup handler.
const setupHandler = setupWithHandler(HandlerMap, client, options.handlers);
// gather and perform work.
const setups = lodash.map(options.handlers, (_, key) => setupHandler(key));
yield global.Promise.all(setups);
logger.log('debug', 'Attempting to attach instance to polyseerio.', {
id: instance.id,
strategy: options.attach_strategy
});
// start monitoring.
yield instance.attach();
return instance;
}
}).catch(logAndReject);
}
/**
* Tearsdown an client's agent.
*
* @param {Client}
* @return {Promise}
*/
function teardown (client, handlerOptions) {
return co(function* () {
logger.log('debug', `Tearing down agent for client: ${client._cid}.`);
const teardownHandler = teardownWithHandler(HandlerMap, client, handlerOptions);
// gather and perform work.
const teardowns = lodash.map(handlerOptions, (_, key) => teardownHandler(key));
yield global.Promise.all(teardowns);
yield client.instance.detach();
return client;
}).catch(logAndReject);
}
module.exports = {
setup,
teardown
};
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon');
describe('SDKHelper', () => {
const Helper = require('../../lib/sdk/helper');
describe('removeNonResolvingValues', () => {
const { removeNonResolvingValues } = Helper;
it('correctly removes values that don\'t resolve', () => {
const map = new Map();
const callable = sinon.spy();
map.set('foo', 'bar');
map.set('length', 200);
map.set('good', true);
map.set('callable', callable);
const result = removeNonResolvingValues(map);
result.size.should.eql(1);
result.has('callable').should.eql(true);
result.get('callable').should.eql(callable);
});
});
describe('reduceOptions', () => {
const { reduceOptions } = Helper;
it('correctly has options trump client options', () => {
const options = {
environment: 'foo'
},
copts = {
environment: 'bar'
};
const result = reduceOptions(options, copts);
result.should.have.property('environment');
result.environment.should.eql('foo');
});
it('correctly includes defaults if present', () => {
const options = {
environment: 'foo'
},
copts = {
environment: 'bar'
},
defaults = {
alpha: 'beta'
};
const result = reduceOptions(options, copts, defaults);
result.should.have.property('alpha');
result.alpha.should.eql('beta');
});
it('complex example', () => {
const options = {
environment: 'foo',
zing: 'zang'
},
copts = {
environment: 'bar',
dork: 'duck'
},
defaults = {
alpha: 'beta',
zing: 'peptide',
dork: 'cork'
};
const result = reduceOptions(options, copts, defaults);
result.should.eql({
environment: 'foo',
zing: 'zang',
dork: 'duck',
alpha: 'beta'
});
});
});
});
<file_sep>'use strict';
var lodash = require('lodash'),
Static = require('./static'),
Method = require('./method'),
_require = require('../url_builder'),
getResourcePath = _require.getResourcePath,
_require2 = require('lodash'),
curry = _require2.curry,
_require3 = require('./helper'),
reduceOptions = _require3.reduceOptions;
var STATIC_ARITY = 4;
var ID_REGEX = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i;
function isId(id) {
return lodash.isNumber(id) || ID_REGEX.test(id);
}
/**
*/
function preProcessMethodCall(instance, copts, method) {}
/**
* Preprocesses a static call.
*
* @param {Request}
* @param {string}
* @param {object}
* @param {function}
* @return {function}
*/
function preprocessStaticCall(request, resource, copts, method) {
return function () {
var callOptions = {};
// we have call site overrides.
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === method.length) {
callOptions = args.pop();
}
var options = reduceOptions(callOptions, copts);
var id = null;
if (isId(lodash.first(args))) {
id = lodash.first(args);
}
var uri = getResourcePath(resource, {
eid: options.environment, id: id
});
var context = {
resource: resource,
request: request,
uri: uri
};
return method.apply(undefined, args.concat([options, context]));
};
}
/**
* Create a static function for a given resource.
*
* @param {request} options
* @param {string} resource type
* @param {object} query params
*/
function staticFactory(request, resource) {
var statics = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return statics.reduce(function (result, method) {
if (!(method in Static)) {
throw new Error('SDK factory was asked to generate a \'' + method + '\' static method; however, a method of that name has not been defined.');
}
result[method] = preprocessStaticCall(request, resource, options, Static[method]);
return result;
}, {});
}
/**
* Create an instance function for a given resource.
*
* @param {request} options
* @param {string} resource type
* @param {object} query params
*/
function methodFactory(request, resource) {
var statics = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return statics.reduce(function (result, method) {
if (!(method in Method)) {
throw new Error('SDK factory was asked to generate a \'' + method + '\' instance method; however, a method of that name has not been defined.');
}
result[method] = Method[method];
return result;
}, {});
}
module.exports = {
staticFactory: staticFactory,
methodFactory: methodFactory
};<file_sep>'use strict';
/**
* Trigger a resource.
*
* @param {string}
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function gauge (id, gauges, options, context = {}) {
gauges = gauges || {};
return context.request.post({
uri: `${context.uri}/gauges`,
body: gauges
});
}
module.exports = gauge;
<file_sep>'use strict';
const Interface = require('./interface'),
{ attachToProcess } = require('../helper'),
{ Event } = require('../enum');
module.exports = {
/**
* Event indicates that the agent has started.
*/
[Event.START] (_config, client) {
return client.Event.create({
name: `${client.instance.get('name')} agent has started.`,
color: client.Color.GREEN,
icon: client.Icon.CHAIN
});
},
/**
* Event indicates that the agent has stopped.
*/
[Event.STOP]: {
[Interface.TEARDOWN] (_config, client) {
return client.Event.create({
name: `${client.instance.get('name')} agent has stopped.`,
color: client.Color.ORANGE,
icon: client.Icon.CHAIN_BROKEN
});
}
}
};
<file_sep>'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var lodash = require('lodash'),
Enum = require('./enum'),
Agent = require('./agent'),
EventEmitter = require('events');
/**
* Reserved resource attribute names / paths.
*/
var RESERVED = ['_request'];
/**
* Default client options.
*/
var DEFAULT_OPTIONS = {
request: null,
resources: {}
};
/**
* Client events.
*/
var Event = {
AGENT_START: Agent.Event.START,
AGENT_STOP: Agent.Event.STOP
};
/**
* The Polyseer.io client.
*/
var Client = function (_EventEmitter) {
_inherits(Client, _EventEmitter);
/**
* @param {object} options
* @param {object} options.request
*/
function Client(cid) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Client);
var _this = _possibleConstructorReturn(this, (Client.__proto__ || Object.getPrototypeOf(Client)).call(this));
options = Object.assign({}, DEFAULT_OPTIONS, options);
if (lodash.isNil(cid)) {
throw new TypeError('Cannot create a Client instance without passing a unique client id (cid).');
}
if (options.request === null) {
throw new TypeError('Cannot create an instance of Client without passing an instance of request to the options.');
}
Object.assign(_this, lodash.omit(options.resources));
_this._cid = cid;
_this._request = options.request;
_this._agent = null;
_this.instance = null; // TODO: unit-test add getter and setter (consider attaching to agent?)
Object.assign(_this, Enum);
return _this;
}
/**
* Start the agent.
*
* TODO: test event emit / attach / forward
*
* @param {...}
* @return {Promise}
*/
_createClass(Client, [{
key: 'startAgent',
value: function startAgent() {
var _this2 = this,
_agent;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (!lodash.isNull(this._agent)) {
return global.Promise.reject(new Error('Agent has already been started for this client.'));
}
this._agent = new Agent(this);
// forward agent events as client events.
[Event.AGENT_START, Event.AGENT_STOP].forEach(function (eventName) {
_this2._agent.on(eventName, function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this2.emit.apply(_this2, [eventName].concat(args));
});
});
return (_agent = this._agent).start.apply(_agent, args);
}
/**
* Stop the agent.
*
* TODO: unit-test
*
* @param {...}
* @return {Promise}
*/
}, {
key: 'stopAgent',
value: function stopAgent() {
var _agent2;
if (lodash.isNull(this._agent)) {
return global.Promise.reject(new Error('No agent to stop.'));
}
return (_agent2 = this._agent).stop.apply(_agent2, arguments);
}
/**
* Return the currently deduced environment.
*/
}, {
key: 'getCurrentEnvironment',
value: function getCurrentEnvironment() {
var Environment = this.Environment;
return Environment.findByName();
}
}]);
return Client;
}(EventEmitter);
Object.assign(Client, {
Event: Event
});
module.exports = Client;<file_sep>'use strict';
const triggerStatic = require('../static/trigger');
/**
* Trigger an instance.
*
* @param {Resource}
* @param {object}
* @return {Promise}
*/
function trigger (instance, payload, options) {
return triggerStatic(
instance._request,
instance.resource,
instance.copts,
instance.id,
payload,
options
);
}
module.exports = trigger;
<file_sep>'use strict';
const factStatic = require('../static/fact'),
{ instanceToContext } = require('../helper');
/**
* Send fact metric for an instance.
*
* @param {Resource}
* @param {key}
* @param {value}
* @return {Promise}
*/
function fact (instance, facts, options) {
return factStatic(
instance.get('id'),
facts,
options,
instanceToContext(instance)
);
}
module.exports = fact;
<file_sep>'use strict';
const removeStatic = require('../static/remove'),
{ instanceToContext } = require('../helper');
/**
* Create a remove instance method for a resource.
*
* @param {request}
* @param {...}
* @return {Promise}
*/
function remove (instance, options) {
const context = instanceToContext(instance);
return removeStatic(
instance.get('id'),
options,
context
);
}
module.exports = remove;
<file_sep>'use strict';
/**
* Trigger a resource.
*
* @param {string}
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function gauge(id, gauges, options) {
var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
gauges = gauges || {};
return context.request.post({
uri: context.uri + '/gauges',
body: gauges
});
}
module.exports = gauge;<file_sep>'use strict';
/**
* Execute a resource.
*
* @param {object}
* @param {object}
* @return {Promise}
*/
function execute(options) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return global.Promise.resolve();
}
module.exports = execute;<file_sep>'use strict';
const { loopPromise } = require('../../helper'),
{ Strategy } = require('../../enum');
/**
* Default attach options.
*/
const DEFAULT_OPTIONS = {
strategy: Strategy.FALLBACK,
delay: 3000,
deduce: true,
env: 'NODE_ENV'
};
// TODO: unit-test
/**
* Attachement strategy implementation.
*/
const StrategyHandler = {
/**
* Attempt to find the resource by name, if not found, create a new one
* with the name passed and attach.
*
* @param {request}
* @param {resource}
* @param {string}
* @param {object}
* @return {Promise}
*/
[Strategy.FALLBACK] (request, resource, uri, options) {
if (!('identifier' in options)) {
return global.Promise.reject(new Error(`Cannot attach as a ${resource} using the ${options.strategy.toString()} strategy without providing a name.`));
}
return request.get({
uri: `${uri}/name/${options.identifier}`
}).
then(result => {
return result;
}, error => {
if (error.statusCode === 404) {
return request.post({
uri,
body: { name: options.identifier }
});
}
return global.Promise.reject(error);
}).
then(data => {
const loop = () => request.post({ uri: `${uri}/${data.id}/heartbeat` }),
id = loopPromise(loop, { delay: options.delay });
return global.Promise.resolve(Object.assign(data, {
loopId: id
}));
});
},
/**
* Attach to a primary id.
*
* @param {request}
* @param {resource}
* @param {string}
* @param {object}
* @return {Promise}
*/
[Strategy.ID] (request, resource, uri, options) {
if (!('identifier' in options)) {
return global.Promise.reject(new Error(`Cannot attach as a ${resource} using the ${options.strategy.toString()} strategy without providing an id.`));
}
const loop = () => request.post({ uri: `${uri}/${options.identifier}/heartbeat` }),
id = loopPromise(loop, { delay: options.delay });
return global.Promise.resolve({});
}
};
/**
* Attach to a resource.
*
* @param {request}
* @param {string}
* @param {object}
* @param {object}
* @return {Promise}
*/
function attach (identifier, options, context = {}) {
if (identifier) {
options.identifier = identifier;
}
if (!(options.strategy in StrategyHandler)) {
throw new TypeError(`Do not know how to attach using the ${options.strategy} strategy.`);
}
return StrategyHandler[options.strategy](context.request, context.resource, context.uri, options);
}
attach.Strategy = Strategy;
module.exports = attach;
<file_sep>'use strict';
const lodash = require('lodash');
/**
* Peform a name based upsert for a resource.
*
* @param {client.Resource} a resource
* @param {object} upsert attributes
* @return {Promise}
*/
function upsert(Resource, attributes) {
if (!lodash.has(attributes, 'name')) {
return global.Promise.reject(new TypeError('Upsert requires a name in attributes.'));
}
return Resource.findByName(attributes.name).
then(lodash.identity, error => {
if (error.statusCode === 404) {
return Resource.create(attributes);
}
return global.Promise.reject(error);
});
}
module.exports = {
upsert
};
<file_sep>'use strict';
const lodash = require('lodash'),
{ getResourcePath } = require('../helper');
/**
* Save an instance.
*
* @param {Resource}
* @param {object}
* @return {Promise}
*/
function save (instance, options) {
const uri = getResourcePath(instance.resource, { eid: instance.eid, id: instance.id });
// TODO: need to avoid even generating another instance, there is no need.
// TODO: need to make a raw, non factory instance creating request.
if (instance.isNew()) {
return instance._request.post({
uri,
body: instance.toJSON()
}).then(result => {
// TODO: i'm not sure if I could possibly hate this more..
instance.setProperties(result._attributes);
return instance;
});
} else {
return instance._request.put({
uri,
body: instance.toJSON()
}).then(result => {
// TODO: i'm not sure if I could possibly hate this more..
instance.setProperties(result._attributes);
return instance;
});
}
}
module.exports = save;
<file_sep>'use strict';
const lodash = require('lodash'),
logger = require('../../logger'),
{ DEFAULT_HEARTBEAT_DELAY } = require('../../constant'),
{ formatPayload,
loopPromise } = require('../../helper'),
{ removeNonResolvingValues,
getResourcePath } = require('../helper');
/**
* Resolves facts in a map.
*
* @param {Map}
*/
function resolveFacts (facts) {
const result = {};
facts.forEach((resolver, key) => {
let value = null;
if (lodash.isFunction(resolver)) {
value = resolver();
} else {
value = resolver;
}
result[key] = value;
});
return result;
}
/**
* Resolves gauges in a map.
*
* @param {Map}
*/
function resolveGauges (gauges) {
const result = {};
gauges.forEach((resolver, key) => {
result[key] = resolver();
});
return result;
}
/**
* Default attach options.
*/
const DEFAULT_OPTIONS = {
delay: DEFAULT_HEARTBEAT_DELAY
};
/**
* Start a heartbeat for an instance.
*
* @param {instance}
* @param {object}
* @return {Promise}
*/
function attach (instance, options) {
options = lodash.defaults(DEFAULT_OPTIONS, options);
const uri = getResourcePath(instance.resource, { eid: instance.eid, id: instance.get('id') });
const loop = () => {
logger.log('debug', 'Heartbeat.');
const body = {};
if (lodash.has(instance, '_heartbeatGauges')) {
body.metrics = {};
body.metrics.gauges = resolveGauges(instance._heartbeatGauges);
instance._gaugeFacts = removeNonResolvingValues(instance._heartbeatGauges);
}
if (lodash.has(instance, '_heartbeatFacts')) {
body.facts = resolveFacts(instance._heartbeatFacts);
instance._heartbeatFacts = removeNonResolvingValues(instance._heartbeatFacts);
}
return instance._request.post({
uri: `${uri}/heartbeat`,
body
});
};
const loopId = loopPromise(loop, { delay: options.delay });
instance._loopId = loopId;
return global.Promise.resolve(loopId);
}
module.exports = attach;
<file_sep>'use strict';
var Fact = {
ARCHITECTURE: 'architecture',
CPU_COUNT: 'cpu_count',
ENDIANNESS: 'endianness',
FREE_MEMORY: 'free_memory',
GID: 'gid',
HOME_DIRECTORY: 'home_directory',
HOSTNAME: 'hostname',
LAUNCH_ARGUMENTS: 'launch_arguments',
NODE_VERSION: 'node_version',
PID: 'pid',
PLATFORM: 'platform',
TITLE: 'title',
UID: 'uid',
UPTIME: 'uptime',
V8_VERSION: 'v8_version'
};
var Expectation = {
IS_ALIVE: 'is_alive'
};
var Event = {
START: 'start',
STOP: 'stop'
};
var Process = {
EXIT: 'exit',
UNCAUGHT_EXCEPTION: 'uncaughtException',
UNHANDLED_REJECTION: 'unhandledRejection',
WARNING: 'warning',
SIGHUP: 'SIGHUP',
SIGINT: 'SIGINT',
SIGTERM: 'SIGTERM'
};
var Metric = {
MEMORY: 'memory',
CPU: 'cpu',
UPTIME: 'uptime'
};
module.exports = {
Event: Event,
Expectation: Expectation,
Fact: Fact,
Metric: Metric,
Process: Process
};<file_sep>'use strict';
const STATIC = Symbol('static'),
METHOD = Symbol('method');
module.exports = {
STATIC,
METHOD
};
<file_sep>'use strict';
var executeStatic = require('../static/execute');
/**
* Create an execute instance method for a resource.
*
* @param {request}
* @param {string}
* @return {function}
*/
function execute(instance) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return executeStatic.apply(undefined, [instance.id].concat(args));
}
module.exports = execute;<file_sep>'use strict';
const should = require('should'),
co = require('co'),
behavior = require('./shared_behavior'),
{ DEFAULT_TIMEOUT } = require('./config'),
{ setup,
teardown,
getUniqueName } = require('./helper');
describe('Instances', function () {
this.timeout(DEFAULT_TIMEOUT);
before(function () {
return setup(this).
then(_ => {
this.Resource = this.client.Instance;
});
});
after(function () { teardown(this); });
beforeEach(function () {
this.attributes = {
name: getUniqueName()
};
});
behavior.creatable();
behavior.findable();
behavior.uniquelyNameable();
behavior.updatable();
behavior.removable();
// Consider attachable behavior.
it('can attach to an instance by id', function () {
const Instance = this.Resource,
client = this.client;
return co(function* () {
let instance = yield Instance.create({
name: getUniqueName()
}).should.be.fulfilled();
instance = yield Instance.attach(instance.get('id'), {
strategy: client.Strategy.ID
}).should.be.fulfilled();
});
});
it('can attach based on name fallback', function () {
const Instance = this.Resource,
client = this.client;
return co(function* () {
const instance = yield Instance.attach(getUniqueName(), {
strategy: client.Strategy.FALLBACK
}).should.be.fulfilled();
});
});
it('can send gauge metrics', function () {
const Instance = this.Resource;
return co(function* () {
let resource = yield Instance.create({
name: getUniqueName()
}).should.be.fulfilled();
const gauge = yield resource.gauge({
foo: 22
}).should.be.fulfilled();
resource = yield Instance.findById(resource.get('id')).should.be.fulfilled();
resource.get('gauges').foo[0][0].should.eql(22);
});
});
it('can set instance facts', function () {
const Instance = this.Resource;
return co(function* () {
let resource = yield Instance.create({
name: getUniqueName()
}).should.be.fulfilled();
const fact = yield resource.fact({
foo: 'bar'
}).should.be.fulfilled();
resource = yield Instance.findById(resource.get('id')).should.be.fulfilled();
resource.get('facts').foo.value.should.eql('bar');
});
});
});
<file_sep>'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DefaultConfig = require('./default_config'),
lodash = require('lodash'),
HandlerMap = require('./handler'),
logger = require('../logger'),
EventEmitter = require('events'),
logAndReject = logger.logAndReject,
_require = require('../helper'),
clearLoop = _require.clearLoop,
loopPromise = _require.loopPromise,
_require2 = require('./helper'),
filterHandlers = _require2.filterHandlers,
_require3 = require('./executor'),
setup = _require3.setup,
teardown = _require3.teardown;
/**
* Agent events.
*/
var Event = {
START: 'agent-start',
STOP: 'agent-stop'
};
/**
* The Polyseer.io agent.
*/
var Agent = function (_EventEmitter) {
_inherits(Agent, _EventEmitter);
/**
* @param {Client}
*/
function Agent(client) {
_classCallCheck(this, Agent);
var _this = _possibleConstructorReturn(this, (Agent.__proto__ || Object.getPrototypeOf(Agent)).call(this));
if (lodash.isNil(client) || !lodash.isObject(client)) {
throw new TypeError('Must pass a Polyseer.io client to Agent.');
}
_this._client = client;
_this._instance = null;
_this._start_args = null;
return _this;
}
/**
* Start the agent.
*
* @param {object}
* @return {Promise}
*/
_createClass(Agent, [{
key: 'start',
value: function start(options) {
var _this2 = this;
options = lodash.defaultsDeep({}, options, DefaultConfig);
var handlerOptions = filterHandlers(lodash.pick(options, lodash.keys(HandlerMap)));
options.handlers = handlerOptions;
this._handler_options = handlerOptions;
return new global.Promise(function (resolve, reject) {
var attempt = 0;
var loop = loopPromise(function () {
var meta = {
attempt: attempt += 1
};
logger.log('info', 'Agent setup attempt.', meta);
return setup(_this2._client, options).then(function (instance) {
logger.log('info', 'Agent setup success.', meta);
_this2._instance = instance; // TODO: is this the right place for this?
clearLoop(loop);
_this2.emit(Event.START);
return resolve(_this2._client);
}).catch(function (error) {
logger.log('error', 'Agent setup failed. Will retry in ' + options.agent_retry + ' ms.', meta);
return logAndReject(error);
});
}, {
delay: options.agent_retry
});
});
}
/**
* Gracefully stop the agent.
*
* @return {Promise}
*/
}, {
key: 'stop',
value: function stop() {
var _this3 = this;
return teardown(this._client, this._handler_options).then(function (_) {
_this3.emit(Event.STOP);
return _this3._client;
});
}
}]);
return Agent;
}(EventEmitter);
Object.assign(Agent, {
Event: Event
});
module.exports = Agent;<file_sep>'use strict';
/**
* Retreive a singleton resource.
*
* @param {object}
* @param {object}
* @return {Promise}
*/
function retreive(options) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return context.request.get({ uri: context.uri });
}
module.exports = retreive;<file_sep>const polyseerio = require('../');
return polyseerio.start({
agent: {
subtype: polyseerio.Subtype.PERIODIC
}
}).
then(client => {
console.log('do work');
});
<file_sep>'use strict';
const winston = require('winston'),
lodash = require('lodash');
/**
* SDK logger.
*/
const logger = new winston.Logger({
level: process.env.POLYSEERIO_LOG_LEVEL || 'error',
transports: [
new winston.transports.Console()
]
});
/**
* Log an error.
*
* @param {winston}
* @param {Error}
*/
function _logErrorWithLogger (logger, error) {
const meta = { stack: error.stack };
logger.log('error', `${error.name}: ${error.message}`, meta);
}
const logErrorWithLogger = lodash.curry(_logErrorWithLogger);
/**
* Log an error and continue to reject.
*
* @param {winston}
* @param {Error}
*/
function _logAndRejectWithLogger (logger, error) {
logErrorWithLogger(logger, error);
return global.Promise.reject(error);
}
const logAndRejectWithLogger = lodash.curry(_logAndRejectWithLogger);
/**
* Create helper methods.
*/
const logError = logErrorWithLogger(logger);
const logAndReject = logAndRejectWithLogger(logger);
// A little bit dangerous. Maybe there is a way to be nicer.
Object.assign(logger, {
logError,
logAndReject
});
module.exports = logger;
<file_sep>'use strict';
var _require = require('../../helper'),
requireDirectory = _require.requireDirectory;
var METHOD_EXT = '.js',
EXCLUDE = ['factory', 'index'];
function predicate(pathObject) {
return pathObject.ext === METHOD_EXT && EXCLUDE.indexOf(pathObject.name) === -1;
}
function iteratee(pathObject) {
return {
name: pathObject.name,
require: __dirname + '/' + pathObject.name
};
}
module.exports = requireDirectory(__dirname, predicate, iteratee);<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon'),
proxyquire = require('proxyquire');
describe('SDK Factory', () => {
const StaticDouble = {
foo: function (a, b, c, d) { return [a, b, c, d]; },
bar: function (a, b, c, d) { return [a, b, c, d]; }
},
InstanceDouble = {
ping: sinon.stub(),
pong: sinon.stub(),
};
const factory = proxyquire('../../lib/sdk/factory', {
'./static': StaticDouble,
'./method': InstanceDouble
});
beforeEach(() => {
InstanceDouble.ping.reset();
InstanceDouble.pong.reset();
});
describe('staticFactory', () => {
const { staticFactory } = factory;
it('returns requested static methods', () => {
const request = sinon.spy(),
resource = 'alpha',
statics = ['foo', 'bar'];
const response = staticFactory(request, resource, statics);
response.should.have.property('foo');
response.should.have.property('bar');
});
it('', () => {
// TODO: ensure that preprocessing occurs.
});
it('throws if the requested static does not exist', () => {
const request = sinon.spy(),
resource = 'alpha',
statics = ['unknown'];
(function () {
staticFactory(request, resource, statics);
}).should.throw(/asked to generate a 'unknown' static method/);
});
});
describe('methodFactory', () => {
const { methodFactory } = factory;
it('returns requested methods', () => {
const request = sinon.spy(),
resource = 'alpha',
statics = ['ping', 'pong'];
const response = methodFactory(request, resource, statics);
response.should.have.property('ping');
response.should.have.property('pong');
});
it('returns result of called requested method', () => {
const request = sinon.spy(),
resource = 'alpha',
statics = ['ping'];
const response = methodFactory(request, resource, statics);
response.ping.should.eql(InstanceDouble.ping);
});
it('throws if the requested method does not exist', () => {
const request = sinon.spy(),
resource = 'alpha',
statics = ['unknown'];
(function () {
methodFactory(request, resource, statics);
}).should.throw(/asked to generate a 'unknown' instance method/);
});
});
});
<file_sep>'use strict';
const { Resource } = require('../enum'),
{ STATIC,
METHOD } = require('./definition_constant');
/**
* Resources that can be created.
*/
const CreatableStatics = [
'create'
];
/**
* Resources that can be read.
*/
const ReadableStatics = [
'find',
'findById'
];
/**
* Resources that can be deleted.
*/
const DeletableStatics = [
'remove'
];
/**
* Resources that can be update.
*/
const UpdatableStatics = [
'update'
];
/**
* Creatable, readable, updatable, deletable resources.
*/
const CRUDStatics = [
...CreatableStatics,
...ReadableStatics,
...UpdatableStatics,
...DeletableStatics
];
/**
* Required instance methods. // TODO: Does this make sense here?
*/
const ResourceInstance = [
'get',
'isNew',
'set',
'setProperties',
'toJSON'
];
/**
* Resources that can be saved (updated and created).
*/
const SavableInstance = [
'save'
];
/**
* Resource definitions.
*/
const DEFINITION = {
[Resource.ALERT]: {
[STATIC]: [
...CRUDStatics,
'findByName',
'trigger'
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'trigger',
'remove'
]
},
[Resource.CHANNEL]: {
[STATIC]: [
...CRUDStatics,
'findByName',
'message'
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'message',
'remove'
]
},
[Resource.ENVIRONMENT]: {
[STATIC]: [
...CRUDStatics,
'findByName',
'message'
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'message',
'remove'
]
},
[Resource.EVENT]: {
[STATIC]: [
...CreatableStatics,
...ReadableStatics
],
[METHOD]: [
...SavableInstance,
...ResourceInstance
]
},
[Resource.EXPECTATION]: {
[STATIC]: [
...CRUDStatics,
'findByName',
'check',
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'remove',
'check'
]
},
[Resource.GAUGE]: {
[STATIC]: [],
[METHOD]: [
...ResourceInstance
]
},
[Resource.INSTANCE]: {
[STATIC]: [
...CRUDStatics,
'findByName',
'gauge',
'attach'
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'gauge',
'addGauge',
'fact',
'addFact',
'attach',
'detach',
'remove'
]
},
[Resource.LOGIC_BLOCK]: {
[STATIC]: [
...CRUDStatics,
'findByName',
'execute'
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'remove',
'execute'
]
},
[Resource.MEMBER]: {
[STATIC]: [
...CRUDStatics,
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'remove'
]
},
[Resource.MESSAGE]: {
[STATIC]: [
...CRUDStatics,
],
[METHOD]: [
...SavableInstance,
...ResourceInstance
]
},
[Resource.SETTING]: {
[STATIC]: [
...UpdatableStatics,
'retrieve'
]
},
[Resource.TASK]: {
[STATIC]: [
...CRUDStatics,
],
[METHOD]: [
...SavableInstance,
...ResourceInstance,
'remove'
]
}
};
module.exports = DEFINITION;
<file_sep>'use strict';
const os = require('os'),
{ Fact } = require('../enum');
module.exports = {
[Fact.ARCHITECTURE] (_config, client) {
client.instance.addFact('architecture', process.arch);
},
[Fact.CPU_COUNT] (_config, client) {
client.instance.addFact('cpu_count', os.cpus().length);
},
[Fact.ENDIANNESS] (_config, client) {
client.instance.addFact('endianness', os.endianness());
},
[Fact.FREE_MEMORY] (_config, client) {
client.instance.addFact('free_memory', function () {
return os.freemem();
});
},
[Fact.HOME_DIRECTORY] (_config, client) {
client.instance.addFact('home_directory', os.homedir());
},
[Fact.HOSTNAME] (_config, client) {
client.instance.addFact('hostname', os.hostname());
},
[Fact.GID] (_config, client) {
client.instance.addFact('gid', process.getgid());
},
[Fact.LAUNCH_ARGUMENTS] (_config, client) {
const value = process.argv.join(' ');
client.instance.addFact('launch_arguments', value);
},
[Fact.UPTIME] (_config, client) {
client.instance.addFact('uptime', function () {
return process.uptime();
});
},
[Fact.NODE_VERSION] (_config, client) {
client.instance.addFact('node_version', process.versions.node);
},
[Fact.PID] (_config, client) {
client.instance.addFact('pid', process.pid);
},
[Fact.PLATFORM] (_config, client) {
client.instance.addFact('platform', process.platform);
},
[Fact.TITLE] (_config, client) {
client.instance.addFact('title', process.title);
},
[Fact.UID] (_config, client) {
client.instance.addFact('uid', process.getuid());
},
[Fact.V8_VERSION] (_config, client) {
client.instance.addFact('v8_version', process.versions.v8);
}
};
<file_sep>'use strict';
var _StrategyHandler;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _require = require('../../helper'),
loopPromise = _require.loopPromise,
_require2 = require('../../enum'),
Strategy = _require2.Strategy;
/**
* Default attach options.
*/
var DEFAULT_OPTIONS = {
strategy: Strategy.FALLBACK,
delay: 3000,
deduce: true,
env: 'NODE_ENV'
};
// TODO: unit-test
/**
* Attachement strategy implementation.
*/
var StrategyHandler = (_StrategyHandler = {}, _defineProperty(_StrategyHandler, Strategy.FALLBACK, function (request, resource, uri, options) {
if (!('identifier' in options)) {
return global.Promise.reject(new Error('Cannot attach as a ' + resource + ' using the ' + options.strategy.toString() + ' strategy without providing a name.'));
}
return request.get({
uri: uri + '/name/' + options.identifier
}).then(function (result) {
return result;
}, function (error) {
if (error.statusCode === 404) {
return request.post({
uri: uri,
body: { name: options.identifier }
});
}
return global.Promise.reject(error);
}).then(function (data) {
var loop = function loop() {
return request.post({ uri: uri + '/' + data.id + '/heartbeat' });
},
id = loopPromise(loop, { delay: options.delay });
return global.Promise.resolve(Object.assign(data, {
loopId: id
}));
});
}), _defineProperty(_StrategyHandler, Strategy.ID, function (request, resource, uri, options) {
if (!('identifier' in options)) {
return global.Promise.reject(new Error('Cannot attach as a ' + resource + ' using the ' + options.strategy.toString() + ' strategy without providing an id.'));
}
var loop = function loop() {
return request.post({ uri: uri + '/' + options.identifier + '/heartbeat' });
},
id = loopPromise(loop, { delay: options.delay });
return global.Promise.resolve({});
}), _StrategyHandler);
/**
* Attach to a resource.
*
* @param {request}
* @param {string}
* @param {object}
* @param {object}
* @return {Promise}
*/
function attach(identifier, options) {
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (identifier) {
options.identifier = identifier;
}
if (!(options.strategy in StrategyHandler)) {
throw new TypeError('Do not know how to attach using the ' + options.strategy + ' strategy.');
}
return StrategyHandler[options.strategy](context.request, context.resource, context.uri, options);
}
attach.Strategy = Strategy;
module.exports = attach;<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon');
describe('Agent EventHandler', () => {
const { createInstance } = require('../../helper');
const Interface = require('../../../../lib/agent/handler/interface');
const Handler = require('../../../../lib/agent/handler/event');
describe('start', () => {
const { start } = Handler;
it('creates an event for the agent being started', () => {
const client = {
Event: {
create: sinon.stub()
},
instance: createInstance({
name: 'foo'
}),
Color: {
GREEN: 'green'
},
Icon: {
CHAIN: 'chain'
}
};
client.Event.create.withArgs({
name: 'foo agent has started.',
color: 'green',
icon: 'chain'
}).returns(global.Promise.resolve('result_double'));
return start({}, client).should.be.fulfilled().
then(result => {
result.should.eql('result_double');
});
});
});
describe('stop', () => {
const stop = Handler.stop[Interface.TEARDOWN];
it('creates an event for the agent being stoped', () => {
const client = {
Event: {
create: sinon.stub()
},
instance: createInstance({
name: 'foo'
}),
Color: {
ORANGE: 'orange'
},
Icon: {
CHAIN_BROKEN: 'chain-broken'
}
};
client.Event.create.returns(global.Promise.resolve('result_double'));
return stop({}, client).should.be.fulfilled().
then(result => {
client.Event.create.calledWithExactly({
name: 'foo agent has stopped.',
color: 'orange',
icon: 'chain-broken'
}).should.eql(true);
result.should.eql('result_double');
});
});
});
});
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon');
describe('Agent MetricHandler', () => {
const Handler = require('../../../../lib/agent/handler/metric');
describe('memory', () => {
const { memory } = Handler;
it('sends memory usage', () => {
// wait for additionso of metric add to instance that will push metrics
// alongside heartbeats instead of making .gauge calls.
});
});
});
<file_sep>const polyseerio = require('../'),
config = require('./config'),
co = require('co');
const { Alert,
Channel,
Environment,
Event,
Expectation,
Instance,
LogicBlock,
Member,
Settings,
Task } = polyseerio(config.token, { env: config.env });
co(function* () {
yield global.Promise.resolve();
/*
const data = {
instance: 'demo',
reason: 'because i said so'
}
yield onExit(data);
*/
/**
* Attach current intance.
*/
/*
const instance = yield Instance.
attach({ name: 'test-instance' });
*/
/**
* Trigger a memory alert.
*/
//yield onMemoryLimit(1000, { name: 'app-1', id: 100 });
/**
* Trigger an event.
*/
/*
const event = yield Event.create({
name: 'an-event'
}).catch(console.log);
*/
/**
* Create a task.
*/
/*
const task = yield Task.create({
name: 'my-new-task'
}).catch(console.log);
*/
/**
* Message an environment by primary id.
*/
/*
const message = yield Environment.
findById('57c67a02f8081a0100fbe5ae').
then(environment => {
return Environment.message(environment.id, 'Testing');
}).
catch(console.log);
*/
}).catch(e => console.log(e));
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon'),
proxyquire = require('proxyquire');
describe('Helper', () => {
function getResponse () {
return {
client: {
_httpMessage: {
path: '/v1/something',
}
},
body: {
data: {
id: 1,
type: 'foo',
attributes: {
ding: 'dong'
},
relationships: {
king: 'kong'
}
},
meta: {
alpha: 'beta'
}
}
};
}
function getResourceCollectionResponse () {
return {
client: {
_httpMessage: {
path: '/v1/something',
}
},
body: {
data: [{
id: 1,
type: 'foo',
attributes: {
ding: 'dong'
},
relationships: {
king: 'kong'
}
}, {
id: 2,
type: 'foo',
attributes: {
ding: 'wing'
},
relationships: {
king: 'hello'
}
}],
meta: {
alpha: 'beta'
}
}
};
}
const factoryDouble = sinon.stub();
class ResourceDouble {}
const Helper = proxyquire('../../../lib/resource/helper', {
'./factory': factoryDouble
});
beforeEach(() => {
factoryDouble.reset();
});
describe('getEidFromRequestPath', () => {
const { getEidFromRequestPath } = Helper;
it('returns correct eid when longer path used', () => {
const path = '/v1/environments/development/instances/10000/gauges';
const result = getEidFromRequestPath(path);
result.should.eql('development');
});
it('returns null when non resource path provided', () => {
const path = '/v1/something';
const result = getEidFromRequestPath(path);
(result === null).should.eql(true);
});
it('returns correct eid when available', () => {
const path = '/polyseer/v1/environments/validation-testing/events';
const result = getEidFromRequestPath(path);
result.should.eql('validation-testing');
});
it('returns null is non could be found', () => {
const path = '/polyseer/v1/members';
const result = getEidFromRequestPath(path);
(result === null).should.eql(true);
});
it('returns the eid when using environment w/ name', () => {
const path = '/environments/name/validation-testing';
const result = getEidFromRequestPath(path);
result.should.eql('validation-testing');
});
});
describe('isResourceCollection', () => {
const { isResourceCollection } = Helper;
it('returns true when array is passed', () => {
const data = [];
const result = isResourceCollection(data);
result.should.eql(true);
});
it('returns false when object is passed', () => {
const data = {};
const result = isResourceCollection(data);
result.should.eql(false);
});
});
describe('isResourceResponse', () => {
const { isResourceResponse } = Helper;
it('returns true when body has data', () => {
const response = {
body: {
data: {}
}
};
const result = isResourceResponse(response);
result.should.eql(true);
});
it('returns false when body has no data', () => {
const response = {
body: {
dork: 'a'
}
};
const result = isResourceResponse(response);
result.should.eql(false);
});
it('returns false when body.data is not an array or object', () => {
const response = {
body: {
data: 'do'
}
};
const result = isResourceResponse(response);
result.should.eql(false);
});
});
describe('parseResourceResponse', () => {
const { parseResourceResponse } = Helper;
it('handles a resource collection', () => {
const response = getResourceCollectionResponse();
factoryDouble.withArgs(response.body.data[0].type).returns(ResourceDouble);
const result = parseResourceResponse(response);
result.should.be.an.instanceOf(Array);
});
it('when a collection each item is an instance of factory result', () => {
const response = getResourceCollectionResponse();
factoryDouble.withArgs(response.body.data[0].type).returns(ResourceDouble);
const result = parseResourceResponse(response);
result.forEach(instance => {
instance.should.be.an.instanceOf(ResourceDouble);
});
});
it('handles a single resource', () => {
const response = getResponse();
factoryDouble.withArgs(response.body.data.type).returns(ResourceDouble);
const result = parseResourceResponse(response);
result.should.be.an.instanceOf(ResourceDouble);
});
});
describe('parseResponse', () => {
const { parseResponse } = Helper;
describe('when a resource based response', () => {
it('returns BaseResource instances', () => {
const response = getResponse();
factoryDouble.withArgs(response.body.data.type).returns(ResourceDouble);
const result = parseResponse(response);
result.should.be.an.instanceOf(ResourceDouble);
});
});
describe('when not a resource based response', () => {
it('returns the response object', () => {
const response = {
body: {
foo: 'bar'
}
};
const result = parseResponse(response);
result.should.eql(response);
});
});
});
});
<file_sep>'use strict';
/**
* Check a resource.
*
* Used for expecations.
*
* @param {object}
* @param {object}
* @return {Promise}
*/
function check (options, context = {}) {
return context.request.get({
uri: `${context.uri}/check`
});
}
module.exports = check;
<file_sep>'use strict';
var lodash = require('lodash'),
_require = require('../../helper'),
clearLoop = _require.clearLoop;
/**
* Clear an attach heartbeat for an instance.
*
* @param {instance}
* @param {object}
* @return {Promise}
*/
function detach(instance, options) {
if (lodash.has(instance, '_loopId') && !lodash.isNil(instance._loopId)) {
return clearLoop(instance._loopId).then(function (_) {
instance._loopId = null;
return 'cleared';
});
}
return global.Promise.resolve('not beating');
}
module.exports = detach;<file_sep>'use strict';
const co = require('co'),
lodash = require('lodash'),
{ getUniqueName } = require('./helper');
function canRemove (Resource) {
return lodash.has(Resource, 'remove');
}
/**
* Ensure that a resource is creatable.
*/
exports.creatable = function () {
it('can create an instance statically: Resource.create', function() {
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
it('can create an instance using: new and instance.save', function() {
const instance = new this.Resource(this.attributes);
return instance.save().
should.be.fulfilledWith(instance).
then(instance => {
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
};
/**
* Ensure that a resource is findable.
*/
exports.findable = function () {
it('can find an instance statically by id: Resource.findById', function() {
return this.Resource.create(this.attributes).
then(instance => {
return this.Resource.findById(instance.get('id'));
}).should.be.fulfilled().
then(instance => {
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
};
/**
* Ensure that a resource is findable by name.
*/
exports.uniquelyNameable = function () {
it('can find an instance statically by name: Resource.findByName', function() {
return this.Resource.create(this.attributes).
then(instance => {
return this.Resource.findByName(instance.get('name'));
}).should.be.fulfilled().
then(instance => {
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
};
/**
* Ensure that a resource is removable.
*/
exports.removable = function () {
it('can remove an instance statically: Resource.remove', function() {
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
const id = instance.get('id');
return this.Resource.remove(id).should.be.fulfilled().
then(_ => {
return id;
});
}).then(id => {
return this.Resource.findById(id).should.be.rejected();
});
});
it('can remove an instance using: instance.remove', function() {
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
const id = instance.get('id');
return instance.remove().should.be.fulfilled().
then(_ => {
return id;
});
}).then(id => {
return this.Resource.findById(id).should.be.rejected();
});
});
};
/**
* Ensure that a resource is updatable.
*/
exports.updatable = function () {
it('can update an instance statically: Resource.update', function() {
const name = getUniqueName();
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
return this.Resource.update(instance.get('id'), { name });
}).should.be.fulfilled().
then(instance => {
instance.get('name').should.eql(name);
return this.Resource.findById(instance.get('id'));
}).
then(instance => {
instance.get('name').should.eql(name);
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
it('can update an instance using: instance.save', function() {
const name = getUniqueName();
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
instance.set('name', name);
return instance.save().should.be.fulfilled();
}).then(instance => {
return this.Resource.findById(instance.get('id'));
}).then(instance => {
instance.get('name').should.eql(name);
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
};
/**
* Ensure that a resource is triggerable.
*/
exports.triggerable = function () {
it('can trigger an instance statically: Resource.trigger', function() {
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
return this.Resource.trigger(instance.get('id'), {}).should.be.fulfilled();
}).then(instance => {
if (canRemove(this.Resource)) {
return this.Resource.remove(instance.get('id'));
}
}).should.be.fulfilled();
});
};
/**
* Ensure that a resource is messagable.
*/
exports.messageable = function () {
it('can message an instance statically: Resource.message', function() {
return this.Resource.create(this.attributes).
should.be.fulfilled().
then(instance => {
return this.Resource.message(instance.get('id'), 'hello world').
then(_ => {
return instance.get('id');
});
}).should.be.fulfilled().
then(id => {
if (canRemove(this.Resource)) {
return this.Resource.remove(id);
}
}).should.be.fulfilled();
});
};
<file_sep>'use strict';
const should = require('should');
describe('Enum', () => {
const Interface = require('../../../../lib/agent/handler/interface');
it('correctly defines SETUP', () => {
const { SETUP } = Interface;
const label = SETUP.toString();
label.should.eql('Symbol(agent-handler-setup)');
});
it('correctly defines TEARDOWN', () => {
const { TEARDOWN } = Interface;
const label = TEARDOWN.toString();
label.should.eql('Symbol(agent-handler-teardown)');
});
});
<file_sep>'use strict';
const { Metric } = require('../enum');
/**
* Resolves the processes current memory.
*
* @param {process}
* @return {function}
*/
function resolveMemory (proc) {
return () => {
return proc.memoryUsage().rss;
};
}
/**
* Resolves the current user cpu usage.
*
* @param {process}
* @return {function}
*/
function resolveCpuUser (proc) {
return () => {
return proc.cpuUsage().user;
};
}
/**
* Resolves the current system cpu usage.
*
* @param {process}
* @return {function}
*/
function resolveCpuSystem (proc) {
return () => {
return proc.cpuUsage().system;
};
}
/**
* Resolves uptime.
*
* @param {process}
* @return {function}
*/
function resolveUptime (proc) {
return () => {
return proc.uptime();
};
}
module.exports = {
/**
* Establish process memory tracking.
*
* @param {Client}
* @param {Instance}
* @param {process}
* @return {Promise}
*/
[Metric.MEMORY] (_config, client) {
client.instance.addGauge('memory', resolveMemory(process));
},
/**
* Establish process cpu usage tracking.
*
* @param {Client}
* @param {Instance}
* @param {process}
* @return {Promise}
*/
[Metric.CPU] (_config, client) {
client.instance.addGauge('cpu_user', resolveCpuUser(process));
client.instance.addGauge('cpu_system', resolveCpuSystem(process));
},
/**
* Establish process uptime tracking.
*
* @param {Client}
* @param {Instance}
* @param {process}
* @return {Promise}
*/
[Metric.UPTIME] (_config, client) {
client.instance.addGauge('uptime', resolveUptime(process));
}
};
<file_sep>'use strict';
const checkStatic = require('../static/check');
/**
* Create a check instance method for a resource.
*
* @param {request}
* @param {string}
* @return {function}
*/
function check (instance, ...args) {
return checkStatic(instance.id, ...args);
}
module.exports = check;
<file_sep>'use strict';
const { requireDirectory } = require('../../helper');
const METHOD_EXT = '.js',
EXCLUDE = ['factory', 'index'];
function predicate (pathObject) {
return (pathObject.ext === METHOD_EXT &&
EXCLUDE.indexOf(pathObject.name) === -1);
}
function iteratee (pathObject) {
return {
name: pathObject.name,
require: `${__dirname}/${pathObject.name}`
};
}
module.exports = requireDirectory(__dirname, predicate, iteratee);
<file_sep>'use strict';
const lodash = require('lodash'),
Enum = require('./enum'),
Client = require('./client'),
requestPromise = require('request-promise'),
{ Resource } = require('./enum'),
{ ACCESS_TOKEN_HEADER,
DEFAULT_ENV,
DEFAULT_TOKEN_ENV,
DEFAULT_LOG_LEVEL,
DEFAULT_ENVIRONMENT,
DEFAULT_HEARTBEAT_DELAY,
DEFAULT_API_BASE_URL,
DEFAULT_API_VERSION,
DEFAULT_TIMEOUT } = require('./constant'),
{ getBaseUrl } = require('./url_builder'),
{ preRequest,
postRequest,
postReject,
forwardCurry } = require('./middleware'),
{ createResource } = require('./resource/helper'),
{ resolveEid,
resolveToken,
createOptions,
remapObjectPaths,
wrapRequest } = require('./helper');
/**
* Resources that are required by the client API.
*/
const RequiredResources = [
Resource.ALERT,
Resource.CHANNEL,
Resource.ENVIRONMENT,
Resource.EVENT,
Resource.EXPECTATION,
Resource.INSTANCE,
Resource.LOGIC_BLOCK,
Resource.MEMBER,
Resource.SETTING,
Resource.TASK
];
/**
* Client Resource path names.
*/
const ClientResourcePaths = {
[Resource.ALERT]: 'Alert',
[Resource.CHANNEL]: 'Channel',
[Resource.ENVIRONMENT]: 'Environment',
[Resource.EVENT]: 'Event',
[Resource.EXPECTATION]: 'Expectation',
[Resource.INSTANCE]: 'Instance',
[Resource.LOGIC_BLOCK]: 'LogicBlock',
[Resource.MEMBER]: 'Member',
[Resource.SETTING]: 'Settings',
[Resource.TASK]: 'Task'
};
/**
* Default factory options.
*/
const DEFAULT_OPTIONS = {
agent: {},
deduce: true,
env: DEFAULT_ENV,
environment: null, // this value is resolved, default null is correct
heartbeat_delay: DEFAULT_HEARTBEAT_DELAY, // implement this?
log_level: DEFAULT_LOG_LEVEL, // need to implement this with logger
timeout: DEFAULT_TIMEOUT,
token: null,
token_env: DEFAULT_TOKEN_ENV,
upsert_env: true,
version: DEFAULT_API_VERSION
};
/**
* Shorthand for creating a client and starting the agent.
*
* @param {...}
* @return {Promise}
*/
function start (...args) {
const client = factory(...args);
return client.startAgent();
}
/**
* Constructrs a polyseer.io client.
*
* @param {object} construction options
* @return {Promise}
*/
function factory (options) {
options = createOptions(options, DEFAULT_OPTIONS);
options.environment = resolveEid(options);
options.token = resolveToken(options);
if (lodash.isNull(options.token)) {
throw new TypeError(`Could not find an access token. None was passed and none could be found in the environment variable: ${options.token_env}.`);
}
const baseUrl = getBaseUrl(undefined, undefined, options.version),
headers = {
[ACCESS_TOKEN_HEADER]: options.token
};
let request = requestPromise.defaults({
headers,
baseUrl,
json: true,
resolveWithFullResponse: true,
timeout: options.timeout
});
const pre = forwardCurry(preRequest, factory._callCount),
post = forwardCurry(postRequest, factory._callCount),
reject = forwardCurry(postReject, factory._callCount, request, options);
request = wrapRequest(request, { pre, post, reject });
const Resources = RequiredResources.reduce((result, resource) => {
result[resource] = createResource(resource, request, options, factory._callCount);
return result;
}, {});
const resources = remapObjectPaths(Resources, ClientResourcePaths),
clientOptions = { request, resources },
client = new Client(factory._callCount, clientOptions);
factory._callCount++; // for memoize in resource factory calls
return client;
}
// call count is used to memoize resource factory calls
factory._callCount = 0;
Object.assign(factory, {
ClientResourcePaths,
RequiredResources,
start
});
Object.assign(factory, Enum);
module.exports = factory;
<file_sep>'use strict';
const lodash = require('lodash'),
{ Resource } = require('./enum'),
{ DEFAULT_API_BASE_URL,
DEFAULT_API_VERSION,
DEFAULT_API_PROTOCOL } = require('./constant');
/**
* Resources that are routable by environment.
*/
const RoutableResources = [
Resource.ALERT,
Resource.ENVIRONMENT_MESSAGE,
Resource.EVENT,
Resource.EXPECTATION,
Resource.INSTANCE,
Resource.TASK
];
/**
* Determines if a resource is routable by environment.
*
* @param {string}
* @return {boolean}
*/
function _isRoutableResource (resource) {
return (RoutableResources.indexOf(resource) !== -1);
}
// Use memoized version.
const isRoutableResource = lodash.memoize(_isRoutableResource);
/**
* Returns the path for a given resource.
*
* @param {string}
* @param {options}
* @return {string}
*/
function _getResourcePath (resource, options = {}) {
let environment = '';
if (isRoutableResource(resource)) {
if (!lodash.has(options, 'eid')) {
throw new TypeError(`Cannot get routable resource path for ${resource}, without passing an eid to the options.`);
}
// convert into a message resource
if (resource === Resource.ENVIRONMENT_MESSAGE) {
resource = Resource.MESSAGE;
}
environment = `environments/${options.eid}/`;
}
const id = ('id' in options && !lodash.isNil(options.id)) ? `/${options.id}` : '';
return `/${environment}${resource}${id}`;
}
// Export memoized version.
const getResourcePath = lodash.memoize(_getResourcePath, (resource, options = {}) => {
return `${resource}.${options.id}.${options.eid}`;
});
/**
* Construct a usable polyseer API base url.
*
* @param {string} base url
* @param {string} version
* @return {string}
*/
function getBaseUrl (
base = DEFAULT_API_BASE_URL,
protocol = DEFAULT_API_PROTOCOL,
version = DEFAULT_API_VERSION
) {
return `${protocol}${base}/${version}`;
}
module.exports = {
getResourcePath,
getBaseUrl,
RoutableResources
};
<file_sep>'use strict';
const lodash = require('lodash');
/**
* Set multiple attribute.
*
* @param {Resoure}
* @param {string}
* @param {mixed}
* @return {mixed}
*/
function setProperties (instance, properties = {}) {
lodash.forEach(properties, (value, key) =>{
instance.set(key, value);
});
return instance;
}
module.exports = setProperties;
<file_sep>const should = require('should'),
co = require('co'),
{ DEFAULT_TIMEOUT } = require('./config'),
{ setup,
teardown } = require('./helper');
describe('Agent', function () {
this.timeout(DEFAULT_TIMEOUT);
before(function () {
return setup(this);
});
after(function () { teardown(this); });
describe('start', function () {
it('the agent can be started', function () {
return this.client.startAgent().should.be.fulfilled().
then(_ => {
this.client.stopAgent().should.be.fulfilled();
});
});
});
});
<file_sep>'use strict';
const should = require('should');
describe('Enum', () => {
const Enum = require('../../../lib/agent/enum');
describe('Fact', () => {
const { Fact } = Enum;
it('correctly defines ARCHITECTURE', () => {
const { ARCHITECTURE } = Fact;
ARCHITECTURE.should.eql('architecture');
});
it('correctly defines CPU_COUNT', () => {
const { CPU_COUNT } = Fact;
CPU_COUNT.should.eql('cpu_count');
});
it('correctly defines ENDIANNESS', () => {
const { ENDIANNESS } = Fact;
ENDIANNESS.should.eql('endianness');
});
it('correctly defines FREE_MEMORY', () => {
const { FREE_MEMORY } = Fact;
FREE_MEMORY.should.eql('free_memory');
});
it('correctly defines GID', () => {
const { GID } = Fact;
GID.should.eql('gid');
});
it('correctly defines HOME_DIRECTORY', () => {
const { HOME_DIRECTORY } = Fact;
HOME_DIRECTORY.should.eql('home_directory');
});
it('correctly defines HOSTNAME', () => {
const { HOSTNAME } = Fact;
HOSTNAME.should.eql('hostname');
});
it('correctly defines LAUNCH_ARGUMENTS', () => {
const { LAUNCH_ARGUMENTS } = Fact;
LAUNCH_ARGUMENTS.should.eql('launch_arguments');
});
it('correctly defines NODE_VERSION', () => {
const { NODE_VERSION } = Fact;
NODE_VERSION.should.eql('node_version');
});
it('correctly defines PID', () => {
const { PID } = Fact;
PID.should.eql('pid');
});
it('correctly defines PLATFORM', () => {
const { PLATFORM } = Fact;
PLATFORM.should.eql('platform');
});
it('correctly defines TITLE', () => {
const { TITLE } = Fact;
TITLE.should.eql('title');
});
it('correctly defines UID', () => {
const { UID } = Fact;
UID.should.eql('uid');
});
it('correctly defines UPTIME', () => {
const { UPTIME } = Fact;
UPTIME.should.eql('uptime');
});
it('correctly defines V8_VERSION', () => {
const { V8_VERSION } = Fact;
V8_VERSION.should.eql('v8_version');
});
});
describe('Expectation', () => {
const { Expectation } = Enum;
it('correctly defines IS_AILVE', () => {
const { IS_ALIVE } = Expectation;
IS_ALIVE.should.eql('is_alive');
});
});
describe('Event', () => {
const { Event } = Enum;
it('correctly defines START', () => {
const { START } = Event;
START.should.eql('start');
});
it('correctly defines STOP', () => {
const { STOP } = Event;
STOP.should.eql('stop');
});
});
describe('Process', () => {
const { Process } = Enum;
it('correctly defines SIGHUP', () => {
const { SIGHUP } = Process;
SIGHUP.should.eql('SIGHUP');
});
it('correctly defines SIGINT', () => {
const { SIGINT } = Process;
SIGINT.should.eql('SIGINT');
});
it('correctly defines SIGTERM', () => {
const { SIGTERM } = Process;
SIGTERM.should.eql('SIGTERM');
});
it('correctly defines EXIT', () => {
const { EXIT } = Process;
EXIT.should.eql('exit');
});
it('correctly defines UNCAUGHT_EXCEPTION', () => {
const { UNCAUGHT_EXCEPTION } = Process;
UNCAUGHT_EXCEPTION.should.eql('uncaughtException');
});
it('correctly defines UNHANDLED_REJECTION', () => {
const { UNHANDLED_REJECTION } = Process;
UNHANDLED_REJECTION.should.eql('unhandledRejection');
});
it('correctly defines WARNING', () => {
const { WARNING } = Process;
WARNING.should.eql('warning');
});
});
describe('Metric', () => {
const { Metric } = Enum;
it('correctly defines MEMORY', () => {
const { MEMORY } = Metric;
MEMORY.should.eql('memory');
});
it('correctly defines CPU', () => {
const { CPU } = Metric;
CPU.should.eql('cpu');
});
it('correctly defines UPTIME', () => {
const { UPTIME } = Metric;
UPTIME.should.eql('uptime');
});
});
});
<file_sep>'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var lodash = require('lodash'),
requestPromise = require('request-promise'),
_require = require('./helper'),
formatPayload = _require.formatPayload,
_require2 = require('./resource/helper'),
getEidFromRequestPath = _require2.getEidFromRequestPath,
parseResponse = _require2.parseResponse;
/**
* Retrty a failed request.
*
* @return {Promise}
*/
function retryRequest(request, failed, cid) {
var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var uri = failed.path.split('polyseer/v1/')[1];
return request({
method: failed.method,
uri: uri,
body: payload
}).then(function (response) {
return parseResponse(response, cid);
});
}
/**
* Creates the missing environment.
*
* @param {request}
* @return {Promise}
*/
function upsertEnvironment(request, name) {
return request.post({
uri: '/environments',
body: formatPayload({
name: name,
description: 'Environment created by agent upsert.'
})
});
}
/**
* Determine if a request was rejected due to a missing
* environment.
*
* @param {request}
* @return {Promise}
*/
function rejectedDueToMissingEnvironment(error) {
if (error.name !== 'StatusCodeError') {
return false;
}
if (error.statusCode !== 404) {
return false;
}
if (!lodash.has(error.error, 'errors') || !lodash.isArray(error.error.errors)) {
return false;
}
return lodash.some(error.error.errors, function (err) {
return err.status === 404 && err.detail.indexOf('Could not find') !== -1 && err.detail.indexOf('environment') !== -1;
});
}
/**
* Used to curry client options along to middleware.
*
* @param {function}
* @param {object}
* @return {function}
*/
function forwardCurry() {
var params = Array.prototype.slice.call(arguments),
func = params.shift();
return function () {
return func.apply(undefined, Array.prototype.slice.call(arguments).concat(_toConsumableArray(params)));
};
}
/**
* Called before a request is made.
*
* @param {object}
* @param {number}
* @return {object}
*/
function preRequest(options, cid) {
if ('body' in options) {
options.body = formatPayload(options.body);
}
return options;
}
/**
* Called after a request is made.
*
* @param {object}
* @param {number}
* @return {Mixed}
*/
function postRequest(response, cid) {
return parseResponse(response, cid);
}
/**
* Called after a request is rejected.
*
* @param {object}
* @param {number}
* @return {Mixed}
*/
function postReject(error, cid, request) {
var copts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
// if we have an error with a response that is not nil.
if (lodash.has(error, 'response') && !lodash.isNil(error.response)) {
if (copts.upsert_env) {
var _ret = function () {
var originalPayload = {};
if (error.response.request.body) {
originalPayload = JSON.parse(error.response.request.body); // becomes undefined (tick issue)
}
var isMissingEnvironment = rejectedDueToMissingEnvironment(error);
if (isMissingEnvironment) {
var _ret2 = function () {
var failedRequest = error.response.req,
name = getEidFromRequestPath(failedRequest.path);
return {
v: {
v: upsertEnvironment(request, name).then(function (_) {
return retryRequest(request, failedRequest, cid, originalPayload);
})
}
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
}
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
}
return global.Promise.reject(error);
}
module.exports = {
forwardCurry: forwardCurry,
preRequest: preRequest,
postRequest: postRequest,
postReject: postReject
};<file_sep>'use strict';
/**
* Find a collection of a resource type.
*
* @param {object}
* @param {object}
* @param {object}
* @return {Promise}
*/
function find(query, options) {
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
query = query || {};
return context.request.get({
uri: context.uri,
qs: query
});
}
module.exports = find;<file_sep>'use strict';
const should = require('should'),
co = require('co'),
behavior = require('./shared_behavior'),
{ DEFAULT_TIMEOUT } = require('./config'),
{ setup,
teardown,
getUniqueName } = require('./helper');
describe('Environment', function () {
this.timeout(DEFAULT_TIMEOUT);
before(function () {
return setup(this).
then(_ => {
this.Resource = this.client.Environment;
});
});
after(function () { teardown(this); });
beforeEach(function () {
this.attributes = {
name: getUniqueName()
};
});
behavior.creatable();
behavior.findable();
behavior.updatable();
behavior.removable();
behavior.messageable();
});
<file_sep>'use strict';
if (!('ROOT_KEY' in process.env)) {
throw new Error(`Validation tests require a ROOT_KEY environment variable be defined.`);
}
module.exports = {
ROOT_KEY: process.env.ROOT_KEY,
DEFAULT_TIMEOUT: 10000 // 10 seconds
};
<file_sep>'use strict';
const should = require('should'),
{ getClient } = require('./helper');
describe('Client API is being defined correctly', () => {
const Client = getClient(),
polyseerio = require('../../');
describe('client', () => {
it('exports Color', () => {
Client.should.have.property('Color');
});
it('exports Icon', () => {
Client.should.have.property('Icon');
});
it('exports Strategy', () => {
Client.should.have.property('Strategy');
});
it('exports Determiner', () => {
Client.should.have.property('Determiner');
});
it('exports Direction', () => {
Client.should.have.property('Direction');
});
it('exports Subtype', () => {
Client.should.have.property('Subtype');
});
it('exports Protocol', () => {
Client.should.have.property('Protocol');
});
});
describe('polyseerio', () => {
it('exports a start convenience method', () => {
polyseerio.should.have.property('start');
});
it('exports Color', () => {
polyseerio.should.have.property('Color');
});
it('exports Icon', () => {
polyseerio.should.have.property('Icon');
});
it('exports Strategy', () => {
polyseerio.should.have.property('Strategy');
});
it('exports Determiner', () => {
polyseerio.should.have.property('Determiner');
});
it('exports Direction', () => {
polyseerio.should.have.property('Direction');
});
it('exports Subtype', () => {
polyseerio.should.have.property('Subtype');
});
it('exports Protocol', () => {
polyseerio.should.have.property('Protocol');
});
});
describe('Alert', () => {
it('has the correct API', () => {
const { Alert } = Client;
(Alert !== undefined).should.eql(true);
Alert.should.have.property('create');
Alert.should.have.property('find');
Alert.should.have.property('findById');
Alert.should.have.property('findByName');
Alert.should.have.property('remove');
Alert.should.have.property('trigger');
Alert.should.have.property('update');
(function () {
new Alert();
}).should.not.throw();
const instance = new Alert();
instance.should.have.property('get');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
instance.should.have.property('trigger');
});
});
describe('Channel', () => {
it('has the correct API', () => {
const { Channel } = Client;
(Channel !== undefined).should.eql(true);
Channel.should.have.property('create');
Channel.should.have.property('find');
Channel.should.have.property('findById');
Channel.should.have.property('findByName');
Channel.should.have.property('remove');
Channel.should.have.property('update');
Channel.should.have.property('message');
(function () {
new Channel();
}).should.not.throw();
const instance = new Channel();
instance.should.have.property('get');
instance.should.have.property('message');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
describe('Environment', () => {
it('has the correct API', () => {
const { Environment } = Client;
(Environment !== undefined).should.eql(true);
Environment.should.have.property('create');
Environment.should.have.property('find');
Environment.should.have.property('findById');
Environment.should.have.property('findByName');
Environment.should.have.property('remove');
Environment.should.have.property('message');
Environment.should.have.property('update');
(function () {
new Environment();
}).should.not.throw();
const instance = new Environment();
instance.should.have.property('get');
instance.should.have.property('message');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
describe('Event', () => {
it('has the correct API', () => {
const { Event } = Client;
(Event !== undefined).should.eql(true);
Event.should.have.property('create');
Event.should.have.property('find');
Event.should.have.property('findById');
(function () {
new Event();
}).should.not.throw();
const instance = new Event();
instance.should.have.property('get');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
});
});
describe('Expectation', () => {
it('has the correct API', () => {
const { Expectation } = Client;
(Expectation !== undefined).should.eql(true);
Expectation.should.have.property('create');
Expectation.should.have.property('find');
Expectation.should.have.property('findById');
Expectation.should.have.property('findByName');
Expectation.should.have.property('remove');
Expectation.should.have.property('update');
Expectation.should.have.property('check');
(function () {
new Expectation();
}).should.not.throw();
const instance = new Expectation();
instance.should.have.property('check');
instance.should.have.property('get');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
describe('Instance', () => {
it('has the correct API', () => {
const { Instance } = Client;
(Instance !== undefined).should.eql(true);
Instance.should.have.property('attach');
Instance.should.have.property('create');
Instance.should.have.property('find');
Instance.should.have.property('findById');
Instance.should.have.property('findByName');
Instance.should.have.property('remove');
Instance.should.have.property('update');
(function () {
new Instance();
}).should.not.throw();
const instance = new Instance();
instance.should.have.property('addFact');
instance.should.have.property('addGauge');
instance.should.have.property('attach');
instance.should.have.property('fact');
instance.should.have.property('gauge');
instance.should.have.property('get');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
describe('LogicBlock', () => {
it('has the correct API', () => {
const { LogicBlock } = Client;
(LogicBlock !== undefined).should.eql(true);
LogicBlock.should.have.property('create');
LogicBlock.should.have.property('execute');
LogicBlock.should.have.property('find');
LogicBlock.should.have.property('findById');
LogicBlock.should.have.property('findByName');
LogicBlock.should.have.property('remove');
LogicBlock.should.have.property('update');
(function () {
new LogicBlock();
}).should.not.throw();
const instance = new LogicBlock();
instance.should.have.property('execute');
instance.should.have.property('get');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
describe('Member', () => {
it('has the correct API', () => {
const { Member } = Client;
(Member !== undefined).should.eql(true);
Member.should.have.property('create');
Member.should.have.property('find');
Member.should.have.property('findById');
Member.should.have.property('remove');
Member.should.have.property('update');
(function () {
new Member();
}).should.not.throw();
const instance = new Member();
instance.should.have.property('get');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
describe('Settings', () => {
it('has the correct API', () => {
const { Settings } = Client;
(Settings !== undefined).should.eql(true);
Settings.should.have.property('retrieve');
Settings.should.have.property('update');
//Settings.should.have.property('toJSON'); // TODO: add toJSON to singleton / static
// Settings is a singleton
(function () {
new Settings();
}).should.throw();
});
});
describe('Task', () => {
it('has the correct API', () => {
const { Task } = Client;
(Task !== undefined).should.eql(true);
Task.should.have.property('create');
Task.should.have.property('find');
Task.should.have.property('findById');
Task.should.have.property('remove');
Task.should.have.property('update');
(function () {
new Task();
}).should.not.throw();
const instance = new Task();
instance.should.have.property('get');
instance.should.have.property('remove');
instance.should.have.property('save');
instance.should.have.property('set');
instance.should.have.property('setProperties');
instance.should.have.property('toJSON');
});
});
});
<file_sep>'use strict';
var lodash = require('lodash');
/**
* Attach facts as part of the instance monitoring.
*
* @param {Resource}
* @param {key}
* @param {value}
* @return {Promise}
*/
function addFact(instance, key, value) {
if (!lodash.has(instance, '_heartbeatFacts')) {
instance._heartbeatFacts = new Map();
}
if (arguments.length === 3 && lodash.isString('key')) {
instance._heartbeatFacts.set(key, value);
}
if (lodash.isPlainObject(key)) {
lodash.forEach(key, function (innerValue, innerKey) {
instance._heartbeatFacts.set(innerKey, innerValue);
});
}
// TODO: should reject if invalid arguments or maybe throw TypeError?
return global.Promise.resolve();
}
module.exports = addFact;<file_sep>'use strict';
const lodash = require('lodash');
/**
* Add a gauge to the instance that will be sent with each heartbeat.
*
* @param {Resource}
* @param {string}
* @param {function}
* @return {Promise}
*/
function addGauge (instance, key, resolver) {
if (!lodash.has(instance, '_heartbeatGauges')) {
instance._heartbeatGauges = new Map();
}
instance._heartbeatGauges.set(key, resolver);
return global.Promise.resolve();
}
module.exports = addGauge;
<file_sep>'use strict';
const should = require('should');
describe('Constant', () => {
const Constant = require('../../lib/constant');
it('correctly defines ACCESS_TOKEN_HEADER ', () => {
const { ACCESS_TOKEN_HEADER } = Constant;
ACCESS_TOKEN_HEADER.should.eql('X-AUTH-HEADER');
});
it('correctly defines DEFAULT_API_BASE_URL ', () => {
const { DEFAULT_API_BASE_URL } = Constant;
DEFAULT_API_BASE_URL.should.eql('api.polyseer.io/polyseer');
});
it('correctly defines DEFAULT_API_PROTOCOL ', () => {
const { DEFAULT_API_PROTOCOL } = Constant;
DEFAULT_API_PROTOCOL.should.eql('https://');
});
it('correctly defines DEFAULT_API_VERSION ', () => {
const { DEFAULT_API_VERSION } = Constant;
DEFAULT_API_VERSION.should.eql('v1');
});
it('correctly defines DEFAULT_ENV ', () => {
const { DEFAULT_ENV } = Constant;
DEFAULT_ENV.should.eql('NODE_ENV');
});
it('correctly defines DEFAULT_ENVIRONMENT ', () => {
const { DEFAULT_ENVIRONMENT } = Constant;
DEFAULT_ENVIRONMENT.should.eql('development');
});
it('correctly defines DEFAULT_HEARTBEAT_DELAY ', () => {
const { DEFAULT_HEARTBEAT_DELAY } = Constant;
DEFAULT_HEARTBEAT_DELAY.should.eql(30000);
});
it('correctly defines DEFAULT_LOG_LEVEL ', () => {
const { DEFAULT_LOG_LEVEL } = Constant;
DEFAULT_LOG_LEVEL.should.eql('error');
});
it('correctly defines DEFAULT_TIMEOUT ', () => {
const { DEFAULT_TIMEOUT } = Constant;
DEFAULT_TIMEOUT.should.eql(10000);
});
it('correctly defines DEFAULT_TOKEN_ENV ', () => {
const { DEFAULT_TOKEN_ENV } = Constant;
DEFAULT_TOKEN_ENV.should.eql('POLYSEERIO_TOKEN');
});
});
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon');
describe('set', () => {
const method = require('../../../../lib/sdk/method/setProperties');
function createInstance () {
return {
foo: 'window',
alpha: 'beta',
ping: 'dork',
set: sinon.spy()
};
}
it('updates the attribute', () => {
const instance = createInstance();
method(instance, {
foo: 'bar',
ping: 'pong'
});
instance.set.calledWithExactly('foo', 'bar').should.eql(true);
instance.set.calledWithExactly('ping', 'pong').should.eql(true);
instance.set.callCount.should.eql(2);
});
it('returns the instance', () => {
const instance = createInstance();
const result = method(instance, {});
result.should.equal(instance);
});
});
<file_sep>'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var fs = require('fs'),
path = require('path'),
lodash = require('lodash'),
inflection = require('inflection'),
_require = require('./constant'),
DEFAULT_ENVIRONMENT = _require.DEFAULT_ENVIRONMENT;
var DEFAULT_LOOP_PROMISE_OPTIONS = {
delay: 1000
};
/**
* Converts a resource (URL section) to resource type.
*
* @param {string}
* @return {string}
*/
function resourceToType(resource) {
return inflection.singularize(resource);
}
/**
* Used in instance methods to forward context to function as the
* first argument.
*
* @param {function}
* @return {function}
*/
function forwardThis(func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
/*jshint validthis:true */
return func.apply(undefined, [this].concat(args));
};
}
/**
* Clear a promise loop.
*
* @param {number}
*/
function clearLoop(loopId) {
if (!lodash.isNumber(loopId)) {
throw new Error('clearLoop expects a number to be passed, got: ' + loopId + '.');
}
var loop = loopPromise.map.get(loopId);
if (loop.tid) {
clearTimeout(loop.tid);
}
return global.Promise.resolve();
}
/**
* Used for each loop created by the loopPromise.
*/
var LoopObject = function LoopObject(id) {
_classCallCheck(this, LoopObject);
this.id = id;
this.clear = false;
this.loop = null;
this.resolve = null;
this.reject = null;
};
/**
* Loop a promise returning function.
*
* @param {promise}
* @return {number}
*/
function loopPromise(promise) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
options = Object.assign({}, DEFAULT_LOOP_PROMISE_OPTIONS, options);
var _options = options,
delay = _options.delay;
loopPromise._id = loopPromise._id++ || 0;
var loopObject = new LoopObject(loopPromise._id);
loopPromise.map.set(loopObject.id, loopObject);
/**
* Returns a delayed promise if the the delay has not yet been met.
*
* @param {number}
* @param {number}
* @param {Mixed}
*/
function delayLoop(start, delay, result) {
var remaining = delay - (Date.now() - start),
amount = remaining > 0 ? remaining : 0;
return delayPromise(amount, loopObject, result);
}
/**
* Takes a start time and a delay amount, returns a higher order
* function that will pass the result of a promise through but first
* delay the resolution by the remaining delay if it exists.
*
* @param {number}
* @param {number}
*/
function delayIdentity(start, delay) {
return function (result) {
return delayLoop(start, delay, result);
};
}
function loop(local) {
var start = Date.now();
return promise().then(delayIdentity(start, delay)).catch(delayIdentity(start, delay)).then(function (result) {
if (loopObject.clear) {
loopPromise.map.delete(loopObject.id);
return global.Promise.reject();
}
return result;
}).then(loop);
}
loop(promise);
return loopObject.id;
}
loopPromise.map = new Map();
/**
* Delay a promise by some amount.
*
* @param {number}
* @param {Mixed}
* @return {function}
*/
function delayPromise(amount, loopObject, result) {
return new global.Promise(function (resolve, reject) {
loopObject.tid = setTimeout(function (_) {
return resolve(result);
}, amount);
loopObject.resolve = resolve;
loopObject.reject = reject;
});
}
/**
* Returns default options given defaults and passed options.
*
* @param {object}
* @param {object}
* @return {object}
*/
function createOptions(options) {
var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return Object.assign({}, defaults, options);
}
/**
* Forward object based arguments with an override.
*
* @param {request} options
* @param {string} resource type
* @param {object} query params
*/
function forward(args, adjustments) {
return lodash.zipWith(args, adjustments, function (left, right) {
return Object.assign({}, left, right);
});
}
// Default options for the wrapRequest middleware parameter.
var DEFAULT_WRAP_REQUEST_MIDDLEWARE = {
pre: lodash.identity,
post: lodash.identity,
reject: function reject(error) {
return global.Promise.reject(error);
}
};
/**
* Wrap a request instance with some option middleware.
*
* @param {request}
* @param {function}
* @param {function}
* @return {object}
*/
function wrapRequest(request, middleware) {
middleware = lodash.defaults(middleware, DEFAULT_WRAP_REQUEST_MIDDLEWARE);
var _middleware = middleware,
pre = _middleware.pre,
post = _middleware.post,
reject = _middleware.reject;
var wrapper = function wrapper(options) {
return request(pre(options)).then(post, reject);
};
['del', 'delete', 'get', 'patch', 'post', 'put'].forEach(function (method) {
wrapper[method] = function (options) {
return request[method](pre(options)).then(post, reject);
};
});
return wrapper;
}
/**
* Requires an entire directory.
*
* @param {string}
* @param {function}
* @param {function}
* @return {object}
*/
function requireDirectory(directory, predicate, iteratee) {
var requireObjects = _getRequireObjects.apply(undefined, arguments);
return _requireRequireObjects(requireObjects);
}
/**
* Given an array of export objects, a reduced object is returned.
*
* @param {array[object]}
* @return {object}
*/
function _requireRequireObjects(requireObjects) {
return requireObjects.reduce(function (result, requireObject) {
result[requireObject.name] = require(requireObject.require);
return result;
}, {});
}
/**
* Creates a loadable directory object given a predicate and iteratee.
*
* @param {string}
* @param {function}
* @param {function}
* @return {object}
*/
function _getRequireObjects(directory, predicate, iteratee) {
return fs.readdirSync(directory).reduce(function (result, file) {
var pathObject = path.parse(file);
if (predicate(pathObject)) {
result.push(iteratee(pathObject));
}
return result;
}, []);
}
/**
* Format a payload before sending.
*
* @param {object}
* @return {object}
*/
function formatPayload(payload) {
return {
data: {
attributes: Object.assign({}, payload)
}
};
}
/**
* Remap an object based on a path mapping.
*
* TODO: name rekey see if there is a single liner lodash
*
* @param {object} the object to remap paths for
* @param {object} the mapping of current paths
* @return {object} the remapped object
*/
function remapObjectPaths(object) {
var paths = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return lodash.reduce(object, function (result, value, key) {
if (!(key in paths)) {
result[key] = value;
} else {
result[paths[key]] = value;
}
return result;
}, {});
}
/**
* Create an environment mapping.
*
* @param {string} the environment variable that holds the current environment
* @param {object} the environments that should be defined
* @param {object} current process.env variables
* @return {object} map
* @return {object} map.current
* @return {object} map.environments
* @throws {Error} when no environment key exists
*/
function _createEnvironmentMap(key, environments, env) {
if (lodash.has(env, key)) {
var current = env[key];
return { current: current, environments: Object.assign({}, environments) };
} else {
throw new Error('Could not create an environment map, no environment variable named: ' + key + ' could be found.');
}
}
/**
* Will attempt to resolve the API token.
*
* Returns undefined if one cannot be resolved.
*
* @param {string} token as passed by client constructor
* @param {object} where to look in the environment for a token
* @return {string|undefined}
*/
function resolveToken(options) {
if (!lodash.isNil(options.token)) {
return options.token;
}
if (lodash.has(process.env, options.token_env)) {
var value = lodash.get(process.env, options.token_env);
if (!lodash.isNil(value)) {
return value;
}
}
return null;
}
/**
* Attempt to resolve the current environment EID from the
* options.
*
* @param {object}
* @return {object}
*/
function resolveEid(options) {
if ('environment' in options && !lodash.isNil(options.environment)) {
return options.environment;
}
if (options.deduce) {
var env = options.env;
if (env in process.env) {
return process.env[env];
}
}
return DEFAULT_ENVIRONMENT;
}
/**
* Given an environment map, the current environment will be returned.
*
* @param {string} the environment variable that holds the current environment
* @param {object} the environments that should be defined
* @param {object} current process.env variables
* @return {string} the current environment id
*/
function deduceEid(key, environments, env) {
var map = _createEnvironmentMap(key, environments, env);
if (lodash.has(map.environments, map.current)) {
return map.environments[map.current];
} else {
throw new Error('Could not find the current environment: ' + map.current + ' in the environments passed.');
}
}
module.exports = {
clearLoop: clearLoop,
createOptions: createOptions,
deduceEid: deduceEid,
formatPayload: formatPayload,
forward: forward,
forwardThis: forwardThis,
loopPromise: loopPromise,
remapObjectPaths: remapObjectPaths,
requireDirectory: requireDirectory,
resolveEid: resolveEid,
resolveToken: resolveToken,
resourceToType: resourceToType,
wrapRequest: wrapRequest
};<file_sep>BUILD_ENV?=development
BABEL?=./node_modules/.bin/babel
NVM?=~/.nvm/nvm.sh
SUPPORTED?=\
v7.0.0 \
v6.0.0 \
v5.0.0 \
v4.0.0
FULL_SUPPORTED?=\
v7.3.0 \
v7.2.1 \
v7.2.0 \
v7.1.0 \
v7.0.0 \
v6.9.2 \
v6.9.1 \
v6.9.0 \
v6.8.1 \
v6.8.0 \
v6.7.0 \
v6.6.0 \
v6.5.0 \
v6.4.0 \
v6.3.1 \
v6.3.0 \
v6.2.2 \
v6.2.1 \
v6.2.0 \
v6.1.0 \
v6.0.0 \
v5.12.0 \
v5.11.1 \
v5.11.0 \
v5.10.1 \
v5.10.0 \
v5.9.1 \
v5.9.0 \
v5.8.0 \
v5.7.1 \
v5.7.0 \
v5.6.0 \
v5.5.0 \
v5.4.1 \
v5.4.0 \
v5.3.0 \
v5.2.0 \
v5.1.1 \
v5.1.0 \
v5.0.0 \
v4.7.0 \
v4.6.2 \
v4.6.1 \
v4.6.0 \
v4.5.0 \
v4.4.7 \
v4.4.6 \
v4.4.5 \
v4.4.4 \
v4.4.3 \
v4.4.2 \
v4.4.1 \
v4.4.0 \
v4.3.2 \
v4.3.1 \
v4.3.0 \
v4.2.6 \
v4.2.5 \
v4.2.4 \
v4.2.3 \
v4.2.2 \
v4.2.1 \
v4.2.0 \
v4.1.2 \
v4.1.1 \
v4.1.0 \
v4.0.0 \
all: install test
compile-lib:
$(BABEL) ./src -d ./lib --copy-files
compile-test:
$(BABEL) ./test -d ./test-dist --copy-files
compile: compile-lib compile-test
install:
npm install
# install supported versions
version-install:
for i in $(SUPPORTED) ; do \
source $(NVM);\
nvm install $$i;\
done
lint:
ifeq ($(BUILD_ENV),ci)
grunt jshint:file
else
grunt jshint:stdout
endif
raw-unit-test:
ifeq ($(BUILD_ENV),ci)
grunt mochaTest:unit_file
else
grunt mochaTest:unit_stdout
endif
unit-test: compile raw-unit-test
raw-integration-test:
ifeq ($(BUILD_ENV),ci)
grunt mochaTest:integration_file
else
grunt mochaTest:integration_stdout
endif
integration-test: compile raw-integration-test
raw-validation-test:
ifeq ($(BUILD_ENV),ci)
grunt mochaTest:validation_file
else
grunt mochaTest:validation_stdout
endif
validation-test: compile raw-validation-test
# test package against all supported versions (when they are installed)
version-test: version-install
for i in $(FULL_SUPPORTED) ; do \
source $(NVM);\
if nvm which $$i ; then \
nvm use $$i;\
$(MAKE) unit-test;\
$(MAKE) integration-test;\
$(MAKE) validation-test;\
else \
echo "Skipping..." && continue;\
fi \
done
# complete test sequence
test: lint \
compile \
raw-unit-test \
raw-integration-test \
raw-validation-test
.PHONY: compile-lib \
compile-test \
compile \
install \
version-install \
lint \
raw-unit-test \
unit-test \
integration-test \
raw-integration-test \
validation-test \
raw-validation-test \
version-test
<file_sep>'use strict';
var _ClientResourcePaths;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var lodash = require('lodash'),
Enum = require('./enum'),
Client = require('./client'),
requestPromise = require('request-promise'),
_require = require('./enum'),
Resource = _require.Resource,
_require2 = require('./constant'),
ACCESS_TOKEN_HEADER = _require2.ACCESS_TOKEN_HEADER,
DEFAULT_ENV = _require2.DEFAULT_ENV,
DEFAULT_TOKEN_ENV = _require2.DEFAULT_TOKEN_ENV,
DEFAULT_LOG_LEVEL = _require2.DEFAULT_LOG_LEVEL,
DEFAULT_ENVIRONMENT = _require2.DEFAULT_ENVIRONMENT,
DEFAULT_HEARTBEAT_DELAY = _require2.DEFAULT_HEARTBEAT_DELAY,
DEFAULT_API_BASE_URL = _require2.DEFAULT_API_BASE_URL,
DEFAULT_API_VERSION = _require2.DEFAULT_API_VERSION,
DEFAULT_TIMEOUT = _require2.DEFAULT_TIMEOUT,
_require3 = require('./url_builder'),
getBaseUrl = _require3.getBaseUrl,
_require4 = require('./middleware'),
preRequest = _require4.preRequest,
postRequest = _require4.postRequest,
postReject = _require4.postReject,
forwardCurry = _require4.forwardCurry,
_require5 = require('./resource/helper'),
createResource = _require5.createResource,
_require6 = require('./helper'),
resolveEid = _require6.resolveEid,
resolveToken = _require6.resolveToken,
createOptions = _require6.createOptions,
remapObjectPaths = _require6.remapObjectPaths,
wrapRequest = _require6.wrapRequest;
/**
* Resources that are required by the client API.
*/
var RequiredResources = [Resource.ALERT, Resource.CHANNEL, Resource.ENVIRONMENT, Resource.EVENT, Resource.EXPECTATION, Resource.INSTANCE, Resource.LOGIC_BLOCK, Resource.MEMBER, Resource.SETTING, Resource.TASK];
/**
* Client Resource path names.
*/
var ClientResourcePaths = (_ClientResourcePaths = {}, _defineProperty(_ClientResourcePaths, Resource.ALERT, 'Alert'), _defineProperty(_ClientResourcePaths, Resource.CHANNEL, 'Channel'), _defineProperty(_ClientResourcePaths, Resource.ENVIRONMENT, 'Environment'), _defineProperty(_ClientResourcePaths, Resource.EVENT, 'Event'), _defineProperty(_ClientResourcePaths, Resource.EXPECTATION, 'Expectation'), _defineProperty(_ClientResourcePaths, Resource.INSTANCE, 'Instance'), _defineProperty(_ClientResourcePaths, Resource.LOGIC_BLOCK, 'LogicBlock'), _defineProperty(_ClientResourcePaths, Resource.MEMBER, 'Member'), _defineProperty(_ClientResourcePaths, Resource.SETTING, 'Settings'), _defineProperty(_ClientResourcePaths, Resource.TASK, 'Task'), _ClientResourcePaths);
/**
* Default factory options.
*/
var DEFAULT_OPTIONS = {
agent: {},
deduce: true,
env: DEFAULT_ENV,
environment: null, // this value is resolved, default null is correct
heartbeat_delay: DEFAULT_HEARTBEAT_DELAY, // implement this?
log_level: DEFAULT_LOG_LEVEL, // need to implement this with logger
timeout: DEFAULT_TIMEOUT,
token: null,
token_env: DEFAULT_TOKEN_ENV,
upsert_env: true,
version: DEFAULT_API_VERSION
};
/**
* Shorthand for creating a client and starting the agent.
*
* @param {...}
* @return {Promise}
*/
function start() {
var client = factory.apply(undefined, arguments);
return client.startAgent();
}
/**
* Constructrs a polyseer.io client.
*
* @param {object} construction options
* @return {Promise}
*/
function factory(options) {
options = createOptions(options, DEFAULT_OPTIONS);
options.environment = resolveEid(options);
options.token = resolveToken(options);
if (lodash.isNull(options.token)) {
throw new TypeError('Could not find an access token. None was passed and none could be found in the environment variable: ' + options.token_env + '.');
}
var baseUrl = getBaseUrl(undefined, undefined, options.version),
headers = _defineProperty({}, ACCESS_TOKEN_HEADER, options.token);
var request = requestPromise.defaults({
headers: headers,
baseUrl: baseUrl,
json: true,
resolveWithFullResponse: true,
timeout: options.timeout
});
var pre = forwardCurry(preRequest, factory._callCount),
post = forwardCurry(postRequest, factory._callCount),
reject = forwardCurry(postReject, factory._callCount, request, options);
request = wrapRequest(request, { pre: pre, post: post, reject: reject });
var Resources = RequiredResources.reduce(function (result, resource) {
result[resource] = createResource(resource, request, options, factory._callCount);
return result;
}, {});
var resources = remapObjectPaths(Resources, ClientResourcePaths),
clientOptions = { request: request, resources: resources },
client = new Client(factory._callCount, clientOptions);
factory._callCount++; // for memoize in resource factory calls
return client;
}
// call count is used to memoize resource factory calls
factory._callCount = 0;
Object.assign(factory, {
ClientResourcePaths: ClientResourcePaths,
RequiredResources: RequiredResources,
start: start
});
Object.assign(factory, Enum);
module.exports = factory;<file_sep>'use strict';
var _module$exports;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _require = require('../enum'),
Metric = _require.Metric;
/**
* Resolves the processes current memory.
*
* @param {process}
* @return {function}
*/
function resolveMemory(proc) {
return function () {
return proc.memoryUsage().rss;
};
}
/**
* Resolves the current user cpu usage.
*
* @param {process}
* @return {function}
*/
function resolveCpuUser(proc) {
return function () {
return proc.cpuUsage().user;
};
}
/**
* Resolves the current system cpu usage.
*
* @param {process}
* @return {function}
*/
function resolveCpuSystem(proc) {
return function () {
return proc.cpuUsage().system;
};
}
/**
* Resolves uptime.
*
* @param {process}
* @return {function}
*/
function resolveUptime(proc) {
return function () {
return proc.uptime();
};
}
module.exports = (_module$exports = {}, _defineProperty(_module$exports, Metric.MEMORY, function (_config, client) {
client.instance.addGauge('memory', resolveMemory(process));
}), _defineProperty(_module$exports, Metric.CPU, function (_config, client) {
client.instance.addGauge('cpu_user', resolveCpuUser(process));
client.instance.addGauge('cpu_system', resolveCpuSystem(process));
}), _defineProperty(_module$exports, Metric.UPTIME, function (_config, client) {
client.instance.addGauge('uptime', resolveUptime(process));
}), _module$exports);<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon'),
helper = require('../../helper');
describe('Process handler', () => {
const Handler = require('../../../../lib/agent/handler/process');
describe('SIGTERM', () => {
const { SIGTERM } = Handler;
it('sends the correct event', () => {
const client = {
Event: {
create: sinon.stub()
},
instance: helper.createInstance(),
Color: {
GREEN: 'green'
},
Icon: {
CHAIN: 'chain'
}
};
//instance.get.withArgs('name').returns('foo');
//client.Event.create.withArgs({
//name: 'foo agent has started.',
//color: 'green',
//icon: 'chain'
//}).returns(global.Promise.resolve('result_double'));
//
//return SIGTERM({}, client).should.be.fulfilled().
//then(result => {
//result.should.eql('result_double');
//});
});
});
});
<file_sep>'use strict';
const should = require('should'),
sinon = require('sinon');
describe('save', () => {
const { createRequestMock } = require('../../helper');
const save = require('../../../../lib/sdk/method/save');
it('makes the correct api call to create when instance is new', () => {
const instance = {
id: null,
resource: 'events',
_request: createRequestMock(),
eid: 'waterworld',
setProperties: sinon.stub(),
isNew () {
return true;
},
toJSON: sinon.stub()
},
resultDouble = sinon.stub();
instance.toJSON.returns({ ding: 'dong' });
instance._request.post.returns(global.Promise.resolve(resultDouble));
return save(instance).should.be.fulfilled().
then(_ => {
instance._request.post.calledWithExactly({
uri: '/environments/waterworld/events',
body: {
ding: 'dong'
}
}).should.eql(true);
});
});
});
<file_sep>'use strict';
const lodash = require('lodash'),
{ DEFAULT_ENVIRONMENT } = require('../constant'),
{ createOptions } = require('../helper'),
{ parseResponse } = require('../resource/helper'),
{ getResourcePath } = require('../url_builder');
/**
* TODO: unit-test
*/
function instanceToContext (instance) {
const uri = getResourcePath(instance.resource, {
eid: instance.eid, id: instance.get('id')
});
return {
environment: instance.eid,
request: instance._request,
uri
};
}
/**
* Removes non callable items from a map.
*
* @param {Map}
* @return {Map}
*/
function removeNonResolvingValues (map) {
const newMap = new Map();
map.forEach((value, key, map) => {
if (lodash.isFunction(value)) {
newMap.set(key, value);
}
});
return newMap;
}
/**
* Reduce options passed to method with client options and
* method defaults.
*
* @param {object} options passed by client to SDK method
* @param {object} options passed by client to SDK client
* @param {object} default options for SDK method
* @return {object}
*/
function reduceOptions (options, clientOptions, defaults = {}) {
return Object.assign({}, defaults, clientOptions, options);
}
module.exports = {
getResourcePath,
removeNonResolvingValues,
createOptions,
instanceToContext,
reduceOptions
};
<file_sep>'use strict';
var lodash = require('lodash'),
logger = require('../../logger'),
_require = require('../../constant'),
DEFAULT_HEARTBEAT_DELAY = _require.DEFAULT_HEARTBEAT_DELAY,
_require2 = require('../../helper'),
formatPayload = _require2.formatPayload,
loopPromise = _require2.loopPromise,
_require3 = require('../helper'),
removeNonResolvingValues = _require3.removeNonResolvingValues,
getResourcePath = _require3.getResourcePath;
/**
* Resolves facts in a map.
*
* @param {Map}
*/
function resolveFacts(facts) {
var result = {};
facts.forEach(function (resolver, key) {
var value = null;
if (lodash.isFunction(resolver)) {
value = resolver();
} else {
value = resolver;
}
result[key] = value;
});
return result;
}
/**
* Resolves gauges in a map.
*
* @param {Map}
*/
function resolveGauges(gauges) {
var result = {};
gauges.forEach(function (resolver, key) {
result[key] = resolver();
});
return result;
}
/**
* Default attach options.
*/
var DEFAULT_OPTIONS = {
delay: DEFAULT_HEARTBEAT_DELAY
};
/**
* Start a heartbeat for an instance.
*
* @param {instance}
* @param {object}
* @return {Promise}
*/
function attach(instance, options) {
options = lodash.defaults(DEFAULT_OPTIONS, options);
var uri = getResourcePath(instance.resource, { eid: instance.eid, id: instance.get('id') });
var loop = function loop() {
logger.log('debug', 'Heartbeat.');
var body = {};
if (lodash.has(instance, '_heartbeatGauges')) {
body.metrics = {};
body.metrics.gauges = resolveGauges(instance._heartbeatGauges);
instance._gaugeFacts = removeNonResolvingValues(instance._heartbeatGauges);
}
if (lodash.has(instance, '_heartbeatFacts')) {
body.facts = resolveFacts(instance._heartbeatFacts);
instance._heartbeatFacts = removeNonResolvingValues(instance._heartbeatFacts);
}
return instance._request.post({
uri: uri + '/heartbeat',
body: body
});
};
var loopId = loopPromise(loop, { delay: options.delay });
instance._loopId = loopId;
return global.Promise.resolve(loopId);
}
module.exports = attach;<file_sep>'use strict';
/**
* Retreive a singleton resource.
*
* @param {object}
* @param {object}
* @return {Promise}
*/
function retreive (options, context = {}) {
return context.request.get({ uri: context.uri });
}
module.exports = retreive;
<file_sep>0.0.0 / 2016-00-00
==================
* pending initial release
<file_sep>'use strict';
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var Logic = require('../logic.json'),
_require = require('../enum'),
Expectation = _require.Expectation;
module.exports = _defineProperty({}, Expectation.IS_ALIVE, function (_config, client) {
return client.Expectation.create({
name: client.instance.get('name') + ' instance is alive.',
description: 'Agent created expectation.',
is_on: true,
determiner: client.Determiner.ONE,
subject: client.Type.INSTANCE,
subjects: [client.instance.get('id')],
is_expected: true,
logic: Logic[Expectation.IS_ALIVE]
});
});<file_sep>'use strict';
const should = require('should');
describe('UrlBuilder', () => {
const UrlBuilder = require('../../lib/url_builder');
describe('RoutableResource', () => {
const { RoutableResources } = UrlBuilder;
it('includes the correct routable resources', () => {
RoutableResources.should.containDeep([
'alerts',
'environment-messages',
'events',
'expectations',
'instances',
'tasks'
]);
});
});
describe('getResourcePath', () => {
const { getResourcePath } = UrlBuilder;
describe('options', () => {
it('correctly appends an id if passed', () => {
const result = getResourcePath('events', {
eid: 'zoo',
id: 'foo'
});
result.should.eql('/environments/zoo/events/foo');
});
it('will not append an id if id is nil (null / undefined)', () => {
const result = getResourcePath('events', {
eid: 'zoo',
id: null
});
result.should.eql('/environments/zoo/events');
});
});
describe('non routable resources', () => {
it('correctly handles environments', () => {
const result = getResourcePath('environments');
result.should.eql('/environments');
});
it('correctly handles logic-blocks', () => {
const result = getResourcePath('logic-blocks');
result.should.eql('/logic-blocks');
});
});
describe('routable resources', () => {
it('throws when a routable resource passed without an eid', () => {
(function () {
getResourcePath('events', {foo: 'bar'});
}).should.throw('Cannot get routable resource path for events, without passing an eid to the options.');
});
it('correctly handles environment-messages', () => {
const result = getResourcePath('environment-messages', {eid: 'foo'});
result.should.eql('/environments/foo/messages');
});
it('correctly handles events', () => {
const result = getResourcePath('events', {eid: 'foo'});
result.should.eql('/environments/foo/events');
});
it('correctly handles instances', () => {
const result = getResourcePath('instances', {eid: 'foo'});
result.should.eql('/environments/foo/instances');
});
});
});
describe('getBaseUrl', () => {
const { getBaseUrl } = UrlBuilder;
it('returns the correctly formatted url', () => {
const base = 'api.foo/bar',
protocol = 'https://',
version = 'v3';
const result = getBaseUrl(base, protocol, version);
result.should.eql('https://api.foo/bar/v3');
});
it('defaults the base correctly', () => {
const protocol = 'ws://',
version = 'v3';
const result = getBaseUrl(undefined, protocol, version);
result.should.eql('ws://api.polyseer.io/polyseer/v3');
});
it('defaults the protocol correctly', () => {
const base = 'api.foo/bar',
version = 'v3';
const result = getBaseUrl(base, undefined, version);
result.should.eql('https://api.foo/bar/v3');
});
it('defaults the version correctly', () => {
const base = 'api.foo/bar',
protocol = 'https://';
const result = getBaseUrl(base, protocol);
result.should.eql('https://api.foo/bar/v1');
});
});
});
<file_sep>'use strict';
const messageStatic = require('../static/message');
/**
* Create a message instance method for a resource.
*
* @param {Resource}
* @param {...}
* @return {Promise}
*/
function message (instance, ...args) {
return messageStatic(instance.id, ...args);
}
module.exports = message;
<file_sep>'use strict';
var _fact, _metric, _event, _process;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var Handler = require('./enum'),
_require = require('../enum'),
Strategy = _require.Strategy,
Direction = _require.Direction,
Subtype = _require.Subtype;
module.exports = {
attach: true,
attach_strategy: Strategy.FALLBACK,
id: null,
name: null,
description: 'Created by the Polyseer.io Node.JS agent.',
group: 'agent',
direction: Direction.INBOUND,
subtype: Subtype.LONG_RUNNING,
agent_retry: 60000, // 1 minute
// disabled until better discovery pattern
expectation: _defineProperty({}, Handler.Expectation.IS_ALIVE, false),
fact: (_fact = {}, _defineProperty(_fact, Handler.Fact.ARCHITECTURE, true), _defineProperty(_fact, Handler.Fact.CPU_COUNT, true), _defineProperty(_fact, Handler.Fact.ENDIANNESS, true), _defineProperty(_fact, Handler.Fact.FREE_MEMORY, true), _defineProperty(_fact, Handler.Fact.GID, true), _defineProperty(_fact, Handler.Fact.HOME_DIRECTORY, true), _defineProperty(_fact, Handler.Fact.HOSTNAME, true), _defineProperty(_fact, Handler.Fact.LAUNCH_ARGUMENTS, true), _defineProperty(_fact, Handler.Fact.NODE_VERSION, true), _defineProperty(_fact, Handler.Fact.PID, true), _defineProperty(_fact, Handler.Fact.PLATFORM, true), _defineProperty(_fact, Handler.Fact.TITLE, true), _defineProperty(_fact, Handler.Fact.UID, true), _defineProperty(_fact, Handler.Fact.UPTIME, true), _defineProperty(_fact, Handler.Fact.V8_VERSION, true), _fact),
metric: (_metric = {}, _defineProperty(_metric, Handler.Metric.MEMORY, true), _defineProperty(_metric, Handler.Metric.CPU, true), _defineProperty(_metric, Handler.Metric.UPTIME, true), _metric),
event: (_event = {}, _defineProperty(_event, Handler.Event.START, true), _defineProperty(_event, Handler.Event.STOP, true), _event),
process: (_process = {}, _defineProperty(_process, Handler.Process.EXIT, true), _defineProperty(_process, Handler.Process.WARNING, true), _defineProperty(_process, Handler.Process.UNCAUGHT_EXCEPTION, true), _defineProperty(_process, Handler.Process.UNHANDLED_REJECTION, true), _defineProperty(_process, Handler.Process.SIGHUP, true), _defineProperty(_process, Handler.Process.SIGINT, true), _defineProperty(_process, Handler.Process.SIGTERM, true), _process)
}; | 47b2a32699db3bd45d7a78c372fa8dc0ebb42157 | [
"Markdown",
"JavaScript",
"Makefile"
] | 121 | Markdown | kgnzt/polyseerio-nodejs | 0ad21e8f7ce7fec431b2c8e809511636a88d000d | 9a0d5569d6de4edc888e0d10a5602b1249f85ce8 |
refs/heads/master | <repo_name>ShoufuDu/my_python<file_sep>/mytool.py
import argparse
import getopt
import os
import re
import shutil
import subprocess
import sys
import time
const_short_opt="hps:d:"
const_long_opt=["help","pid","src=","dst="]
# arguments for all process procedure
process_pid=False
process_src=None
process_dst=None
class Args:
def __init__(self):
self.process_pid=False
self.process_src=None
self.process_dst=None
self.process_wd=False
def showUsage():
print ("-h|--help for help")
print ("-p|--pid")
print ("-s src -d dst")
print ("exp: -p -s c:\\src -d d:\\")
return 0
def parseCmd(opts):
args = Args()
for o,p in opts:
if o in('-h','--help'):
showUsage()
return 0
# parse process pid arguments
if o in('-p','--pid'):
args.pid=True
if o in('-wd','--wizardswand'):
args.process_wd=True
if o in('-s','--src'):
if args.pid or args.process_wd:
args.src=p
if o in('-d','--dst'):
if args.pid or args.process_wd:
args.dst=p
# parse new process arguments...
return args
def walkDir(top,**args):
for root,dirs,files in os.walk(top,True):
# exclude dirs
# dirs[:] = [os.path.join(root, d) for d in dirs]
if 'excludes' in args:
dirs[:] = [d for d in dirs if not re.endswith(tuple(args['excludes']))]
# exclude/include files
# files = [os.path.join(root, f) for f in files]
if 'excludes' in args:
files = [f for f in files if not f.endswith(tuple(args['excludes']))]
if 'includes' in args:
files = [f for f in files if f.endswith(tuple(args['includes']))]
for fname in files:
args['hook_f'](root,fname,args['hook_f_arg'])
# print(fname)
#--------------------------------------------------------------------------------------
# name : process_pid_hook
# func: process pid
# root : the root dir of source file to be processed
# file : the source file to be processed
# arg : additional arguments needed
#--------------------------------------------------------------------------------------
def process_pid_hook(root,file,arg):
(fn,ext) = os.path.splitext(file)
new_name = fn+'_bk'+ext
old_path = os.path.join(root,file)
new_path= os.path.join(arg,new_name)
if not os.path.exists(arg):
os.mkdir(arg)
shutil.copy(old_path,new_path)
return 0
def process_pid_proc(src,dst):
args={'hook_f':process_pid_hook,
'hook_f_arg':"./a12"}
walkDir(src,**args)
return 0
#--------------------------------------------------------------------------------------
# name : # add new process ...
# func: process pid
# root : the root dir of source file to be processed
# file : the source file to be processed
# arg : additional arguments needed
#--------------------------------------------------------------------------------------
def process_wd_hook(root,file,arg):
winegPath = os.path.join(root,"GameCompiler.exe")
inputFile = os.path.join(root,file)
cmdline = winegPath,inputFile
subprocess.call(cmdline,shell=True)
outfile = os.path.join(root,"GameDef.dat.enc")
# time.sleep(1)
try:
if not os.path.exists(outfile):
exit(1)
varation = re.sub(r"WW_(V\d+).agm",r"\1",file)
outDir = os.path.join(arg,varation)
if not os.path.exists(outDir):
os.mkdir(outDir)
# #copy GameDef.dat.enc
dstFile = os.path.join(outDir,"GameDef.dat.enc")
shutil.copy(outfile,dstFile)
os.remove(outfile)
#copy agm files
shutil.copy(inputFile,os.path.join(outDir,file))
except IOError as e:
print(e)
return 0
def process_wd_proc(src,dst):
args={'includes':['.agm'],'hook_f':process_wd_hook,'hook_f_arg':dst}
walkDir(src,**args)
return 0
def processMain(args):
# process pid
if args.pid:
return process_pid_proc(args.src,
args.dst)
# add new process ...
if args.wizardswand:
return process_wd_proc(args.src,args.dst)
#--------------------------------------------------------------------------------------
# main
#--------------------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="mypython tool for game")
# group = parser.add_mutually_exclusive_group()
parser.add_argument("-p","--pid", help="process pid",action="store_true")
parser.add_argument("-s",'--src',help="source path")
parser.add_argument("-d",'--dst',help="destination path")
parser.add_argument("-wd","--wizardswand", help="process wizardswand agm files",action="store_true")
args = parser.parse_args()
processMain(args)
if __name__ == "__main__":
main()
def example_xopy():
Dest = "/a1"
rules = re.compile("/a")
for root,dirs,files in os.walk(top,True):
newTop = rules.sub(Dest,root)
if not os.path.exists(newTop):
os.mkdir(newTop)
for d in dirs:
print(os.path.join(root,d))
d = os.path.join(newTop,d)
if not os.path.exists(d):
os.mkdir(d)
for f in files:
(fn,ext) = os.path.splitext(f)
old_path = os.path.join(root,f)
new_name = fn+'_bk'+ext
new_path= os.path.join(newTop,new_name)
try:
shutil.copy(old_path,new_path)
except IOError as e:
print(e)
return 1
<file_sep>/wd.py
import os
import re
import shutil
import subprocess
import sys
inc_file='.agm'
g_dst='C:\\mywork\\tasks\\NSW\\EntityGames\\maths'
g_src='C:\\mywork\\tasks\\NSW\\EntityGames\\Win'
def walkDir(top):
global inc_file
global g_dst
for root,dirs,files in os.walk(top,True):
files = [f for f in files if f.endswith(inc_file)]
for fname in files:
process_wd(root,fname,g_dst)
def process_wd(root,file,arg):
winegPath = os.path.join(root,"GameCompiler.exe")
inputFile = os.path.join(root,file)
cmdline = winegPath,inputFile
subprocess.call(cmdline,shell=True)
outfile = os.path.join(root,"GameDef.dat.enc")
try:
if not os.path.exists(outfile):
exit(1)
varation = re.sub(r"WW_(V\d+).agm",r"\1",file)
outDir = os.path.join(arg,varation)
if not os.path.exists(outDir):
os.mkdir(outDir)
# #copy GameDef.dat.enc
dstFile = os.path.join(outDir,"GameDef.dat.enc")
shutil.copy(outfile,dstFile)
os.remove(outfile)
#copy agm files
shutil.copy(inputFile,os.path.join(outDir,file))
except IOError as e:
print(e)
return 0
walkDir(g_src) | 79b86b14a26ca9917845738af1da0dd91ecf063a | [
"Python"
] | 2 | Python | ShoufuDu/my_python | bdd54b73e90fb1360b997a6b32adae56b8644177 | cf1d65ca640bca65c9be9c5ddaf599e95e673c7e |
refs/heads/master | <file_sep># Baboule
Just a mother repository
<file_sep>package baboule;
import static org.mockito.Matchers.anyInt;
import baboule.Bonus;
import baboule.Table;
import com.diffblue.deeptestutils.Reflector;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.InvocationTargetException;
import java.util.Random;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*"})
public class BonusTest {
@Rule public final Timeout globalTimeout = new Timeout(10000);
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid11() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(1).thenReturn(3).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNotNullOutputVoid() throws Exception {
// Arrange
final Table table = new Table();
Reflector.setField(table, "nulbonul", 0);
table.bonuss = null;
table.joueurY = 0;
table.perdu = false;
table.kelbonus = null;
table.highscore = 0;
table.joueurX = 0;
table.score = 0;
table.mechants = null;
table.level = 0;
table.sc0re = 0;
Reflector.setField(table, "label", null);
table.nivo = 0;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(0).thenReturn(0).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNotNullOutputVoid3() throws Exception {
// Arrange
final Table table = new Table();
Reflector.setField(table, "nulbonul", 0);
table.bonuss = null;
table.joueurY = 0;
table.perdu = false;
table.kelbonus = null;
table.highscore = 0;
table.joueurX = 0;
table.score = 0;
table.mechants = null;
table.level = 0;
table.sc0re = 0;
Reflector.setField(table, "label", null);
table.nivo = 0;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(182).thenReturn(4).thenReturn(1);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(180, actual.direction);
Assert.assertEquals(1, actual.X);
Assert.assertEquals(4, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNotNullOutputVoid4() throws Exception {
// Arrange
final Table table = new Table();
Reflector.setField(table, "nulbonul", 0);
table.bonuss = null;
table.joueurY = 0;
table.perdu = false;
table.kelbonus = null;
table.highscore = 0;
table.joueurX = 0;
table.score = 0;
table.mechants = null;
table.level = 0;
table.sc0re = 0;
Reflector.setField(table, "label", null);
table.nivo = 0;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(176).thenReturn(3).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(270, actual.direction);
Assert.assertEquals(480, actual.X);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNotNullOutputVoid5() throws Exception {
// Arrange
final Table table = new Table();
Reflector.setField(table, "nulbonul", 0);
table.bonuss = null;
table.joueurY = 0;
table.perdu = false;
table.kelbonus = null;
table.highscore = 0;
table.joueurX = 0;
table.score = 0;
table.mechants = null;
table.level = 0;
table.sc0re = 0;
Reflector.setField(table, "label", null);
table.nivo = 0;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(352).thenReturn(3).thenReturn(225);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(225, actual.X);
Assert.assertEquals(480, actual.Y);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid1() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(0).thenReturn(0).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid2() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(0).thenReturn(4).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(4, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid3() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(182).thenReturn(4).thenReturn(1);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(180, actual.direction);
Assert.assertEquals(1, actual.X);
Assert.assertEquals(4, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid4() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(176).thenReturn(3).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(270, actual.direction);
Assert.assertEquals(480, actual.X);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid5() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(320).thenReturn(3).thenReturn(128);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(128, actual.X);
Assert.assertEquals(480, actual.Y);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid6() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(0).thenReturn(5).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid7() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(90).thenReturn(5).thenReturn(4);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(270, actual.direction);
Assert.assertEquals(480, actual.X);
Assert.assertEquals(4, actual.Y);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid8() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(180).thenReturn(5).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(180, actual.direction);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid9() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(270).thenReturn(5).thenReturn(5);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(5, actual.X);
Assert.assertEquals(480, actual.Y);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid10() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(1).thenReturn(0).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNotNullOutputVoid2() throws Exception {
// Arrange
final Table table = new Table();
Reflector.setField(table, "nulbonul", 0);
table.bonuss = null;
table.joueurY = 0;
table.perdu = false;
table.kelbonus = null;
table.highscore = 0;
table.joueurX = 0;
table.score = 0;
table.mechants = null;
table.level = 0;
table.sc0re = 0;
Reflector.setField(table, "label", null);
table.nivo = 0;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(0).thenReturn(4).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(90, actual.direction);
Assert.assertEquals(4, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid12() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(90).thenReturn(3).thenReturn(1);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(270, actual.direction);
Assert.assertEquals(480, actual.X);
Assert.assertEquals(1, actual.Y);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid13() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(218).thenReturn(3).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(180, actual.direction);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid14() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(353).thenReturn(3).thenReturn(1);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(1, actual.X);
Assert.assertEquals(480, actual.Y);
Assert.assertEquals(3, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid15() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(299).thenReturn(4).thenReturn(5);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(5, actual.X);
Assert.assertEquals(480, actual.Y);
Assert.assertEquals(4, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid16() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(265).thenReturn(5).thenReturn(5);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(180, actual.direction);
Assert.assertEquals(5, actual.X);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid17() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(128).thenReturn(5).thenReturn(5);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(270, actual.direction);
Assert.assertEquals(480, actual.X);
Assert.assertEquals(5, actual.Y);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid18() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(328).thenReturn(4).thenReturn(1);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(1, actual.X);
Assert.assertEquals(480, actual.Y);
Assert.assertEquals(4, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid19() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(264).thenReturn(5).thenReturn(1);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(180, actual.direction);
Assert.assertEquals(1, actual.X);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@PrepareForTest({Random.class, Bonus.class})
@Test
public void constructorInputNullOutputVoid20() throws Exception {
// Arrange
final Table table = null;
final Random random = PowerMockito.mock(Random.class);
PowerMockito.when(random.nextInt(anyInt())).thenReturn(128).thenReturn(5).thenReturn(0);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
// Act, creating object to test constructor
final Bonus actual = new Bonus(table);
// Assert side effects
Assert.assertEquals(270, actual.direction);
Assert.assertEquals(480, actual.X);
Assert.assertEquals(5, actual.vitesse);
}
// Test written by Diffblue Cover.
@Test
public void deplacementOutputVoid() throws InvocationTargetException {
// Arrange
final Bonus bonus = (Bonus)Reflector.getInstance("baboule.Bonus");
bonus.direction = 0;
bonus.X = 0;
bonus.Y = 0;
bonus.vitesse = 0;
// Act
bonus.deplacement();
// The method returns void, testing that no exception is thrown
}
// Test written by Diffblue Cover.
@Test
public void deplacementOutputVoid1() throws InvocationTargetException {
// Arrange
final Bonus bonus = (Bonus)Reflector.getInstance("baboule.Bonus");
bonus.direction = 32;
bonus.X = 0;
bonus.Y = 0;
bonus.vitesse = 0;
// Act
bonus.deplacement();
// The method returns void, testing that no exception is thrown
}
// Test written by Diffblue Cover.
@Test
public void deplacementOutputVoid2() throws InvocationTargetException {
// Arrange
final Bonus bonus = (Bonus)Reflector.getInstance("baboule.Bonus");
bonus.direction = 90;
bonus.X = 0;
bonus.Y = 0;
bonus.vitesse = 0;
// Act
bonus.deplacement();
// The method returns void, testing that no exception is thrown
}
// Test written by Diffblue Cover.
@Test
public void deplacementOutputVoid3() throws InvocationTargetException {
// Arrange
final Bonus bonus = (Bonus)Reflector.getInstance("baboule.Bonus");
bonus.direction = 270;
bonus.X = 0;
bonus.Y = 0;
bonus.vitesse = 0;
// Act
bonus.deplacement();
// The method returns void, testing that no exception is thrown
}
// Test written by Diffblue Cover.
@Test
public void deplacementOutputVoid4() throws InvocationTargetException {
// Arrange
final Bonus bonus = (Bonus)Reflector.getInstance("baboule.Bonus");
bonus.direction = 180;
bonus.X = 0;
bonus.Y = 0;
bonus.vitesse = 0;
// Act
bonus.deplacement();
// The method returns void, testing that no exception is thrown
}
}
<file_sep>package baboule;
import java.util.Random;
public class Bonus {
int vitesse = 1;
int Y = 1;
int X = 1;
int direction = 0;
public void deplacement() {
if (direction == 0) {
Y = Y - vitesse;
} else if (direction == 90) {
X = X + vitesse;
} else if (direction == 180) {
Y = Y + vitesse;
} else if (direction == 270) {
X = X - vitesse;
}
}
Bonus(Table table) {
Random rand = new Random();
direction = rand.nextInt(360);
vitesse = rand.nextInt(7);
if (vitesse < 3) {
vitesse = 5;
}
if (direction < 90 && direction >= 0) {
direction = 90;
Y = rand.nextInt(480);
X = 0;
} else if (direction < 180 && direction >= 90) {
direction = 270;
Y = rand.nextInt(480);
X = 480;
} else if (direction < 270 && direction >= 180) {
direction = 180;
X = rand.nextInt(480);
Y = 0;
} else if (direction < 360 && direction >= 270) {
direction = 0;
X = rand.nextInt(480);
Y = 480;
}
}
}<file_sep>package baboule;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
* Cette classe dessine la table de ping-pong, la balle et les raquettes et
* affiche le score
*/
public class Table extends JPanel implements ConstantesDuJeu {
private JLabel label;
public int joueurX = 0;
public int joueurY = 0;
public boolean perdu = false;
public int score = 0;
public int sc0re = 0;
public int nivo = 0;
public int highscore = 0;
public String kelbonus = " nope ...";
private int nulbonul = 0;
public int level = 0;
ArrayList<Mechant> mechants = new ArrayList<Mechant>();
ArrayList<Bonus> bonuss = new ArrayList<Bonus>();
// Constructeur. key listener
Table() {
Principale moteurJeu = new Principale(this);
// mouse motion
addMouseMotionListener(moteurJeu);
// key
addKeyListener(moteurJeu);
repaint();
}
public void restart() {
if (highscore < sc0re) {
highscore = sc0re;
}
label.setText("High score : " + highscore);
score = 0;
sc0re = 0;
nulbonul = 0;
kelbonus = " nope ...";
perdu = false;
bonuss.clear();
}
public void paintComponent(Graphics contexteGraphique) {
super.paintComponent(contexteGraphique);
// Dessine la table verte
if (perdu == false) {
if (nivo == 0) {
contexteGraphique.setColor(Color.GREEN);
level = 1;
} else if (nivo == 1) {
contexteGraphique.setColor(Color.CYAN);
level = 2;
} else if (nivo == 2) {
contexteGraphique.setColor(Color.ORANGE);
level = 3;
} else if (nivo == 3) {
contexteGraphique.setColor(Color.LIGHT_GRAY);
level = 4;
} else if (nivo == 4) {
contexteGraphique.setColor(Color.GRAY);
level = 5;
} else if (nivo == 5) {
contexteGraphique.setColor(Color.DARK_GRAY);
level = 6;
} else if (nivo > 5) {
contexteGraphique.setColor(Color.BLACK);
level = 7;
}
} else {
contexteGraphique.setColor(Color.WHITE);
}
contexteGraphique.fillRect(0, 0, LARGEUR_TABLE, HAUTEUR_TABLE);
contexteGraphique.setColor(Color.YELLOW);
contexteGraphique.fillOval(joueurX, joueurY, 20, 20);
boolean isLost = false;
for (Mechant mechant : mechants) {
contexteGraphique.setColor(Color.RED);
contexteGraphique.fillOval(mechant.X, mechant.Y, 20, 20);
if (mechant.X > joueurX - 15 && mechant.X < joueurX + 20
&& mechant.Y > joueurY - 15 && mechant.Y < joueurY + 20) {
isLost = true;
}
mechant.deplacement();
}
boolean isBonus = false;
for (Bonus bonus : bonuss) {
contexteGraphique.setColor(Color.BLUE);
contexteGraphique.fillOval(bonus.X, bonus.Y, 20, 20);
if (bonus.X > joueurX - 15 && bonus.X < joueurX + 20
&& bonus.Y > joueurY - 15 && bonus.Y < joueurY + 20) {
isBonus = true;
}
bonus.deplacement();
}
if (isLost) {
perdu();
}
if (isBonus) {
bonus();
}
requestFocus();
}
private void perdu() {
perdu = true;
nulbonul = 0;
label.setText("High score : " + highscore + " Score : "
+ sc0re + " press enter to restart");
mechants.clear();
bonuss.clear();
// System.out.println("perdu, score: " + score);
// System.exit(0);
}
private void bonus() {
int bon = 0;
Random rando = new Random();
bon = rando.nextInt(7);
if (bon == 0 || bon == 1 || bon == 2) {
kelbonus = " Cleared!! ";
mechants.clear();
} else if (bon == 3 || bon == 4) {
kelbonus = " + 100 !!";
sc0re = sc0re + 100;
} else if (bon == 5) {
kelbonus = " + 200 !!";
sc0re = sc0re + 200;
} else if (bon == 6) {
kelbonus = " +1 each ! !";
nulbonul++;
} else if (bon == 7) {
kelbonus = " bonus x 2 ! !";
nulbonul = (nulbonul + 1) * 2;
}
label.setText("High score : " + highscore + " Score : "
+ sc0re + " Bonus -> " + kelbonus
+ " level : " + level);
bonuss.clear();
}
public void creerMechant() {
mechants.add(new Mechant(this));
score++;
label.setText("High score : " + highscore + " Score : "
+ sc0re + " level : " + level
+ " Bonus : " + kelbonus);
nivo = score / 25;
sc0re = sc0re + nivo + 1 + nulbonul;
}
public void creerBonus() {
bonuss.add(new Bonus(this));
}
// Affecte le texte du message du jeu
public void affecterTexteMessage(String texte) {
label.setText(texte);
repaint();
}
void ajouteAuCadre(Container conteneur) {
conteneur.setLayout(new BoxLayout(conteneur, BoxLayout.Y_AXIS));
conteneur.add(this);
label = new JLabel("");
label.setText("High score : " + highscore);
label.setForeground(Color.BLUE);
conteneur.add(label);
conteneur.setBackground(Color.YELLOW);
}
public static void main(String[] args) {
try {
// Crée une instance du cadre
JFrame monCadre = new JFrame("Baboule");
// Permet la fermeture de la fenêtre par clic sur la
// petite croix dans le coin.
monCadre.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Table table = new Table();
table.ajouteAuCadre(monCadre.getContentPane());
// Affecte sa taille au cadre et le rend visible.
monCadre.setBounds(0, 0, LARGEUR_TABLE + 0, HAUTEUR_TABLE + 33);
monCadre.setVisible(true);
monCadre.setResizable(false);
} catch (Exception e) {
}
}
} | 7224be79471a5ea5223a590f1b341697f8a4f777 | [
"Markdown",
"Java"
] | 4 | Markdown | Ichkamo/Baboule | c9533365f46cb6872cb243be9b614328fbd7cb29 | e7017e80f12de069c7ac46fa8f82d77db308b270 |
refs/heads/master | <repo_name>mandykoh/webscrubble<file_sep>/version.go
package webscrubble
//go:generate go run vendor/github.com/mandykoh/go-bump/main.go webscrubble
const VersionMajor = "0"
const VersionMinor = "0"
const VersionRevision = "2"
const Version = "0.0.2"
<file_sep>/api/version.go
package api
import (
"encoding/json"
"net/http"
"github.com/mandykoh/scrubble"
"github.com/mandykoh/webscrubble"
)
func (e Endpoints) Version(w http.ResponseWriter, r *http.Request) {
info := struct {
Version string `json:"version"`
EngineVersion string `json:"engineVersion"`
}{
webscrubble.Version,
scrubble.Version,
}
versionJson, _ := json.Marshal(&info)
w.Header().Set("content-type", "application/json")
w.Write(versionJson)
}
<file_sep>/api/endpoints.go
package api
type Endpoints struct {
}
<file_sep>/cmd/server/main.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/go-chi/chi"
"github.com/mandykoh/webscrubble"
"github.com/mandykoh/webscrubble/api"
)
func main() {
const FrontendRoot = "frontend"
const DefaultHTTPPort = 8080
const DefaultHTTPSPort = 8443
const TLSCertFile = "cert.pem"
const TLSPrivateKeyFile = "privkey.pem"
log.Printf("Webscrubble Server %s", webscrubble.Version)
useTLS := true
if _, err := os.Stat(TLSCertFile); err != nil {
useTLS = false
log.Printf("Couldn't find %s", TLSCertFile)
}
if _, err := os.Stat(TLSPrivateKeyFile); err != nil {
useTLS = false
log.Printf("Couldn't find %s", TLSPrivateKeyFile)
}
port := DefaultHTTPPort
if useTLS {
port = DefaultHTTPSPort
}
if len(os.Args) > 1 {
parsedPort, err := strconv.ParseInt(os.Args[1], 10, 16)
if err != nil {
log.Fatalf("Unable to parse port '%s'", os.Args[1])
os.Exit(1)
}
port = int(parsedPort)
}
endpoints := api.Endpoints{}
fileServer := http.FileServer(http.Dir(FrontendRoot))
router := chi.NewRouter()
router.Get("/api/version", endpoints.Version)
router.Get("/*", fileServer.ServeHTTP)
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1024 * 256,
}
if useTLS {
log.Printf("Starting HTTPS server on port %d", port)
log.Fatal(server.ListenAndServeTLS(TLSCertFile, TLSPrivateKeyFile))
} else {
log.Printf("Starting HTTP server on port %d", port)
log.Fatal(server.ListenAndServe())
}
}
<file_sep>/README.md
# webscrubble
[](https://godoc.org/github.com/mandykoh/webscrubble)
[](https://goreportcard.com/report/github.com/mandykoh/webscrubble)
[](https://travis-ci.org/mandykoh/webscrubble)
`
| cecd67fc0aff9053ccb429f8e31410449cbe431a | [
"Markdown",
"Go"
] | 5 | Go | mandykoh/webscrubble | 1128b610668ea74a820ed25ace63e6313ec6bb65 | 56ccfb9af1f9737edb46d51aaf966acd52809901 |
refs/heads/master | <repo_name>quyetlc2198/ProjectII<file_sep>/example22_1/myshop/orders/migrations/0002_auto_20200417_0848.py
# Generated by Django 3.0.4 on 2020-04-17 01:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='order',
name='total',
field=models.DecimalField(decimal_places=3, default=0, max_digits=10),
preserve_default=False,
),
migrations.AlterField(
model_name='orderitem',
name='quantity',
field=models.PositiveIntegerField(default=0),
),
]
<file_sep>/example22_1/myshop/orders/migrations/0003_auto_20200417_0925.py
# Generated by Django 3.0.4 on 2020-04-17 02:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0002_auto_20200417_0848'),
]
operations = [
migrations.AlterField(
model_name='order',
name='contact',
field=models.CharField(max_length=11),
),
]
<file_sep>/example22_1/myshop/shop/admin.py
from django.contrib import admin
from .models import Category, Product
import decimal
admin.site.site_header = 'Duc Quyet shop'
admin.site.index_title = '<NAME>'
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category,CategoryAdmin)
class ProductAdmin(admin.ModelAdmin):
list_display =['id','name', 'category', 'price','price_sale','available']
search_fields=[ 'name', 'price','category']
list_filter = ['category','price']
list_editable = ['price', 'name']
prepopulated_fields = {'slug': ('name',)}
fields = (('category','name') , 'price' , 'image' , 'description','slug')
list_per_page = 20
actions = ('set_available','set_notavailable','apply_discount1','apply_discount2','apply_default',)
# set còn hàng
def set_available(self, request, queryset):
queryset.update(available = True)
self.message_user(request , 'Thành công')
set_available.short_description = 'Còn hàng'
# set hết hàng
def set_notavailable(self, request, queryset):
queryset.update(available = False)
self.message_user(request , 'Thành công')
set_notavailable.short_description = 'Hết hàng'
# set giảm giá
def apply_discount1(self, request, queryset):
for product in queryset:
product.price_sale = product.price * decimal.Decimal('0.9')
product.save()
apply_discount1.short_description = 'Giảm 10%% '
#
def apply_discount2(self, request, queryset):
for product in queryset:
product.price_sale = product.price * decimal.Decimal('0.8')
product.save()
apply_discount2.short_description = 'Giảm 20%% '
#đưa về giá mặc định
def apply_default(self, request, queryset):
for product in queryset:
product.price_sale = product.price
product.save()
apply_default.short_description = 'Giá mặc định'
admin.site.register(Product,ProductAdmin)<file_sep>/example22/myshop/shop/migrations/0003_product_price_sale.py
# Generated by Django 3.0.4 on 2020-04-20 12:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_auto_20200403_1618'),
]
operations = [
migrations.AddField(
model_name='product',
name='price_sale',
field=models.DecimalField(decimal_places=3, default=1, max_digits=10),
preserve_default=False,
),
]
<file_sep>/example22_1/myshop/orders/migrations/0004_auto_20200417_0929.py
# Generated by Django 3.0.4 on 2020-04-17 02:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0003_auto_20200417_0925'),
]
operations = [
migrations.AlterField(
model_name='order',
name='total',
field=models.DecimalField(decimal_places=3, max_digits=10, null=True),
),
]
<file_sep>/example22_1/myshop/user/migrations/0003_remove_myuser_phone.py
# Generated by Django 3.0.4 on 2020-04-17 02:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('user', '0002_auto_20200416_1659'),
]
operations = [
migrations.RemoveField(
model_name='myuser',
name='phone',
),
]
<file_sep>/example22_1/myshop/shop/migrations/0005_auto_20200420_1916.py
# Generated by Django 3.0.4 on 2020-04-20 12:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_auto_20200420_1909'),
]
operations = [
migrations.AlterField(
model_name='product',
name='price_sale',
field=models.DecimalField(decimal_places=3, max_digits=10),
),
]
<file_sep>/final_1/venv/myshop/orders/admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import Order, OrderItem
from user.models import MyUser
from django.urls import reverse
from django.utils.safestring import mark_safe
class OrderItemInline(admin.TabularInline):
model = OrderItem
list_display = ['name' , 'price', 'quantity']
raw_id_fields = ['product']
def order_detail(obj):
return mark_safe('<a href="{}">View</a>'.format(reverse('orders:admin_order_detail', args=[obj.id])))
def tong(obj):
return Order.get_total_cost(obj);
@admin.register(Order)
class OrderAdmin(ImportExportModelAdmin):
list_display = ['confirm','paid', 'first_name', 'address', 'contact', 'note',tong, 'created',order_detail]
list_filter = [ 'confirm','paid','created']
inlines = [OrderItemInline]
actions = ('set_confirm','set_paid','set_confirm_default','set_paid_default')
def set_confirm(self, request, queryset):
queryset.update(confirm = True)
self.message_user(request , 'Thành công')
set_confirm.short_description = 'Xác nhận'
def set_paid(self, request, queryset):
queryset.update(paid = True)
self.message_user(request , 'Thành công')
set_paid.short_description = 'Thanh toán'
def set_confirm_default(self, request, queryset):
queryset.update(confirm = False)
self.message_user(request , 'Thành công')
set_confirm_default.short_description = 'Chưa xác nhận'
def set_paid_default(self, request, queryset):
queryset.update(paid = False)
self.message_user(request , 'Thành công')
set_paid_default.short_description = 'Chưa thanh toán'
<file_sep>/example22_1/myshop/cart/forms.py
from django import forms
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(0, 20)]
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField( choices=PRODUCT_QUANTITY_CHOICES,coerce=int,initial=1)
update = forms.BooleanField(required=False,initial=False, widget=forms.HiddenInput)
widgets = {
'quantity' : forms.Select(attrs={'class' : 'btn_quantity'},)
}
<file_sep>/final_1/venv/myshop/orders/views.py
from django.shortcuts import render, redirect
from .models import OrderItem , Order
from .forms import OrderCreateForm
from django.contrib.auth import authenticate
from cart.cart import Cart
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
import decimal
def order_create(request):
cart = Cart(request)
if request.user.is_authenticated:
total = cart.get_total_price_user()
else:
total = cart.get_total_price()
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save()
order.total = total
order.save()
for item in cart:
OrderItem.objects.create(order=order,product=item['product'],price=item['price'],quantity=item['quantity'])
total = order.get_total_cost()
cart.clear()
return render(request,'orders/order/created.html',{'order': order})
else:
form = OrderCreateForm()
return render(request,'orders/order/create.html',{'cart': cart, 'form': form})
@staff_member_required
def admin_order_detail(request, order_id):
order = get_object_or_404(Order, id=order_id)
return render(request,'admin/orders/order/detail.html',{'order': order})
<file_sep>/example22_1/myshop/shop/views.py
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator , EmptyPage, PageNotAnInteger
from .models import Category, Product
from cart.forms import CartAddProductForm
from django.views.generic import ListView
def product_list(request, category_slug=None):
category = None
# lấy tất cả các giỏ hàng
categories = Category.objects.all()
#chỉ hiện những product còn hàng
products = Product.objects.filter(available=True)
# nếu truy cập vào từng cate thì lọc ra các sản phẩm của cate đó
if category_slug :
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
# phân trang 12 sản phẩm /1 page
paginator = Paginator(products, 12)
pageNumber = request.GET.get('page')
try:
products = paginator.page(pageNumber)
except PageNotAnInteger:
products = paginator.page(1)
except EmptyPage:
products = paginator.page(paginator.num_pages)
context = {'category': category,
'categories': categories,
'products': products}
return render(request,'shop/product/list.html', context)
def product_detail(request, id, slug):
product = get_object_or_404(Product,id=id,slug=slug,available=True)
cart_product_form = CartAddProductForm()
return render(request,'shop/product/detail.html',{'product': product,'cart_product_form': cart_product_form })
<file_sep>/final_1/venv/myshop/user/views.py
from django.shortcuts import render , redirect ,HttpResponse
from .forms import RegisForm
from django.views.generic import TemplateView
from django.contrib.auth import authenticate, login, logout
from django.views import View
# Create your views here.
def register(request):
if request.method == 'POST':
form = RegisForm(request.POST)
if form.is_valid():
form.save()
return redirect('user:login')
else:
form = RegisForm()
return render (request , 'user/reg_form.html', {'form': form} )
def SiteLogin(request):
if request.method == 'POST':
user_name = request.POST.get('tendangnhap')
mat_khau = request.POST.get('password')
my_user = authenticate(username = user_name , password = <PASSWORD> )
if my_user is None:
return render(request , 'user/login.html')
else:
login(request, my_user)
return redirect('shop:product_list')
else:
return render(request ,'user/login.html')
def Logout(request):
if request.user.is_authenticated:
logout(request)
return redirect('shop:product_list')
else:
return redirect('shop:product_list')
<file_sep>/final_1/venv/myshop/orders/urls.py
from django.urls import path
from . import views
# itemms
app_name = 'orders'
urlpatterns = [
path('create/', views.order_create, name='orders'),
path('admin/order/<int:order_id>/', views.admin_order_detail,name='admin_order_detail'),
]<file_sep>/example22_1/myshop/user/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class MyUser(User):
pass
<file_sep>/final_1/venv/myshop/cart/forms.py
from django import forms
class CartAddProductForm(forms.Form):
quantity = forms.IntegerField()
update = forms.BooleanField(required=False,initial=False, widget=forms.HiddenInput)
<file_sep>/example22_1/myshop/user/migrations/0002_auto_20200416_1659.py
# Generated by Django 3.0.4 on 2020-04-16 09:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('user', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='myuser',
name='date_joined',
),
migrations.RemoveField(
model_name='myuser',
name='email',
),
migrations.RemoveField(
model_name='myuser',
name='first_name',
),
migrations.RemoveField(
model_name='myuser',
name='groups',
),
migrations.RemoveField(
model_name='myuser',
name='id',
),
migrations.RemoveField(
model_name='myuser',
name='is_active',
),
migrations.RemoveField(
model_name='myuser',
name='is_staff',
),
migrations.RemoveField(
model_name='myuser',
name='is_superuser',
),
migrations.RemoveField(
model_name='myuser',
name='last_login',
),
migrations.RemoveField(
model_name='myuser',
name='last_name',
),
migrations.RemoveField(
model_name='myuser',
name='password',
),
migrations.RemoveField(
model_name='myuser',
name='user_permissions',
),
migrations.RemoveField(
model_name='myuser',
name='username',
),
migrations.AddField(
model_name='myuser',
name='user_ptr',
field=models.OneToOneField(auto_created=True, default=1, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
| 59cc6ed0318d0b382dee8631e09ba08501acabfd | [
"Python"
] | 16 | Python | quyetlc2198/ProjectII | 3c730c8f04f011b5931f345f9e51e9a803561a23 | 17a7712e5a727acc192bd5881a020898b7dfb113 |
refs/heads/master | <repo_name>GerardoCano/ventas<file_sep>/module/Cporders/src/Module.php
<?php
namespace Cporders;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\TableGateway\TableGateway;
use Laminas\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
//Se manda a llamar el getConfig() el cual carga el module.config.php
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
//Supplier TableGateway function
Model\SupplierTable::class => function($container) {
$tableGateway = $container->get(Model\SupplierTableGateway::class);
return new Model\SupplierTable($tableGateway);
},
Model\SupplierTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Supplier());
//Aqui debemos de agregar el nombre de la tabla que queremos enlazar
return new TableGateway('suppliers', $dbAdapter, null, $resultSetPrototype);
},
//Customer TableGateway function
Model\CustomerTable::class => function($container) {
$tableGateway = $container->get(Model\CustomerTableGateway::class);
return new Model\CustomerTable($tableGateway);
},
Model\CustomerTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Customer());
//Aqui debemos de agregar el nombre de la tabla que queremos enlazar
return new TableGateway('customers', $dbAdapter, null, $resultSetPrototype);
},
//Product TableGateway function
Model\ProductTable::class => function($container) {
$tableGateway = $container->get(Model\ProductTableGateway::class);
return new Model\ProductTable($tableGateway);
},
Model\ProductTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Product());
//Aqui debemos de agregar el nombre de la tabla que queremos enlazar
return new TableGateway('products', $dbAdapter, null, $resultSetPrototype);
},
//Order TableGateway function
Model\OrderTable::class => function($container) {
$tableGateway = $container->get(Model\OrderTableGateway::class);
return new Model\OrderTable($tableGateway);
},
Model\OrderTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Order());
//Aqui debemos de agregar el nombre de la tabla que queremos enlazar
return new TableGateway('orders', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
//Se crea un factory(fabrica) propio
public function getControllerConfig()
{
return [
'factories' => [
//Supplier Controller function
Controller\SupplierController::class => function($container) {
return new Controller\SupplierController(
$container->get(Model\SupplierTable::class)
);
},
//Customer Controller function
Controller\CustomerController::class => function($container) {
return new Controller\CustomerController(
$container->get(Model\CustomerTable::class)
);
},
//Product Controller function
Controller\ProductController::class => function($container) {
return new Controller\ProductController(
$container->get(Model\ProductTable::class)
);
},
//Order Controller function
Controller\OrderController::class => function($container) {
return new Controller\OrderController(
$container->get(Model\OrderTable::class)
);
},
],
];
}
}<file_sep>/module/Cporders/src/Controller/ProductController.php
<?php
namespace Cporders\Controller;
use Cporders\Form\ProductForm;
use Cporders\Model\Product;
use Cporders\Model\ProductTable;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
class ProductController extends AbstractActionController
{
private $table;
public function __construct(ProductTable $table)
{
$this->table = $table;
}
public function indexAction()
{
return new ViewModel([
'products' => $this->table->fetchAll(),
]);
}
public function addAction()
{
$form = new ProductForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
$product = new Product();
$form->setInputFilter($product->getInputFilter());
$form->setData($request->getPost());
if (! $form->isValid()) {
return ['form' => $form];
}
$product->exchangeArray($form->getData());
$this->table->saveProduct($product);
return $this->redirect()->toRoute('product');
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if ($id === 0) {
return $this->redirect()->toRoute('product', ['action' => 'add']);
}
// recupera el producto con el id proporcionado. Doing so raises
// una excepción si es que el producto no se encuentra, el cual resulta en
// redireccionar al usuario a la lista de productos
try {
$product = $this->table->getProduct($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('product', ['action' => 'index']);
}
$form = new ProductForm();
$form->bind($product);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
$viewData = ['p_id' => $id, 'form' => $form];
if (! $request->isPost()) {
return $viewData;
}
$form->setInputFilter($product->getInputFilter());
$form->setData($request->getPost());
if (! $form->isValid()) {
return $viewData;
}
$this->table->saveProduct($product);
return $this->redirect()->toRoute('product', ['action' => 'index']);
}
public function deleteAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('product');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Yes') {
$id = (int) $request->getPost('p_id');
$this->table->deleteProduct($id);
}
// Redirecciona a la lista de productos
return $this->redirect()->toRoute('product');
}
return [
'p_id' => $id,
'product' => $this->table->getProduct($id),
];
}
}<file_sep>/module/ModulosExtras/Supplier/src/Model/Supplier.php
<?php
namespace Supplier\Model;
use DomainException;
use Laminas\Filter\StringTrim;
use Laminas\Filter\StripTags;
use Laminas\Filter\ToInt;
use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\InputFilterAwareInterface;
use Laminas\InputFilter\InputFilterInterface;
use Laminas\Validator\StringLength;
class Supplier implements InputFilterAwareInterface
{
public $id;
public $name;
public $address_street;
public $address_city;
public $address_country;
public $address_post_code;
public $phone_no;
public $fax_no;
public $payment_terms;
private $inputFilter;
public function exchangeArray(array $data)
{
$this->id = !empty($data['id']) ? $data['id'] : null;
$this->name = !empty($data['name']) ? $data['name'] : null;
$this->address_street = !empty($data['address_street']) ? $data['address_street'] : null;
$this->address_city = !empty($data['address_city']) ? $data['address_city'] : null;
$this->address_country = !empty($data['address_country']) ? $data['address_country'] : null;
$this->address_post_code = !empty($data['address_post_code']) ? $data['address_post_code'] : null;
$this->phone_no = !empty($data['phone_no']) ? $data['phone_no'] : null;
$this->fax_no = !empty($data['fax_no']) ? $data['fax_no'] : null;
$this->payment_terms = !empty($data['payment_terms']) ? $data['payment_terms'] : null;
}
public function getArrayCopy()
{
return [
'id'=> $this->id,
'name' => $this->name,
'address_street' => $this->address_street,
'address_city' => $this->address_city,
'address_country' => $this->address_country,
'address_post_code' => $this->address_post_code,
'phone_no' => $this->phone_no,
'fax_no' => $this->fax_no,
'payment_terms' => $this->payment_terms,
];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new DomainException(sprintf(
'%s does not allow injection of an alternate input filter',
__CLASS__
));
}
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'name',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 100,
],
],
],
]);
$inputFilter->add([
'name' => 'address_street',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'address_city',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'address_country',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'address_post_code',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 5,
'max' => 7,
],
],
],
]);
$inputFilter->add([
'name' => 'phone_no',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 10,
'max' => 16,
],
],
],
]);
$inputFilter->add([
'name' => 'fax_no',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 10,
'max' => 16,
],
],
],
]);
$inputFilter->add([
'name' => 'payment_terms',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
}<file_sep>/module/Album/src/Controller/AlbumController.php
<?php
namespace Album\Controller;
use Album\Model\AlbumTable;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use Album\Form\AlbumForm;
use Album\Model\Album;
class AlbumController extends AbstractActionController
{
private $table;
//Este constructor permite que nuestro controlador dependa de Albumtable
public function __construct(AlbumTable $table)
{
$this->table = $table;
}
//Devuelve una instancia ViewModel con una matriz que contiene los datos de los albumes
public function indexAction()
{
return new ViewModel([
'albums' => $this->table->fetchAll(),
]);
}
public function addAction()
{
//Se crea una instancia AlbumForm y se etiqueta el botón de enviar como un add, esto es para poder reutilizar el formulario
$form = new AlbumForm();
$form->get('submit')->setValue('Add');
//Si la solicitud no es de tipo POST no se van a enviar los datos y se volverá a mostrar el formulario
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
//Se crea una instancia y pasamos los datos del formulario por el filtro
$album = new Album();
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
//Si la validacion falla se volvera a mostrar el formulario con la información de que campos fallaron y por qué
if (! $form->isValid()) {
return ['form' => $form];
}
//Si la informacion enviada es valida se almcenan los datos del formulario en el modelo saveAlbum()
$album->exchangeArray($form->getData());
$this->table->saveAlbum($album);
//Una vez guardados los datos redireccionamos a la lista de albumes
return $this->redirect()->toRoute('album');
}
public function editAction()
{
//Busca el id del album que se desea editar
$id = (int) $this->params()->fromRoute('id', 0);
//Si id es 0 redirigimos a AGREGAR
if (0 === $id) {
return $this->redirect()->toRoute('album', ['action' => 'add']);
}
// Recupera el álbum con el id especificado
// arrojando una excepción si no se encuentra,
// redireccionando a la lista de albumes
try {
$album = $this->table->getAlbum($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
$viewData = ['id' => $id, 'form' => $form];
if (! $request->isPost()) {
return $viewData;
}
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if (! $form->isValid()) {
return $viewData;
}
//Guardar los cambios hecho al album
$this->table->saveAlbum($album);
// Redireccionar a la lista de albumes
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
public function deleteAction()
{
//Obtenemos el id del album que se desea eliminar
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album');
}
//Verificamos que la solicitud sea de tipo POST para determinar si se muestra una confiramción o se elimina el album
$request = $this->getRequest();
if ($request->isPost()) {
//Hacemos la confirmacion, si la respuesta es sí, se elimina, si es no, se cancela el proceso
$del = $request->getPost('del', 'No');
if ($del == 'Si') {
$id = (int) $request->getPost('id');
//Se usa un objeto de la tabla para eliminar la fila con el metodo deleteAlbum()
$this->table->deleteAlbum($id);
}
//Redirecciona a la lista de albumes
return $this->redirect()->toRoute('album');
}
return [
'id' => $id,
'album' => $this->table->getAlbum($id),
];
}
}<file_sep>/module/Cporders/src/Model/Product.php
<?php
namespace Cporders\Model;
use DomainException;
use Laminas\Filter\StringTrim;
use Laminas\Filter\StripTags;
use Laminas\Filter\ToInt;
use Laminas\Filter\ToFloat;
use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\InputFilterAwareInterface;
use Laminas\InputFilter\InputFilterInterface;
use Laminas\Validator\StringLength;
class Product implements InputFilterAwareInterface
{
public $p_id;
public $p_name;
public $in_stock;
public $units_in_stock;
public $unit_purchase_price;
public $unit_sale_price;
public $sp_id;
public $name;
private $inputFilter;
public function exchangeArray(array $data)
{
$this->p_id = !empty($data['p_id']) ? $data['p_id'] : null;
$this->p_name = !empty($data['p_name']) ? $data['p_name'] : null;
$this->in_stock = !empty($data['in_stock']) ? $data['in_stock'] : null;
$this->units_in_stock = !empty($data['units_in_stock']) ? $data['units_in_stock'] : null;
$this->unit_purchase_price = !empty($data['unit_purchase_price']) ? $data['unit_purchase_price'] : null;
$this->unit_sale_price = !empty($data['unit_sale_price']) ? $data['unit_sale_price'] : null;
$this->sp_id = !empty($data['sp_id']) ? $data['sp_id'] : null;
$this->name = !empty($data['name']) ? $data['name'] : null;
}
public function getArrayCopy()
{
return [
'p_id' => $this->p_id,
'p_name' => $this->p_name,
'in_stock' => $this->in_stock,
'units_in_stock' => $this->units_in_stock,
'unit_purchase_price' => $this->unit_purchase_price,
'unit_sale_price' => $this->unit_sale_price,
'sp_id' => $this->sp_id,
];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new DomainException(sprintf(
'%s does not allow injection of an alternate input filter',
__CLASS__
));
}
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'p_id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'p_name',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'in_stock',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 2,
'max' => 3,
],
],
],
]);
$inputFilter->add([
'name' => 'units_in_stock',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'unit_purchase_price',
'required' => true,
'filters' => [
['name' => ToFloat::class],
],
]);
$inputFilter->add([
'name' => 'unit_sale_price',
'required' => true,
'filters' => [
['name' => ToFloat::class],
],
]);
$inputFilter->add([
'name' => 'sp_id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
}<file_sep>/module/ModulosExtras/Customer/src/Module.php
<?php
namespace Customer;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\TableGateway\TableGateway;
use Laminas\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
//Se manda a llamar el getConfig() el cual carga el module.config.php
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
Model\CustomerTable::class => function($container) {
$tableGateway = $container->get(Model\CustomerTableGateway::class);
return new Model\CustomerTable($tableGateway);
},
Model\CustomerTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Customer());
//Aqui debemos de agregar el nombre de la tabla que queremos enlazar
return new TableGateway('customers', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
//Se crea un factory(fabrica) propio
public function getControllerConfig()
{
return [
'factories' => [
Controller\CustomerController::class => function($container) {
return new Controller\CustomerController(
$container->get(Model\CustomerTable::class)
);
},
],
];
}
}<file_sep>/module/Cporders/src/Model/CustomerTable.php
<?php
namespace Cporders\Model;
use RuntimeException;
use Laminas\Db\TableGateway\TableGatewayInterface;
class CustomerTable
{
private $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
return $this->tableGateway->select();
}
public function getCustomer($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(['id' => $id]);
$row = $rowset->current();
if (! $row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
public function saveCustomer(Customer $customer)
{
$data = [
'first_name' => $customer->first_name,
'last_name' => $customer->last_name,
'address_street' => $customer->address_street,
'address_city' => $customer->address_city,
'address_country' => $customer->address_country,
'address_post_code' => $customer->address_post_code,
'contact_phone_no' => $customer->contact_phone_no,
];
$id = (int) $customer->id;
//Se modificó esta condicion para que permita la inserción de los datos
if ($id === 0) {
$this->tableGateway->insert($data);
return;
}
try {
$this->getCustomer($id);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf(
'Cannot update Customer with identifier %d; does not exist',
$id
));
}
$this->tableGateway->update($data, ['id' => $id]);
}
public function deleteCustomer($id)
{
$this->tableGateway->delete(['id' => (int) $id]);
}
}<file_sep>/data/albumData/schemaorder.sql
create table suppliers(
SpID integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
SpName varchar (100) NOT NULL,
SpAddressStreet varchar (150) NOT NULL,
SpAddressCity varchar (150) NOT NULL,
SpAddressCountry varchar (150) NOT NULL,
SpAddressPostCode varchar (7) NOT NULL,
SpPhoneNo varchar (16) NOT NULL,
SpFaxNo varchar (16) NULL,
SpPaymentTerms varchar (150) NOT NULL
);
create table products(
PdID integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
PdName varchar (150) NOT NULL,
PdInStock int (1) NOT NULL,
PdUnitsInStock int (6) NOT NULL,
PdUnitPurchasePrice decimal (8,2) NOT NULL,
PdUnitSalePrice decimal (8,2) NOT NULL,
SpId int NOT NULL,
FOREIGN KEY(SpId) REFERENCES suppliers(SpID) ON DELETE CASCADE ON UPDATE CASCADE
);
create table customers(
CtmID integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
CtmFirstName varchar (100) NOT NULL,
CtmLastName varchar (120) NOT NULL,
CtmAddressStreet varchar (150) NOT NULL,
CtmAddressCity varchar (150) NOT NULL,
CtmAddressCountry varchar (150) NOT NULL,
CtmAddressPostCode varchar (10) NOT NULL,
CtmContactPhoneNo varchar (20) NOT NULL
);
create table orders(
OrID integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
CtmId integer NOT NULL,
OrDateOrderPlaced date NOT NULL,
OrTimeOrderPlaced time NOT NULL,
OrOrderTotalProductNo int (6) NOT NULL,
OrOrderCompleted int (1) NOT NULL,
OrDateOrderCompleted date NOT NULL,
OrAnyAdditionalInfo text NULL,
FOREIGN KEY(CtmId) REFERENCES customers(CtmID) ON DELETE CASCADE ON UPDATE CASCADE
);
create table order_product(
OrOrderId integer NOT NULL,
PdProductId integer NOT NULL,
OPTotalProductSaleCost decimal (9,2) NOT NULL,
OPArrangeDeliveryDate date NOT NULL,
OPArrangeDeliveryTime time NOT NULL,
OPProductDelivery int (1) NOT NULL,
OPActualDeliveryDate date NOT NULL,
OPActualDeliveryTime time NOT NULL,
FOREIGN KEY(OrOrderId) REFERENCES orders(OrID) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY(PdProductId) REFERENCES products(PdID) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO customers VALUES (NULL,'GERARDO','CANO','<NAME>','CHIMALHUACAN','ESTADO DE MÉXICO','56338','5951137059');
INSERT INTO customers VALUES (NULL,'DIANA','<NAME>','<NAME>','NEZAHUALCÓYOTL','ESTADO DE MÉXICO','57000','5531137722');
INSERT INTO customers VALUES (NULL,'JUAN','ALVAREZ','CALLE <NAME>O','ECATEPEC','ESTADO DE MÉXICO','07410','5548986535');
INSERT INTO customers VALUES (NULL,'PEDRO','<NAME>','<NAME>15','IZTACALCO','CDMX','08700','5578471232');
INSERT INTO customers VALUES (NULL,'ALEJANDRO','PAZ','<NAME>','CUAUHTÉMOC','CDMX','06090','5587129654');
INSERT INTO suppliers (SpName,SpAddressStreet,SpAddressCity,SpAddressCountry,SpAddressPostCode,SpPhoneNo,SpFaxNo,SpPaymentTerms) VALUES ('<NAME>', '<NAME>', '<NAME>', 'CDMX', '03020', '5598745632', '5545781245', 'TARJETA DE CREDITO');
INSERT INTO suppliers (SpName,SpAddressStreet,SpAddressCity,SpAddressCountry,SpAddressPostCode,SpPhoneNo,SpFaxNo,SpPaymentTerms) VALUES ('<NAME>', 'ESTUDIO LA NACIONAL 10', 'IZTACALCO', 'CDMX', '08920', '5515226587', NULL, 'EFECTIVO');
INSERT INTO suppliers (SpName,SpAddressStreet,SpAddressCity,SpAddressCountry,SpAddressPostCode,SpPhoneNo,SpFaxNo,SpPaymentTerms) VALUES ('<NAME>', 'CDA ROSALES', 'CHIMALHUACAN', 'ESTADO DE MEXICO', '55330', '5578124563', '5598875421', 'TARJETA DE CREDITO');
INSERT INTO suppliers (SpName,SpAddressStreet,SpAddressCity,SpAddressCountry,SpAddressPostCode,SpPhoneNo,SpFaxNo,SpPaymentTerms) VALUES ('<NAME>', 'MONEDITA DE ORO', 'NEZAHUALCÓYOTL', 'ESTADO DE MÉXICO', '57000', '5512234556', NULL, 'TARJETA DE CREDITO');
INSERT INTO suppliers (SpName,SpAddressStreet,SpAddressCity,SpAddressCountry,SpAddressPostCode,SpPhoneNo,SpFaxNo,SpPaymentTerms) VALUES ('<NAME>', 'TEJOCOTE', 'TEXCOCO', 'ESTADO DE MEXICO', '56199', '5578784545', NULL, 'TARJETA DE CREDITO');
INSERT INTO products VALUES (NULL,'RAM KINGSTON', 1, 500, 700.000, 900.000, 1);
INSERT INTO products VALUES (NULL,'SSD KINGSTON', 1, 600, 1000.000, 1200.000, 2);
INSERT INTO products VALUES (NULL,'HDD WESTERN DIGITAL', 0, 0, 700.000, 1500.000, 3);
INSERT INTO products VALUES (NULL,'MOTHERBOARD AORUS', 1, 100, 2000.000, 2500.000, 4);
INSERT INTO products VALUES (NULL,'PROCESADOR INTEL CORE i9', 1, 50, 7500.000, 9000.000, 5);
INSERT INTO orders VALUES (NULL,1,'2020-08-31','12:30:00',5,1,'2020-09-10', NULL);
INSERT INTO orders VALUES (NULL,2,'2020-08-25','17:30:00',20,0,'0000-00-00', NULL);
INSERT INTO orders VALUES (NULL,5,'2020-09-01','13:30:00',10,0,'0000-00-00', NULL);
INSERT INTO orders VALUES (NULL,3,'2020-09-10','10:20:00',7,1,'2020-09-5', NULL);
INSERT INTO orders VALUES (NULL,4,'2020-07-20','11:40:00',5,1,'2020-09-10', NULL);
INSERT INTO order_product VALUES (1,1, 4500.00, '2020-08-25','17:30:00', 0, '0000-00-00','00:00:00');
INSERT INTO order_product VALUES (2,3, 30000.00, '2020-08-31','12:30:00', 1, '2020-09-01','14:30:00');
INSERT INTO order_product VALUES (3,2, 12000.00, '2020-09-01','13:30:00', 0, '0000-00-00', '00:00:00');
INSERT INTO order_product VALUES (4,4, 17500.00, '2020-09-10','10:20:00', 1, '2020-09-08','18:25:00');
INSERT INTO order_product VALUES (5,5, 45000.00, '2020-07-20','11:40:00', 0, '0000-00-00','00:00:00');<file_sep>/module/Cporders/src/Form/OrderForm.php
<?php
namespace Cporders\Form;
use Laminas\Form\Form;
use Laminas\Form\Element;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\Adapter\Driver\ResultInterface;
class OrderForm extends Form
{
public function __construct($name = null)
{
$adapter = new Adapter([
'driver' => 'Pdo_Sqlite',
'database' => __DIR__ . '/../../../../data/order.db',
]);
$statement = $adapter->createStatement('SELECT id,first_name,last_name FROM customers');
$statement->prepare();
$result = $statement->execute();
$dato = array();
if ($result instanceof ResultInterface && $result->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($result);
foreach ($resultSet as $row) {
$dato += array($row->id => $row->last_name.' '.$row->first_name);
}
}
$names = new Element\Select('ctm_id');
$names->setLabel('Which the customer name');
$names->setEmptyOption('Choose the customer name');
$names->setValueOptions($dato);
$element = new Element\Select('order_completed');
$element->setLabel('¿Order Completed?');
$element->setValueOptions([
'Yes' => 'Yes',
'No' => 'No'
]);
// We will ignore the name provided to the constructor
parent::__construct('order');
$this->add([
'name' => 'o_id',
'type' => 'hidden',
]);
$this->add($names);
$this->add([
'name' => 'date_order_placed',
'type' => 'date',
'options' => [
'label' => 'Date Order Placed',
],
]);
$this->add([
'name' => 'time_order_placed',
'type' => 'text',
'options' => [
'label' => 'Units in stock',
],
]);
$this->add([
'name' => 'total_product_no',
'type' => 'text',
'options' => [
'label' => 'Unit Purchase Price',
],
]);
$this->add($element);
$this->add([
'name' => 'date_order_completed',
'type' => 'date',
'options' => [
'label' => 'Date Order Completed',
],
]);
$this->add([
'name' => 'any_additional_info',
'type' => 'text',
'options' => [
'label' => 'Additional Info',
],
]);
$this->add([
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Submit',
'id' => 'submitbutton',
],
]);
}
}
<file_sep>/data/schema.sql
create table suppliers(
id Integer PRIMARY KEY AUTOINCREMENT,
name varchar (100) NOT NULL,
address_street varchar (150) NOT NULL,
address_city varchar (150) NOT NULL,
address_country varchar (150) NOT NULL,
address_post_code varchar (7) NOT NULL,
phone_no varchar (16) NOT NULL,
fax_no varchar (16) NULL,
payment_terms varchar (150) NOT NULL
);
create table customers(
id Integer PRIMARY KEY AUTOINCREMENT,
first_name varchar (100) NOT NULL,
last_name varchar (120) NOT NULL,
address_street varchar (150) NOT NULL,
address_city varchar (150) NOT NULL,
address_country varchar (150) NOT NULL,
address_post_code varchar (10) NOT NULL,
contact_phone_no varchar (20) NOT NULL
);
create table orders(
o_id Integer PRIMARY KEY AUTOINCREMENT,
ctm_id int NOT NULL,
date_order_placed date NOT NULL,
time_order_placed time NOT NULL,
total_product_no int (6) NOT NULL,
order_completed int (1) NOT NULL,
date_order_completed date NOT NULL,
any_additional_info text NULL,
FOREIGN KEY(ctm_id) REFERENCES customers(id) ON DELETE CASCADE ON UPDATE CASCADE
);
create table products(
p_id Integer PRIMARY KEY AUTOINCREMENT,
p_name varchar (150) NOT NULL,
in_stock varchar (3) NOT NULL,
units_in_stock int (6),
unit_purchase_price double (9,2),
unit_sale_price double (9,2),
sp_id int NOT NULL,
FOREIGN KEY(sp_id) REFERENCES suppliers(id) ON DELETE CASCADE ON UPDATE CASCADE
);
create table orders(
o_id Integer PRIMARY KEY AUTOINCREMENT,
ctm_id int NOT NULL,
date_order_placed date NOT NULL,
time_order_placed time NOT NULL,
total_product_no int (6) NOT NULL,
order_completed varchar (3) (9,2),
date_order_completed date,
any_additional_info text NULL,
FOREIGN KEY(ctm_id) REFERENCES customers(id) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO suppliers (name,address_street,address_city,address_country,address_post_code,phone_no,fax_no,payment_terms) VALUES ('<NAME>', '<NAME>', '<NAME>', 'CDMX', '03020', '5598745632', '5545781245', 'Tarjeta de Credito');
INSERT INTO suppliers (name,address_street,address_city,address_country,address_post_code,phone_no,fax_no,payment_terms) VALUES ('<NAME>', 'Estudio la Nacional 10', 'Iztacalco', 'CDMX', '08920', '5515226587', NULL, 'Efectivo');
INSERT INTO suppliers (name,address_street,address_city,address_country,address_post_code,phone_no,fax_no,payment_terms) VALUES ('<NAME>', 'Cda Rosales', 'Chimalhuacán', 'Estado de México', '55330', '5578124563', '5598875421', 'Tarjeta de Credito');
INSERT INTO suppliers (name,address_street,address_city,address_country,address_post_code,phone_no,fax_no,payment_terms) VALUES ('<NAME>', 'Monedita de Oro', 'Nezahualcóyotl', 'Estado de México', '57000', '5512234556', NULL, 'Tarjeta de Credito');
INSERT INTO suppliers (name,address_street,address_city,address_country,address_post_code,phone_no,fax_no,payment_terms) VALUES ('<NAME>', 'Tejocote', 'Texcoco', 'Estado de México', '56199', '5578784545', NULL, 'Tarjeta de Credito');
INSERT INTO customers (first_name,last_name,address_street,address_city,address_country,address_post_code,contact_phone_no) VALUES ('Gerardo','Cano','<NAME>','Chimalhuacán','ESTADO DE MÉXICO','56338','5951137059');
INSERT INTO customers (first_name,last_name,address_street,address_city,address_country,address_post_code,contact_phone_no) VALUES ('DIANA','<NAME>','<NAME>','NEZAHUALCÓYOTL','ESTADO DE MÉXICO','57000','5531137722');
INSERT INTO customers (first_name,last_name,address_street,address_city,address_country,address_post_code,contact_phone_no) VALUES ('JUAN','ALVAREZ','CALLE 1 DE MAYO','ECATEPEC','ESTADO DE MÉXICO','07410','5548986535');
INSERT INTO customers (first_name,last_name,address_street,address_city,address_country,address_post_code,contact_phone_no) VALUES ('PEDRO','<NAME>','CALLE SUR 115','IZTACALCO','CDMX','08700','5578471232');
INSERT INTO customers (first_name,last_name,address_street,address_city,address_country,address_post_code,contact_phone_no) VALUES ('ALEJANDRO','PAZ','<NAME>','CUAUHTÉMOC','CDMX','06090','5587129654');
INSERT INTO products (p_name,in_stock,units_in_stock,unit_purchase_price,unit_sale_price,sp_id) VALUES ('<NAME>', 'Yes', 500, 700.00, 900.00, 2);
INSERT INTO products (p_name,in_stock,units_in_stock,unit_purchase_price,unit_sale_price,sp_id) VALUES ('SSD KINGSTON', 'Yes', 600, 1000.00, 1200.00, 2);
INSERT INTO products (p_name,in_stock,units_in_stock,unit_purchase_price,unit_sale_price,sp_id) VALUES ('HDD WESTERN DIGITAL', 'No', 0, 700.00, 1500.00, 2);
INSERT INTO products (p_name,in_stock,units_in_stock,unit_purchase_price,unit_sale_price,sp_id) VALUES ('MOTHERBOARD AORUS', 'Yes', 100, 2000.00, 2500.00, 5);
INSERT INTO products (p_name,in_stock,units_in_stock,unit_purchase_price,unit_sale_price,sp_id) VALUES ('PROCESADOR INTEL CORE i9', 'Yes', 50, 7500.000, 9000.00, 4);
INSERT INTO orders (ctm_id,date_order_placed,time_order_placed,total_product_no,order_completed,date_order_completed,any_additional_info) VALUES (1, '2020/01/01', '09:30:00', 15, 'No', '2000/01/01', NULL);<file_sep>/module/ModulosExtras/Supplier/src/Model/SupplierTable.php
<?php
namespace Supplier\Model;
use RuntimeException;
use Laminas\Db\TableGateway\TableGatewayInterface;
class SupplierTable
{
private $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
return $this->tableGateway->select();
}
public function getSupplier($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(['id' => $id]);
$row = $rowset->current();
if (! $row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
public function saveSupplier(Supplier $supplier)
{
$data = [
'name' => $supplier->name,
'address_street' => $supplier->address_street,
'address_city' => $supplier->address_city,
'address_country' => $supplier->address_country,
'address_post_code' => $supplier->address_post_code,
'phone_no' => $supplier->phone_no,
'fax_no' => $supplier->fax_no,
'payment_terms' => $supplier->payment_terms,
];
$id = (int) $supplier->id;
//Se modificó esta condicion para que permita la inserción de los datos
if ($id === 0) {
$this->tableGateway->insert($data);
return;
}
try {
$this->getSupplier($id);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf(
'Cannot update supplier with identifier %d; does not exist',
$id
));
}
$this->tableGateway->update($data, ['id' => $id]);
}
public function deleteSupplier($id)
{
$this->tableGateway->delete(['id' => (int) $id]);
}
}<file_sep>/module/ModulosExtras/Customer/src/Model/Customer.php
<?php
namespace Customer\Model;
use DomainException;
use Laminas\Filter\StringTrim;
use Laminas\Filter\StripTags;
use Laminas\Filter\ToInt;
use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\InputFilterAwareInterface;
use Laminas\InputFilter\InputFilterInterface;
use Laminas\Validator\StringLength;
class Customer implements InputFilterAwareInterface
{
public $id;
public $first_name;
public $last_name;
public $address_street;
public $address_city;
public $address_country;
public $address_post_code;
public $contact_phone_no;
private $inputFilter;
public function exchangeArray(array $data)
{
$this->id = !empty($data['id']) ? $data['id'] : null;
$this->first_name = !empty($data['first_name']) ? $data['first_name'] : null;
$this->last_name = !empty($data['last_name']) ? $data['last_name'] : null;
$this->address_street = !empty($data['address_street']) ? $data['address_street'] : null;
$this->address_city = !empty($data['address_city']) ? $data['address_city'] : null;
$this->address_country = !empty($data['address_country']) ? $data['address_country'] : null;
$this->address_post_code = !empty($data['address_post_code']) ? $data['address_post_code'] : null;
$this->contact_phone_no = !empty($data['contact_phone_no']) ? $data['contact_phone_no'] : null;
}
public function getArrayCopy()
{
return [
'id'=> $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'address_street' => $this->address_street,
'address_city' => $this->address_city,
'address_country' => $this->address_country,
'address_post_code' => $this->address_post_code,
'contact_phone_no' => $this->contact_phone_no,
];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new DomainException(sprintf(
'%s does not allow injection of an alternate input filter',
__CLASS__
));
}
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'first_name',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 100,
],
],
],
]);
$inputFilter->add([
'name' => 'last_name',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 120,
],
],
],
]);
$inputFilter->add([
'name' => 'address_street',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'address_city',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'address_country',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'address_post_code',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 5,
'max' => 10,
],
],
],
]);
$inputFilter->add([
'name' => 'contact_phone_no',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 10,
'max' => 16,
],
],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
}<file_sep>/module/ModulosExtras/Supplier/src/Form/SupplierForm.php
<?php
namespace Supplier\Form;
use Laminas\Form\Form;
class SupplierForm extends Form
{
public function __construct($name = null)
{
// We will ignore the name provided to the constructor
parent::__construct('supplier');
$this->add([
'name' => 'id',
'type' => 'hidden',
]);
$this->add([
'name' => 'name',
'type' => 'text',
'options' => [
'label' => 'Supplier Name',
],
]);
$this->add([
'name' => 'address_street',
'type' => 'text',
'options' => [
'label' => 'Address Street',
],
]);
$this->add([
'name' => 'address_city',
'type' => 'text',
'options' => [
'label' => 'Address City',
],
]);
$this->add([
'name' => 'address_country',
'type' => 'text',
'options' => [
'label' => 'Address Country',
],
]);
$this->add([
'name' => 'address_post_code',
'type' => 'text',
'options' => [
'label' => 'Address Post Code',
],
]);
$this->add([
'name' => 'phone_no',
'type' => 'text',
'options' => [
'label' => 'Phone Number',
],
]);
$this->add([
'name' => 'fax_no',
'type' => 'text',
'options' => [
'label' => 'Fax Number',
],
]);
$this->add([
'name' => 'payment_terms',
'type' => 'text',
'options' => [
'label' => 'Payment Terms',
],
]);
$this->add([
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Submit',
'id' => 'submitbutton',
],
]);
}
}<file_sep>/module/Comida/src/Module.php
<?php
namespace Comida;
use Laminas\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
//Se manda a llamar el getConfig() el cual carga el module.config.php
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
}<file_sep>/module/ModulosExtras/Product/src/Form/ProductForm.php
<?php
namespace Product\Form;
use Laminas\Form\Form;
class ProductForm extends Form
{
public function __construct($name = null)
{
// We will ignore the name provided to the constructor
parent::__construct('product');
$this->add([
'name' => 'id',
'type' => 'hidden',
]);
$this->add([
'name' => 'name',
'type' => 'text',
'options' => [
'label' => 'Product Name',
],
]);
$this->add([
'name' => 'in_stock',
'type' => 'text',
'options' => [
'label' => 'Products in Stock?',
],
]);
$this->add([
'name' => 'units_in_stock',
'type' => 'text',
'options' => [
'label' => 'Units in stock',
],
]);
$this->add([
'name' => 'unit_purchase_price',
'type' => 'text',
'options' => [
'label' => 'Unit Purchase Price',
],
]);
$this->add([
'name' => 'unit_sale_price',
'type' => 'text',
'options' => [
'label' => 'Unit Sale Price',
],
]);
$this->add([
'name' => 'sp_id',
'type' => 'text',
'options' => [
'label' => 'Supplier Name',
],
]);
}
}<file_sep>/module/Comida/src/Controller/ComidaController.php
<?php
namespace Comida\Controller;
use Laminas\Mvc\Controller\AbstractActionController;
class ComidaController extends AbstractActionController
{
//Devuelve una instancia ViewModel con una matriz que contiene los datos de los albumes
public function indexAction()
{
}
public function addAction()
{
}
public function editAction()
{
}
public function deleteAction()
{
}
}<file_sep>/module/ModulosExtras/Supplier/src/Module.php
<?php
namespace Supplier;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\TableGateway\TableGateway;
use Laminas\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
//Se manda a llamar el getConfig() el cual carga el module.config.php
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
Model\SupplierTable::class => function($container) {
$tableGateway = $container->get(Model\SupplierTableGateway::class);
return new Model\SupplierTable($tableGateway);
},
Model\SupplierTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Supplier());
//Aqui debemos de agregar el nombre de la tabla que queremos enlazar
return new TableGateway('suppliers', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
//Se crea un factory(fabrica) propio
public function getControllerConfig()
{
return [
'factories' => [
Controller\SupplierController::class => function($container) {
return new Controller\SupplierController(
$container->get(Model\SupplierTable::class)
);
},
],
];
}
}<file_sep>/module/Cporders/src/Form/ProductForm.php
<?php
namespace Cporders\Form;
use Laminas\Form\Form;
use Laminas\Form\Element;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\Adapter\Driver\ResultInterface;
class ProductForm extends Form
{
public function __construct($name = null)
{
$adapter = new Adapter([
'driver' => 'Pdo_Sqlite',
'database' => __DIR__ . '/../../../../data/order.db',
]);
$statement = $adapter->createStatement('SELECT name,id FROM suppliers');
$statement->prepare();
$result = $statement->execute();
$dato = array();
if ($result instanceof ResultInterface && $result->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($result);
foreach ($resultSet as $row) {
$dato += array($row->id => $row->name);
}
}
$names = new Element\Select('sp_id');
$names->setLabel('Which the supplier name');
//$names->setOptions($valores);
$names->setEmptyOption('Seleccione un vendedor');
$names->setValueOptions($dato);
$element = new Element\Select('in_stock');
$element->setLabel('Are products in stock?');
$element->setValueOptions([
'Yes' => 'Yes',
'No' => 'No'
]);
// We will ignore the name provided to the constructor
parent::__construct('product');
$this->add([
'name' => 'p_id',
'type' => 'hidden',
]);
$this->add([
'name' => 'p_name',
'type' => 'text',
'options' => [
'label' => 'Product Name',
],
]);
$this->add($element);
$this->add([
'name' => 'units_in_stock',
'type' => 'text',
'options' => [
'label' => 'Units in stock',
],
]);
$this->add([
'name' => 'unit_purchase_price',
'type' => 'text',
'options' => [
'label' => 'Unit Purchase Price',
],
]);
$this->add([
'name' => 'unit_sale_price',
'type' => 'text',
'options' => [
'label' => 'Unit Sale Price',
],
]);
$this->add($names);
$this->add([
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Submit',
'id' => 'submitbutton',
],
]);
}
}
<file_sep>/module/Cporders/src/Model/OrderTable.php
<?php
namespace Cporders\Model;
use RuntimeException;
use Laminas\Db\TableGateway\TableGatewayInterface;
use Laminas\Db\Sql\Select;
class OrderTable
{
private $tableGateway;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
return $this->tableGateway->select(function (Select $select) {
$select->join('customers','ctm_id = customers.id');
});
}
public function getOrder($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(['o_id' => $id]);
$row = $rowset->current();
if (!$row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
public function saveOrder(Order $order)
{
$data = [
'ctm_id' => $order->ctm_id,
'date_order_placed' => $order->date_order_placed,
'time_order_placed' => $order->time_order_placed,
'total_product_no' => $order->total_product_no,
'order_completed' => $order->order_completed,
'date_order_completed' => $order->date_order_completed,
'any_additional_info' => $order->any_additional_info,
];
$id = (int) $order->o_id;
if ($id === 0) {
$this->tableGateway->insert($data);
return;
}
try {
$this->getOrder($id);
} catch (RuntimeException $e) {
throw new RuntimeException(sprintf(
'Cannot update Order with identifier %d; does not exist',
$id
));
}
$this->tableGateway->update($data, ['o_id' => $id]);
}
public function deleteOrder($id)
{
$this->tableGateway->delete(['o_id' => (int) $id]);
}
}<file_sep>/module/ModulosExtras/Product/src/Model/Product.php
<?php
namespace Product\Model;
use DomainException;
use Laminas\Filter\StringTrim;
use Laminas\Filter\StripTags;
use Laminas\Filter\ToInt;
use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\InputFilterAwareInterface;
use Laminas\InputFilter\InputFilterInterface;
use Laminas\Validator\StringLength;
class Product implements InputFilterAwareInterface
{
public $id;
public $name;
public $in_stock;
public $units_in_stock;
public $unit_purchase_price;
public $unit_sale_price;
public $sp_id;
private $inputFilter;
public function exchangeArray(array $data)
{
$this->id = !empty($data['id']) ? $data['id'] : null;
$this->name = !empty($data['name']) ? $data['name'] : null;
$this->in_stock = !empty($data['in_stock']) ? $data['in_stock'] : null;
$this->units_in_stock = !empty($data['units_in_stock']) ? $data['units_in_stock'] : null;
$this->unit_purchase_price = !empty($data['unit_purchase_price']) ? $data['unit_purchase_price'] : null;
$this->unit_sale_price = !empty($data['unit_sale_price']) ? $data['unit_sale_price'] : null;
$this->sp_id = !empty($data['sp_idsp_id']) ? $data['sp_id'] : null;
}
public function getArrayCopy()
{
return [
'id'=> $this->id,
'name' => $this->name,
'in_stock' => $this->in_stock,
'units_in_stock' => $this->units_in_stock,
'unit_purchase_price' => $this->unit_purchase_price,
'unit_sale_price' => $this->unit_sale_price,
'sp_id' => $this->sp_id,
];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new DomainException(sprintf(
'%s does not allow injection of an alternate input filter',
__CLASS__
));
}
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'name',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 3,
'max' => 150,
],
],
],
]);
$inputFilter->add([
'name' => 'in_stock',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'units_in_stock',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'unit_purchase_price',
'required' => true,
'filters' => [
['name' => ToDouble::class],
],
]);
$inputFilter->add([
'name' => 'unit_sale_price',
'required' => true,
'filters' => [
['name' => ToDouble::class],
],
]);
$inputFilter->add([
'name' => 'sp_id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
}<file_sep>/module/Cporders/src/Model/Order.php
<?php
namespace Cporders\Model;
use DomainException;
use Laminas\Filter\StringTrim;
use Laminas\Filter\StripTags;
use Laminas\Filter\ToInt;
use Laminas\Filter\ToFloat;
use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\InputFilterAwareInterface;
use Laminas\InputFilter\InputFilterInterface;
use Laminas\Validator\StringLength;
class Order implements InputFilterAwareInterface
{
public $o_id;
public $ctm_id;
public $date_order_placed;
public $time_order_placed;
public $total_product_no;
public $order_completed;
public $date_order_completed;
public $any_additional_info;
public $first_name;
public $last_name;
private $inputFilter;
public function exchangeArray(array $data)
{
$this->o_id = !empty($data['o_id']) ? $data['o_id'] : null;
$this->ctm_id = !empty($data['ctm_id']) ? $data['ctm_id'] : null;
$this->date_order_placed = !empty($data['date_order_placed']) ? $data['date_order_placed'] : null;
$this->time_order_placed = !empty($data['time_order_placed']) ? $data['time_order_placed'] : null;
$this->total_product_no = !empty($data['total_product_no']) ? $data['total_product_no'] : null;
$this->order_completed = !empty($data['order_completed']) ? $data['order_completed'] : null;
$this->date_order_completed = !empty($data['date_order_completed']) ? $data['date_order_completed'] : null;
$this->any_additional_info = !empty($data['any_additional_info']) ? $data['any_additional_info'] : null;
$this->first_name = !empty($data['first_name']) ? $data['first_name'] : null;
$this->last_name = !empty($data['last_name']) ? $data['last_name'] : null;
$this->ctm_name = $this->first_name. " ".$this->last_name;
}
public function getArrayCopy()
{
return [
'o_id' => $this->o_id,
'ctm_id' => $this->ctm_id,
'date_order_placed' => $this->date_order_placed,
'time_order_placed' => $this->time_order_placed,
'total_product_no' => $this->total_product_no,
'order_completed' => $this->order_completed,
'date_order_completed' => $this->date_order_completed,
'any_additional_info' => $this->any_additional_info,
];
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new DomainException(sprintf(
'%s does not allow injection of an alternate input filter',
__CLASS__
));
}
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'o_id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'ctm_id',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'date_order_placed',
'required' => true,
]);
$inputFilter->add([
'name' => 'time_order_placed',
'required' => true,
]);
$inputFilter->add([
'name' => 'total_product_no',
'required' => true,
'filters' => [
['name' => ToInt::class],
],
]);
$inputFilter->add([
'name' => 'order_completed',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
'min' => 2,
'max' => 3,
],
],
],
]);
$inputFilter->add([
'name' => 'date_order_completed',
'required' => false,
]);
$inputFilter->add([
'name' => 'any_additional_info',
'required' => true,
'filters' => [
['name' => StripTags::class],
['name' => StringTrim::class],
],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'encoding' => 'UTF-8',
],
],
],
]);
$this->inputFilter = $inputFilter;
return $this->inputFilter;
}
}<file_sep>/config/modules.config.php
<?php
/**
* List of enabled modules for this application.
*
* This should be an array of module namespaces used in the application.
*
* Modulos usados en la aplicación
*/
return [
'Laminas\Db',
'Laminas\Form',
'Laminas\Router',
'Laminas\Validator',
'Application',
'Album',
'Comida',
'Cporders',
];
| d3942d1cd5090c5978c9a714956a5bbf74db2fc9 | [
"SQL",
"PHP"
] | 22 | PHP | GerardoCano/ventas | 8ca66aa5b2e69d3f117ac68fcd46e67eef6602b7 | b14721d8cb12873db75212ba074a5affcfee50d6 |
refs/heads/master | <file_sep>### Reproduce browsers failure to follow redirects in case of Pre-flighted CORS requests
# Running the repro servers
* Download and install [golang[ (https://golang.org/dl/)
* Clone the repo
`git clone <EMAIL>:monmohan/cors-experiment.git`
* Running the API and page server
+ Change to the `issue` directory
+ Type `go run apiserver_303.go`
+ This will run the api server
+ Type `go run pageserver.go`
+ This will start the page server
+ Go to `http://localhost:12345/redirectfails.html`
+ This will show a page with two buttons, one with successfull pre-flighted request
+ The other with a failed 303 response (same URI)
<file_sep># cors-experiment
* Simple GET with Allow-Origin
* POST with application/json content type, support for OPTIONS
* Share cookie, xhrCredentials
# Running the demo
* Download and install [golang](https://golang.org/dl/)
* Clone the repo
`git clone <EMAIL>:monmohan/cors-tutorial-practical.git`
* Running the Servers
+ Map couple of loopback interfaces to page and apiserver. For example here is my etc/hosts file
```
127.0.0.2 pageserver.cors.com
127.0.0.3 apiserver.cors.com
```
+ The servers can be run directly from the source
+ Change to the relevent directory
+ Type `go run <filename>`
- For example to run the apiserver_preflight,
+ cd to apiserver directory
+ `go run apiserver_preflight.go`
Follow CORS.MD to try out the examples in the blog article
<file_sep>package main
import (
"flag"
"fmt"
"log"
"net/http"
)
var port = flag.Int("port", 12345, "port to run the server on, default is 12345")
var setCookie = flag.Bool("set-cookie", false, "enable to set cookie in response")
func fileHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Requested URL %v\n", r.URL.Path)
if *setCookie {
http.SetCookie(w, &http.Cookie{Name: "token", Value: "secret_token"})
}
http.ServeFile(w, r, r.URL.Path[1:])
}
func main() {
flag.Parse()
http.HandleFunc("/", fileHandler)
log.Fatal(http.ListenAndServe(fmt.Sprintf("127.0.0.2:%d", *port), nil))
}
<file_sep>package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
)
type User struct {
UserName string
FirstName string
LastName string
Country string
}
var userData = map[string]User{
"john": User{"jdoe", "John", "Doe", "France"},
}
var port = flag.Int("port", 12346, "port to listen on, default is 12346")
func corsWrapper(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
fmt.Printf("Request Origin header %s\n", origin)
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
}
fn(w, r)
}
}
func userHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
b, _ := json.Marshal(userData[r.URL.Path[len("/users/"):]])
io.WriteString(w, string(b))
}
func main() {
flag.Parse()
http.HandleFunc("/users/", corsWrapper(userHandler))
log.Fatal(http.ListenAndServe(fmt.Sprintf("127.0.0.3:%d", *port), nil))
}
<file_sep>### About this article
In this article we will explore CORS (Cross-Origin Resource sharing), understand the interaction between Browsers and Servers, see what is needed to support Cross Origin request by Servers, and walkthrough some sample code/demo.
### Code Samples
All the code shown in the blog is available at https://github.com/monmohan/cors-experiment.
The server code is written in golang and the client samples are web pages that use javascript [XMLHttpRequest Object](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) . Although the code is in golang, the reader doesn't require knowledge of the language to understand what's going on. Its fairly obvious.
You can run the servers locally by following instructions in the [Readme](https://github.com/monmohan/cors-experiment/blob/master/README.md)
### Cross-Origin Resource Sharing (CORS)
is a W3C spec that allows cross-domain communication from the browser. CORS is becoming increasingly more important as we use multiple API's and services to create a mashup/stitched user experience
But, in order to understand cross origin resource sharing, first we need to understand the concept of an "origin".
### What is an Origin?
Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.
So
* http://api.mysite.com/resource.html
has same origin as
* http://api.mysite.com/somepath/resource2.html
but different from
* http://api.mysite.com:99/resource.html (different port)
or
* https://api.mysite.com:99/resource.html (different protocol)
There are some exceptions to the above rule (mostly by, suprise surprise IE !) but they are non-standard.
###Same Origin Policy
By default, Browsers enforce "Same Origin Policy" for HTTP requests initiated from within scripts. A web application using XMLHttpRequest could only make HTTP requests to its own domain. One important thing to be aware of, is that, cross origin "embedding" is allowed. Browsers can load scripts(source),images, media files embedded within the page even if they are from a different origin.
In this blog we will focus on the main restriction, cross origin requests using XMLHttpRequest
### Enter CORS
The [Cross-Origin Resource Sharing standard](https://www.w3.org/TR/cors/) works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Important thing to note is that it's the Servers which are in control, not the client.
### Example 1 - Simple Request
So lets first see what happens when we do a cross origin XMLHttpRequest. For this example, we will be running two servers.
*PageServer* : A simple server which serves requested page. This server runs on a port 12345 and serves an HTML file. You can override the port by providing -port option when running the server. Here is relevant code :
func fileHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Requested URL %v\n", r.URL.Path)
if *setCookie {
http.SetCookie(w, &http.Cookie{Name: "token", Value: "<PASSWORD>_token"})
}
http.ServeFile(w, r, r.URL.Path[1:])
}
func main() {
flag.Parse()
http.HandleFunc("/", fileHandler)
log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", *port), nil))
}
- Start the page server
> $ cd pageserver
> $ go run pageserver.go
*ApiServers* : These are the different servers which expose a basic User REST API, that returns a JSON representing a User object based on the user name in the request URL. The User is just a simple struct saved in an in-memory map. The servers will run by default on port 12346
NOTE: you can change the port by providing the -port option when you run the program but you will need to update the HTML files to point to new host:port combination
var userData = map[string]User{
"john": User{"jdoe", "John", "Doe", "France"},
}
var port = flag.Int("port", 10001, "help message for flagname")
func userHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
b, _ := json.Marshal(userData[r.URL.Path[len("/users/"):]])
io.WriteString(w, string(b))
}
func main() {
flag.Parse()
http.HandleFunc("/users/", userHandler)
log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", *port), nil))
}
Run the simple apiserver
>$ cd apiserver
>$ go run apiserver.go
- Open the browser and load the html http://localhost:12345/showuser.html
Here is how this looks

if you click "show", it is supposed to go to http://localhost:12346/users/john and get the user json to display but instead you see this error in console :
>showuser.html:1 XMLHttpRequest cannot load http://localhost:12346/users/john. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:12345' is therefore not allowed access.
**This is called a "Simple" Cross origin GET request**
Simple requests are requests that meet the following criteria:
HTTP Method matches one of
- HEAD, GET or POST
and
HTTP Headers matches one or more of these
- Accept
- Accept-Language
- Content-Language
- Content-Type, but only if the value is one of:
- application/x-www-form-urlencoded, multipart/form-data, text/plain
*Lets see what we can do to succeed in serving a simple cross origin request*
- Stop the simple apiserver
- Start the apiserver\_allow\_origin server.
> $ go run apiserver\_allow\_origin.go
What we have done here is added the _Access-Control-Allow-Origin_ header for any incoming GET request. The value of the header is same as the value sent by browser for the Origin header in the request. This is equivalent to allowing requests that come from any origin (*)
func corsWrapper(fn func(http.ResponseWriter, *http.Request)) httpHandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
fmt.Printf("Request Origin header %s\n", origin)
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
}
fn(w, r)
}
}
Lets attempt clicking the "show" button again and Voila we see the data returned by the server:
> {"UserName":"jdoe","FirstName":"John","LastName":"Doe","Country":"France"}
Its all good until we realize that just adding Access-Control-Allow-Origin isn't sufficient for certain "complex" requests (or anything which isn't covered in the Simple request).
*An example of such a request is POST request with Content-Type as application/json.*
###Example 2 - 'Complex' Request
- Point your browser to http://localhost:12345/createUser.html
This is a simple form which looks like below. Entering the data and clicking "create" send a POST request to the ApiServer in-memory store
Here is how this looks

So, lets add some string data in the form fields and click "create" button. This should convert the data to JSON and do a POST to http://localhost:12346/users with the json data as the body of the request
Here is the relevant code in createUser.html:
> function sendRequest(url) {
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("POST", url);
oReq.setRequestHeader("Content-Type", "application/json")
var data = serializeUser($('#fcreate').serializeArray());
console.log(data)
oReq.send(JSON.stringify(data));
}
But once you hit, "create", the browser reports the following error :-
>XMLHttpRequest cannot load http://localhost:12346/users. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:12345' is therefore not allowed access.
###Pre-Flight
What we called as "Complex" request actually causes two http requests under the covers. The browser first issues a preflight or an OPTIONS request, which is basically asking the server for permission to make the actual request. Once permissions have been granted, the browser makes the actual request.
So, in this case, the pre-flight request is something like below
OPTIONS /users HTTP/1.1
Host: localhost:12346
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:12345
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:12345/createUser.html
The preflight request contains a few additional headers:
- Access-Control-Request-Method - The HTTP method of the actual request.
- Access-Control-Request-Headers - A comma-delimited list of non-simple headers that are included in the request. Notice that all CORS related headers are prefixed with "Access-Control-".
In order for the POST to succeed, the server should support this request, "granting" permission based on the above request headers.
Lets do that.
- Stop apiserver_allow_origin
- Start apiserver_preflight
> $ go run apiserver_preflight
What we have done here is added some code in the apiserver to respond to OPTIONS request, granting the permission for GET, and POST calls with Content-Type header.
func optionsWrapper(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
reqMethod, reqHeader := r.Header.Get("Access-Control-Request-Method"), r.Header.Get("Access-Control-Request-Headers")
//check for validity
if (r.Method == "OPTIONS") && (reqMethod == "GET" || reqMethod == "POST") && (strings.EqualFold(reqHeader, "Content-Type")) {
w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
return
}
fn(w, r)
}
}
Enter data and hit "create" button again. You will see that the request succeeded. Using chrome tools or similar debugger, the response to OPTIONS request can be examined as well.
>HTTP/1.1 200 OK
*Access-Control-Allow-Headers: Content-Type*
*Access-Control-Allow-Methods: POST, GET, OPTIONS*
Access-Control-Allow-Origin: http://localhost:12345
Date: Thu, 12 May 2016 10:10:13 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8
The response headers from the server grant permission to the different cross origin request methods (comma separated list of GET, POST) and also the allowed headers (in this case Content-Type header).
In addition, the server can also return a header called _Access-Control-Max-Age_. The value of the header indicates how long the pre-flight response can be cached by the browser and hence browsers can skip the check for that duration
### Handling credentials
By default, cookies are not included in CORS requests. This means that a cookie set by one origin will not sent as part of the HTTP request sent to the different origin.
Lets see an example
- Stop apiserver_preflight
- Start apiserver_creds_fail
>$ go run apiserver_creds_fail.go
- Stop pageserver
- Start pageserver with cookie option set so that it sets a cookie when serving the page
>$ go run pageserver.go -set-cookie
- Point your browser to http://localhost:12345/showusermore.html.
The UI is same as showuser.html but the pageserver_cookie server now adds a cookie *(name="token", value="<PASSWORD>")* to the page when its served.
Also, the apiserver will attempt to read this cookie, and respond with additional secret data.
func userHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
b, _ := json.Marshal(userData[r.URL.Path[len("/users/"):]])
io.WriteString(w, string(b))
if c, err := r.Cookie("token"); err == nil && c.Value == "secret_token" {
io.WriteString(w, "<br/>Show Secret Data !!")
}
}
Enter "john" in the text box and hit "show". The request doesn't succeed!
You will see following error in the console
>XMLHttpRequest cannot load http://localhost:12346/users/john. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:12345' is therefore not allowed access.
What happened here is that page tried to send the cookie to the different origin API server. Here is the sendRequest method from page
function sendRequest(url) {
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.withCredentials = true;
oReq.open("GET", url);
oReq.send();
}
Notice the *"oReq.withCredentials = true;"* statement. The XMLHttpRequest object needs to set a property called "withCredentials" in order to share the cookie to the different origin server. However that's not enough.
The server should have responded with a header called _Access-Control-Allow-Credentials_ with value as _true_ in order for this cookie to be accepted. This request header works in conjunction with the XMLHttpRequest property. If _.withCredentials_ is true, but there is no _Access-Control-Allow-Credentials_ header, the request will fail.
Lets try again
- Stop apiserver_creds_fail
- Start apiserver_allow_creds
> $ go run apiserver_allow_creds.go
What we done now is added support for _Access-Control-Allow-Credentials_ header
func corsWrapper(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
fmt.Printf("Request Origin header %s\n", origin)
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
fn(w, r)
}
}
Again enter "john" in the text box and hit "show".
You will see the following response with the secret data text now shown !
>{"UserName":"jdoe","FirstName":"John","LastName":"Doe","Country":"France"}
Show Secret Data !!
Hopefully this has given a hands on experience with supporting CORS.
There are few more optional headers supported by CORS, to read more about the subject, please take a look at the links in the reference section.
References
- [Browser Security Handbook](https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy)
- [W3C Cross-Origin Resource Sharing](https://www.w3.org/TR/cors/)
- [HTML5 Rocks](http://www.html5rocks.com/en/tutorials/cors/#toc-introduction)
- [CORS on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
| f171e6f14828fbface221cfd6864efa9b7af34a2 | [
"Markdown",
"Go"
] | 5 | Markdown | devocasion/cors-tutorial-practical | 6defee14893a5f26d595365351df56b3d19d2884 | 29eca94f0e7aba919d048a74de96cacb2be5b1b8 |
refs/heads/master | <repo_name>WojRubin/helpdesk<file_sep>/spec/models/comment_spec.rb
require 'spec_helper'
describe Comment do
pending "add some examples to (or delete) #{__FILE__}"
it "get all from table " do
comment1 = Comment.create do |t|
t.ticket_id = '1'
t.user_id = '1'
t.status = 'yes'
t.sharing = 'yes'
t.title = 'why '
t.body = 'why ask the question'
end
expect(Comment.all).to eq([comment1])
end
end
<file_sep>/app/controllers/registreds_controller.rb
class RegistredsController < ApplicationController
before_filter :authenticate_user!
def index
@subjects = Subject.all.includes(:tickets => :comments)
@comment = Comment.new
respond_to do |format|
format.html
end
end
end
<file_sep>/app/views/tickets/index.json.jbuilder
json.array!(@tickets) do |ticket|
json.extract! ticket, :id, :title, :body, :user_id, :subject_id, :status, :sharing
json.url ticket_url(ticket, format: :json)
end
<file_sep>/app/views/comments/show.json.jbuilder
json.extract! @comment, :id, :ticket_id, :user_id, :status, :sharing, :created_at, :updated_at
<file_sep>/app/controllers/admin/admins_controller.rb
class Admin::AdminsController < ApplicationController
before_filter :authenticate_admin
def index
@tickets = Ticket.all
respond_to do |format|
format.html
format.json
end
end
private
def authenticate_admin
authenticate_user!
redirect_to root_path, alert: 'You arent admin' unless current_user.role == 'super_admin' || current_user.role == 'admin'
end
end<file_sep>/app/controllers/main_controller.rb
class MainController < ApplicationController
before_filter :check_role
def index
@subjects = Subject.all.includes(:tickets => :comments)
@comment = Comment.new
respond_to do |format|
format.html
end
end
private
def check_role
if user_signed_in?
if current_user.role == 'admin' || current_user.role == 'super_admin'
redirect_to admin_root_path
elsif
redirect_to registred_path
end
end
end
end
<file_sep>/app/models/ticket.rb
class Ticket < ActiveRecord::Base
belongs_to :subject
has_many :comments
end
| c0737b68922abd27d7997cec9524fd1060bc6af1 | [
"Ruby"
] | 7 | Ruby | WojRubin/helpdesk | 8114b1a19c3525bb217ad2a60b1165fece5f603d | b59566c82657730ca60225b51e43ef2dca165de5 |
refs/heads/master | <file_sep>def merge(L, R):
array = []
i, j = 0, 0
while i < len(L) and j < len(R):
if L[i] <= R[j]:
array.append(L[i])
i += 1
else:
array.append(R[j])
j += 1
array += L[i:]
array += R[j:]
return array
def mergesort(array):
if len(array) > 1:
q = len(array) // 2
L = mergesort(array[:q])
R = mergesort(array[q:])
return merge(L, R)
return array
arrayEx = [12,64,23,58,34,72,12,7,29]
res = mergesort(arrayEx)
print(res)
<file_sep>#selection sort in increasing order
array = [5,6,7,1,2,78,32,62,12,8,2,7]
def selectionSort(arrayEx) :
for m in range(0, len(arrayEx)) :
maxElem = -float('inf')
key = arrayEx[m]
for j in range(m, len(arrayEx)) :
if(arrayEx[j] >= maxElem) :
maxElem = arrayEx[j]
k = j
arrayEx[k] = key
arrayEx[m] = maxElem
return arrayEx
res = selectionSort(array)
print(res)
#selection sort in decreasing order
array = [5,6,7,1,2,78,32,62,12,8,2,7]
def selectionSortReverse(arrayEx1) :
for m in range(0, len(arrayEx1)) :
minElem = float('inf')
key = arrayEx1[m]
for j in range(m, len(arrayEx1)) :
if(arrayEx1[j] <= minElem) :
minElem = arrayEx1[j]
k = j
arrayEx1[k] = key
arrayEx1[m] = minElem
return arrayEx1
res1 = selectionSortReverse(array)
print(res1)
<file_sep>
def bubbleSort(array) :
for m in range(0, len(array)) :
for i in range(1, len(array) - m) :
if array[i-1] > array[i] :
array[i-1], array[i] = array[i], array[i-1]
return array
arrayEx = [12,125,122,1200,4,143]
res = bubbleSort(arrayEx)
print(res)
<file_sep>def quickSort(array, p, r) :
if p < r :
q = partition(array, p, r)
quickSort(array, p, q - 1)
quickSort(array, q + 1, r)
def partition(array, p, r):
x = array[r]
i = p - 1
for j in range(p, r) :
if array[j] <= x :
i = i + 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[r] = array[r], array[i + 1]
return i + 1
array = [12,56,23,84,1200,64,23,75,35,109,98,117]
quickSort(array, 0, len(array)-1)
print(array)
<file_sep>#insertion sort
array = [4,1,6,3,2,5,7]
def insertionSort(arrayEx) :
for j in range(1, len(arrayEx)) :
key = arrayEx[j]
i = j - 1
while i >= 0 and arrayEx[i] > key :
arrayEx[i + 1] = arrayEx[i]
i = i - 1
arrayEx[i + 1] = key
return arrayEx
res = insertionSort(array)
print(array)
# reverse insertion sort
def insertionSortReverse(arrayExReverse) :
for m in range(1, len(arrayExReverse)) :
keyReverse = arrayExReverse[m]
i = m - 1
while i >= 0 and arrayExReverse[i] < keyReverse :
arrayExReverse[i + 1] = arrayExReverse[i]
i = i - 1
arrayExReverse[i + 1] = keyReverse
return arrayExReverse
resReverse = insertionSortReverse(array)
print(resReverse)
| a33be357260eeb32d3862df2b28fd8e01a06f268 | [
"Python"
] | 5 | Python | ElminsteAumar/Sorting_algorithms | 9cd907500d522fd0fb3cb00870487bc4db8fd4fc | 1b4c0ccea88b0d1a35571a3006d527cea8966f31 |
refs/heads/main | <file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { AppState } from '../app/store';
export type ArrangeType = 'none' | 'same' | 'next';
export type StyleState = {
startTime: number;
shouldArrangeHorizontally: ArrangeType;
nameConversionTable: { [key: string]: string };
};
const initialState: StyleState = {
startTime: 90,
shouldArrangeHorizontally: 'same',
nameConversionTable: {},
};
export const styleSlice = createSlice({
name: 'style',
initialState,
reducers: {
addNameConversionRule: (
state,
action: PayloadAction<{ key: string; value: string }>,
) => {
state.nameConversionTable[action.payload.key] = action.payload.value;
localStorage.setItem(
`name${process.env.version}`,
JSON.stringify(state.nameConversionTable),
);
},
deleteNameConversionRule: (state, action: PayloadAction<string>) => {
delete state.nameConversionTable[action.payload];
localStorage.setItem(
`name${process.env.version}`,
JSON.stringify(state.nameConversionTable),
);
},
initNameConversionRule: (
state,
action: PayloadAction<{ [key: string]: string }>,
) => {
state.nameConversionTable = action.payload;
},
changeArrangement: (state, action: PayloadAction<ArrangeType>) => {
state.shouldArrangeHorizontally = action.payload;
},
changeStartTime: (state, action: PayloadAction<number>) => {
state.startTime = action.payload;
},
},
});
export const {
addNameConversionRule,
deleteNameConversionRule,
initNameConversionRule,
changeArrangement,
changeStartTime,
} = styleSlice.actions;
export const selectNameConversionTable = (
state: AppState,
): { [key: string]: string } => state.style.nameConversionTable;
export const selectArrangement = (state: AppState): ArrangeType =>
state.style.shouldArrangeHorizontally;
export const selectStartTime = (state: AppState): number =>
state.style.startTime;
export default styleSlice.reducer;
<file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { MAX_PHASE } from '../lib/gameConstants';
import type { AppState } from '../app/store';
export type Character = {
name: string;
star: number;
lv: number;
rank: number;
specialLv: number;
comment: string;
};
export type UB = {
id: number;
time: number;
name: string;
comment: string;
};
export type TLState = {
phase: number;
damage: number;
bossName: string;
startTime: number;
endTime: number;
characters: Character[];
timeline: UB[];
comment: string;
};
const initialState: TLState = {
phase: MAX_PHASE,
damage: 0,
bossName: '',
startTime: 90,
endTime: 0,
characters: [],
timeline: [],
comment: '',
};
export const tLSlice = createSlice({
name: 'tl',
initialState,
reducers: {
changePhase: (state, action: PayloadAction<number>) => {
state.phase = action.payload;
},
changeDamage: (state, action: PayloadAction<number>) => {
state.damage = action.payload;
},
changeBossName: (state, action: PayloadAction<string>) => {
state.bossName = action.payload;
},
changeStartTime: (state, action: PayloadAction<number>) => {
state.startTime = action.payload;
},
changeEndTime: (state, action: PayloadAction<number>) => {
state.endTime = action.payload;
},
changeComment: (state, action: PayloadAction<string>) => {
state.comment = action.payload;
},
selectCharacters: (state, action: PayloadAction<Character[]>) => {
state.characters = action.payload;
},
changeCharacterName: (
state,
action: PayloadAction<{ index: number; value: string }>,
) => {
state.characters[action.payload.index].name = action.payload.value;
},
changeCharacterStar: (
state,
action: PayloadAction<{ index: number; value: number }>,
) => {
state.characters[action.payload.index].star = action.payload.value;
},
changeCharacterLv: (
state,
action: PayloadAction<{ index: number; value: number }>,
) => {
state.characters[action.payload.index].lv = action.payload.value;
},
changeCharacterRank: (
state,
action: PayloadAction<{ index: number; value: number }>,
) => {
state.characters[action.payload.index].rank = action.payload.value;
},
changeCharacterSpecialLv: (
state,
action: PayloadAction<{ index: number; value: number }>,
) => {
state.characters[action.payload.index].specialLv = action.payload.value;
},
changeCharacterComment: (
state,
action: PayloadAction<{ index: number; value: string }>,
) => {
state.characters[action.payload.index].comment = action.payload.value;
},
changeUBTime: (
state,
action: PayloadAction<{ index: number; value: number }>,
) => {
state.timeline[action.payload.index].time = action.payload.value;
},
changeUBName: (
state,
action: PayloadAction<{ index: number; value: string }>,
) => {
state.timeline[action.payload.index].name = action.payload.value;
},
changeUBComment: (
state,
action: PayloadAction<{ index: number; value: string }>,
) => {
state.timeline[action.payload.index].comment = action.payload.value;
},
addUB: (state, action: PayloadAction<{ index: number; ub: UB }>) => {
state.timeline.splice(action.payload.index, 0, action.payload.ub);
},
deleteUB: (state, action: PayloadAction<number>) => {
state.timeline.splice(action.payload, 1);
},
sanitizeUB: (state) => {
state.timeline = state.timeline.filter(
(ub) =>
ub.name === state.bossName ||
state.characters.map((character) => character.name).includes(ub.name),
);
},
loadTL: (state, action: PayloadAction<TLState>) => {
state.bossName = action.payload.bossName;
state.characters = action.payload.characters;
state.comment = action.payload.comment;
state.damage = action.payload.damage;
state.endTime = action.payload.endTime;
state.timeline = action.payload.timeline;
state.phase = action.payload.phase;
state.startTime = action.payload.startTime;
state.endTime = action.payload.endTime;
},
},
});
export const {
changePhase,
changeDamage,
changeBossName,
changeStartTime,
changeEndTime,
changeComment,
changeCharacterName,
changeCharacterStar,
changeCharacterLv,
changeCharacterRank,
changeCharacterSpecialLv,
changeCharacterComment,
changeUBTime,
changeUBName,
changeUBComment,
addUB,
deleteUB,
selectCharacters,
sanitizeUB,
loadTL,
} = tLSlice.actions;
export const selectTL = (state: AppState): TLState => state.tl;
export const selectIsCharactersInputVisible = (state: AppState): boolean =>
state.tl.characters.length === 5;
export const selectIsTLBasicDataInputVisible = (state: AppState): boolean =>
state.tl.characters.length === 5;
export const selectIsUBsInputVisible = (state: AppState): boolean =>
state.tl.bossName !== '' && state.tl.characters.length === 5;
export default tLSlice.reducer;
<file_sep>module.exports = {
env: {
version: '1.0.0',
},
i18n: {
locales: ['ja'],
defaultLocale: 'ja',
},
};
<file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppState } from 'app/store';
export type CommonAlertState = {
isOpen: boolean;
message: string;
anchorOrigin: {
vertical: 'bottom' | 'top';
horizontal: 'center' | 'left' | 'right';
};
severity: 'error' | 'info' | 'success' | 'warning';
duration: number;
};
const initialState: CommonAlertState = {
isOpen: false,
message: 'aaa',
severity: 'error',
anchorOrigin: {
vertical: 'top',
horizontal: 'center',
},
duration: 10000,
};
export const commonAlertSlice = createSlice({
name: 'commonAlert',
initialState,
reducers: {
openAlert: (
state,
action: PayloadAction<Omit<CommonAlertState, 'isOpen'>>,
) => {
state.isOpen = true;
state.message = action.payload.message;
state.severity = action.payload.severity;
state.anchorOrigin = action.payload.anchorOrigin;
state.duration = action.payload.duration;
},
closeAlert: (state) => {
state.isOpen = false;
},
},
});
export const { openAlert, closeAlert } = commonAlertSlice.actions;
export const selectCommonAlertState = (state: AppState): CommonAlertState =>
state.commonAlert;
export default commonAlertSlice.reducer;
<file_sep>import { TLState } from 'ducks/tl';
import { ArrangeType } from 'ducks/style';
import { timeNum2Str } from 'lib/util';
// 半角は1文字 全角は2文字として文字数をカウント
const getLen = (str: string) => {
let halfCount = 0;
let fullCount = 0;
for (let i = 0; i < str.length; i += 1) {
const chr = str.charCodeAt(i);
if (
(chr >= 0x00 && chr < 0x81) ||
chr === 0xf8f0 ||
(chr >= 0xff61 && chr < 0xffa0) ||
(chr >= 0xf8f1 && chr < 0xf8f4)
) {
// 半角文字の場合は1を加算
halfCount += 1;
} else {
// それ以外の文字の場合は2を加算
fullCount += 1;
}
}
// 結果を返す
return [halfCount, fullCount];
};
/** 最大の長さの名前にあわせてパディングを入れる */
const makePaddedNameList = (
nameList: string[],
nameConversionTable: { [key: string]: string },
): { [key: string]: string } => {
const maxHalfLength = Math.max(
...nameList.map((name) => getLen(nameConversionTable[name] ?? name)[0]),
);
const maxFullLength = Math.max(
...nameList.map((name) => getLen(nameConversionTable[name] ?? name)[1]),
);
const resultList = {};
nameList.forEach((name) => {
const [halfLength, fullLength] = getLen(nameConversionTable[name] ?? name);
resultList[name] =
(nameConversionTable[name] ?? name) +
' '.repeat(maxHalfLength - halfLength) +
' '.repeat(maxFullLength - fullLength);
});
return resultList;
};
const formatTL = (
tlData: TLState,
nameConversionTable: { [key: string]: string },
arrange: ArrangeType = 'next',
startTime = 90,
): string[] => {
// TLがまだ記述されていない場合は空配列を返す
if (tlData.bossName === '' || tlData.characters.length !== 5) {
return [];
}
let tlTextLines = [
`【${tlData.phase}段階目 ${tlData.bossName} ${tlData.damage}万】`,
];
const paddedNameList = makePaddedNameList(
tlData.characters.map((character) => character.name),
nameConversionTable,
);
tlTextLines = tlTextLines.concat(
tlData.characters.map(
(character) =>
`${paddedNameList[character.name]} ${character.star}/${character.rank}${
character.specialLv === 0 ? ' ' : `/${character.specialLv} `
}${character.comment}`,
),
);
tlTextLines.push(' ');
const lessTime = tlData.startTime - startTime;
tlTextLines.push(
`<${timeNum2Str(tlData.startTime - lessTime).substr(1)} バトル開始>`,
);
if (arrange === 'none') {
for (let i = 0; i < tlData.timeline.length; i += 1) {
const line = tlData.timeline[i];
if (line.time - lessTime < 1) {
// 時間不足によりUBが打てなければ以降をカット
break;
}
if (line.name === tlData.bossName) {
tlTextLines.push(' ');
tlTextLines.push(
`--- ${timeNum2Str(line.time - lessTime).substr(1)} BOSS --- ${
line.comment
}`,
);
tlTextLines.push(' ');
} else {
tlTextLines.push(
`${timeNum2Str(line.time - lessTime).substr(1)} ${
paddedNameList[line.name]
} ${line.comment}`,
);
}
}
} else {
let i = 0;
while (i < tlData.timeline.length) {
const line = tlData.timeline[i];
if (line.time - lessTime < 1) {
// 時間不足によりUBが打てなければ以降をカット
break;
}
if (line.name === tlData.bossName) {
tlTextLines.push(' ');
tlTextLines.push(
`--- ${timeNum2Str(line.time - lessTime).substr(1)} BOSS --- ${
line.comment
}`,
);
tlTextLines.push(' ');
} else {
let subNames = '';
for (let j = i + 1; j < tlData.timeline.length; j += 1) {
const subLine = tlData.timeline[j];
if (
subLine.name !== tlData.bossName &&
subLine.comment === '' &&
line.time === subLine.time
) {
subNames += ` ${nameConversionTable[subLine.name] ?? subLine.name}`;
i = j;
} else {
break;
}
}
if (arrange === 'same') {
tlTextLines.push(
`${timeNum2Str(line.time - lessTime).substr(1)} ${
nameConversionTable[line.name] ?? line.name
}${subNames} ${line.comment}`,
);
} else {
tlTextLines.push(
`${timeNum2Str(line.time - lessTime).substr(1)} ${
nameConversionTable[line.name] ?? line.name
} ${line.comment}`,
);
if (subNames !== '') {
tlTextLines.push(`⇒${subNames}`);
}
}
}
i += 1;
}
}
// tlTextLines = tlTextLines.concat(
// tlData.timeline.map((line) => {
// if (line.name === tlData.bossName) {
// return `--- ${timeNum2Str(line.time, true)} BOSS --- ${line.comment}`;
// }
// return `${timeNum2Str(line.time, true)} ${paddedNameList[line.name]} ${
// line.comment
// }`;
// }),
// );
tlTextLines.push(
`<${timeNum2Str(
tlData.endTime - lessTime > 0 ? tlData.endTime - lessTime : 0,
).substr(1)} バトル終了>`,
);
return tlTextLines;
};
export default formatTL;
<file_sep>import { CHARACTERS_INFO, MAX_SPECIAL_LV } from 'lib/gameConstants';
/** 01:20⇒80のように分秒表記を秒に変更 */
export const timeStr2Num = (timeStr: string): number =>
parseInt(timeStr.substr(0, 2), 10) * 60 + parseInt(timeStr.substr(3, 2), 10);
/** 80⇒01:20のように秒を分秒表記に変更 */
export const timeNum2Str = (timeNum: number): string => {
const min = Math.floor(timeNum / 60);
const sec = timeNum % 60;
return `${`00${min}`.slice(-2)}:${`00${sec}`.slice(-2)}`;
};
/** キャラ名から専用装備の有無を確認し、専用レベルのデフォルト値を返す */
export const getDefaultSpecialLv = (name: string): number => {
if (CHARACTERS_INFO[name] && CHARACTERS_INFO[name].hasSpecial) {
return MAX_SPECIAL_LV;
}
return 0;
};
// 半角は1文字 全角は2文字として文字数をカウント
const getLen = (str: string) => {
let halfCount = 0;
let fullCount = 0;
for (let i = 0; i < str.length; i += 1) {
const chr = str.charCodeAt(i);
if (
(chr >= 0x00 && chr < 0x81) ||
chr === 0xf8f0 ||
(chr >= 0xff61 && chr < 0xffa0) ||
(chr >= 0xf8f1 && chr < 0xf8f4)
) {
// 半角文字の場合は1を加算
halfCount += 1;
} else {
// それ以外の文字の場合は2を加算
fullCount += 1;
}
}
// 結果を返す
return [halfCount, fullCount];
};
/** 最大の長さの名前にあわせてパディングを入れる */
export const makePaddedNameList = (
nameList: string[],
nameConversionTable: { [key: string]: string },
): { [key: string]: string } => {
const maxHalfLength = Math.max(
...nameList.map((name) => getLen(nameConversionTable[name] ?? name)[0]),
);
const maxFullLength = Math.max(
...nameList.map((name) => getLen(nameConversionTable[name] ?? name)[1]),
);
const resultList = {};
nameList.forEach((name) => {
const [halfLength, fullLength] = getLen(nameConversionTable[name] ?? name);
resultList[name] =
(nameConversionTable[name] ?? name) +
' '.repeat(maxHalfLength - halfLength) +
' '.repeat(maxFullLength - fullLength);
});
return resultList;
};
<file_sep>import { TLState } from 'ducks/tl';
import { timeStr2Num, getDefaultSpecialLv } from 'lib/util';
import { CHARACTERS_INFO } from 'lib/gameConstants';
// プリコネのTL書き出し機能により出力された文字列から情報を抜き出す
const parseTlData = (text: string): TLState | null => {
const generateLineReader = () => {
const lines: string[] = text
.split(/\r\n|\n/)
.filter((line: string) => line !== '');
let lineIndex = 0;
return () => {
if (lineIndex < lines.length) {
lineIndex += 1;
return lines[lineIndex - 1].split(' ');
}
return [];
};
};
const lineReader = generateLineReader();
const tlData: TLState = <TLState>{};
tlData.comment = '';
// 1行目
// クランモード 5段階目 シードレイク
let line = lineReader();
if (line.length >= 3) {
if (!Number.isNaN(line[1].replace('段階目', ''))) {
tlData.phase = parseInt(line[1].replace('段階目', ''), 10);
} else {
return null;
}
[tlData.bossName] = [line[2]];
} else {
return null;
}
// 2行目
// 32702296ダメージ
line = lineReader();
if (line.length >= 1 && !Number.isNaN(line[0].replace('ダメージ', ''))) {
tlData.damage = Math.floor(
parseInt(line[0].replace('ダメージ', ''), 10) / 10000,
);
} else {
return null;
}
// 3行目
// バトル時間 01:30
line = lineReader();
// 4行目
// バトル日時 2021/06/29 22:40
line = lineReader();
// 5行目
// ----
line = lineReader();
// 6行目
// ◆パーティ編成
line = lineReader();
// 7~11行目
// アカリ ★6 Lv202 RANK14
// サレン(サマー) ★3 Lv202 RANK14
// ネネカ ★5 Lv202 RANK21
// キャル(ニューイヤー) ★4 Lv202 RANK21
// ルナ ★5 Lv202 RANK21
tlData.characters = [];
for (let i = 0; i < 5; i += 1) {
line = lineReader();
if (
line.length >= 4 &&
!Number.isNaN(line[1].replace('★', '')) &&
!Number.isNaN(line[2].replace('Lv', '')) &&
!Number.isNaN(line[3].replace('RANK', '')) &&
CHARACTERS_INFO[line[0]]
) {
tlData.characters.push({
lv: parseInt(line[2].replace('Lv', ''), 10),
name: line[0],
star: parseInt(line[1].replace('★', ''), 10),
rank: parseInt(line[3].replace('RANK', ''), 10),
specialLv: getDefaultSpecialLv(line[0]),
comment: '',
});
} else {
return null;
}
}
// 12行目
// ----
line = lineReader();
// 13行目
// ◆ユニオンバースト発動時間
line = lineReader();
// 14行目
// 01:30 バトル開始
line = lineReader();
if (line.length >= 1 && /^0[0-1]:[0-5][0-9]$/.test(line[0])) {
tlData.startTime = timeStr2Num(line[0]);
} else {
return null;
}
line = lineReader();
tlData.timeline = [];
while (line.length >= 2) {
if (line[1] === 'バトル終了' && /^0[0-1]:[0-5][0-9]$/.test(line[0])) {
tlData.endTime = timeStr2Num(line[0]);
} else if (
/^0[0-1]:[0-5][0-9]$/.test(line[0]) &&
(tlData.characters.map((character) => character.name).includes(line[1]) ||
tlData.bossName === line[1])
) {
tlData.timeline.push({
id: Math.random(),
name: line[1],
time: timeStr2Num(line[0]),
comment: '',
});
}
line = lineReader();
}
return tlData;
};
export default parseTlData;
<file_sep>import { createSlice } from '@reduxjs/toolkit';
import type { AppState } from '../app/store';
import { Character } from './tl';
export type Fav = {
phase: number;
bossName: string;
damage: number;
duration: number;
characters: Character[];
};
export type FavsState = {
favs: { [key: string]: Fav };
};
const initialState: FavsState = {
favs: {},
};
export const favsSlice = createSlice({
name: 'favs',
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
// changeHeaderFormat: (state, action: PayloadAction<string>) => {
// state.headerFormat = action.payload;
// },
},
});
// export const { changeHeaderFormat } = styleSlice.actions;
export const selectFavs = (state: AppState): { [key: string]: Fav } =>
state.favs.favs;
export default favsSlice.reducer;
<file_sep>import { configureStore /* , ThunkAction, Action */ } from '@reduxjs/toolkit';
import tlReducer from 'ducks/tl';
import styleReducer from 'ducks/style';
import favsReducer from 'ducks/favs';
import mainReducer from 'ducks/main';
import commonAlertReducer from 'ducks/commonAlert';
export function makeStore() {
return configureStore({
reducer: {
tl: tlReducer,
style: styleReducer,
favs: favsReducer,
main: mainReducer,
commonAlert: commonAlertReducer,
},
});
}
const store = makeStore();
export type AppState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
// export type AppThunk<ReturnType = void> = ThunkAction<
// ReturnType,
// AppState,
// unknown,
// Action<string>
// >
export default store;
<file_sep>import firebase from 'firebase/app';
import { TLState } from 'ducks/tl';
const TL_COLLECTION_NAME = 'tl';
if (firebase.apps.length === 0) {
const firebaseConfig = {
apiKey: '<KEY>',
authDomain: 'tlformatter.firebaseapp.com',
projectId: 'tlformatter',
storageBucket: 'tlformatter.appspot.com',
messagingSenderId: '718811297260',
appId: '1:718811297260:web:ddb8ad68b51b9bbc293cc9',
measurementId: 'G-4CP0QKZ23X',
};
firebase.initializeApp(firebaseConfig);
}
const storeTL: (tlData: TLState) => void = async (tlData) => {
const db = firebase.firestore();
await db.collection(TL_COLLECTION_NAME).add(tlData);
};
export default storeTL;
<file_sep>export const MAX_RANK = 22;
export const MAX_LV = 211;
export const MAX_SPECIAL_LV = 220;
export const MAX_STAR = 6;
export const MAX_PHASE = 5;
export const MAX_DAMAGE = 999999999;
export const BOSSES_INFO = {
アクアリオス: {},
アルゲティ: {},
オークチーフ: {},
オブシダンワイバーン: {},
オルレオン: {},
カルキノス: {},
グラットン: {},
ゴブリングレート: {},
サイクロプス: {},
シードレイク: {},
スカイワルキューレ: {},
ソードコブラ: {},
ダークガーゴイル: {},
ツインピッグス: {},
ティタノタートル: {},
トライロッカー: {},
トルペドン: {},
ニードルクリーパー: {},
ネプテリオン: {},
バジリスク: {},
'マスター・センリ': {},
マダムプリズム: {},
マッドベア: {},
ミノタウロス: {},
ムーバ: {},
ムシュフシュ: {},
メガラバーン: {},
メサルティム: {},
メデューサ: {},
ライデン: {},
ライライ: {},
ランドスロース: {},
レイスロード: {},
レサトパルト: {},
ワイバーン: {},
ワイルドグリフォン: {},
};
export const CHARACTERS_INFO: {
[key: string]: {
maxStar: number;
position: number;
hasSpecial: boolean;
defaultShortName?: string;
};
} = {
リマ: {
maxStar: 6,
position: 105,
hasSpecial: true,
},
ミヤコ: {
maxStar: 5,
position: 125,
hasSpecial: true,
},
クウカ: {
maxStar: 5,
position: 130,
hasSpecial: true,
},
ジュン: {
maxStar: 5,
position: 135,
hasSpecial: true,
},
'ムイミ(ニューイヤー)': {
maxStar: 5,
position: 138,
hasSpecial: false,
defaultShortName: 'ニュイミ',
},
'クウカ(オーエド)': {
maxStar: 5,
position: 140,
hasSpecial: true,
defaultShortName: 'オウカ',
},
カオリ: {
maxStar: 6,
position: 145,
hasSpecial: true,
},
'サレン(クリスマス)': {
maxStar: 5,
position: 150,
hasSpecial: false,
defaultShortName: 'クリサレ',
},
'ツムギ(ハロウィン)': {
maxStar: 5,
position: 152,
hasSpecial: false,
defaultShortName: 'ハロツム',
},
'レイ(ニューイヤー)': {
maxStar: 5,
position: 153,
hasSpecial: true,
defaultShortName: 'ニュレイ',
},
'リン(デレマス)': {
maxStar: 5,
position: 153.1,
hasSpecial: true,
defaultShortName: 'デレリン',
},
ペコリーヌ: {
maxStar: 6,
position: 155,
hasSpecial: true,
defaultShortName: 'ペコ',
},
'ペコリーヌ(プリンセス)': {
maxStar: 5,
position: 155.1,
hasSpecial: false,
defaultShortName: 'プリペコ',
},
ルカ: {
maxStar: 5,
position: 158,
hasSpecial: true,
},
'コッコロ(ニューイヤー)': {
maxStar: 5,
position: 159,
hasSpecial: true,
defaultShortName: 'ニュコロ',
},
ノゾミ: {
maxStar: 6,
position: 160,
hasSpecial: true,
},
ムイミ: {
maxStar: 5,
position: 162,
hasSpecial: true,
},
'シズル(サマー)': {
maxStar: 5,
position: 163,
hasSpecial: false,
defaultShortName: '水シズル',
},
マコト: {
maxStar: 5,
position: 165,
hasSpecial: true,
},
'マコト(シンデレラ)': {
maxStar: 5,
position: 166,
hasSpecial: false,
defaultShortName: 'デレマコ',
},
カヤ: {
maxStar: 5,
position: 168,
hasSpecial: true,
},
'カヤ(タイムトラベル)': {
maxStar: 5,
position: 169,
hasSpecial: false,
defaultShortName: 'カヤベル',
},
'ヒヨリ(ニューイヤー)': {
maxStar: 5,
position: 170,
hasSpecial: true,
defaultShortName: 'ニュヨリ',
},
'リマ(シンデレラ)': {
maxStar: 5,
position: 173,
hasSpecial: false,
defaultShortName: 'デレリマ',
},
'ニノン(オーエド)': {
maxStar: 5,
position: 175,
hasSpecial: true,
defaultShortName: 'オノン',
},
アキノ: {
maxStar: 6,
position: 180,
hasSpecial: true,
},
'マコト(サマー)': {
maxStar: 5,
position: 180.1,
hasSpecial: true,
defaultShortName: '水マコ',
},
'ジュン(サマー)': {
maxStar: 5,
position: 182,
hasSpecial: true,
defaultShortName: '水ジュン',
},
'クロエ(聖学祭)': {
maxStar: 5,
position: 184,
hasSpecial: false,
defaultShortName: '聖クロエ',
},
マツリ: {
maxStar: 5,
position: 185,
hasSpecial: true,
},
クロエ: {
maxStar: 5,
position: 185.1,
hasSpecial: true,
},
'マツリ(ハロウィン)': {
maxStar: 5,
position: 186,
hasSpecial: true,
defaultShortName: 'ハロマツ',
},
'エリコ(バレンタイン)': {
maxStar: 5,
position: 187,
hasSpecial: true,
defaultShortName: 'バレエリコ',
},
'アキノ(クリスマス)': {
maxStar: 5,
position: 189,
hasSpecial: false,
defaultShortName: 'クリアキノ',
},
'アヤネ(クリスマス)': {
maxStar: 5,
position: 190,
hasSpecial: true,
defaultShortName: 'クリキチ',
},
'ルカ(サマー)': {
maxStar: 5,
position: 192,
hasSpecial: true,
defaultShortName: '水ルカ',
},
ツムギ: {
maxStar: 5,
position: 195,
hasSpecial: true,
},
イノリ: {
maxStar: 5,
position: 197,
hasSpecial: true,
},
'ヒヨリ(プリンセス)': {
maxStar: 5,
position: 199,
hasSpecial: false,
defaultShortName: 'プヨリ',
},
ヒヨリ: {
maxStar: 6,
position: 200,
hasSpecial: true,
},
ミソギ: {
maxStar: 6,
position: 205,
hasSpecial: true,
},
アヤネ: {
maxStar: 6,
position: 210,
hasSpecial: true,
},
'ミソギ(ハロウィン)': {
maxStar: 5,
position: 212,
hasSpecial: true,
defaultShortName: 'ハロミソ',
},
タマキ: {
maxStar: 6,
position: 215,
hasSpecial: true,
},
'タマキ(作業服)': {
maxStar: 5,
position: 216,
hasSpecial: false,
defaultShortName: '作タマ',
},
トモ: {
maxStar: 5,
position: 220,
hasSpecial: true,
},
チエル: {
maxStar: 5,
position: 222,
hasSpecial: true,
},
'チエル(聖学祭)': {
maxStar: 5,
position: 223,
hasSpecial: false,
defaultShortName: '聖チエル',
},
'タマキ(サマー)': {
maxStar: 5,
position: 225,
hasSpecial: true,
defaultShortName: '水タマ',
},
エリコ: {
maxStar: 5,
position: 230,
hasSpecial: true,
},
'ペコリーヌ(サマー)': {
maxStar: 5,
position: 235,
hasSpecial: true,
defaultShortName: '水ペコ',
},
クルミ: {
maxStar: 6,
position: 240,
hasSpecial: true,
},
ジータ: {
maxStar: 6,
position: 245,
hasSpecial: true,
},
'ペコリーヌ(ニューイヤー)': {
maxStar: 5,
position: 248,
hasSpecial: true,
defaultShortName: 'ニュペコ',
},
レイ: {
maxStar: 6,
position: 250,
hasSpecial: true,
},
'イノリ(タイムトラベル)': {
maxStar: 5,
position: 252,
hasSpecial: false,
defaultShortName: 'タイノリ',
},
'イリヤ(クリスマス)': {
maxStar: 5,
position: 255,
hasSpecial: true,
defaultShortName: 'クリヤ',
},
'アンナ(サマー)': {
maxStar: 5,
position: 256,
hasSpecial: true,
defaultShortName: '水アンナ',
},
'クリスティーナ(クリスマス)': {
maxStar: 5,
position: 265,
hasSpecial: true,
defaultShortName: 'クリクリス',
},
'ミフユ(作業服)': {
maxStar: 5,
position: 275,
hasSpecial: false,
defaultShortName: 'サフユ',
},
シズル: {
maxStar: 6,
position: 285,
hasSpecial: true,
},
クリスティーナ: {
maxStar: 5,
position: 290,
hasSpecial: true,
defaultShortName: 'クリス',
},
'クルミ(クリスマス)': {
maxStar: 5,
position: 295,
hasSpecial: true,
defaultShortName: 'クリクルミ',
},
'ツムギ(サマー)': {
maxStar: 5,
position: 355,
hasSpecial: false,
defaultShortName: '水ツムギ',
},
ミミ: {
maxStar: 6,
position: 360,
hasSpecial: true,
},
シノブ: {
maxStar: 5,
position: 365,
hasSpecial: true,
},
'ミミ(ハロウィン)': {
maxStar: 5,
position: 365.1,
hasSpecial: true,
defaultShortName: 'ハロミミ',
},
シェフィ: {
maxStar: 5,
position: 368,
hasSpecial: false,
},
'ウヅキ(デレマス)': {
maxStar: 5,
position: 370,
hasSpecial: true,
defaultShortName: 'ウヅキ',
},
'レイ(ハロウィン)': {
maxStar: 5,
position: 375,
hasSpecial: true,
defaultShortName: 'ハロレイ',
},
'レイ(プリンセス)': {
maxStar: 5,
position: 377,
hasSpecial: false,
defaultShortName: 'プリレイ',
},
'シズル(バレンタイン)': {
maxStar: 5,
position: 385,
hasSpecial: true,
defaultShortName: 'バレシズ',
},
'マヒル(レンジャー)': {
maxStar: 5,
position: 390,
hasSpecial: true,
defaultShortName: '卍',
},
マヒル: {
maxStar: 6,
position: 395,
hasSpecial: true,
},
'トモ(マジカル)': {
maxStar: 5,
position: 402,
hasSpecial: false,
defaultShortName: 'ニートモ',
},
ユカリ: {
maxStar: 6,
position: 405,
hasSpecial: true,
},
'エリコ(サマー)': {
maxStar: 5,
position: 407,
hasSpecial: false,
defaultShortName: '水エリコ',
},
'ユカリ(クリスマス)': {
maxStar: 5,
position: 408,
hasSpecial: false,
defaultShortName: 'Xユカリ',
},
モニカ: {
maxStar: 5,
position: 410,
hasSpecial: true,
},
ニノン: {
maxStar: 6,
position: 415,
hasSpecial: true,
},
'ノゾミ(サマー)': {
maxStar: 5,
position: 417,
hasSpecial: false,
defaultShortName: '水ノゾミ',
},
'ノゾミ(クリスマス)': {
maxStar: 5,
position: 418,
hasSpecial: true,
defaultShortName: 'Xノゾミ',
},
ミフユ: {
maxStar: 6,
position: 420,
hasSpecial: true,
},
'リン(レンジャー)': {
maxStar: 5,
position: 422,
hasSpecial: true,
defaultShortName: 'リンジャー',
},
イリヤ: {
maxStar: 5,
position: 425,
hasSpecial: true,
},
'カオリ(サマー)': {
maxStar: 5,
position: 425.1,
hasSpecial: true,
defaultShortName: '水カオリ',
},
サレン: {
maxStar: 6,
position: 430,
hasSpecial: true,
},
アンナ: {
maxStar: 5,
position: 440,
hasSpecial: true,
},
'シノブ(ハロウィン)': {
maxStar: 5,
position: 440.1,
hasSpecial: true,
defaultShortName: 'ハロシノ',
},
'ナナカ(サマー)': {
maxStar: 5,
position: 468,
hasSpecial: true,
defaultShortName: '水ナナカ',
},
'ミフユ(サマー)': {
maxStar: 5,
position: 495,
hasSpecial: true,
defaultShortName: '水ミフユ',
},
コッコロ: {
maxStar: 6,
position: 500,
hasSpecial: true,
},
'アユミ(ワンダー)': {
maxStar: 5,
position: 508,
hasSpecial: true,
defaultShortName: 'ワユミ',
},
アユミ: {
maxStar: 5,
position: 510,
hasSpecial: true,
},
'チカ(サマー)': {
maxStar: 5,
position: 520,
hasSpecial: false,
defaultShortName: '水チカ',
},
グレア: {
maxStar: 5,
position: 525,
hasSpecial: true,
},
'アオイ(作業服)': {
maxStar: 5,
position: 527,
hasSpecial: false,
defaultShortName: 'サオイ',
},
'モニカ(マジカル)': {
maxStar: 5,
position: 528,
hasSpecial: false,
defaultShortName: 'ラブモニ',
},
'アカリ(エンジェル)': {
maxStar: 5,
position: 530,
hasSpecial: true,
defaultShortName: '天アカリ',
},
'ヨリ(エンジェル)': {
maxStar: 5,
position: 531,
hasSpecial: true,
defaultShortName: '天ヨリ',
},
'コッコロ(儀装束)': {
maxStar: 5,
position: 533,
hasSpecial: false,
defaultShortName: 'ギッコロ',
},
'コッコロ(サマー)': {
maxStar: 5,
position: 535,
hasSpecial: true,
defaultShortName: '水コロ',
},
レム: {
maxStar: 5,
position: 540,
hasSpecial: true,
},
ラム: {
maxStar: 5,
position: 545,
hasSpecial: true,
},
リン: {
maxStar: 5,
position: 550,
hasSpecial: true,
},
'ミツキ(オーエド)': {
maxStar: 5,
position: 552,
hasSpecial: false,
defaultShortName: 'オツキ',
},
'コッコロ(プリンセス)': {
maxStar: 5,
position: 555,
hasSpecial: false,
defaultShortName: 'セスコ',
},
ラビリスタ: {
maxStar: 5,
position: 560,
hasSpecial: false,
defaultShortName: 'ラビリ',
},
'ネネカ(ニューイヤー)': {
maxStar: 5,
position: 562,
hasSpecial: false,
defaultShortName: '傘',
},
ミツキ: {
maxStar: 5,
position: 565,
hasSpecial: true,
},
'ハツネ(サマー)': {
maxStar: 5,
position: 567,
hasSpecial: true,
defaultShortName: '水ハツネ',
},
アカリ: {
maxStar: 6,
position: 570,
hasSpecial: true,
},
ヨリ: {
maxStar: 6,
position: 575,
hasSpecial: true,
},
'ユイ(儀装束)': {
maxStar: 5,
position: 578,
hasSpecial: false,
defaultShortName: 'ギュイ',
},
'サレン(サマー)': {
maxStar: 5,
position: 585,
hasSpecial: true,
defaultShortName: '水サレ',
},
'ミヤコ(ハロウィン)': {
maxStar: 5,
position: 590,
hasSpecial: true,
defaultShortName: 'ハロプリン',
},
アリサ: {
maxStar: 5,
position: 625,
hasSpecial: true,
},
アン: {
maxStar: 5,
position: 630,
hasSpecial: true,
},
ルゥ: {
maxStar: 5,
position: 640,
hasSpecial: true,
},
'マホ(シンデレラ)': {
maxStar: 5,
position: 645,
hasSpecial: false,
defaultShortName: 'デレマホ',
},
ネネカ: {
maxStar: 5,
position: 660,
hasSpecial: true,
},
'アオイ(編入生)': {
maxStar: 5,
position: 680,
hasSpecial: true,
defaultShortName: 'ヘオイ',
},
'キャル(ニューイヤー)': {
maxStar: 5,
position: 690,
hasSpecial: false,
defaultShortName: 'ニャル',
},
'ミオ(デレマス)': {
maxStar: 5,
position: 695,
hasSpecial: true,
defaultShortName: 'ミオ',
},
'ミサト(サマー)': {
maxStar: 5,
position: 697,
hasSpecial: true,
defaultShortName: '水ミサト',
},
リノ: {
maxStar: 6,
position: 700,
hasSpecial: true,
},
スズナ: {
maxStar: 5,
position: 705,
hasSpecial: true,
},
'スズナ(サマー)': {
maxStar: 5,
position: 705.1,
hasSpecial: true,
defaultShortName: '水菜',
},
シオリ: {
maxStar: 5,
position: 710,
hasSpecial: true,
},
'シオリ(マジカル)': {
maxStar: 5,
position: 712,
hasSpecial: true,
defaultShortName: 'マオリ',
},
イオ: {
maxStar: 5,
position: 715,
hasSpecial: true,
},
'イオ(サマー)': {
maxStar: 5,
position: 715.1,
hasSpecial: true,
defaultShortName: '水イオ',
},
スズメ: {
maxStar: 5,
position: 720,
hasSpecial: true,
},
'スズメ(ニューイヤー)': {
maxStar: 5,
position: 722,
hasSpecial: true,
defaultShortName: 'ニュズメ',
},
エミリア: {
maxStar: 5,
position: 725,
hasSpecial: true,
},
カスミ: {
maxStar: 5,
position: 730,
hasSpecial: true,
},
'カスミ(マジカル)': {
maxStar: 5,
position: 730.1,
hasSpecial: true,
defaultShortName: 'マジカス',
},
'リノ(ワンダー)': {
maxStar: 5,
position: 730.2,
hasSpecial: true,
defaultShortName: 'ワリノ',
},
'ハツネ&シオリ': {
maxStar: 5,
position: 732,
hasSpecial: false,
defaultShortName: 'ハツシオ',
},
ミサト: {
maxStar: 5,
position: 735,
hasSpecial: true,
},
'カスミ(サマー)': {
maxStar: 5,
position: 738,
hasSpecial: true,
defaultShortName: '水カス',
},
ナナカ: {
maxStar: 5,
position: 740,
hasSpecial: true,
},
'ユイ(ニューイヤー)': {
maxStar: 5,
position: 745,
hasSpecial: true,
defaultShortName: 'ニュイ',
},
'キャル(プリンセス)': {
maxStar: 5,
position: 747,
hasSpecial: false,
defaultShortName: 'プリキャル',
},
キャル: {
maxStar: 6,
position: 750,
hasSpecial: true,
},
ハツネ: {
maxStar: 6,
position: 755,
hasSpecial: true,
},
ミサキ: {
maxStar: 5,
position: 760,
hasSpecial: true,
},
ルナ: {
maxStar: 5,
position: 765,
hasSpecial: true,
},
'ユイ(プリンセス)': {
maxStar: 5,
position: 767,
hasSpecial: false,
defaultShortName: 'プリユイ',
},
'チカ(クリスマス)': {
maxStar: 5,
position: 770,
hasSpecial: true,
defaultShortName: 'クリチカ',
},
'スズメ(サマー)': {
maxStar: 5,
position: 775,
hasSpecial: true,
defaultShortName: '水メ',
},
'キャル(サマー)': {
maxStar: 5,
position: 780,
hasSpecial: true,
defaultShortName: '水キャル',
},
アオイ: {
maxStar: 6,
position: 785,
hasSpecial: true,
},
チカ: {
maxStar: 5,
position: 790,
hasSpecial: true,
},
'マホ(サマー)': {
maxStar: 5,
position: 792,
hasSpecial: true,
defaultShortName: '水マホ',
},
マホ: {
maxStar: 6,
position: 795,
hasSpecial: true,
},
ユイ: {
maxStar: 6,
position: 800,
hasSpecial: true,
},
ユキ: {
maxStar: 5,
position: 805,
hasSpecial: true,
},
ユニ: {
maxStar: 5,
position: 807,
hasSpecial: true,
},
キョウカ: {
maxStar: 6,
position: 810,
hasSpecial: true,
},
'ミサキ(ハロウィン)': {
maxStar: 5,
position: 815,
hasSpecial: true,
defaultShortName: 'ハロミサ',
},
'キョウカ(ハロウィン)': {
maxStar: 5,
position: 820,
hasSpecial: true,
defaultShortName: 'ハロキョ',
},
};
<file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { AppState } from '../app/store';
export type TabType = 'tl' | 'format' | 'name' | 'config' | 'output' | 'favs';
export type MainState = {
activeTab: TabType;
};
const initialState: MainState = {
activeTab: 'tl',
};
export const mainSlice = createSlice({
name: 'main',
initialState,
reducers: {
changeActiveTab: (
state,
action: PayloadAction<{
activeTab: TabType;
}>,
) => {
state.activeTab = action.payload.activeTab;
},
},
});
export const { changeActiveTab } = mainSlice.actions;
export const selectActiveTab = (state: AppState): TabType =>
state.main.activeTab;
export default mainSlice.reducer;
| 7be7faae3ee96ac6d4a505e67793894ec0b11ece | [
"JavaScript",
"TypeScript"
] | 12 | TypeScript | pacifist24/pricone_tl_app | 8b94a4aacf846d67ded647fc6b322cf7527e72bc | 2ff85dca464dd7db2cc8918626ed74446aa8679f |
refs/heads/master | <repo_name>OssamaGh/Gulpv4<file_sep>/gulpfile.js
//Project Code used in the asset directories
const projectCode = "LRS";
//scss OR sass?
const projectType = "scss";
//Directory
const directory = "./MY-DIRECTORY/" + projectCode;
//Asset Directories
const buildDir = directory + '/bundles';
const cssDir = directory + '/css/';
const projectTypeDir = directory + '/scss/';
const jsDir = directory + '/js/';
//Initialization of packages
var gulp = require('gulp');
var concat = require('gulp-concat');
var scss = require('gulp-sass');
var debug = require('gulp-debug');
var cleanCSS = require('gulp-clean-css');
var minify = require("gulp-minify");
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var del = require('del');
function compile() {
return gulp
.src(projectTypeDir + 'app.scss')
.pipe(sourcemaps.init())
.pipe(debug())
.pipe(scss())
.pipe(sourcemaps.write("./maps"))
.pipe(gulp.dest(cssDir));
}
function minifyCSS() {
return gulp.src(cssDir + "app.css")
.pipe(cleanCSS({
compatibility: 'ie8'
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest(cssDir));
}
function deleteCustomCSS() {
return gulp.src(cssDir + 'app.min.css', {
force: true
})
.pipe(clean());
}
function watchScss() {
return gulp.watch(projectTypeDir + '**/*.' + projectType)
.on('change', function (path) {
console.log(path);
compile();
})
.on('unlink', function (path) {
console.log(path);
});
}
//Clean Functions
function removeJS() {
return del([
buildDir + '/*.js'
]);
}
function removeCSS() {
return del([
buildDir + '/*.css'
]);
}
//Build Functions
function packJS(done) {
done();
return gulp
.src([
jsDir + "app.min.js",
jsDir + "vendor/jquery.flexslider.js"
])
.pipe(concat("app.bundle.js"))
.pipe(minify({
ext: {
min: ".js"
},
noSource: true
}))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest(buildDir));
}
function packCSS(done) {
done();
return gulp
.src([
cssDir + "app.css",
cssDir + "vendor/fontawesome.css",
cssDir + "vendor/flexslider.css"
])
.pipe(concat("app.bundle.css"))
.pipe(cleanCSS({
compatibility: "ie8"
}))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest(buildDir));
}
function done(done) {
return done();
}
gulp.task(projectType, compile);
gulp.task('minify-css', minifyCSS);
gulp.task('delete-minified-css', deleteCustomCSS);
gulp.task('watch', watchScss);
gulp.task('clean-js', removeJS);
gulp.task('clean-css', removeCSS);
gulp.task('pack-js', gulp.series(removeJS, packJS));
gulp.task('pack-css', gulp.series(removeCSS, packCSS));
gulp.task('build', gulp.series('scss', 'pack-css', 'pack-js', done));<file_sep>/README.md
# Gulpv4
A Gulp file running on gulpv4 for SCSS and SASS
| 46d08161ed6e78953963d408cd95366949d8525d | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | OssamaGh/Gulpv4 | a5c08d1a9cc94839c291323d3ff8daec3bf70712 | bab8c63de7df1e1efbc4aea575c92a53f33d0c7c |
refs/heads/master | <repo_name>nokisnojok/useful-for-everything<file_sep>/stream-iframe/index.js
function streamXHR(content = document.body) {
const iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
iframe.onload = () => {
iframe.onload = null;
const xhr = new XMLHttpRequest();
let pos = 0;
xhr.onprogress = function() {
iframe.contentDocument.write(xhr.response.slice(pos));
pos = xhr.response.length;
while (iframe.contentDocument.body.childNodes.length > 0) {
content.appendChild(iframe.contentDocument.body.childNodes[0]);
}
};
xhr.onload = function() {
iframe.contentDocument.close();
document.body.removeChild(iframe);
};
xhr.responseType = "text";
xhr.open("GET", "/"); // get some html
xhr.send();
};
iframe.src = "";
}
<file_sep>/RequestAnimationFrameManager/index.ts
class RequestAnimationFrameManager {
callBacks: Function[] = [];
timer: any = null;
constructor(public animationFrameProvider: AnimationFrameProvider) {
}
start() {
const self = this;
this.timer = self.animationFrameProvider.requestAnimationFrame(function f() {
self.callBacks.forEach(fn => {
fn()
})
self.timer = self.animationFrameProvider.requestAnimationFrame(f);
})
}
stop() {
this.animationFrameProvider.cancelAnimationFrame(this.timer);
this.timer = null;
}
addLoop(fn: Function) {
this.callBacks.push(fn)
if (this.timer === null) {
this.start();
}
return fn;
}
removeLoop(fn: Function) {
const index = this.callBacks.findIndex(i => i === fn);
if (index === -1) {
return false;
}
this.callBacks.splice(index, 1);
if (this.callBacks.length === 0) {
this.stop();
}
return true;
}
}<file_sep>/navigator-send-beacon/server.js
require("http")
.createServer(function (req, res) {
if (req.method === "POST") {
let buf = Buffer.from("");
req.on("data", (chunk) => {
buf = Buffer.concat([buf, chunk]);
});
req.on("end", () => {
console.log("req headers", req.headers);
console.log("post data", buf.toString());
res.end(buf.toString());
});
}
})
.listen(3333, () => {
console.log("server start at http://localhost:3333");
});
<file_sep>/jsx-htm/dist-c/index.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _core = _interopRequireDefault(require("./core.js"));
var _react = _interopRequireDefault(require("react"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function A(props) {
return (0, _core.default)`<h1 className=${props.className}>${props.name}</h1>`;
}
function _default(props) {
return (0, _core.default)`<div ...${props}><${A} ...${props}/></div>`;
} | 76a381e4e3d4040a0f74667192a22c42bb2b16a0 | [
"JavaScript",
"TypeScript"
] | 4 | JavaScript | nokisnojok/useful-for-everything | 79a7e565bbd070f5034aee7fc5a5dba62f524fd6 | 3983178e6dea138832f0e491d84c60bc38942f78 |
refs/heads/master | <repo_name>ChausAnton/chronos-anchaus<file_sep>/laravel/app/Http/Controllers/EventController.php
<?php
namespace App\Http\Controllers;
use App\Models\Events;
use Illuminate\Http\Request;
use DB;
class EventController extends Controller
{
public function getEventsForCalendar($id)
{
$calendar = DB::select("select * from calendars where id = $id;");
if(!$calendar)
return response("not found", 404);
if(auth()->user() && auth()->user()->id == $calendar[0]->calendar_author_id) {
return DB::select("select * from events where event_calendar_id = $id;");
}
return response("Forbidden", 403);
}
public function createEventForCalendar(Request $request, $id)
{
$calendar = DB::select("select * from calendars where id = $id;");
if(!$calendar)
return response(["message" => "not found"], 404);
$validated = $request->validate([
'event_content' => 'required|string',
'event_title' => 'required|string',
'event_date' => 'required|date|date_format:Y-m-d',
'event_category' => 'required|in:arrangement,reminder,task',
'event_duration' => 'required|date|date_format:Y-m-d|after_or_equal:event_date'
]);
if(auth()->user() && auth()->user()->id == $calendar[0]->calendar_author_id) {
$data = [
'event_author_id' => auth()->user()->id,
'event_calendar_id' => $id,
'event_content' => $validated['event_content'],
'event_title' => $validated['event_title'],
'event_date' => $validated['event_date'],
'event_category' => $validated['event_category'],
'event_duration' => $validated['event_duration']
];
return Events::create($data);
}
return response(["message" => "Forbidden"], 403);
}
public function getEventForCalendar($id, $eventId)
{
$calendar = DB::select("select * from calendars where id = $id;");
if(!$calendar)
return response("not found", 404);
if(auth()->user() && auth()->user()->id == $calendar[0]->calendar_author_id) {
return DB::select("select * from events where id = $eventId;");
}
return response("Forbidden", 403);
}
public function DeleteEventFromCalendar($id, $eventId)
{
$calendar = DB::select("select * from calendars where id = $id;");
if(!$calendar)
return response("not found", 404);
if(auth()->user() && auth()->user()->id == $calendar[0]->calendar_author_id) {
return Events::destroy($eventId);
}
return response("Forbidden", 403);
}
}
<file_sep>/laravel/app/Support/helpers.php
<?php
//include '/Users/antoncaus/Desktop/usoft/app/Http/Controllers/CategorySubTableController.php';
use App\Models\User;
use App\Models\Post;
use App\Models\Comment;
use Illuminate\Http\Request;
function isAdmin($user) {
if(!$user || strcmp($user->role, 'admin') != 0) {
return false;
}
return true;
}
function isUser($token, $userId) {
$user = User::find($userId);
if($user && strcmp($token, $user->token) == 0) {
return true;
}
return false;
}
function getUserByLogin($login) {
return DB::table('users')->where('login', $login)->first();
}
function getOnlyAtivePosts($id) {
if($id) {
return DB::select("select * from posts where status = 'active' and id = $id;");
}
return DB::select("select * from posts where status = 'active';");
}
function getOnlyAtiveComments($id, $post_id) {
if($id) {
return DB::select("select * from comments where status = 'active' and id = $id;");
}
if($post_id) {
return DB::select("select * from comments where status = 'active' and post_id = $post_id;");
}
return DB::select("select * from comments where status = 'active';");
}
function changeRating($post_id, $comment_id, $like) {
$author_id = 0;
if($comment_id) {
$author_id = DB::table('comments')->where('id', $comment_id)->first()->user_id;
//$author_id = DB::select("select * from comments where id = $comment_id;")[0]->user_id;
$Comment = Comment::find($comment_id);
if(strcmp($like, 'like') == 0)
$Comment->rating++;
else
$Comment->rating--;
$Comment->save();
}
else {
$author_id = DB::select("select * from posts where id = $post_id;")[0]->author_id;
$post = Post::find($post_id);
if(strcmp($like, 'like') == 0)
$post->likes++;
else
$post->likes--;
$post->save();
}
$user = User::find($author_id);
if(strcmp($like, 'like') == 0)
$user->rating++;
else
$user->rating--;
$user->save();
}
function filter($posts, Request $request) {
if ($request->header('dateStart') != null) {
return $posts->whereBetween('created_at', [$request->header('dateStart'), $request->header('dateEnd')])->all();
}
if(strcmp($request->header('filter'), 'status') == 0 && isAdmin(auth()->user())) {
return $posts->where('status', $request->header('filter_status'))->all();
}
if(strcmp($request->header('filter'), 'category') == 0) {
$str = "";
$i = 0;
foreach(explode(" ", $request->header('categories')) as $id) {
if($i > 0)
$str .= " or ";
$str .= "category_id = " . $id;
$i += 1;
}
$postsID = DB::select("select distinct post_id from category_sub where " . $str . ";");
$res = array();
foreach($postsID as $id) {
array_push($res, Post::find($id->post_id));
}
return $res;
}
}
function applySortingFiltersAdmin($posts, Request $request) {
if($request->header('filter') != null) {
return filter($posts, $request);
}
$sort = $request->header('sort');
if ($sort == null)
$sort = 'likes';
switch ($sort) {
case 'likes':
return array_values($posts->sortByDesc('likes')->all());
break;
case 'likes-asc':
return array_values($posts->sortBy('likes')->all());
break;
case 'date':
return array_values($posts->sortBy('created_at')->all());
break;
case 'date-desc':
return array_values($posts->sortByDesc('created_at')->all());
break;
default:
return array_values($posts->sortByDesc('likes')->all());
break;
}
}
function applySortingFiltersUser($posts, Request $request) {
if($request->header('filter') != null) {
return filter($posts, $request);
}
$sort = $request->header('sort');
if ($sort == null)
$sort = 'likes';
switch ($sort) {
case 'likes':
return array_values($posts->sortByDesc('likes')->where('status', 'active')->all());
break;
case 'likes-asc':
return array_values($posts->sortBy('likes')->where('status', 'active')->all());
break;
case 'date':
return array_values($posts->sortBy('created_at')->where('status', 'active')->all());
break;
case 'date-desc':
return array_values($posts->sortByDesc('created_at')->where('status', 'active')->all());
break;
default:
return array_values($posts->sortByDesc('likes')->where('status', 'active')->all());
break;
}
}
// function addCategories($cat_id, $post_id) {
// $CategorySub = New CategorySubTableController();
// $CategorySub->addCategory($cat_id, $post_id);
// }
<file_sep>/laravel/app/Http/Controllers/Admin/LikesCrudController.php
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController as ControllersCrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use App\Models\Like;
use DB;
class LikesCrudController extends ControllersCrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation { update as traitUpdate; }
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation { destroy as traitDestroy; }
public function setup() {
CRUD::setModel(\App\Models\Like::class);
CRUD::setRoute(config('backpack.base.route_prefix') . '/like');
CRUD::setEntityNameStrings('Like', 'Likes');
}
protected function setupShowOperation() {
CRUD::removeButton('update');
}
protected function setupListOperation() {
CRUD::removeButton('update');
CRUD::column('id');
CRUD::setFromDb();
}
protected function setupCreateOperation() {
CRUD::removeButton('update');
CRUD::field('type');
CRUD::addField([
'name' => 'postId',
'label' => 'post id',
'type' => 'text'
]);
CRUD::addField([
'name' => 'commentId',
'label' => 'comment id',
'type' => 'text'
]);
CRUD::modifyField('type', [
'type' => 'enum',
]);
}
protected function setupUpdateOperation() {
CRUD::removeButton('update');
}
public function store()
{
$validated = request()->validate([
'postId' => 'required_without:commentId',
'commentId' => 'required_without:postId',
'Type' => 'in:like,dislike',
]);
if(request()->postId)
$like = DB::select("select * from likes where user_id = " . backpack_user()->id . " and post_id = " . request()->postId . ";");
else
$like = DB::select("select * from likes where user_id = " . backpack_user()->id . " and comment_id = " . request()->commentId . ";");
if(!$like) {
changeRating(request()->postId, request()->commentId, request()->input('type'));
$data = [
'author' => backpack_user()->login,
'user_id' => backpack_user()->id,
'post_id' => request()->input('postId'),
'comment_id' => request()->input('ccommentId'),
'type' => request()->input('type'),
];
$like_res = Like::create($data);
return redirect('/admin/like/' . $like_res->id . '/show');
}
elseif($like && strcmp($like[0]->type, request()['type']) != 0) {
changeRating(request()->postId, request()->commentId, request()->input('type'));
if(request()->postId)
DB::delete("delete from likes where user_id = " . backpack_user()->id . " and post_id = " . request()->postId . ";");
else
DB::delete("delete from likes where user_id = " . backpack_user()->id . " and comment_id = " . request()->commentId . ";");
$data = [
'author' => backpack_user()->login,
'user_id' => backpack_user()->id,
'post_id' => request()->input('postId'),
'comment_id' => request()->input('commentId'),
'type' => request()->input('type'),
];
$like_res = Like::create($data);
return redirect('/admin/like/' . $like_res->id . '/show');
}
return redirect('/admin/like/');
}
}
<file_sep>/client/src/components/Calendar.js
import React, {useContext} from "react";
import { useHistory } from 'react-router-dom';
import {AuthContext} from '../context/AuthContext'
import { useHttp } from '../hooks/http.hook';
export const Calendar = ({calendar, month}) => {
const history = useHistory();
const {token} = useContext(AuthContext);
const {request} = useHttp();
let eventsDates = [];
if(calendar.events.length !== 0) {
eventsDates = calendar.events.map((event) => {
return event.event_date.split(' ')[0]
})
}
const moveToCalendarPage = (event) => {
event.preventDefault();
history.push(`/calendarpage/${calendar.calendar.id}`)
}
const RemoveCalendar = async(event) => {
event.preventDefault()
try {
await request('/api/DeleteCalendar/' + calendar.calendar.id, 'DELETE', null, {'Authorization': token})
}
catch (e) {}
history.push(`/`)
}
return (
<div className="card">
<div className="card-panel teal DaysBlockGrid" onClick={moveToCalendarPage}>
{
month.map((day, index) => {
const className = eventsDates.indexOf(day) !== -1 ? "DayBlock DayBlockWithEvent" : "DayBlock"
return (
<div key={index} className={ index === 0 ? "MonthBlock white-text" : className}>
<div>
<p className="white-text">
{day !== 0 ? day.indexOf('-') !== -1 ? parseInt(day.split('-').slice(-1)[0]) : day : ''}
</p>
</div>
</div>
)
})
}
</div>
<div className="card-content center">
<span className="card-title grey-text text-darken-4">{calendar.calendar.calendar_title}</span>
<button className="btn btn-large waves-effect waves-light red" onClick={RemoveCalendar}>Remove Calendar</button>
</div>
</div>
);
}<file_sep>/laravel/app/Http/Controllers/CalendarController.php
<?php
namespace App\Http\Controllers;
use App\Models\Calendar;
use Illuminate\Http\Request;
use DB;
class CalendarController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function getCalendarsForUser()
{
if(!auth()->user())
return response("Forbidden", 403);
$user_id = auth()->user()->id;
return DB::select("select * from calendars where calendar_author_id = $user_id;");
}
public function getCalendarsWithEvents()
{
if(!auth()->user())
return response("Forbidden", 403);
$user_id = auth()->user()->id;
$calendars = DB::select("select * from calendars where calendar_author_id = $user_id;");
$data = [];
foreach($calendars as $calendar) {
$temp = [
'calendar' => $calendar,
'events' => []
];
$event_calendar_id = $calendar->id;
$Events = DB::select("select * from events where event_calendar_id = $event_calendar_id;");
foreach($Events as $event) {
array_push($temp['events'], $event);
}
array_push($data, $temp);
}
return $data;
}
public function getCalendarWithEvents($id)
{
if(!auth()->user())
return response("Forbidden", 403);
$user_id = auth()->user()->id;
$calendar = DB::select("select * from calendars where calendar_author_id = $user_id and id = $id;")[0];
$data = [
'calendar' => $calendar,
'events' => []
];
$Events = DB::select("select * from events where event_calendar_id = $id;");
foreach($Events as $event) {
array_push($data['events'], $event);
}
return $data;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function CreateCalendar(Request $request)
{
$validated = $request->validate([
'calendar_title'=> 'required|string'
]);
if(auth()->user()) {
$data = [
'calendar_author_id' => auth()->user()->id,
'calendar_title' => $validated['calendar_title'],
];
return Calendar::create($data);
}
return response("Forbidden", 403);
}
/**
* Display the specified resource.
*
* @param \App\Models\Calendar $calendar
* @return \Illuminate\Http\Response
*/
public function getCalendar($id)
{
$calendar = Calendar::find($id);
if(!$calendar)
return response("not found", 404);
if(auth()->user() && auth()->user()->id == $calendar->calendar_author_id) {
return $calendar;
}
return response("Forbidden", 403);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Calendar $calendar
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Calendar $calendar)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Calendar $calendar
* @return \Illuminate\Http\Response
*/
public function DeleteCalendar(Calendar $calendar, $id)
{
$calendar = Calendar::find($id);
if(!$calendar)
return response("not found", 404);
if(auth()->user() && auth()->user()->id == $calendar->calendar_author_id) {
return Calendar::destroy($id);
}
return response("Forbidden", 403);
}
}
<file_sep>/laravel/app/Http/Controllers/Admin/PostCrudController.php
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController as ControllersCrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use App\Models\Post;
use App\Http\Controllers\CategorySubTableController;
class PostCrudController extends ControllersCrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation { update as traitUpdate; }
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation { destroy as traitDestroy; }
public function setup() {
CRUD::setModel(\App\Models\Post::class);
CRUD::setRoute(config('backpack.base.route_prefix') . '/post');
CRUD::setEntityNameStrings('Post', 'Posts');
}
protected function setupShowOperation() {
$post = CRUD::getCurrentEntry();
$CategorySub = New CategorySubTableController();
$categories = $CategorySub->getCategoriesForPost($post->id);
$i = 0;
$post->categories = '[';
foreach($categories as $category) {
if($i > 0)
$post->categories .= ', ';
$post->categories .= $category->category_id;
$i++;
}
$post->categories .= ']';
CRUD::column('id');
CRUD::column('author');
CRUD::column('author_id');
CRUD::column('title');
CRUD::column('content');
CRUD::column('likes');
CRUD::column('status');
CRUD::column('categories');
}
protected function setupListOperation() {
CRUD::column('id');
CRUD::column('author');
CRUD::column('title');
CRUD::column('likes');
CRUD::column('status');
}
protected function setupCreateOperation() {
CRUD::field('title');
CRUD::field('content');
CRUD::field('status');
CRUD::modifyField('status', [
'type' => 'enum',
]);
CRUD::addField([
'name' => 'categoryID',
'label' => 'categories id',
'type' => 'text'
]);
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
public function store() {
$validated = request()->validate([
'title' => 'required|string',
'content' => 'required|string',
'status' => 'in:active,inactive',
'categoryID' => 'required|string',
]);
$data = [
'author' => backpack_user()->login,
'author_id' => backpack_user()->id,
'title' => $validated['title'],
'content' => $validated['content'],
'likes' => 0,
'status' => $validated['status']
];
$post = Post::create($data);
$CategorySub = New CategorySubTableController();
$CategorySub->addCategory(explode(',', request()->categoryID), $post->id);
return redirect('/admin/post/' . $post->id . '/show');
}
public function update()
{
$post = CRUD::getCurrentEntry();
if(isset(request()->categoryID)) {
$CategorySub = New CategorySubTableController();
$CategorySub->addCategory(explode(',', request()->categoryID), $post->id);
}
if(isset($request['status'])) {
$post->status = $request['status'];
$post->save();
}
if($post->author_id == backpack_user()->id) {
$data = [
'title' => (request()->input('title') ? request()->input('title') : $post->title),
'content' => (request()->input('content') ? request()->input('content') : $post->content),
];
$post->update($data);
}
return redirect('/admin/post/' . $post->id . '/show');
}
}
<file_sep>/laravel/app/Http/Controllers/Admin/CommentsCrudController.php
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController as ControllersCrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use App\Models\Comment;
class CommentsCrudController extends ControllersCrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation { update as traitUpdate; }
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation { destroy as traitDestroy; }
public function setup() {
CRUD::setModel(\App\Models\Comment::class);
CRUD::setRoute(config('backpack.base.route_prefix') . '/comment');
CRUD::setEntityNameStrings('comment', 'comments');
}
protected function setupListOperation() {
CRUD::column('id');
CRUD::setFromDb();
}
protected function setupCreateOperation() {
CRUD::addField([
'name' => 'post_id',
'label' => 'post id',
'type' => 'text'
]);
CRUD::field('content');
CRUD::field('status');
CRUD::modifyField('status', [
'type' => 'enum',
]);
}
protected function setupUpdateOperation() {
CRUD::field('status');
CRUD::modifyField('status', [
'type' => 'enum',
]);
}
public function store() {
$validated = request()->validate([
'post_id' => 'required|string',
'content' => 'required|string',
'status' => 'in:active,inactive',
]);
$credentials = request()->only('content', 'post_id', 'status');
$credentials['author'] = backpack_user()->login;
$credentials['user_id'] = backpack_user()->id;
$comment = Comment::create($credentials);
return redirect('/admin/comment/' . $comment->id . '/show');
}
public function destroy($id) {
$this->crud->hasAccessOrFail('delete');
$comment = CRUD::getCurrentEntry();
$user = \App\Models\User::find($comment->user_id);
$user->rating -= $comment->rating;
$user->save();
return $this->crud->delete($id);
}
}
<file_sep>/laravel/routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/test', function () {
return ['message' => 'hello'];
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
///////////
Route::post('/CreateCalendar', 'App\Http\Controllers\CalendarController@CreateCalendar');
Route::get('/getCalendarsForUser', 'App\Http\Controllers\CalendarController@getCalendarsForUser');
Route::get('/getCalendarWithEvents/{id}', 'App\Http\Controllers\CalendarController@getCalendarWithEvents');
Route::get('/getCalendar/{id}', 'App\Http\Controllers\CalendarController@getCalendar');
Route::get('/getCalendarsWithEvents', 'App\Http\Controllers\CalendarController@getCalendarsWithEvents');
Route::delete('/DeleteCalendar/{id}', 'App\Http\Controllers\CalendarController@DeleteCalendar');
////////
Route::get('/getEventForCalendar/{id}/{eventId}', 'App\Http\Controllers\EventController@getEventForCalendar');
Route::get('/getEventsForCalendar/{id}', 'App\Http\Controllers\EventController@getEventsForCalendar');
Route::post('/createEventForCalendar/{id}', 'App\Http\Controllers\EventController@createEventForCalendar');
Route::delete('/DeleteEventFromCalendar/{id}/{eventId}', 'App\Http\Controllers\EventController@DeleteEventFromCalendar');
//getCalendarsWithEvents
Route::post('/login', 'App\Http\Controllers\AuthController@Login');
Route::post('/register', 'App\Http\Controllers\AuthController@register');
Route::get('/logout', 'App\Http\Controllers\AuthController@Logout');
Route::post('/requestForPasswordReset', 'App\Http\Controllers\AuthController@requestForPasswordReset');
Route::post('/reset/{token}/{userId}', 'App\Http\Controllers\AuthController@PasswordReset');
<file_sep>/client/src/components/CreateEvent.js
import React, {useState, useEffect, useContext} from 'react';
import { useHttp } from '../hooks/http.hook';
import { useMessage } from '../hooks/message.hook';
import { AuthContext } from "../context/AuthContext";
import { FiArrowLeft, FiSend } from "react-icons/fi";
import { useParams } from "react-router-dom";
import Select from 'react-select';
export const CreateEvent = ({createEventOnFalse, eventStart}) => {
const message = useMessage();
const {token} = useContext(AuthContext);
const {loading, error, request, clearError} = useHttp()
const {id} = useParams();
const [form, setForm] = useState ( {
event_content: '', event_title: '', event_category: 'task', event_date: eventStart, event_duration: eventStart
});
useEffect( () => {
message(error);
clearError();
}, [error, message, clearError]);
useEffect( () => {
window.M.updateTextFields()
}, []);
const chengeHandler = event => {
if(event.target)
setForm({...form, [event.target.name]: event.target.value})
else {
form.event_category = event.value
}
};
const CreateEventHandler = async(event) => {
try {
event.preventDefault();
await request('/api/createEventForCalendar/' + id, 'POST', {...form}, {
'Authorization': token
})
window.location.reload();
createEventOnFalse()
}
catch (e) {}
};
const options = ['arrangement', 'reminder', 'task'].map((category) => {
return {value: category, label: category}
})
const SelectStyle = {
option: (provided) => ({
...provided,
color: '#000000',
padding: 10,
}),
valueContainer: base => ({
...base,
color: 'white',
}),
multiValueLabel: base => ({
...base,
backgroundColor: "#1976d2",
color: "#FFFFFF"
}),
multiValueRemove: base => ({
...base,
color: "#000000"
}),
control: (base, state) => ({
...base,
boxShadow: "none",
border: `2px solid ${state.isFocused ? "#ffeb3b" : "#1976d2"}`,
'&:hover': {
border: `2px solid ${state.isFocused ? "#ffeb3b" : "#1976d2"}`
}
})
}
return (
<div>
<div className="card blue darken-1">
<div className="card-content white-text">
<button className="btn-floating btn-large waves-effect waves-light grey lighten-1 EditPostButtonBack" onClick={createEventOnFalse}>
<FiArrowLeft className="FiArrowLeftSizeEditProfile"/>
</button>
<span className="card-title center">Create Event</span>
<div>
<div className="input-field">
<input placeholder="input event title"
id="event_title"
type="text"
name="event_title"
className="yellow-input white-text"
onChange={chengeHandler}
/>
<label htmlFor="event_title">event title</label>
</div>
<div className="input-field">
<input placeholder="input event content"
id="event_content"
type="text"
name="event_content"
className="yellow-input white-text"
onChange={chengeHandler}
/>
<label htmlFor="event_content">event content</label>
</div>
<div className="input-field">
<input placeholder="input event date"
id="event_date"
type="text"
name="event_date"
className="yellow-input white-text"
onChange={chengeHandler}
defaultValue={eventStart}
/>
<label htmlFor="event_date">event date</label>
</div>
<div className="input-field">
<input placeholder="input event duration"
id="event_duration"
type="text"
name="event_duration"
className="yellow-input white-text"
onChange={chengeHandler}
defaultValue={eventStart}
/>
<label htmlFor="event_duration">event duration</label>
</div>
<div className="input-field">
<p className="categories">event category</p>
<Select options={options}
placeholder={"Select event category"}
closeMenuOnSelect={true}
id="event_category"
name="event_category"
styles={SelectStyle}
defaultValue={options[2]}
onChange={chengeHandler}
/>
<label htmlFor="event_category" hidden>event category</label>
</div>
</div>
</div>
<div className="card-action">
<div className="center">
<button className="btn waves-light red" onClick={CreateEventHandler} disabled={loading}>Submit
<FiSend className="FiSendSizeEditProfile"/>
</button>
</div>
</div>
</div>
</div>
);
}<file_sep>/laravel/app/Http/Controllers/AuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use DB;
use App\Mail\reset_password;
class AuthController extends Controller
{
public function register(Request $request) {
$validated = $request->validate([
'login'=> 'required|string|unique:users,login',
'real_name'=> 'string',
'email'=> 'required|email|unique:users,email',
'password'=> '<PASSWORD>',
]);
$validated['password'] = <PASSWORD>($validated['password']);
$user = User::create($validated);
return response([
'message' => 'User registered. Please log in',
'user' => $user
]);
}
public function Login(Request $request)
{
$credentials = $request->only(['login', 'password']);
if(($token = JWTAuth::attempt($credentials))) {
$user = JWTAuth::user();
$user->token = $token;
$user->save();
return response([
'message' => 'Logged in',
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => JWTAuth::factory()->getTTL() * 60,
'user' => $user
]);
}
}
public function requestForPasswordReset(Request $request) {
$validated = $request->validate([
'email'=> 'required|email'
]);
$user = null;
$temp_user = DB::table('users')->where('email', '=', $validated['email'])->first();
if($temp_user)
$user = User::find($temp_user->id);
if (!$user) {
return response("Not Found", 404);
}
$token = Str::random(60);
$user->password_reset_token = $token;
$user->save();
$mailObj = new \stdClass();
$mailObj->token = $token;
$mailObj->receiver = $user->real_name;
$mailObj->id = $user->id;
$mailObj->url = 'http://localhost:3000/resetPassword/' . $token . '/' . $user->id;
Mail::to($validated['email'])->send(new reset_password($mailObj));
return response(['message' => "check your mail"], 200);
}
public function PasswordReset(Request $request, $token, $userId) {
$validated = $request->validate([
'password'=> '<PASSWORD>:4',
]);
$user = User::find($userId);
if (!$user) {
return response("Not Found", 404);
}
if(strcmp($token, $user->password_reset_token) == 0) {
$user->password = <PASSWORD>($validated['password']);
$user->password_reset_token = "";
$user->save();
return response(['message' => "password was changed"], 200);
}
return response(['message' => "token not match"], 403);
}
public function Logout()
{
try {
$user = auth()->user();
if($user) {
JWTAuth::invalidate(JWTAuth::getToken());
$user->token = '';
$user->save();
}
return response(['message' => "logout"], 200);
} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response(['error' => $e->getMessage()], 401);
}
}
}
<file_sep>/laravel/database/migrations/2021_10_05_112347_create_events_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEventsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('event_author_id');
$table->unsignedBigInteger('event_calendar_id');
$table->foreign('event_author_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('event_calendar_id')->references('id')->on('calendars')->onUpdate('cascade')->onDelete('cascade');
$table->string('event_content')->default('');
$table->string('event_title')->default('');
$table->dateTime('event_duration');
$table->dateTime('event_date');
$table->enum('event_category', ['arrangement', 'reminder', 'task'])->default('reminder');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('events');
}
}
<file_sep>/laravel/app/Http/Controllers/Admin/UserCrudController.php
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController as ControllersCrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class UserCrudController extends ControllersCrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation { update as traitUpdate; }
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation { destroy as traitDestroy; }
protected function setupShowOperation() {
CRUD::column('id');
CRUD::column('login');
CRUD::column('real_name');
CRUD::column('rating');
CRUD::column('email');
CRUD::column('role');
CRUD::addColumn([
'name' => 'image_path',
'label' => 'Avatar',
'type' => 'image',
'width' => '150px',
'height' => '150px'
]);
}
public function setup() {
CRUD::setModel(\App\Models\User::class);
CRUD::setRoute(config('backpack.base.route_prefix') . '/user');
CRUD::setEntityNameStrings('User', 'Users');
}
protected function setupListOperation() {
CRUD::column('id');
CRUD::setFromDb();
}
protected function setupCreateOperation() {
CRUD::field('login');
CRUD::field('real_name');
CRUD::field('email');
CRUD::field('password');
CRUD::field('password_confirmation');
CRUD::field('role');
CRUD::addField([
'name' => 'image_path',
'label' => 'Avatar',
'type' => 'image',
'crop' => true,
'aspect_ratio' => 1,
]);
CRUD::modifyField('role', [
'type' => 'enum',
]);
}
protected function setupUpdateOperation()
{
CRUD::field('role');
CRUD::modifyField('role', [
'type' => 'enum',
]);
}
public function store() {
$credentials = request()->only([
'login',
'password',
'password_confirmation',
'email',
'role',
'full_name',
'image_path'
]);
$validated = request()->validate([
'login'=> 'required|string|unique:users,login',
'real_name'=> 'string',
'email'=> 'required|email|unique:users,email',
'password'=> '<PASSWORD>',
'password_confirmation'=> '<PASSWORD>',
'role' => 'in:admin,user'
]);
$credentials['password'] = <PASSWORD>($validated['password']);
$image_data = '';
if (isset($credentials['image_path'])) {
$image_data = $credentials['image_path'];
unset($credentials['image_path']);
}
$user = User::create($validated);
if (isset($credentials['image_path'])) {
$avatar_data = explode(';', $image_data);
$avatar_data[1] = explode(',', $avatar_data[1])[1];
$image_data = 'avatars/' . $user->id . '.png';
$file = fopen($image_data, "w");
fwrite($file, base64_decode($avatar_data[1]));
fclose($file);
$user->image_path = $image_data;
$user->save();
}
return redirect('/admin/user/' . $user->id . '/show');
}
public function update()
{
request()->validate([
'role' => 'in:admin,user'
]);
$user = CRUD::getCurrentEntry();
$user->update(['role' => request()->input('role')]);;
$response = $this->traitUpdate();
return $response;
}
}
<file_sep>/client/src/components/Navbar.js
import React, {useContext} from "react";
import {AuthContext} from '../context/AuthContext'
import { useHistory } from "react-router-dom";
import { useHttp } from '../hooks/http.hook';
export const Navbar = () => {
const auth = useContext(AuthContext);
const history = useHistory();
const {request} = useHttp();
const {token} = useContext(AuthContext);
const logoutHandler = event => {
event.preventDefault();
request('/api/logout', 'GET', null, {'Authorization': token})
auth.logout();
history.push('/')
};
return (
<nav>
<div className="nav-wrapper blue darken-2">
<a href="/home" className="brand-logo">Logo</a>
<ul id="nav-mobile" className="right">
<li><a className="blue darken-3" href="/home" onClick={logoutHandler}>Logout</a></li>
</ul>
</div>
</nav>
);
}
<file_sep>/laravel/app/Models/Events.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Events extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'event_author_id',
'event_calendar_id',
'event_content',
'event_title',
'event_date',
'event_category',
'event_duration'
];
use HasFactory;
}
<file_sep>/laravel/app/Http/Controllers/Admin/CategoryCrudController.php
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController as ControllersCrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use App\Models\Category;
class CategoryCrudController extends ControllersCrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation { update as traitUpdate; }
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation { destroy as traitDestroy; }
public function setup() {
CRUD::setModel(\App\Models\Category::class);
CRUD::setRoute(config('backpack.base.route_prefix') . '/category');
CRUD::setEntityNameStrings('category', 'categories');
}
protected function setupListOperation() {
CRUD::column('id');
CRUD::setFromDb();
}
protected function setupCreateOperation() {
CRUD::field('title');
CRUD::field('description');
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
public function store() {
$validated = request()->validate([
'title' => 'required|string',
'description' => 'required|string',
]);
$category = Category::create(request()->all());
return redirect('/admin/category/' . $category->id . '/show');
}
public function update()
{
$validated = request()->validate([
'title' => 'required|string',
'description' => 'required|string',
]);
$response = $this->traitUpdate();
return $response;
}
}
| 007942ef0434b64e3a25b81a60fdcac3cb556ddf | [
"JavaScript",
"PHP"
] | 15 | PHP | ChausAnton/chronos-anchaus | 025d979624aaaea3deeb797eb4466c3c1cb29a59 | 2fe967d6d4775f6d25c8e6a2fb0bbf7349b63dfb |
refs/heads/main | <repo_name>mlhomsi/Navio-Pirata-e-Bruxaria<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed;
private Rigidbody2D rb;
//public AudioSource passos;
bool isMoving;
private Vector2 adjustOperation;
// public Animator playerMov;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate() {
float inputX = Input.GetAxisRaw("Horizontal");
float inputY = Input.GetAxisRaw("Vertical");
if (inputX != 0 && inputY != 0) {
}
// playerMov.SetFloat("VelX", inputX);
// playerMov.SetFloat("VelY", inputY);
adjustOperation = new Vector2(inputX * speed, inputY * speed);
adjustOperation.Normalize();
rb.velocity = adjustOperation*speed;
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/Effect.cs
using UnityEngine;
public abstract class Effect : ScriptableObject
{
public abstract void WhenChant(GameObject target);
public virtual void Update()
{
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/Path.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Path : MonoBehaviour
{
[SerializeField]
private List<Vector2> visitedPoints;
private int currentTarget;
private Rigidbody2D rb;
private Vector2 currentPos;
[SerializeField]
private float speed;
[SerializeField]
private float waitTime;
private float timeCounter;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
currentTarget = 0;
}
private IEnumerator waitAndWalk()
{
Debug.Log("Wait and walk triggered. Wating...");
yield return new WaitForSeconds(waitTime);
Debug.Log("Wait time ended");
if (currentTarget + 1 == visitedPoints.Count)
{
currentTarget = 0;
}
else currentTarget++;
yield break;
}
void FixedUpdate()
{
currentPos = new Vector2(transform.position.x,transform.position.y);
if (currentPos == visitedPoints[currentTarget])
{
if (timeCounter < waitTime)
{
timeCounter += Time.deltaTime;
}
else
{
timeCounter = 0f;
if (currentTarget + 1 == visitedPoints.Count)
{
currentTarget = 0;
}
else currentTarget++;
}
}
else
{
Debug.Log("Its else");
transform.position = Vector2.MoveTowards(transform.position, visitedPoints[currentTarget], speed * Time.deltaTime);
}
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/UI/HUD.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD : MonoBehaviour
{
[SerializeField]
private Inventory inventory;
private void Start()
{
inventory.SpellAdded += InventoryAdding;
}
private void InventoryAdding (object sender,InventoryArgs target)
{
Transform inventoryPanel = transform.Find("Inventory");
foreach(Transform slot in inventoryPanel)
{
print("Fui pro inventário");
Image image = slot.GetChild(0).GetChild(0).GetComponent<Image>();
if (!image.enabled)
{
image.enabled = true;
image.sprite = target.Spell.getSprite;
break;
}
}
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/GameController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
[SerializeField]
private GameSettings gameSettings;
[SerializeField]
private SpellSpawner spawner;
[SerializeField]
SelectSpell selectSpell;
[SerializeField]
public Spell SpellSelected; //dps trocar pra Private
public bool isSelected = false;
public event Action Spelldeselect;
public void Chant(Effect effect)
{
effect.WhenChant(this.gameObject);
}
private void SelectHandler (object sender, InventoryArgs s)
{
SpellSelected = s.Spell;
print("Alo");
isSelected = true;
}
private void Start()
{
//spawner.ClearSpells(spells);
spawner.AddSpells(gameSettings.ListSpells, gameSettings.Locations);
selectSpell.Spellselected += SelectHandler;
Spelldeselect += selectSpell.DeselectSpell;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && SpellSelected && isSelected)
{
print("CASTING "+ isSelected);
Chant(SpellSelected.Geteffect);
isSelected = false;
SpellSelected = null;
Spelldeselect?.Invoke();
}
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/GameSettings.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Custom/GameSettings")]
public class GameSettings : ScriptableObject
{
[SerializeField]
private List<Spell> spells;
public List<Spell> ListSpells => spells;
[SerializeField]
private List<Vector2> locations;
public List<Vector2> Locations => locations;
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/SelectSpell.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SelectSpell : MonoBehaviour
{
[SerializeField]
private GameSettings gameSettings;
public event EventHandler<InventoryArgs> Spellselected;
private Image slotimage;
private Inventory inventorystored;
private Spell spellstored;
private void Selectspell(Spell spell)
{
if (Spellselected != null)
{
Spellselected(this, new InventoryArgs(spell));
}
}
public void DeselectSpell()
{
slotimage.sprite = null;
slotimage.enabled = false;
inventorystored.RemoveSpell(spellstored);
}
public void Buttonfunct(int i)
{
Transform HUD = transform.parent;
Transform inventoryPanel = HUD.Find("Inventory");
Inventory inventory = inventoryPanel.GetComponent<Inventory>();
Transform slot = inventoryPanel.GetChild(i);
Image image = slot.GetChild(0).GetChild(0).GetComponent<Image>();
Spell spell = inventory.Storage.Find(p => p.getSprite == image.sprite);
if (spell != null)
{
Selectspell(spell);
}
slotimage = image;
inventorystored = inventory;
spellstored = spell;
}
}
<file_sep>/README.md
# <NAME>
Repositório da GGJ 2021
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/InventoryArgs.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InventoryArgs : EventArgs
{
public InventoryArgs (Spell spell)
{
Spell = spell;
}
public Spell Spell;
//QUE COISA HORROROSA É ESSA Q EU CRIEI DEUS.
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/PlaceholderSpell.cs
using System;
using UnityEngine;
[CreateAssetMenu(menuName = "Custom/Spells/Placeholder")]
public class PlaceholderSpell :Effect
{
public override void WhenChant(GameObject target)
{
Debug.Log("Sh<NAME>ai");
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Collider2D))]
public class Player : MonoBehaviour
{
private Rigidbody2D rb;
[SerializeField]
private float speed = 5f;
Vector2 direction;
public Animator PlayerAnim;
[SerializeField]
private Inventory inventory;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
PlayerAnim = this.gameObject.GetComponent<Animator>();
//inventory = GetComponent<Inventory>();
}
// Update is called once per frame
void Update()
{
direction.x = Input.GetAxisRaw("Horizontal");
direction.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + direction * speed * Time.fixedDeltaTime);
if(direction.x != 0 || direction.y != 0)
{
if(direction.x >0)
{
PlayerAnim.SetBool("Idle", false);
PlayerAnim.Play("PlayerWalkDir");
}else
{
PlayerAnim.SetBool("Idle", false);
PlayerAnim.Play("PlayerWalkFront");
}
} else PlayerAnim.SetBool("Idle", true);
}
private void OnTriggerEnter2D (Collider2D collider2D)
{
Spell spell = collider2D.GetComponent<Spell>();
if (spell != null)
{
inventory.AddSpell(spell);
}
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/Spell.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//[RequireComponent(typeof(Rigidbody2D))] maybe not ?
[RequireComponent(typeof(Collider2D))]
[RequireComponent(typeof(SpriteRenderer))]
public class Spell : MonoBehaviour
{
//protected GameController controller;
//protected SpellSpawner spawner => controller.Spawner;
[SerializeField]
[Tooltip("Efeito da magia")]
private Effect effect;
public Effect Geteffect => effect;
private SpriteRenderer spriteRenderer;
public Sprite getSprite => spriteRenderer.sprite;
public static Spell CreateSpellItem(Spell prefab, Vector3 Pos0 /*,GameController controller*/)
{
Spell spell = Instantiate(prefab, Pos0, Quaternion.identity);
//spell.controller = controller; possibly not needed
//spell.spriteRenderer.sprite = prefab.spriteRenderer.sprite;
return spell;
}
public void OnPickup()
{
//Maybe more things later ?
gameObject.SetActive(false);
print("Fui chamado");
}
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/SpellSpawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpellSpawner : MonoBehaviour
{
public void AddSpells (List<Spell> spells,List<Vector2> locals)
{
spells.Shuffle();
for (int i = 0; i< spells.Count; i++)
{
Spell.CreateSpellItem(spells[i],locals[i]);
}
}
public void ClearSpells (List<Spell> spells)
{
foreach(Spell s in spells)
{
Destroy(s.gameObject);
}
spells.Clear();
}
}
<file_sep>/Navio Pirata e Bruxaria/Assets/Scripts/Game/Inventory.cs
using System;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
private const int Slots = 3;
private List<Spell> nSpells = new List<Spell>();
public List<Spell> Storage => nSpells;
public event EventHandler<InventoryArgs> SpellAdded;
public void AddSpell(Spell spell)
{
if (nSpells.Count < Slots)
{
Collider2D collider = spell.GetComponent<Collider2D>();
if (collider.enabled)
{
collider.enabled = false;
nSpells.Add(spell);
spell.OnPickup();
}
if (SpellAdded != null)
{
SpellAdded(this, new InventoryArgs(spell));
}
}
}
public void RemoveSpell(Spell spell)
{
print("Count F "+nSpells.Count);
nSpells.Remove(spell);
print("Count E "+nSpells.Count);
}
} | 77e445f41e736572aa7252fb6b39c2a377b8b229 | [
"Markdown",
"C#"
] | 14 | C# | mlhomsi/Navio-Pirata-e-Bruxaria | 7488ca9176ab5ee48c585d54e63d4c76f5951b21 | 1643e6deae8ba2da935534941a44f9cdc9a5a876 |
refs/heads/master | <repo_name>Nixtov/Arrays<file_sep>/demo2/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo2
{
class Program
{
static void Main(string[] args)
{
int [] test = new int [5];
test [2] = 2;
for (int i = 0; i < test.Length; i++)
{
Console.WriteLine(test[i]);
}
}
}
}
<file_sep>/exersise2/Program.cs
using System;
using System.Linq;
namespace exersise2
{
public class Program
{
public static void Main()
{
string[] firstArr = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string[] secondArr = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int lenght = Math.Min(firstArr.Length, secondArr.Length);
int count = 0;
for (int i = 0; i < firstArr.Length; i++)
{
if (firstArr[i] == secondArr[i])
{
count++;
}
else
{
break;
}
}
Array.Reverse(firstArr);
Array.Reverse(secondArr);
Console.WriteLine(count);
}
private static int FindMaxCommonItems(string[] secondArr, string[] firstArr);
}
}
<file_sep>/Demo/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
int [] nums = { 10, 20, 30 };
foreach (var num in nums)
{
Console.Write(num);
Console.Write(' ');
}
}
}
}
| 0dde5e57403e97379a9ff84e2ee31a7062dcb63c | [
"C#"
] | 3 | C# | Nixtov/Arrays | 21a6bd18131f2db7a31e1e7ec0649b781fc58c6f | 28d393e9989bd7277dd2471f23bc26f9f74ce713 |
refs/heads/master | <repo_name>radames-rex/wforecast<file_sep>/app/components/app.js
'use strict';
/**
* @ngdoc overview
* @name wForecastApp
* @description
* # wForecastApp
*
* Main module of the application.
*/
angular
.module('wForecastApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ui.router',
'ngSanitize',
'ngTouch',
'pascalprecht.translate',
'ngMaterial'
])
.constant('PATH', {
main: '/wforecast',
weather: '/weather'
})
.constant('REQUEST', {
api: {
url: 'http://api.openweathermap.org',
weatherbycity: '/data/2.5/forecast?q=',
scale: '&units=',
key: '&appid=4abbabeb92b59021a08e2cfa48d7ec0d&lang=pt'
}
})
.config(function($stateProvider, $urlRouterProvider, $translateProvider, PATH) {
/* Configuração do provider de universalização e da linguagem padrão. */
$translateProvider.useStaticFilesLoader({
prefix: 'translate/messages-',
suffix: '.json'
});
$translateProvider.preferredLanguage('pt');
/* Configuração dos estados e rotas da aplicação */
$stateProvider.state('main', {
abstract: true,
url: PATH.main,
templateUrl: 'views/main.html'
}).state('main.weather', {
url: PATH.weather,
templateUrl: 'views/weather.html',
controller: 'WeatherCtrl as ctrl'
});
$urlRouterProvider.otherwise(function() {
return '/wforecast/weather';
});
});
<file_sep>/app/components/weather/weather.factory.js
'use strict';
(function() {
/**
* @ngdoc function
* @name wForecastApp.factory:WeatherFactory
* @description
* # WeatherFactory
* Factory of the wForecastApp
*/
var WeatherFactory = function(REQUEST, RequestFactory, $q) {
var WeatherFactory = {};
// Faz uma requisição para recuperar os dados da previsão do tempo
WeatherFactory.getWeather = function(city, scale) {
var defer = $q.defer();
RequestFactory.get(REQUEST.api.url + REQUEST.api.weatherbycity + city + REQUEST.api.scale + scale + REQUEST.api.key).then(function(data) {
data = data.data;
if (typeof data === 'object') {
defer.resolve(data);
} else {
defer.reject("hasnt object");
}
}, function(response, status) {
defer.reject(response, status);
});
return defer.promise;
};
return WeatherFactory;
};
WeatherFactory.$inject = ['REQUEST', 'RequestFactory', '$q'];
angular
.module('wForecastApp')
.factory('WeatherFactory', WeatherFactory);
})();
<file_sep>/README.md
# wForecast | Aurum Challenge
## Use Guide
Digite uma cidade no campo de busca e você obterá a previsão do tempo atual para a respectiva cidade, com indicações de clima e temperatura. Existe a opção para alternar a escala de temperatura e uma opção para revelar a previsão do tempo para as próximas horas e dias.
## Get Started
Para instalar as dependências é necessário ter o NodeJS e NPM instalados e as seguintes dependências:
```npm install -g grunt-cli bower yo generator-karma generator-angular```
Para instalar as demais dependências de desenvolvimento:
```npm install```
Para instalar as demais dependências de front-end:
```bower install```
ou
```sudo bower install --allow-root```
Para instalar demais dependências de teste:
```npm install grunt-karma karma karma-phantomjs-launcher karma-jasmine jasmine-core phantomjs-prebuilt --save-dev```
## Build & development
`grunt build` para buildar a aplicação and `grunt serve` para iniciar o servidor e rodar a aplicação.
## Testing
`grunt test` para rodar os testes com Karma.
| 171b8edc31be3a6e90d27662face150797e2c3c6 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | radames-rex/wforecast | 085adba56e93752b6b18cde0f22d3f66890af3e5 | f1cac9d88b98bfcf85ab8b2a048dbcb2de63893e |
refs/heads/master | <file_sep># landmark-test
Authors: [<NAME>](<EMAIL>), [<NAME>](mailto:<EMAIL>), [<NAME>](), [<NAME>](), [<NAME>](), [<NAME>](), [<NAME>](), [<NAME>](), [<NAME>](), [<NAME>]()
This repository contains all the code and data used in the manuscript:
<NAME>., <NAME>., <NAME>. et al. Individual variation of the masticatory system dominates 3D skull shape in the herbivory-adapted marsupial wombats. Front Zool 16, 41 (2019) [doi:10.1186/s12983-019-0338-5](https://frontiersinzoology.biomedcentral.com/articles/10.1186/s12983-019-0338-5)
This repo is based on code from the [`landvR` package](https://github.com/TGuillerme/landvR).
# Analyses
The tables and figures present in the manuscript are all reproducible through the following scripts:
## 01 - Data preparation
This script contains all the procedure to modify and prepare the data in a format usable in the analysis below.
1. Loading the landmark data
2. Selecting the different landmark partitions
3. Running the General Procrustes Analysis (`geomorph::gpagen`)
4. Running the Principal Components Analysis (`stats::prcomp`)
<!-- This procedure is described in the paper in the section @@@ -->
This script is available [here in Rmd](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/01-Data_preparation.Rmd) or [here in html](https://rawgit.com/TGuillerme/landmark-test/master/Analysis/01-Data_preparation.html).
## 02 - Landmark region difference
This [vignette](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/02-Landmark_region_difference.Rmd) (or [here in html](https://rawgit.com/TGuillerme/landmark-test/master/Analysis/02-Landmark_region_difference.html)) describes in details the test used to compare different regions of landmarks in geometric morphometrics.
This example uses the `plethodon` dataset from the `geomorph` package as an illustration.
The same test applied to our dataset is available in the following scripts `03` and `04` below.
<!-- This procedure is described in the paper in section @@@ and implemented in the [dispRity](https://github.com/TGuillerme/dispRity) package -->
## 03 - Landmark test analysis and 04 - landmark test analysis rarefied
These scripts runs the full landmark test analysis on each tested partition for each dataset (cranium and mandible) with and without rarefaction.
In brief, for each partition within each dataset and each species/genus/genera, the script does:
1. Load the data generated by the script `01-Data_preparation` above
2. Calculates the range of variation in the Procrustes space (using the radius of the spherical coordinates)
3. Running the random test with 1000 replicates using the area difference and the Bhattacharrya Coefficient as statistics
4. Saving the test results in `../Data/Results/` and saving the results figures and tables in `../Manuscript/Tables/` and `../Manuscript/Figures/`
This is done through the `pipeline.test` function available in [`../Functions/utilities.R`](https://github.com/TGuillerme/landmark-test/blob/master/Functions/utilities.R)
These script take some time to run (~30 min each) and will automatically save data in `../Data/Results/`.
If the results are already computed, it is possible to run the script faster by commenting out the lines containing:
```{r}
results <- pipeline.test(species, dataset, "../Data/Processed/", [...])
save(results, file = paste0("../Data/Results/", species, [...]))
```
And un-commenting the lines containing:
```{r}
load(file = paste0("../Data/Results/", species, "_", [...]))
```
The test run for either the 100\% confidence interval or the 95\% confidence intervals.
To switch between both, you can search and replace `CI = 0.95` and `CI95` by respectively `CI = 1` and `CI100` or the other way around.
This script is available [here in Rmd](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/03-Landmark_test_analysis.Rmd) ([here for the rarefied](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/04-Landmark_test_analysis_rarefied.Rmd)).
<!-- This procedure is described in the paper in the section @@@ -->
## 05 - Results summary
This script produces the figure 4 in the manuscript and the tables in the supplementary materials.
This script is available [here in Rmd](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/05-Results_summary.Rmd) or [here in html](https://rawgit.com/TGuillerme/landmark-test/master/Analysis/05-Results_summary.html).
## 06 - Main analyses
This script contains the Procrustes distances analysis and covers the allometry analysis, the linear models and the partial least squares analysis.
It was used to produce tables 1 and 2 in the manuscript.
This script is available [here in Rmd](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/06-Main_Analyses.Rmd).
## 07 Heatplots
This script contains the code for producing the landmark variation heaplots (figures 2 and 3).
The script is based on a modified version of the function `geomorph::plotRefToTarget`.
This script is available [here in Rmd](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/07-heatplots.Rmd).
## 08 Figures
Finally, this script was used to produce the figures 1 in the manuscript and can be found [here in Rmd](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/08-Figures.Rmd).
# Checkpoint for reproducibility
To rerun all the code with packages as they existed on CRAN at time of our analyses we recommend using the `checkpoint` package, and running this code prior to the analysis:
```{r}
checkpoint("2018-06-15")
```
The analysis were run on two different machines.
For reproducibility purposes, the output of `devtools::session_info()` used to perform the analyses in the publication for the analysis `03-Landmark_test_analysis.Rmd`, `04-Landmark_test_analysis_rarefied.Rmd` and `05-Results_summary.Rmd` is available [here](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/Session_info-2018-06-15_machine1.txt).
The `devtools::session_info()` used to perform the analyses in the publication for the analysis `06-Main_Analyses.Rmd`, `07-heatplots.Rmd` and `08-Figures.Rmd` is available [here](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/Session_info-2018-06-15_machine2.txt).
The other analysis where run on both machines.
<file_sep>---
title: "Figures/supplementary figures for wombat shape variation paper, except heatplots"
author: "<NAME>"
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
# Loading the data
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools"); library(devtools)
if(!require(geomorph)) install.packages("geomorph"); library(geomorph)
if(!require(landvR)) install_github("TGuillerme/landvR") ; library(landvR)
if(!require(stringr)) install.packages("stringr"); library(stringr)
library(ggplot2)
# Install and load ggConvexHull
#devtools::install_github("cmartin/ggConvexHull")
library(ggConvexHull)
source("../Functions/utilities.R")
set.seed(42)
# load the data
#for hairy-nosed wombats (needed below for PCA)
load("../Data/Processed/wombat_lasiorhinus.Rda")
HN <- land_data
##the below loads the Wombat.Rda from the processed data (i.e. partitions, procrustes data, and ordination results); but the object is NOT called the file name called under "load", it is "land_data"
load("../Data/Processed/wombat.Rda")
rawdata_cranium_wombat <- read.csv ("../Data/Raw/landmarkdata_cranium_wombat.csv")
rawdata_mandible_wombat <- read.csv ("../Data/Raw/landmarkdata_mandible_wombat.csv")
## Remove juvenile
nhnw_b34 <- which(colnames(rawdata_mandible_wombat) == "NHNW_B34")
rawdata_mandible_wombat <- rawdata_mandible_wombat[,-nhnw_b34]
# load allometry residuals
load("../Data/Processed/Allometry_residuals.rda")
#read classifiers
cranium <- read.csv("../Data/Raw/classifier_cranium_wombat.csv")
mandible <- read.csv("../Data/Raw/classifier_mandible_wombat.csv")
## Remove juvenile
nhnw_b34 <- which(mandible[,1] == "NHNW_B34")
mandible <- mandible[-nhnw_b34, ]
```
# PCA plot for Figure 1
```{r, message = FALSE, warning = FALSE}
## Loading the data for the PCA plots
load("../Data/Processed/wombat.Rda")
classifier_cranium <- cranium
classifier_mandible <- mandible
##loading hues
gg.color.hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
## PCA plots - Figure 1
pdf("../Manuscript/Figures/Figure1_PCA.pdf", height = 10, width = 12)
par(mfrow = c(2,2))
plot.pca(land_data$cranium$ordination, classifier_cranium$Species, cex.axis=1.2 );legend("bottomleft", c("Common", "Southern HN", "Northern HN"), pt.bg=(gg.color.hue(3)),pch=21, bty="n", cex=1.2); legend ("top", "All Species - Cranium", bty="n", cex=1.5)
plot.pca(land_data$mandible$ordination, classifier_mandible$Species,cex.axis=1.2 ); legend ("top", "All Species - Mandible", bty="n", cex=1.5)
## Loading the data for the within-species PCA plots
load("../Data/Processed/wombat_lasiorhinus.Rda")
classifier_cranium_Lasio= subset(classifier_cranium, classifier_cranium$Species != "Common wombat" )
classifier_mandible_Lasio= subset(classifier_mandible, classifier_mandible$Species != "Common wombat" )
plot.pca(HN$cranium$ordination, classifier_cranium_Lasio$Species, cex.axis=1.5 ); legend ("top", "Hairy-nosed - Cranium", bty="n", cex=1.5)
plot.pca(HN$mandible$ordination, classifier_mandible_Lasio$Species, cex.axis=1.5 ); legend ("top", "Hairy-nosed - Mandible", bty="n", cex=1.5)
dev.off()
```
#the same plot with allometry residuals (residuals of the regression of shape against centroid size)
```{r, message = FALSE, warning = FALSE}
load("../Data/Processed/Allometry_residuals.rda")
#make ordination as required for plot.pca (in utilities)
array_2d_cran <- geomorph::two.d.array(Allom_plus_consensus_cran)
ordination_cran <- prcomp(array_2d_cran, center = TRUE, scale. = FALSE, retx = TRUE,
tol = NULL)
# Mandible, all species
array_2d_mand <- geomorph::two.d.array(Allom_plus_consensus_mand)
ordination_mand <- prcomp(array_2d_mand, center = TRUE, scale. = FALSE, retx = TRUE,
tol = NULL)
#Cranium, Lasiorhinus
array_2d_cran_las <- geomorph::two.d.array(Allom_plus_consensus_cran_Lasio)
ordination_cran_las <- prcomp(array_2d_cran_las, center = TRUE, scale. = FALSE, retx = TRUE,
tol = NULL)
# Mandible, Lasiorhinus
array_2d_mand_las <- geomorph::two.d.array(Allom_plus_consensus_mand_Lasio)
ordination_mand_las <- prcomp(array_2d_mand_las, center = TRUE, scale. = FALSE, retx = TRUE,
tol = NULL)
classifier_cranium <- cranium
classifier_mandible <- mandible
##loading hues
gg.color.hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
## PCA plots - supplementary fig. 2
pdf("../Manuscript/Figures/SuppX_Residual_PCA.pdf", height = 10, width = 12)
#plot.new()
par(mfrow = c(2,2))
plot.pca(ordination_cran, classifier_cranium$Species, cex.axis=1.2 );legend("bottomleft", c("Common", "Southern HN", "Northern HN"), pt.bg=(gg.color.hue(3)),pch=21, bty="n", cex=1.2 ); legend ("top", "All Species - Cranium", bty="n", cex=1.5)
plot.pca(ordination_mand, classifier_mandible$Species, cex.axis=1.2); legend ("top", "All Species - Mandible", bty="n", cex=1.5)
## Loading the data for the within-species PCA plots
load("../Data/Processed/wombat_latifrons.Rda")
classifier_cranium_Lasio= subset(classifier_cranium, classifier_cranium$Species != "Common wombat" )
classifier_mandible_Lasio= subset(classifier_mandible, classifier_mandible$Species != "Common wombat" )
plot.pca(ordination_cran_las, classifier_cranium_Lasio$Species, cex.axis=1.2); legend ("top", "Hairy-nosed - Cranium", bty="n", cex=1.5)
plot.pca(ordination_mand_las, classifier_mandible_Lasio$Species, cex.axis=1.2); legend ("top", "Hairy-nosed - Mandible", bty="n", cex=1.5 )
dev.off()
```
# Pull out landmark designations. These need to be raw data because the landmark names are in the raw data
```{r}
## Create vectors of patch points, semi-landmarks, and landmarks; this requires raw data because they contain the landmark designations.
# LM point name metadata
#change "cranium" designations to "mandible" designations as needed
pt_names <-rawdata_mandible_wombat[, 1] # grabs first column of raw coords
foo2 <- str_sub(pt_names, 3, -1) # gets rid of X, Y, Z designations
u_pt_names <- unique(foo2)
patches <- str_detect(u_pt_names, "patch") #
pat_num <- which(patches == TRUE)
sliders <- str_detect(u_pt_names, "CUR")
sli_num <- which(sliders == TRUE)
LM <- !(sliders | patches)
LM_num <- which(LM == TRUE)
#Assign each landmark the appropriate number; Fixed is 1, semis are 2, patches are 3
#using landmarkgroups as a file to fill in
landmarkgroups_for_type=read.csv("../Data/Raw/landmarkgroups_mandible_wombat.csv")
landmark_LM_types<-landmarkgroups_for_type
for (i in 1:length(landmark_LM_types[,1])){
if(landmark_LM_types[i,1] %in% pat_num ==TRUE)
landmark_LM_types[i,2]<-3
else
if(landmark_LM_types[i,1] %in% sli_num ==TRUE)
landmark_LM_types[i,2]<-2
else
if(landmark_LM_types[i,1] %in% LM_num ==TRUE)
landmark_LM_types[i,2]<-1
}
write.csv(landmark_LM_types, "../Data/Raw/landmarktypes_mandible_wombat.csv")
```
#Visualize landmark types or landmark partitions without ply file
```{r, message = FALSE, warning = FALSE}
#separate land_data into the relevant components
#Define the partitions (needs to be done individually); this produces a csv file that can be manually edited (see comments below)
#LandmarkRegions=define.modules(land_data$cranium$procrustes$coords[,,5],2)
#write.csv(LandmarkRegions, file="../Data/Results/additional_snout.csv")
#Optional:
PartNames<-c("Zyg", "Sn", "Oc", "Po", "Rest")# This is not necessary for colouring the cranium AND needs to be separately accessed, but helps in identifying the partitionss
plot.partitions(land_data$cranium, PointSize = 0.001)
plot.partitions(land_data$mandible, PointSize = 0.001)
#Visualize partitions as colours
plot.partitions(land_data$cranium, PointSize = 0.001)
#optional - adding text helps with identifying landmarks if define.modules has not captured all landmarks of a partition. These numbers can then be manually edited in the LandmarkRegions file.
#text3d(mshape(land_data$cranium$procrustes$coords), text=c(1:826), adj = 2, cex = 0.8)
```
#Visualize landmark types or landmark partitions superimposed on a surface using a ply file; more involved as it requires the use of raw data
```{r, eval = FALSE}
#Create a ply file of the mean shape by warping the mean specimen in the PCA to the mean shape; for this, non-procrustes superimposed coordinates are required. The mean shapes are used here because they are easy to register with the landmarks.
#Find mean specimen, determine mean shape to warp mean specimen to
findMeanSpec(land_data$cranium$procrustes$coords)
findMeanSpec(land_data$mandible$procrustes$coords)
mshape_cranium<-mshape(land_data$cranium$procrustes$coords)
mshape_mandible<-mshape(land_data$mandible$procrustes$coords)
#Load ply file for specimens closest to mean
mean_specimen_mesh_cranium<-read.ply("../Data/Raw/NHNW_JM12487_Cranium.ply")
mean_specimen_mesh_mandible<-read.ply("../Data/Raw/SHNW NR1326 Mandible.ply")
#read raw data needed to register to ply files
WomCrData <- read.csv("../Data/Raw/landmarkdata_cranium_wombat.csv", header = T, row.names = 1)
WomCrData <- t(WomCrData)
WomCrData <- WomCrData[complete.cases(WomCrData),]
WomCrData <- arrayspecs(WomCrData, k=3, p=ncol(WomCrData)/3)
WomMaData <- read.csv("../Data/Raw/landmarkdata_mandible_wombat.csv", header = T, row.names = 1)
WomMaData <- t(WomMaData)
WomMaData <- WomMaData[complete.cases(WomMaData),]
WomMaData <- arrayspecs(WomMaData, k=3, p=ncol(WomMaData)/3)
# raw coordinates of the mean specimen to register to their respective ply files
mean_coords_cranium=WomCrData[,,38]
mean_coords_mandible=WomMaData[,,39]
# Check that ply files and raw coordinates align
plotspec(mean_specimen_mesh_cranium,mean_coords_cranium, centered = F, asp=T)
plotspec(mean_specimen_mesh_mandible,mean_coords_mandible, centered = F, asp=T)
#warp reference mesh to mean shape - warped ply files are already in the Data/Processed folder
#wombat_cranium_meanwarp- warpRefMesh(mean_specimen_mesh_cranium, mean_coords_cranium, mshape_cranium, centered=F) # Warps the ref mesh to the mean shape
#wombat_mandible_meanwarp <- warpRefMesh(mean_specimen_mesh_mandible, mean_coords_mandible, mshape_mandible, centered=F) # Warps the ref mesh to the mean shape
#save mean meshes
#open3d(); shade3d(wombat_cranium_meanwarp); writePLY("../Data/Processed/wombat_cranium_meanwarp.ply",withColors=T, format=("ascii"))#Export the warped mean specimen as a ply file; if you want to import this back into R, it needs to be formatted to ascii ply in meshlab
#open3d(); shade3d(wombat_mandible_meanwarp); writePLY("../Data/Processed/wombat_mandible_meanwarp.ply",withColors=T, format=("ascii"))
#or open meshes
wombat_cranium_meanwarp<-read.ply("../Data/Processed/wombat_cranium_meanwarp.ply")
wombat_mandible_meanwarp<-read.ply("../Data/Processed/wombat_mandible_meanwarp.ply")
#for plotting coloured landmarks on surface mesh
lm_types_cranium=read.csv("../Data/Raw/landmarktypes_cranium_wombat.csv")
lm_types_mandible=read.csv("../Data/Raw/landmarktypes_mandible_wombat.csv")
#separate colour vectors are needed because the code assigns the first landmark type it encounters withe the first colour in the vector.
col_cranium <- c("blue", "orange", "green")
col_mandible <- c("orange","blue", "green")
#plotting coloured landmarks on surface mesh for partitions; change to mandible as needed
PartLevels= unique(land_data$cranium$landmarkgroups[,2])
Colours <- c("blue", "orange", "green")
Part=list()
###Subsetting the partition levels
for(i in 1:length(PartLevels)){
Part[[i]]<-which (land_data$cranium$landmarkgroups[,2] == PartLevels[[i]])
}
###plotting the spheres- if you get only white, increase the radius.
open3d()
for (i in 1:length(PartLevels)){
spheres3d(mshape_cranium[Part[[i]],1], mshape_cranium[Part[[i]],2], mshape_cranium[Part[[i]],3], col=Colours[i], lit=TRUE,radius = 0.001, asp=F)
}
shade3d(wombat_cranium_meanwarp, color="grey")
#change from here between cranium and cranium as needed
PartLevels= unique(lm_types_mandible$x)
Part=list()
###Subsetting the partition levels
for(i in 1:length(PartLevels)){
Part[[i]]<-which (lm_types_mandible[,3] == PartLevels[[i]])
}
###plotting the spheres- if you get only white, increase the radius
open3d()
for (i in 1:length(PartLevels)){
spheres3d(mshape_mandible[Part[[i]],1], mshape_mandible[Part[[i]],2], mshape_mandible[Part[[i]],3], col=col_mandible[i], lit=TRUE,radius = 0.001, asp=F)
}
shade3d(wombat_mandible_meanwarp, color="grey")
```
#Supplementary Figure 3 - multivariate allometry
```{r}
cranium_gdf=geomorph.data.frame(coords=land_data$cranium$procrustes$coords, Csize=land_data$cranium$procrustes$Csize)
AllomCranium=procD.lm(coords~Csize, data=cranium_gdf, method="RegScore", logsz=FALSE)
mandible_gdf=geomorph.data.frame(coords=land_data$mandible$procrustes$coords, Csize=land_data$mandible$procrustes$Csize)
AllomMandible=procD.lm(coords~Csize, data=mandible_gdf, method="RegScore", logsz=FALSE)
## Allometry plots
gg.color.hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
pdf("../Manuscript/Figures/Allom_Suppfigure.pdf", height=6, width=12)
par(mfrow = c(1,2))
plotAllometry(AllomCranium, size=cranium_gdf$Csize, method="RegScore", bg = gg.color.hue (length(levels(cranium$Species))) [cranium$Species], pch=21, cex=1.5, logsz = FALSE);
legend ("topleft", "Cranium", bty="n", cex=1.2);
legend("bottomright", c("Common", "Southern HN", "Northern HN"), pt.bg=(gg.color.hue(3)),pch=21, bty="n", cex=1.2 )
plotAllometry(AllomMandible, size=mandible_gdf$Csize, method="RegScore", bg = gg.color.hue (length(levels(mandible$Species))) [mandible$Species], pch=21, cex=1.5, logsz = FALSE);
legend ("topleft", "Mandible", bty="n", cex=1.2);
legend("bottomright", c("Common", "Southern HN", "Northern HN"), pt.bg=(gg.color.hue(3)),pch=21, bty="n", cex=1.2 )
dev.off()
```<file_sep># @param species the species name
# @param dataset the type of dataset (cranium or mandible)
# @param path the path where the processed data is
# @param combine.land whether to combine the landmarks (only two partitions)
# @param CI the confidence intervals
# @param use.PC.range whether to use the variation range algorithm or pick the max/min on the PC1 for the differences.
# @param use.PC.range whether to use the procrustes variation between the two hypothetical specimens on PC1.
## Test pipeline
pipeline.test <- function(species, dataset, path, verbose = FALSE, rarefaction, combine.land = FALSE, CI, use.PC.range = FALSE, use.PC.hypo = FALSE){
## Loading a dataset
if(verbose) message("Load data...")
load(paste0(path, species, ".Rda"))
if(verbose) message("Done.\n")
## Selecting a dataset
if(verbose) message("Select dataset...")
data <- land_data[[dataset]]
if(verbose) message("Done.\n")
## Procrustes variation ranges
if(verbose) message("Calculate range...")
if(!use.PC.range && !use.PC.hypo){
procrustes_var <- variation.range(data$procrustes, type = "spherical", what = "radius", CI = CI)
} else {
if(use.PC.range) {
## Select the min-max on the PC1
axis <- 1
ordination <- data$ordination$x
if(CI == 1) {
max <- which(ordination[,axis] == max(ordination[,axis]))
min <- which(ordination[,axis] == min(ordination[,axis]))
} else {
CI_percent <- CI * 100
cis <- sort(c(50-CI_percent/2, 50+CI_percent/2)/100)
quantile_max <- cis[2]
quantile_min <- cis[1]
max <- which(ordination[,axis] == max(ordination[,axis][which(ordination[,axis] <= quantile(ordination[,axis], probs = quantile_max))]))
min <- which(ordination[,axis] == min(ordination[,axis][which(ordination[,axis] >= quantile(ordination[,axis], probs = quantile_min))]))
}
procrustes_var <- coordinates.difference(data$procrustes$coords[,,unname(max)], data$procrustes$coords[,,unname(min)], type = "spherical")[[1]]
}
if(use.PC.hypo) {
## Select the range two hypothetical specimen
procrustes_var <- variation.range(data$procrustes, type = "spherical", what = "radius", CI = CI, ordination = data$ordination, axis = 1)
}
}
if(verbose) message("Done.\n")
## landmarks partitions
if(verbose) message("Determine partitions...")
partitions <- list()
## Combine the landmarks
if(combine.land) {
## Select the biggest partitions
biggest_partition <- which(table(data$landmarkgroups[,2]) == max(table(data$landmarkgroups[,2])))
## Combine landmarks not in that partition
data$landmarkgroups[,2] <- ifelse(data$landmarkgroups[,2] != biggest_partition, 1, biggest_partition)
}
for(part in 1:length(unique(data$landmarkgroups[,2]))) {
partitions[[part]] <- which(data$landmarkgroups[,2] == unique(data$landmarkgroups[,2])[part])
}
if(missing(rarefaction)) {
rarefaction <- FALSE
}
if(rarefaction) {
part_min <- min(unlist(lapply(partitions, length)))
}
if(verbose) message("Done.\n")
## Size differences
if(verbose) message("Run size difference test...")
if(rarefaction) {
differences <- lapply(partitions, lapply.rand.test, data = procrustes_var, test = area.diff, replicates = 1000, rarefaction = part_min, resample = FALSE)
} else {
differences <- lapply(partitions, lapply.rand.test, data = procrustes_var, test = area.diff, replicates = 1000, resample = FALSE)
}
if(verbose) message("Done.\n")
## Probabilities of overlap
if(verbose) message("Run overlap probability test...")
if(rarefaction) {
overlaps <- lapply(partitions, lapply.rand.test, data = procrustes_var, test = bhatt.coeff, replicates = 1000, rarefaction = part_min, resample = FALSE)
} else {
overlaps <- lapply(partitions, lapply.rand.test, data = procrustes_var, test = bhatt.coeff, replicates = 1000, resample = FALSE)
}
if(verbose) message("Done.\n")
if(!rarefaction) {
return(list("differences" = differences, "overlaps" = overlaps, "species" = species, "dataset" = dataset))
} else {
return(list("differences" = differences, "overlaps" = overlaps, "species" = species, "dataset" = dataset, "rarefaction" = part_min))
}
}
##Summary pipeline
pipeline.plots <- function(results, export = FALSE){
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
}
## Function for applying the rand tests
lapply.rand.test <- function(partition, data, test, ...) {
rand.test(data[, "radius"], partition, test = test, test.parameter = TRUE, ...)
}
lapply.bootstrap.test <- function(partition, data, statistic, ...) {
bootstrap.test(data[, "radius"], partition, statistic = statistic, ...)
}
## Function for translating the names in the datasets into the actual species names
translate.name <- function(name) {
names <- c("All species", "Lasiorhinus", "Lasiorhinus krefftii", "Lasiorhinus latifrons", "Vombatus ursinus")
if(name == "Wombat_ursinus") {
return(names[5])
}
if(name == "Wombat") {
return(names[1])
}
if(name == "Wombat_lasiorhinus") {
return(names[2])
}
if(name == "Wombat_krefftii") {
return(names[3])
}
if(name == "Wombat_latifrons") {
return(names[4])
}
return(name)
}
## Function for getting the partition order and names
get.partition.args <- function(partition) {
if(partition == "cranium") {
return(list("partitions" = c("Zygomatic Arch", "Tip of snout", "Remainder"), "partitions.order" = c(1, 3, 2)))
}
if(partition == "mandible") {
return(list("partitions" = c("Masticatory insertions", "Symphyseal area", "Remainder"), "partitions.order" = c(3, 1, 2)))
}
return(list(NULL))
}
## Function for plotting the test results
make.table <- function(results, correction, partition.args) {
if(missing(partition.args)) {
partition.args <- list(NULL)
}
## Extract the values
values <- lapply(results, function(X) return(c(X$obs, X$expvar, X$pvalue)))
## make the table
summary_table <- cbind(seq(1:length(values)), do.call(rbind, values))
## Correcting the p.value
if(!missing(correction)) {
summary_table[, ncol(summary_table)] <- p.adjust(summary_table[, ncol(summary_table)],
method = correction)
p_name <- "p value (adjusted)"
} else {
p_name <- "p value"
}
##Adding the partitions names
if(!is.null(partition.args$partitions)) {
summary_table <- data.frame(summary_table)
summary_table[,1] <- partition.args$partitions
}
## Adding the colnames
colnames(summary_table)[c(1,2,6)] <- c("Partition", "Observed", p_name)
## Re-ordering partitions (if not missing)
if(!is.null(partition.args$order.partitions)) {
summary_table <- summary_table[, partition.args$order.partitions]
}
return(summary_table)
}
make.xtable <- function(results, correction, partition.args, digits = 3, caption, label, longtable = FALSE, path) {
## Make the results table
results_table <- make.table(results, correction = correction, partition.args)
## Rounding
results_table[, c(2,3,6)] <- round(results_table[, c(2,3,6)], digits = digits)
if(all(as.vector(round(results_table[, c(4,5)], digits = digits) == 0))) {
results_table[, c(4,5)] <- round(results_table[, c(4,5)], digits = digits+2)
} else {
results_table[, c(4,5)] <- round(results_table[, c(4,5)], digits = digits)
}
## Add significance values
p_col <- grep("p value", colnames(results_table))
if(length(p_col) > 0) {
for(row in 1:nrow(results_table)) {
if(as.numeric(results_table[row, p_col]) < 0.05) {
results_table[row, p_col] <- paste0("BOLD", results_table[row, p_col])
}
}
}
##Bold cells function
bold.cells <- function(x) gsub('BOLD(.*)', paste0('\\\\textbf{\\1', '}'), x)
## convert into xtable format
textable <- xtable(results_table, caption = caption, label = label)
if(!missing(path)) {
if(longtable == TRUE) {
cat(print(textable, tabular.environment = 'longtable', floating = FALSE, include.rownames = FALSE, sanitize.text.function = bold.cells), file = paste0(path, label, ".tex"))
} else {
cat(print(textable, include.rownames = FALSE, sanitize.text.function = bold.cells), file = paste0(path, label, ".tex"))
}
}
if(longtable == TRUE) {
print(textable, tabular.environment = 'longtable', floating = FALSE, include.rownames = FALSE, sanitize.text.function = bold.cells)
} else {
print(textable, include.rownames = FALSE, sanitize.text.function = bold.cells)
}
}
make.plots <- function(results, type, add.p = FALSE, correction, rarefaction = FALSE, rare.level, path) {
## Number of plots
n_plots <- length(results)
##Plotting parameters
if(!missing(path)) {
pdf(file = path)
} else {
n_rows <- c(ceiling(sqrt(n_plots)), floor(sqrt(n_plots)))
if(n_rows[1]*n_rows[2] < n_plots) {
n_rows <- c(ceiling(sqrt(n_plots)), ceiling(sqrt(n_plots)))
}
par(mfrow = n_rows, bty = "n")
}
## Getting the results table
if(add.p) {
table_res <- make.table(results, correction)
}
for(one_plot in 1:n_plots) {
## Plot
if(!rarefaction) {
main_lab <- paste("Partition", one_plot)
} else {
main_lab <- paste0("Partition ", one_plot, " (rarefied - ", rare.level, ")")
}
plot(results[[one_plot]], xlab = type, main = main_lab)
## Rarefaction (unless the rarefied results are invariant, i.e. minimum level)
if(rarefaction && length(unique(unlist(results[[one_plot]]$observed))) != 1) {
add.rare.plot(results[[one_plot]])
}
## p_value
if(add.p) {
##Get the coordinates for the text
text_pos <- ifelse(table_res[one_plot, "Observed"] < table_res[one_plot, "Random mean"], "topleft", "topright")
## Add the text
legend(text_pos, paste(colnames(table_res)[6], round(table_res[one_plot, 6], 5), sep = "\n") , bty = "n")
}
}
if(!missing(path)) {
dev.off()
}
}
# Utilities based on existing functions
#colouring partition spheres
#@param land_data_partition the landmark data e.g. land_data$cranium
#@param partnames is an optional vector with names for each partition number
#@param PointSize is for changing the size of spheres plotted
#Defining partitions using the define.module (needs individual execution)
plot.partitions<-function(land_data_partition, PartNames, PointSize){
##the object with the landmarks subset according to partitions
Part=list()
WomCrGPA<-land_data_partition$procrustes
WomCrPart<-land_data_partition$landmarkgroups
WomCrRef <- mshape(land_data_partition$procrustes$coords)
#provides the numbers of the parts
PartLevels= unique(WomCrPart[,2])
Colours<-rainbow(length(PartLevels))
Colours <- c("blue", "orange", "green")
##subset the landmarks according to the partitions
for(i in 1:length(PartLevels)){
Part[[i]]<-which (WomCrPart[,2] == PartLevels[[i]])
}
##provides names for each of the partitions (optional and requires a name vector to be given)
if (!missing(PartNames)){
for (i in 1:length(PartLevels)){
names(Part)[i]<-PartNames[i]
}
}
##colours the spheres for each partition
open3d()
for (i in 1:length(PartLevels)){
spheres3d(WomCrRef[Part[[i]],1], WomCrRef[Part[[i]],2], WomCrRef[Part[[i]],3], col=Colours[i], lit=TRUE,radius = PointSize, asp=F)
}
}
#Visualizing differences between PC min and max
#@param x is the coordinates after gpa e.g. land_data$cranium
#@param minfirst is whether min vs max or other way round (for PlotRefToTarget )
PCA.vectors<-function(x, minfirst=TRUE){
gridPar=gridPar(pt.bg = "white", pt.size = 0.5)#These are needed to give it the right parameters for the point size, colour and size - the default is too large points
open3d()
PCA=plotTangentSpace(x$procrustes$coords)
open3d()
if (minfirst==TRUE){
plotRefToTarget(PCA$pc.shapes$PC1min,PCA$pc.shapes$PC1max, method="vector", gridPars=gridPar, label = F)
} else {
plotRefToTarget(PCA$pc.shapes$PC1max,PCA$pc.shapes$PC1min, method="vector", gridPars=gridPar, label = F)
}
}
#procD code (for procD.lm and procD.lm) analysis
#@param formula: a formula object (e.g. coords ~ Csize)
#@param procrustes: the procrustes object (e.g. land_data$cranium$procrustes)
#@param procD.fun: the procD function (e.g. procD.lm)
#@param ...: any optional arguments to be passed to procD.fun (e.g. logsz = FALSE, iter = 1, etc...)
handle.procD.formula <- function(formula, procrustes, procD.fun = procD.lm, ...) {
geomorph_data_frame <- geomorph.data.frame(procrustes)
return(procD.fun(f1 = formula, data = geomorph_data_frame, ...))
}
# heatplot.PCs(CW$cranium, minfirst=FALSE, PC_axis=1)
#Allometry analysis (based on above handle.procD.formula)
allom.shape<-function (procrustes_coordinate_file_with_centroid_size){
Allometry <- handle.procD.formula(formula=coords~ Csize, procrustes=procrustes_coordinate_file_with_centroid_size, procD.fun = procD.lm, logsz = FALSE, iter = 1000)
print(attributes(Allometry))
return(Allometry)
}
#Reducing datasets to those with counterparts
#@params AllData is a list of procrustes objects after gpa (e.g. land_data, in this case the different species); AllClassifiers is a list of classifiers matched with the AllData shape dataset, which includes subsetting information
reduce.check<-function(AllData, AllClassifiers, procrustes = 2){
coords_PLS_output=list()
check_output=list()
for (i in 1:length(AllData)){
coords_PLS_output[[i]]=list()
for (k in 1:length(AllClassifiers[[i]])){
coords_PLS_output[[i]][[k]] <- AllData [[i]][[k]][[procrustes]]$coords [ , ,as.character(AllClassifiers[[i]][[k]]$TBPLS) != "Nil"]
}
names(coords_PLS_output[[i]])<-names(AllData[[i]])
}
names(coords_PLS_output)<-names(AllData)
for (i in 1:length(AllData)){
matchCheck=match(attributes(coords_PLS_output[[i]]$cranium)$dimnames[[3]], attributes(coords_PLS_output[[i]]$mandible)$dimnames[[3]])
check_output[[i]]=!is.na(matchCheck)&&all(matchCheck==sort(matchCheck))
}
names(check_output)<-names(AllData)
return(list(coords_PLS_output, check_output))
}
#@param CI: the confidence interval level or "mean" for the results of the mean comparisons
#@param rarefaction: whether to use the rarefied results (TRUE) or not (FALSE)
#@param print.token: whether to add the significance tokens (i.e. stars)
#@param rounding: the number of digits to print after 0.
#@param path: the path to the results
#@param species: the list of species as written in the results
#@param datasets: the names of the datasets as written in the results
#@param partitions.order: optional, reordering the partition names
#@param partitions: optional, the name of the landmark partitions columns
#@param species.names: the names of species to display
#@param result.type: the type of results to summarise (variation.range, pc1.extremes, pc1.hypothetical)
summarise.results <- function(CI, rarefaction, print.token = FALSE, rounding = 4, path = "../Data/Results/", species = c("Wombat", "Wombat_lasiorhinus", "Wombat_krefftii", "Wombat_latifrons", "Wombat_ursinus"), datasets = c("cranium", "mandible"), partitions.order = c(1, 3, 2, 6, 4, 5), partitions, species.names, result.type = "variation.range") {
## Printing significance tokens
get.token <- function(p) {
if(p > 0.05) {
return("")
}
if(p < 0.05 && p > 0.01) {
return(".")
}
if(p < 0.01 && p > 0.001) {
return("*")
}
if(p < 0.001) {
return("**")
}
}
## Mean results reading
if(CI == "mean") {
## Summarising the results of the pairwise mean shape comparisons
summarise.results.pairwise <- function(results, dataset, rounding) {
## number of comparisons
n_comp <- length(results)
## number of paritions
n_part <- unique(unlist(lapply(results, length)))
## Making the empty dataframe results holder
results_table <- data.frame(matrix(NA, ncol = n_part+1, nrow = n_comp*2))
## Filling the table for each results first two columns
colnames(results_table) <- c("test", paste(dataset, c(1:n_part)))
rownames(results_table) <- paste0(rep(names(results), each = 2), rep(1:2))
results_table[, 1] <- rep(c("diff", "p"), n_comp)
## Filling the rest of the table
get.one.result <- function(one_result, rounding) {
return(do.call(cbind, lapply(one_result, function(X) return(round(c(X$obs, X$pvalue), digits = rounding)))))
}
results_table[, -1] <- do.call(rbind, lapply(results, get.one.result, rounding))
return(results_table)
}
## Loading the means results (observed)
if(result.type == "variation.range"){
if(rarefaction == FALSE) {
load(paste0(path, "Group_cranium_means.Rda"))
load(paste0(path, "Group_mandible_means.Rda"))
} else {
load(paste0(path, "Group_craniumrarefied_means.Rda"))
load(paste0(path, "Group_mandiblerarefied_means.Rda"))
}
} else {
if(rarefaction == FALSE) {
load(paste0(path, "Group_cranium_means_hypo.Rda"))
load(paste0(path, "Group_mandible_means_hypo.Rda"))
} else {
load(paste0(path, "Group_craniumrarefied_means_hypo.Rda"))
load(paste0(path, "Group_mandiblerarefied_means_hypo.Rda"))
}
}
## Getting the pairwise results
diff_cran <- summarise.results.pairwise(group_cranium$differences, "Cranium", rounding)
over_cran <- summarise.results.pairwise(group_cranium$overlaps, "Cranium", rounding)
diff_mand <- summarise.results.pairwise(group_mandible$differences, "Mandible", rounding)
over_mand <- summarise.results.pairwise(group_mandible$overlaps, "Mandible", rounding)
## Changing the test name for the overlaps
over_cran[,1] <- gsub("diff", "overlap", over_cran[,1])
over_mand[,1] <- gsub("diff", "overlap", over_mand[,1])
## Combine both tables
merge.table <- function(tab1, tab2) {
merge.row <- function(X, tab1, tab2) rbind(tab1[c(X, X+1), ], tab2[c(X, X+1), ])
return(do.call(rbind,
lapply(as.list(seq(from = 1, to = (nrow(tab1)-1), by = 2)),
merge.row, tab1 = tab1, tab2 = tab2)
)
)
}
## Combine everything
results_table <- cbind(merge.table(diff_cran, over_cran), merge.table(diff_mand, over_mand)[, -1])
## Order the partitions
results_table <- results_table[, c(1, (partitions.order+1))]
return(results_table)
} else {
##Make the empty table
results_table <- data.frame(matrix(NA, ncol = length(species)*4, nrow = 6+1))
## Loop through the datasets
for(sp in 1:length(species)) {
for(ds in 1:length(datasets)) {
## Get the type of results to load
if(result.type == "variation.range") {
result_type <- ""
}
if(result.type == "pc1.extremes") {
result_type <- "_PC1"
}
if(result.type == "pc1.hypothetical") {
result_type <- "_PChypo"
}
## Extract the results
if(rarefaction) {
load(paste0(path, species[sp], "_", datasets[ds], "rarefied_CI", CI, result_type, ".Rda"))
} else {
load(paste0(path, species[sp], "_", datasets[ds], "_CI", CI, result_type, ".Rda"))
}
## Summarise the results
difference <- make.table(results$difference)#, correction = "bonferroni")
overlap <- make.table(results$overlaps)#, correction = "bonferroni")
## Fill the table
if(ds == 1) {
## Values
results_table[2:4, 1+(4*(sp-1))] <- round(difference[,2], digits = rounding)
results_table[2:4, 3+(4*(sp-1))] <- round(overlap[,2], digits = rounding-1)
## Signif
if(print.token) {
results_table[2:4, 2+(4*(sp-1))] <- paste0(round(difference[,6], digits = rounding), sapply(difference[,6], get.token))
results_table[2:4, 4+(4*(sp-1))] <- paste0(round(overlap[,6], digits = rounding), sapply(overlap[,6], get.token))
} else {
results_table[2:4, 2+(4*(sp-1))] <- round(difference[,6], digits = rounding)
results_table[2:4, 4+(4*(sp-1))] <- round(overlap[,6], digits = rounding)
}
} else {
## Values
results_table[5:7, 1+(4*(sp-1))] <- round(difference[,2], digits = rounding)
results_table[5:7, 3+(4*(sp-1))] <- round(overlap[,2], digits = rounding-1)
## Signif
if(print.token) {
results_table[5:7, 2+(4*(sp-1))] <- paste0(round(difference[,6], digits = rounding), sapply(difference[,6], get.token))
results_table[5:7, 4+(4*(sp-1))] <- paste0(round(overlap[,6], digits = rounding), sapply(overlap[,6], get.token))
} else {
results_table[5:7, 2+(4*(sp-1))] <- round(difference[,6], digits = rounding)
results_table[5:7, 4+(4*(sp-1))] <- round(overlap[,6], digits = rounding)
}
}
}
}
## Reordering the rows (future columns)
results_table[2:7,] <- results_table[(partitions.order+1),]
## Renaming the table elements
if(!missing(partitions)) {
rownames(results_table) <- c("test", partitions)
} else {
rownames(results_table) <- c("test", c(paste("Cranium", c(1,2,3)), paste("Mandible", c(1,2,3)))[partitions.order])
}
## Transpose the table
results_table <- as.data.frame(t(results_table))
results_table[,1] <- rep(c("diff", "p", "overlap", "p"), length(species))
if(!missing(species.names)) {
rownames(results_table) <- names(unlist(sapply(species.names, rep, 4, simplify = FALSE)))
} else {
rownames(results_table) <- names(unlist(sapply(species, rep, 4, simplify = FALSE)))
}
## Flip the table
return(results_table)
}
}
## Exporting results in xtable format
xtable.results <- function(results, partitions.names, test.names, path, file.name, caption, digits) {
get.token <- function(p) {
if(p > 0.001) {
return(paste0(p, ""))
}
# if(p < 0.01 && p > 0.005) {
# return(paste0(p, "."))
# }
# if(p < 0.005 && p > 0.001) {
# return(paste0(p, "*"))
# }
if(p <= 0.001) {
return(paste0(p, "*"))
}
}
## get the p tokens
p_rows <- which(results[,1] == "p")
results[p_rows, -1] <- apply(results[p_rows, -1], c(1,2), get.token)
## Add the test names tables
results_out <- cbind(c(sapply(test.names, function(X) return(c(X, rep("", 3))), simplify = TRUE)), results)
colnames(results_out) <- c("", "test", partitions.names)
## convert into xtable format
textable <- xtable(results_out, caption = caption, label = file.name)
bold.cells <- function(x) gsub('BOLD(.*)', paste0('\\\\textbf{\\1', '}'), x)
if(missing(path)) {
print(textable, include.rownames = FALSE, sanitize.text.function = bold.cells)
} else {
cat(print(textable, include.rownames = FALSE, sanitize.text.function = bold.cells), file = paste0(path, file.name, ".tex"))
}
}
#@param data: the non-rarefied summarised data
#@param rarefaction: the rarefied summarised data
#@param no.rar: optional, which columns to highlight as not rarefied (e.g. cranium 3 and mandible 1: no.rar = c(3,4))
#@param ignore.non.signif: whether to ignore the non-significant results for rarefaction highlights (TRUE) or not (FALSE).
#@pram partitions: the names of the partitions (c("cranium", "mandible"))
#@param cols: a vector of three colours for each pixel, the first one is non-significant results, the second one is when the difference is significant but not the overlap and the third one is when everything is significant
#@param threshold: the significance threshold (default = 0.01)
#@param ylabs: the labels for the y axis ("all_data", "Vombatus", etc). If missing the ones from data are used.
#@param xlabs: the labels for the x axis ("cranium1", etc). If missing the ones from data are used.
#@param digits: the digits to display
#@param left.pad: the space on the left for the text on the left
plot.test.results <- function(data, rarefaction, p.value = 0.001, no.rar, ignore.non.signif = TRUE, partitions = c(expression(bold("Cranium")), expression(bold("Mandible"))), cols = c("grey", "magenta", "green"), ylabs, ylabs2, xlabs, digits, left.pad = 4, ylab.cex = 1, hypothesis, col.hypo) {
## Making the x and y labels (if needed)
if(missing(ylabs)) {
ylabs <- gsub("1", "", rownames(data)[seq(from = 1, to = nrow(data), by = 4)])
}
if(missing(xlabs)) {
xlabs <- colnames(data[, -1])
}
## Converting the matrix in to numeric blocks
make.blocks <- function(col) {
from <- as.list(seq(from = 1, to = length(col), by = 4))
to <- as.list(seq(from = 0, to = length(col), by = 4)[-1])
return(mapply(function(from, to, col) return(col[from:to]), from, to, MoreArgs = list(col = col), SIMPLIFY = FALSE))
}
blocks <- apply(apply(data[,-1], 2, as.numeric), 2, make.blocks)
## Selecting the threshold level
level.selector <- function(block, threshold = p.value) {
return(ifelse(block[2] > threshold, 1, ifelse(block[4] > threshold, 2, 3)))
}
## Transform the list of blocks in an image matrix
image_matrix <- matrix(unlist(lapply(blocks, lapply, level.selector, threshold = p.value)), ncol = ncol(data[, -1]), byrow = FALSE)
## Plot the main image
par(mar = c(2, max(nchar(ylabs))/2, 4, 2), mar = c(5, left.pad, 4, 4)) #c(bottom, left, top, right)
#image(t(image_matrix[nrow(image_matrix):1,]), col = cols, xaxt = "n", yaxt = "n", ...)
image(t(image_matrix[nrow(image_matrix):1,]), col = cols, xaxt = "n", yaxt = "n")
## Adding the y labels
axis(2, at = seq(from = 0, to = 1, length.out = nrow(image_matrix)), las = 2, label = rev(ylabs), tick = FALSE, cex.axis = ylab.cex)
axis(4, at = seq(from = 0.25, to = 0.85, length.out = 3), las = 3, label = rev(ylabs2), tick = FALSE, cex.axis = ylab.cex, padj = 0.2)
## Add the x labels
if(length(grep("\\n", xlabs) > 0)) {
padj <- 0.5
} else {
padj <- 1
}
axis(3, at = seq(from = 0, to = 1, length.out = ncol(image_matrix)), label = xlabs, tick = FALSE, padj = padj)
axis(3, at = c(0.25, 0.75), label = partitions, tick = FALSE, padj = -2)
## Adding the values
value_to_plot <- ifelse(image_matrix != 1, TRUE, FALSE)
rownames(value_to_plot) <- rev(seq(from = 0, to = 1, length.out = nrow(value_to_plot)))
colnames(value_to_plot) <- seq(from = 0, to = 1, length.out = ncol(value_to_plot))
##Getting the list of blocks coordinates from a named TRUE/FALSE matrix
get.coords <- function(list_coords) {
list_blocks_x <- as.numeric(t(apply(list_coords, 1, function(x) names(x))))
list_blocks_y <- as.numeric(apply(list_coords, 2, function(x) names(x)))
coords_x <- list_blocks_x[list_coords]
coords_y <- list_blocks_y[list_coords]
return(list(coords_x, coords_y))
}
values_coords <- get.coords(value_to_plot)
values <- round(unlist(lapply(blocks, lapply, function(x) return(x[1])))[value_to_plot], digits = digits)
text(x = values_coords[[1]], y = values_coords[[2]], labels = values)
## Adding the rarefaction (square the pixel if equal)
blocks <- apply(apply(rarefaction[,-1], 2, as.numeric), 2, make.blocks)
## Transform the list of blocks in an image matrix
image_rar <- matrix(unlist(lapply(blocks, lapply, level.selector, threshold = p.value)), ncol = ncol(rarefaction[, -1]), byrow = FALSE)
## Getting the rarefaction coordinates
if(ignore.non.signif) {
rar_coords <- image_rar == ifelse(image_matrix == 1, 0, image_matrix)
} else {
rar_coords <- image_rar == image_matrix
}
rownames(rar_coords) <- rev(seq(from = 0, to = 1, length.out = nrow(image_matrix)))
colnames(rar_coords) <- seq(from = 0, to = 1, length.out = ncol(image_matrix))
## Removing no.rar columns if not missing
if(!missing(no.rar)) {
rar_coords[,no.rar] <- FALSE
}
##Getting the list of blocks coordinates that are the same between rar and normal
rar_coords <- get.coords(rar_coords)
## Getting the polygon coordinates
get.polygon.coordinates <- function(block_x, block_y, image_matrix, lwd) {
##Get the size of the pixels
x_size <- diff(seq(from = 0, to = 1, length.out = ncol(image_matrix)))[1]
y_size <- diff(seq(from = 0, to = 1, length.out = nrow(image_matrix)))[1]
if(!missing(lwd)) {
x_size <- x_size - lwd/1000
y_size <- y_size - lwd/1000
}
x_coords <- c(block_x-x_size/2, block_x-x_size/2, block_x+x_size/2, block_x+x_size/2)
y_coords <- c(block_y-y_size/2, block_y+y_size/2, block_y+y_size/2, block_y-y_size/2)
return(list(x_coords, y_coords))
}
## Adding the polygons
for(poly in 1:length(rar_coords[[1]])) {
block_polygon <- get.polygon.coordinates(rar_coords[[1]][poly], rar_coords[[2]][poly], image_matrix)
polygon(x = block_polygon[[1]], y = block_polygon[[2]], lwd = 3)
}
# ## Adding the hypothesis difference (if not equal)
# if(!missing(hypothesis)) {
# ## Get list of hypothesis change
# check.hypothesis <- function(columns, hypothesis) {
# if(hypothesis == 1) {
# ifelse(column > 0, FALSE, TRUE)
# } else {
# ifelse(column < 0, FALSE, TRUE)
# }
# }
# }
## Adding the hypothesis difference (if not equal)
if(!missing(hypothesis)) {
## Get the values
matrix_values <- data[seq(from = 1, to = nrow(data), by = 4),-1]
image_hypothesis <- matrix(NA, ncol = ncol(matrix_values), nrow = nrow(matrix_values))
## Get the hypothesis
positives <- which(hypothesis > 0)
image_hypothesis[, positives] <- ifelse(matrix_values[, positives] > 0, 0, 1)
negatives <- which(hypothesis < 0)
image_hypothesis[, negatives] <- ifelse(matrix_values[, negatives] < 0, 0, 1)
## Get the image coordinates matrix (remove the ignored - if necessary)
if(ignore.non.signif) {
image_coords <- image_hypothesis & ifelse(image_matrix == 1, 0, 1)
} else {
image_coords <- ifelse(image_hypothesis == 1, TRUE, FALSE)
}
rownames(image_coords) <- rev(seq(from = 0, to = 1, length.out = nrow(image_matrix)))
colnames(image_coords) <- seq(from = 0, to = 1, length.out = ncol(image_matrix))
##Getting the list of blocks coordinates that are the same between rar and normal
image_coords <- get.coords(image_coords)
## Adding the polygons
for(poly in 1:length(image_coords[[1]])) {
block_polygon <- get.polygon.coordinates(image_coords[[1]][poly], image_coords[[2]][poly], image_matrix)
polygon(x = block_polygon[[1]], y = block_polygon[[2]], lwd = 3, border = col.hypo)
}
}
## Separator
abline(v = 0.5, lty = 2, lwd = 1.2)
## set the number of categories border
categories <- c(2,8,14)
## Get the coordinates of the centres of each cell
centers <- seq(from = 0, to = 1, length.out = nrow(image_matrix))
## Get the splits between categories (mean of c(categorie, categorie+1))
borders <- apply(matrix(c(centers[categories], centers[categories+1]), ncol = length(categories), byrow = TRUE), 2, mean)
abline(h=borders, lty = 2, lwd = 1.2)
}
## Easy PCA plotting
#@param ordination: the ordination data (prcomp). (e.g. cranium$ordination)
#@param classifier: the classifier (e.g. Species, etc..)
#@param axis: which axis to plot (default is 1 and 2)
#@param ...: any graphical arguments for plot()
plot.pca <- function(ordination, classifier, axis = c(1, 2), ...) {
## The ggplot colours
gg.color.hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
## The data
data <- ordination$x[,axis]
##The plot limits
plot_lim <- range(as.vector(c(data)))
## The loadings
load <- summary(ordination)$importance[2,axis]*100
## The plot
plot(NULL, xlim = plot_lim, ylim = plot_lim,
xlab = paste0("PC", axis[1], " (", round(load[1], 0), "%)"),
ylab = paste0("PC", axis[2], " (", round(load[2], 0), "%)"),
cex.lab = 1.3,
...)
## The convex hull
get.chulls <- function(data, classifier) {
## Placeholder
chull_list <- list()
##Splitting the data per classifiers
data_class <- mapply(cbind, split(data[,1], classifier), split(data[,2], classifier))
##Getting the convex hull positions per classifiers
chull_pos <- lapply(data_class, chull)
## Getting the chull coordinates per classifier
get.chull.coords <- function(pos, data) return(rbind(data[pos, ], data[pos[1], ]))
return(mapply(get.chull.coords, chull_pos, data_class))
}
## Plotting the polygons
plot.one.polygon <- function(polygon, col) {
polygon(polygon, col = paste0(col, "50"), border = col)
}
silent <- mapply(plot.one.polygon, get.chulls(data, classifier),
as.list(gg.color.hue(length(levels(classifier)))))
## The points
points(data, pch = 21,
bg = gg.color.hue(length(levels(classifier)))[classifier])
}
#Heatplot code for hypothetical PC shapes; requires landmarktest to be loaded
#@params Species_dataset is the dataset in question (e.g.CW$cranium);
#@params min_or_max_first ("min", "max")is if you want min referenced to max or vice versa. this is handy if one common lm displacement pattern happens to be associated with opposite signed PC scores.
heatplot.PCs<-function (species_dataset,minfirst, PC_axis,...){
## Procrustes variation ranges for PCA; axis determines which ordination axis to use
variation <- variation.range(species_dataset$procrustes, return.ID = TRUE, axis=PC_axis, ordination=species_dataset$ordination)
#determines range of variation between PC extremes
procrustes_var <- variation$range[,1]
#runs PCA for min/max plotting
PCA=plotTangentSpace(species_dataset$procrustes$coords, verbose=FALSE)
gridPar = gridPar(pt.bg = "white", pt.size = 0.5)
#converting pc shape ID of PCA into column numbers so the PC number can be chosen (e.g. PC6min is PCA$pc.shapes[[11]])
pc_IDs <- c(PC_axis*2-1, PC_axis*2)
if(minfirst==TRUE){
open3d()
procrustes.var.plot(PCA$pc.shapes[[pc_IDs[1]]],
PCA$pc.shapes[[pc_IDs[2]]],
col = heat.colors, pt.size = 0.7, col.val = procrustes_var,...)}
else {
open3d()
procrustes.var.plot(PCA$pc.shapes[[pc_IDs[2]]],
PCA$pc.shapes[[pc_IDs[1]]],
col = heat.colors, pt.size = 0.7, col.val = procrustes_var, ...)}
}<file_sep>---
title: "Standard analyses"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(knitr)) install.packages("knitr"); library(knitr)
if(!require(xtable)) install.packages("xtable"); library(xtable)
if(!require(geomorph)) install.packages("geomorph"); library(geomorph)
if(!require(dispRity)) install.packages("dispRity");library(dispRity)
source("../Functions/utilities.R")
set.seed(42)
## Loading and renaming the land_data objects
load("../Data/Processed/wombat.Rda")
AllWombats <- land_data
load("../Data/Processed/wombat_krefftii.Rda")
NHNW <- land_data
load("../Data/Processed/wombat_latifrons.Rda")
SHNW <- land_data
load("../Data/Processed/wombat_ursinus.Rda")
CW <- land_data
## Read the classifiers
cranium <- read.csv("../Data/Raw/classifier_cranium_wombat.csv")
mandible <- read.csv("../Data/Raw/classifier_mandible_wombat.csv")
## Remove juvenile from mandibles
nhnw_b34 <- which(mandible[,1] == "NHNW_B34")
mandible <- mandible[-nhnw_b34, ]
##brief check that the landmarks were pulled out correctly - number of landmarks and plotting of landmarks
### fixed landmarks only: 65 fixed landmarks for cranium, 35 fixed landmarks for mandible
length(dimnames(mshape(AllWombats$cranium$procrustes_no_patches$coords))[[1]]); plot3d(mshape(AllWombats$cranium$procrustes_no_patches$coords),asp=FALSE)
length( dimnames(mshape(AllWombats$mandible$procrustes_no_patches$coords))[[1]])
plot3d(mshape(AllWombats$mandible$procrustes_no_patches$coords),asp=FALSE)
### fixed landmarks and curves only: 261 curve landmarks for cranium, 142 fixed landmarks for mandible
length(dimnames(mshape(AllWombats$cranium$procrustes_no_patches_no_curves$coords))[[1]])-65; plot3d(mshape(AllWombats$cranium$procrustes_no_patches$coords),asp=FALSE)
length( dimnames(mshape(AllWombats$mandible$procrustes_no_patches_no_curves$coords))[[1]])-35;
plot3d(mshape(AllWombats$mandible$procrustes_no_patches$coords),asp=FALSE)
```
#Separating the classifier file by species
```{r, message = FALSE, warning = FALSE}
## Creating the vectors holding the species names
species <- c("CW", "SHNW", "NHNW")
sp_holders <-c("Common wombat", "SHN wombat", "NHN wombat")
## Assigning the right class to each species (for the cranium)
for (i in 1:length(unique(cranium$Species))) {
## Extracting the class for each species
class <- cranium[cranium$Species == sp_holders[i],]
## Preparing the sp name for giving names to outputs
sp_name <- paste(species[i], deparse(substitute(cranium)), "class", sep = "_")
## Assigning the class to the names
assign(sp_name, class)
}
## Assigning the right class to each species (for the mandible)
for (i in 1:length(unique(mandible$Species))) {
## Extracting the class for each species
class <- mandible[mandible$Species == sp_holders[i],]
## Preparing the sp name for giving names to outputs
sp_name <- paste(species[i], deparse(substitute(mandible)), "class", sep = "_")
## Assigning the class to the names
assign(sp_name, class)
}
```
#How much % variation is explained by PC1?
```{r}
plotTangentSpace(NHNW$cranium$procrustes_no_patches$coords)
plotTangentSpace(NHNW$mandible$procrustes_no_patches$coords)
plotTangentSpace(SHNW$cranium$procrustes_no_patches$coords)
plotTangentSpace(SHNW$mandible$procrustes_no_patches$coords)
plotTangentSpace(CW$cranium$procrustes_no_patches$coords)
plotTangentSpace(CW$mandible$procrustes_no_patches$coords)
```
# disparity comparison between wombat species
```{r, message = FALSE, warning = FALSE}
## Create gdfs with species for the data frames
cranium_gdf <- geomorph.data.frame(coords = AllWombats$cranium$procrustes_no_patches$coords,
Csize = AllWombats$cranium$procrustes_no_patches$Csize,
species = as.factor(cranium$Species))
mandible_gdf <- geomorph.data.frame(coords = AllWombats$mandible$procrustes_no_patches$coords,
Csize = AllWombats$mandible$procrustes_no_patches$Csize,
species = as.factor(mandible$Species))
## Running the analyses on the gdf objects (Disparity within groups compared to that group's mean)
cranium_disparity <- morphol.disparity(coords ~ species, groups = ~species, iter = 1000, seed = 42,
data = cranium_gdf, print.progress = FALSE)
## Disparity within groups compared to that group's mean
mandible_disparity <- morphol.disparity(coords ~ species, groups = ~species, iter = 1000, seed = 42,
data = mandible_gdf, print.progress = FALSE)
```
And we can display the results as follows:
```{r, echo = FALSE}
## Cranium disparity values
kable(data.frame("Procrustes variance" = cranium_disparity[[1]]), digits = 5, caption = "Cranium disparity (procrustes variance) per groups (only fixed landmarks).")
## Cranium disparity differences
kable(cranium_disparity[[2]], digits = 5, caption = "Cranium pairwise absolute differences between variances between groups (only fixed landmarks).")
## Cranium disparity differences p
kable(cranium_disparity[[3]], digits = 5, caption = "Cranium pairwise absolute differences between variances between groups (p-values - only fixed landmarks).")
## Mandible disparity values
kable(data.frame("Procrustes variance" = mandible_disparity[[1]]), digits = 5, caption = "Mandible disparity (procrustes variance) per groups (only fixed landmarks).")
## Mandible disparity differences
kable(mandible_disparity[[2]], digits = 5, caption = "Mandible pairwise absolute differences between variances between groups (only fixed landmarks).")
## Mandible disparity differences p
kable(mandible_disparity[[3]], digits = 5, caption = "Mandible pairwise absolute differences between variances between groups (p-values - only fixed landmarks).")
```
#Are wombats sexually dimorphic?
## Make the sex subsets
The following analysis don't contain the northern hairy nose wombats because there is no variation in sex assignment in the dataset.
```{r, message = FALSE, warning = FALSE}
## Making the classifiers list
all_data <- list("SHNW" = SHNW, "CW" = CW)
all_classifiers <- list("SHNW" = list("cranium" = SHNW_cranium_class,
"mandible" = SHNW_mandible_class),
"CW" = list("cranium" = CW_cranium_class,
"mandible" = CW_mandible_class))
```
Creating the sex subsets and the centroid size per sex subsets:
```{r}
## Results placeholder
coords_sex_output <- c_size_sex_output <- list()
## Getting the coordinates for specimens with Sex
for (i in 1:length(all_data)){
## Result placeholder
list() ->
coords_sex_output[[i]] ->
c_size_sex_output[[i]]
##┬ Getting the coordinates for each classifier
for (k in 1:length(all_classifiers[[i]])){
## Sex coordinates
coords_sex_output[[i]][[k]] <- all_data[[i]][[k]]$procrustes_no_patches$coords[,,
!is.na(all_classifiers[[i]][[k]]$Sex)]
## Sex centroid size
c_size_sex_output[[i]][[k]] <- all_data[[i]][[k]]$procrustes_no_patches$Csize[
!is.na(all_classifiers[[i]][[k]]$Sex)]
}
## Naming the element
names(all_data[[i]]) ->
names(coords_sex_output[[i]]) ->
names(c_size_sex_output[[i]])
}
names(all_data) ->
names(coords_sex_output) ->
names(c_size_sex_output)
```
Creating the coordinates subsets and the centroid size subsets for sex:
```{r}
## Results placeholder
sex_gdfs <- list()
## Creating the geomorph dataframe for both species and datasets
for (i in 1:length(coords_sex_output)){
## Results placeholder
sex_gdfs[[i]] <- list()
for (k in 1:length(all_classifiers[[i]])){
## Sex data frame object
sex_gdfs[[i]][[k]] <- geomorph.data.frame(
coords = coords_sex_output[[i]][[k]],
Csize = c_size_sex_output[[i]][[k]],
Sex = all_classifiers[[i]][[k]]$Sex[!is.na(all_classifiers[[i]][[k]]$Sex)]
)
}
## Naming the elements
names(sex_gdfs[[i]]) <- names(all_data[[i]])
}
names(sex_gdfs) <- names(all_data)
## Making sure the dimension names are correct;requires testthat
#expect_equal(match(dimnames(geo_gdfs$SHNW$cranium$coords)[[3]],names(geo_gdfs$SHNW$cranium$Csize)),
# seq(1:length(names(geo_gdfs$SHNW$cranium$Csize))))
```
## Running procD.lm analyses
We can run the three following linear models for each species and each datasets:
* coordinates ~ sex + centroid size
* centroid size ~ sex
```{r, message = FALSE, warning = FALSE}
## Results placeholder
coord_sex_lm <- csize_sex_lm <- list()
## Running all the linear models
for (i in 1:length(sex_gdfs)){
## Results placeholder
coord_sex_lm[[i]] <- csize_sex_lm[[i]] <- list()
for (k in 1:length(sex_gdfs[[2]])){
## Running the coordinates ~ sex + centroid size models
coord_sex_lm[[i]][[k]] <- procD.lm(coords ~ Sex , print.progress = FALSE,
data = sex_gdfs[[i]][[k]], iter = 1000)
## Running the centroid size ~ sex models
csize_sex_lm[[i]][[k]] <- procD.lm(Csize ~ Sex, print.progress = FALSE,
data = sex_gdfs[[i]][[k]], iter = 1000)
}
## Renaming the models
names(coord_sex_lm[[i]]) -> names(csize_sex_lm[[i]])
}
names(coord_sex_lm) <- names(csize_sex_lm)
```
And we can display them as follows:
```{r, echo = FALSE}
## coordinates ~ sex + centroid size
kable(coord_sex_lm[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for coordinates as a function of sex and centroid size for the southern hairy nose wombat's cranium.")
kable(coord_sex_lm[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for coordinates as a function of sex and centroid size for the southern hairy nose wombat's mandible.")
kable(coord_sex_lm[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for coordinates as a function of sex and centroid size for the common wombat's cranium.")
kable(coord_sex_lm[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for coordinates as a function of sex and centroid size for the common wombat's mandible.")
## centroid size ~ sex
kable(csize_sex_lm[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for centroid size as a function of sex for the southern hairy nose wombat's cranium.")
kable(csize_sex_lm[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for centroid size as a function of sex for the southern hairy nose wombat's mandible.")
kable(csize_sex_lm[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for centroid size as a function of sex for the common wombat's cranium.")
kable(csize_sex_lm[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes (only fixed landmarks) linear model for centroid size as a function of sex for the common wombat's mandible.")
```
# Allometry Analyses
We can run the allometry tests using the `handle.procD.formula` wrapper function:
```{r, message = FALSE, warning = FALSE, result = 'hide'}
## List of all the data
all_data <- list("NHNW" = NHNW, "SHNW" = SHNW, "CW" = CW)
## Placeholder for the results
allom_output <- list()
## Running the allometry tests
for (i in 1:length(all_data)){
for (k in 1:length(all_data[[1]])){
## Result placeholder
allom_output[i][[k]] <- list()
## Procrustes allometry test (wrapper around the procD.allometry function)
allom_output[[i]][[k]] <- handle.procD.formula(coords ~ Csize,
all_data[[i]][[k]]$procrustes_no_patches,
procD.fun = procD.lm, iter = 1000,
print.progress = FALSE)
}
}
## Naming the results
names(allom_output) <- names(all_data)
## Naming the partitions
for(i in 1:length(all_data)) {
names(allom_output[[i]]) <- names(all_data[[i]])
}
```
And we can display them as follows:
```{r, echo = FALSE}
kable(allom_output[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the northern hairy nose wombat's cranium (only fixed landmarks).")
kable(allom_output[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the northern hairy nose wombat's mandible (only fixed landmarks).")
kable(allom_output[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the southern hairy nose wombat's cranium (only fixed landmarks).")
kable(allom_output[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the southern hairy nose wombat's mandible (only fixed landmarks).")
kable(allom_output[[3]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the common wombat's cranium (only fixed landmarks).")
kable(allom_output[[3]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the common wombat's mandible (only fixed landmarks).")
```
#Allometry between species
```{r}
#Cranium
##turn into gdf frame
gdf_cranium <- geomorph.data.frame(coords = AllWombats$cranium$procrustes_no_patches$coords,
Csize = AllWombats$cranium$procrustes_no_patches$Csize)
##run analysis
AllomCranium <- procD.lm(coords~Csize, data = gdf_cranium, method = "RegScore")
#Mandible
##turn into gdf frame
gdf_mandible <- geomorph.data.frame(coords = AllWombats$mandible$procrustes_no_patches$coords,
Csize = AllWombats$mandible$procrustes_no_patches$Csize)
##run analysis
AllomMandible <- procD.lm(coords~Csize, data = gdf_mandible, method = "RegScore")
```
# 2-Block Partial Least Squares analysis (2BPLS)
## Partition classifiers according to species
<!-- Full_classifier_Table_ is the tables of mandibular or cranial classifiers (e.g. read.csv("../Data/Raw/classifier_cranium_wombat.csv")); spp is a vector of species (e.g. c("CW", "SHNW", "NHNW")) -->
## Reduce coordinate datasets to only those that have mandibles and crania
```{r, message = FALSE, warning = FALSE}
## Data list
all_data <- list("NHNW" = NHNW, "SHNW" = SHNW, "CW" = CW)
## Classifiers list
all_classifiers <- list(
"NHNW" = list("cranium" = NHNW_cranium_class, "mandible" = NHNW_mandible_class),
"SHNW" = list("cranium" = SHNW_cranium_class, "mandible" = SHNW_mandible_class),
"CW" = list("cranium" = CW_cranium_class, "mandible" = CW_mandible_class)
)
## Checking whether the cranial and mandibular coordinates datasets match; see utilities for function
matched_coords <- reduce.check(all_data, all_classifiers, procrustes=4)
```
## Run 2BPLS
Depending on processor speed, this can take a while, so we recommend just loading the results which are saved in the `Results` folder.
The results can be run using the following code chunk:
```{r, message = FALSE, warning = FALSE, eval = TRUE}
## 2BPLS for the southern hairy nose wombats
SHNWTBPLS <- two.b.pls(matched_coords[[1]]$SHNW$cranium ,matched_coords[[1]]$SHNW$mandible,
iter = 1000)
save(SHNWTBPLS, file = "../Data/Results/SHNWTBLS_nocurves_nopatches.Rda")
## 2BPLS for the northern hairy nose wombats
NHNWTBPLS <- two.b.pls(matched_coords[[1]]$NHNW$cranium ,matched_coords[[1]]$NHNW$mandible,
iter = 1000)
save(NHNWTBPLS, file="../Data/Results/NHNWTBLS_nocurves_nopatches.Rda")
## 2BPLS for the common wombats
CWTBPLS <- two.b.pls(matched_coords[[1]]$CW$cranium ,matched_coords[[1]]$CW$mandible,
iter = 1000)
save(CWTBPLS, file="../Data/Results/CWTBLS_nocurves_nopatches.Rda")
```
Or directly loaded using this one:
```{r}
## 2BPLS for the southern hairy nose wombats
load("../Data/Results/SHNWTBLS_nocurves_nopatches.Rda")
## 2BPLS for the northern hairy nose wombats
load("../Data/Results/CWTBLS_nocurves_nopatches.Rda")
## 2BPLS for the common wombats
load("../Data/Results/NHNWTBLS_nocurves_nopatches.Rda")
```
## Subsetting data to run correlations of PLS score with csize and allometry
```{r, message = FALSE, warning = FALSE}
## Getting the list of 2BPLS results
all_TBPLS <- list("NHNW" = NHNWTBPLS, "SHNW" = SHNWTBPLS, "CW" = CWTBPLS)
## Placeholder lists
pls_pca_c_size <- TBPLS_scores <- pc_scores <- centroid_size <- pls_pca <- merged_pls <- list()
## Creating the subsets
for (i in 1:length(all_data)){
## Placeholder lists
list() ->
pls_pca_c_size [[i]] ->
TBPLS_scores[[i]] ->
pc_scores[[i]] ->
centroid_size[[i]] ->
pls_pca [[i]] ->
merged_pls[[i]]
## Create data frames for subsequent merging.
for (k in 1:length(all_data$NHNW)){
## TBPLS needs to contain i(species), an address for k (x/yscores as per cranium/mandible, and a
## designation of how long the first singular vector goes, i.e. the species number); the 5+k i
## the "address" of cranial/mandibular scores in the TBPLS data frames
TBPLS_scores[[i]][[k]] <- as.data.frame(all_TBPLS[[i]][[5+k]]
[c(1:length(dimnames(all_TBPLS[[i]][[5+k]])[[1]]))],
row.names = dimnames(all_TBPLS[[i]][[5+k]])[[1]])
## Get the PC scores
pc_scores[[i]][[k]] <- as.data.frame(all_data[[i]][[k]]$ordination$x[,1])
## Get the centroid sizes
centroid_size[[i]][[k]] <- as.data.frame(all_data[[i]][[k]]$procrustes_no_patches$Csize)
## Combine the pls data
pls_pca[[i]][[k]] <- merge(TBPLS_scores[[i]][[k]], pc_scores[[i]][[k]],
by = "row.names", all.x = TRUE)
## Renaming the rows
row.names(pls_pca[[i]][[k]]) <- pls_pca[[i]][[k]]$Row.names
## Combined the merged PLS
merged_pls[[i]][[k]] <- merge(pls_pca[[i]][[k]], centroid_size[[i]][[k]],
by = "row.names", all.x = TRUE)
## Renaming the rows
row.names(merged_pls[[i]][[k]]) <- merged_pls[[i]][[k]]$Row.names
## Remove the two first columns
merged_pls[[i]][[k]] <- merged_pls[[i]][[k]][,-(1:2)]
## Renaming the columns
colnames(merged_pls[[i]][[k]]) <- c("PLS_Scores", "PC1","Csize")
}
## Add the species names
names(merged_pls)[[i]] <- names(all_data)[[i]]
## Add the dataset name (cranium/mandible)
names(merged_pls[[i]]) <- names(all_data[[1]])
}
```
# Run the linear models of PLS scores with PC1 scores and centroid size
```{r, message = FALSE, warning = FALSE}
## Placeholder lists
pca_pls_cor <- c_size_pls_cor <- list()
##corelating the pls scores with PC1 scores and centroid sizes for each species and mandible/cranium
for (i in 1:length(merged_pls)){
##Placeholders
pca_pls_cor[[i]] <- c_size_pls_cor[[i]] <- list()
##this runs the lm analyses for [1] PC scores and [2] Csize
for (k in 1: length(merged_pls[[1]])){
pca_pls_cor[[i]][[k]] <- list()
##
pca_pls_cor[[i]][[k]][[1]] <- cor.test(
merged_pls[[i]][[k]]$PLS_Scores , merged_pls[[i]][[k]]$PC1
)
##
pca_pls_cor[[i]][[k]][[2]] <- cor.test(
merged_pls[[i]][[k]]$PLS_Scores , merged_pls[[i]][[k]]$Csize
)
}
## Renaming the list elements
names(pca_pls_cor)[[i]] <- names(merged_pls)[[i]]
names(pca_pls_cor[[i]]) <- names(merged_pls[[1]])
names(pca_pls_cor[[i]][[k]]) <- c("pls_pca", "PLS_Csize")
}
```
## SHNW cranial PLS scores are the only ones with no significant correlation of PLS and PC1 scores. Therefore testing this correlation with PC2 as well
```{r}
#Turn cranial PLS scores and PC scores into a data frame for merging
SHNW_cranial_scores <- as.data.frame(SHNWTBPLS$XScores[c(1:19)],
row.names = dimnames(SHNWTBPLS$XScores)[[1]])
SHNWPC2 <- as.data.frame(SHNW$cranium$ordination$x[,2])
#Merge data frames
SHNW_PLS_PC2<-merge(SHNW_cranial_scores,SHNWPC2,by="row.names", all.x=TRUE )
colnames(SHNW_PLS_PC2)=c("Species","PLS_Scores", "PC2")
#run analysis
cor.test(SHNW_PLS_PC2$PLS_Scores, SHNW_PLS_PC2$PC2)
```
<file_sep>---
title: "Extreme specimens"
author: "<NAME>"
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools")
if(!require(geomorph)) install.packages("geomorph")
if(!require(landvR)) install_github("TGuillerme/landvR")
source("../Functions/utilities.R")
set.seed(42)
```
## Vombatus ursinus
```{r}
## Loading the data
load("../Data/Processed/wombat_ursinus.Rda")
## The procrustes data
procrustes_cranium <- land_data$cranium$procrustes
procrustes_mandible <- land_data$mandible$procrustes
## The range selection (based on spherical coordinates radius)
range_cranium <- variation.range(procrustes_cranium, return.ID = TRUE)
range_mandible <- variation.range(procrustes_mandible, return.ID = TRUE)
## The min/max specimens
dimnames(procrustes_cranium$coords)[[3]][range_cranium$min.max]
dimnames(procrustes_mandible$coords)[[3]][range_mandible$min.max]
```
For _Vombatus usrsinus_ the min/max specimens based on the cranium are the specimens `r dimnames(procrustes_cranium$coords)[[3]][range_cranium$min.max]`.
For the mandible they are `r dimnames(procrustes_mandible$coords)[[3]][range_mandible$min.max]`.
## Lasiorhinus latifrons
```{r}
## Loading the data
load("../Data/Processed/wombat_latifrons.Rda")
## The procrustes data
procrustes_cranium <- land_data$cranium$procrustes
procrustes_mandible <- land_data$mandible$procrustes
## The range selection (based on spherical coordinates radius)
range_cranium <- variation.range(procrustes_cranium, return.ID = TRUE)
range_mandible <- variation.range(procrustes_mandible, return.ID = TRUE)
## The min/max specimens
dimnames(procrustes_cranium$coords)[[3]][range_cranium$min.max]
dimnames(procrustes_mandible$coords)[[3]][range_mandible$min.max]
```
For _Lasiorhinus latifrons_ the min/max specimens based on the cranium are the specimens `r dimnames(procrustes_cranium$coords)[[3]][range_cranium$min.max]`.
For the mandible they are `r dimnames(procrustes_mandible$coords)[[3]][range_mandible$min.max]`.
## Lasiorhinus kreftii
```{r}
## Loading the data
load("../Data/Processed/wombat_krefftii.Rda")
## The procrustes data
procrustes_cranium <- land_data$cranium$procrustes
procrustes_mandible <- land_data$mandible$procrustes
## The range selection (based on spherical coordinates radius)
range_cranium <- variation.range(procrustes_cranium, return.ID = TRUE)
range_mandible <- variation.range(procrustes_mandible, return.ID = TRUE)
## The min/max specimens
dimnames(procrustes_cranium$coords)[[3]][range_cranium$min.max]
dimnames(procrustes_mandible$coords)[[3]][range_mandible$min.max]
```
For _Lasiorhinus kreftii_ the min/max specimens based on the cranium are the specimens `r dimnames(procrustes_cranium$coords)[[3]][range_cranium$min.max]`.
For the mandible they are `r dimnames(procrustes_mandible$coords)[[3]][range_mandible$min.max]`.<file_sep>---
title: "Landmark region difference between mean species"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools")
if(!require(knitr)) install.packages("knitr")
if(!require(xtable)) install.packages("xtable")
if(!require(geomorph)) install.packages("geomorph")
if(!require(dispRity)) install.packages("dispRity")
if(!require(landvR)) install_github("TGuillerme/landvR")
source("../Functions/utilities.R")
set.seed(42)
```
Here we test the Procrustes landmarks position variation not between the two extremes (or 95%) of the Procrustes space but between the mean Procrustes shapes between the two genera and the two species in _Lasiorhinus_.
# Preparing the data
First we load the two GPA for either all the three species (to compare _Vombatus vs. Lasiorhinus_) or either for the two _Lasiorhinus_ species (to compare _L. krefftii vs. L. latifrons_).
```{r}
## Reading the full GPA data
path <- "../Data/Processed/"
save_path <- "../Data/Results/"
## The GPA for the cranium and mandible of all the taxa
load(paste0(path, "Wombat", ".Rda"))
all_gpa_cran <- land_data[["cranium"]]
all_gpa_mand <- land_data[["mandible"]]
## Getting the partitions
partitions_cran <- partitions_mand <- list()
for(part in 1:length(unique(all_gpa_cran$landmarkgroups[,2]))) {
partitions_cran[[part]] <- which(
all_gpa_cran$landmarkgroups[,2] == unique(all_gpa_cran$landmarkgroups[,2])[part])
partitions_mand[[part]] <- which(
all_gpa_mand$landmarkgroups[,2] == unique(all_gpa_mand$landmarkgroups[,2])[part])
}
## The GPA for the cranium and mandible for the Lasiorhinus
load(paste0(path, "wombat_lasiorhinus", ".Rda"))
las_gpa_cran <- land_data[["cranium"]]
las_gpa_mand <- land_data[["mandible"]]
## Creating the groups
## All species
specimens_names <- attr(all_gpa_cran$procrustes$coords, "dimnames")[[3]]
all_groups_cran <- list("Vombatus_ursinus" = grep("CW_", specimens_names),
"Lasiorhinus" = c(grep("SHNW_", specimens_names), grep("NHNW_", specimens_names)))
specimens_names <- attr(all_gpa_mand$procrustes$coords, "dimnames")[[3]]
all_groups_mand <- list("Vombatus_ursinus" = grep("CW_", specimens_names),
"Lasiorhinus" = c(grep("SHNW_", specimens_names), grep("NHNW_", specimens_names)))
## Lasiorhinus only
specimens_names <- attr(las_gpa_cran$procrustes$coords, "dimnames")[[3]]
las_groups_cran <- list("Lasiorhinus_latifrons" = grep("SHNW_", specimens_names),
"Lasiorhinus_krefftii" = grep("NHNW_", specimens_names))
specimens_names <- attr(las_gpa_mand$procrustes$coords, "dimnames")[[3]]
las_groups_mand <- list("Lasiorhinus_latifrons" = grep("SHNW_", specimens_names),
"Lasiorhinus_krefftii" = grep("NHNW_", specimens_names))
```
We can then get the coordinates differences (spherical) between the two pairs of taxa for the cranium and the mandible.
```{r}
## Getting the mean specimens for each group
all_means_cran <- select.procrustes(all_gpa_cran$procrustes, factors = all_groups_cran)
all_means_mand <- select.procrustes(all_gpa_mand$procrustes, factors = all_groups_mand)
las_means_cran <- select.procrustes(las_gpa_cran$procrustes, factors = las_groups_cran)
las_means_mand <- select.procrustes(las_gpa_mand$procrustes, factors = las_groups_mand)
## Get the hypothetical mean based on the PCA and the GPA
get.hypothetical.mean <- function(GPA, PCA, axis) {
## Transforming the matrix (generalised from geomorph::plotRefToTarget)
transform_matrix <- as.vector(t(GPA)) + c(mean(PCA$x[,axis]), rep(0, ncol(PCA$x)-length(axis))) %*% t(PCA$rotation)
## Converting into a array
output <- geomorph::arrayspecs(A = transform_matrix, p = dim(GPA)[1], k = dim(GPA)[2])
return(output)
}
all_cran_hypothetical <- lapply(all_means_cran, get.hypothetical.mean, PCA = las_gpa_cran$ordination, axis = 1)
all_mand_hypothetical <- lapply(all_means_mand, get.hypothetical.mean, PCA = las_gpa_mand$ordination, axis = 1)
las_cran_hypothetical <- lapply(las_means_cran, get.hypothetical.mean, PCA = las_gpa_cran$ordination, axis = 1)
las_mand_hypothetical <- lapply(las_means_mand, get.hypothetical.mean, PCA = las_gpa_mand$ordination, axis = 1)
## Coordinates differences between pairs of species
differences_list_cran <- list(
"vomba_lasio" = coordinates.difference(type = "spherical",
all_cran_hypothetical$Vombatus_ursinus[,,1], all_cran_hypothetical$Lasiorhinus[,,1]),
"latif_kreft" = coordinates.difference(type = "spherical",
las_cran_hypothetical$Lasiorhinus_latifrons[,,1], las_cran_hypothetical$Lasiorhinus_krefftii[,,1]))
differences_list_mand <- list(
"vomba_lasio" = coordinates.difference(type = "spherical",
all_mand_hypothetical$Vombatus_ursinus[,,1], all_mand_hypothetical$Lasiorhinus[,,1]),
"latif_kreft" = coordinates.difference(type = "spherical",
las_mand_hypothetical$Lasiorhinus_latifrons[,,1], las_mand_hypothetical$Lasiorhinus_krefftii[,,1]))
```
# Running the Procrustes coordinates variation tests
We can then test whether the partitions in each dataset (cranium or mandible) differ in terms of coordinates magnitude change between the two groups (_Vombatus vs. Lasiorhinus_ and _L. krefftii vs. L. latifrons_):
```{r}
## Test wrapper
wrap.rand.test <- function(procrustes_var, partitions, test, rarefaction, verbose = TRUE) {
if(verbose) message("Running test...")
if(rarefaction != FALSE) {
rarefaction <- min(unlist(lapply(partitions, length)))
test_out <- lapply(partitions, lapply.rand.test, data = procrustes_var[[1]], test = test,
replicates = 1000, resample = FALSE, rarefaction = rarefaction)
} else {
test_out <- lapply(partitions, lapply.rand.test, data = procrustes_var[[1]], test = test,
replicates = 1000, resample = FALSE)
}
if(verbose) message("Done.\n")
return(test_out)
}
## Running the tests (no rarefaction)
differences_cran <- lapply(differences_list_cran, wrap.rand.test, partitions = partitions_cran,
test = area.diff, rarefaction = FALSE)
differences_mand <- lapply(differences_list_mand, wrap.rand.test, partitions = partitions_mand,
test = area.diff, rarefaction = FALSE)
overlaps_cran <- lapply(differences_list_cran, wrap.rand.test, partitions = partitions_cran,
test = bhatt.coeff, rarefaction = FALSE)
overlaps_mand <- lapply(differences_list_mand, wrap.rand.test, partitions = partitions_mand,
test = bhatt.coeff, rarefaction = FALSE)
group_cranium <- list("differences" = differences_cran, "overlaps" = overlaps_cran)
group_mandible <- list("differences" = differences_mand, "overlaps" = overlaps_mand)
## Saving the test results
save(group_cranium, file = paste0(save_path, "Group_cranium_means_hypo.Rda"))
save(group_mandible, file = paste0(save_path, "Group_mandible_means_hypo.Rda"))
## Running the tests (with rarefaction)
differences_cran <- lapply(differences_list_cran, wrap.rand.test, partitions = partitions_cran,
test = area.diff, rarefaction = TRUE)
differences_mand <- lapply(differences_list_mand, wrap.rand.test, partitions = partitions_mand,
test = area.diff, rarefaction = TRUE)
overlaps_cran <- lapply(differences_list_cran, wrap.rand.test, partitions = partitions_cran,
test = bhatt.coeff, rarefaction = TRUE)
overlaps_mand <- lapply(differences_list_mand, wrap.rand.test, partitions = partitions_mand,
test = bhatt.coeff, rarefaction = TRUE)
group_cranium <- list("differences" = differences_cran, "overlaps" = overlaps_cran)
group_mandible <- list("differences" = differences_mand, "overlaps" = overlaps_mand)
## Saving the test results
save(group_cranium, file = paste0(save_path, "Group_craniumrarefied_means_hypo.Rda"))
save(group_mandible, file = paste0(save_path, "Group_mandiblerarefied_means_hypo.Rda"))
```
<file_sep>---
title: "Testing the variation of landmark regions within and between species"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 8
fig_height: 4
---
To understand among and between species variation, we tested whether some landmark regions (e.g. the landmarks on the zygomatic arch) varied significantly more or less than the rest of the skull within and between each species.
Here we detail the applied "landmark partition test" testing whether the maximum variation between landmarks position in a set of landmarks is significantly different than any random same size set of landmarks.
This test is a sort of permutation test testing $H_{0}: \Theta_{0} = \Theta$ (the tested sample is equal to the whole population) with a two-sided alternative $H_{1}: \Theta_{0} \neq \Theta$ (the tested sample is _not_ equal to the whole population).
If $H_{0}$ can be rejected it means that the statistic measured from the set of landmarks (see below) is different than the overall statistic from the population of landmarks (in other words: the landmark set is different than the all the landmarks combined).
We measured two statistic, the overall difference in landmark size (displacement difference - see below) and the probability of size overlap between two landmarks sets (Bhattacharyya Coefficient - see below).
These two statistics were measured between the two most extreme specimens selected on the range of variation between the specimens landmarks coordinates (see below).
We tested the differences for three cranium partitions (the zygomatic arch, the tip of the snout and the rest of the skull) and three mandible ones (the tip of the mandible, the back of the mandible and the rest of the mandible) for each species (_Vombatus ursinus_, _Lasiorhinus krefftii_ and _Lasiorhinus latifrons_), for the _Lasiorhinus_ genus combined and for the three species combined.
To account for type I error due to multiple testing and for the number of replicates involved in the landmark partition tests, we adjusted the _p_-values using a Bonferonni-Holm [@holm1979simple] correction and lowered our _p_-value rejection threshold to 0.01 (see below).
The whole procedure, including the landmark variation is described in details below and implemented in `R` [here](https://github.com/TGuillerme/landmark-test).
## Selecting the range of landmark variation {#varalgorithm}
One approach for selecting the range of landmark variation is based on a specific axis of an ordination matrix.
This approach has several advantages namely (1) its intuitiveness and (2) the fact that the selected range is based on a specific axis of variation (e.g. the range on the first ordination axis is based on first axis of variance/covariance in the dataset).
However, this approach suffers also from several statistical drawbacks namely (1) that not all the variance/covariance is taken into account (even if based on an ordination axis that contain a great amount of the datasets' variance) and that (2) the resulting range of landmark variation is based on the ordination of the variance and not directly on the range of the actual variation _per se_ (i.e. in an Euclidean space).
Here we propose a an approach based directly on the Procrustes superimposed landmarks' differences rather than their ordination (i.e. we compare the two skulls or mandibles with the most different landmark positions).
We calculate this difference as the length of the radius in spherical coordinates between a pair of homologuous landmarks.
Spherical coordinates are a coordinate system measured in a sphere and are expressed by three parameters: (1) the radius ($\rho$, the euclidean distance between the two landmarks); (2) the azimuth angle ($\phi$, the angle on the equatorial plan); and (3) the polar angle ($\theta$, the angle measured on the polar plan).
Since we are only interested in the _magnitude_ of difference ($\rho$) regardless of the direction ($\phi$ and $\theta$) we will use only the radius below.
To calculate the maximum range of landmark variation (the two individuals with the most different radii) we use the following algorithm:
1. Calculate the radii for all _n_ landmarks between the mean Procrustes superimposition and each specimen's superimposition.
2. Rank each set of _n_ radii and measure the area under the resulting curve (see [below](#areadiff)).
3. Select the specimen with the highest _n_ radii area. This is now the "maximum" Procrustes (i.e. the specimen with the most different shape compared to the mean).
4. Calculate the radii for all _n_ landmarks between the "maximum" Procrustes and the remaining individual ones.
5. Repeat step 2 and 3. The resulting specimen with the highest _n_ radii area is now the "minimum" Procrustes (i.e. the specimen with the most different shape compared to the "maximum" Procrustes).
These two "maximum" and "minimum" Procrustes superimpositions are not the biggest/smallest, widest/narowest, etc. skulls or mandibles _per se_ but rather the two extremes of the overall distribution of landmark variation ($\rho$).
Because of the multidimensionality aspect of the problem, it is probably impossible to even determine which one of the two selected "maximum" and "minimum" craniums/mandibles has actually the most variation.
However, since we are not interest in _direction_ of difference, these two selected craniums/mandibles are sufficient to give us the magnitude of differences between specimens (while taking into account _all_ the landmarks the three dimensions).
## Difference statistic between partitions
As mentioned above, we will use two different statistics between to compare the partitions to the rest of the cranium/mandible: (1) the overall difference in landmark size between the "maximum" and "minimum" cranium/mandible (this statistic is a proxy for length difference between landmarks ranges); (2) the probability of overlap between the size differences (between the "maximum" and "minimum") in the partition and the rest of the cranium/mandible (this statistic is a proxy for measuring whether both partitions comes from the same distribution).
### Overall difference in landmark size (displacement difference) {#areadiff}
To measure the overall differences in the length of the radii, we can calculate the displacement difference as follows:
##### Displacement difference
$\Delta_{displacement} = \int_{0}^{n-1} (f_{x} - f_{y})d(x,y)$
Where _n_ is minimum number of comparable landmarks and $f_{x}$ and $f_{y}$ are ranked functions (i.e. $f_{0} \geq f_{1} \geq f_{2} ...$) for the landmarks in the partition and all the landmarks respectively.
If one of the functions $f_{x}$ or $f_{y}$ have _m_ elements (with $m > n$) $f^{*}_{z}$, a rarefied estimated of the function with _m_ elements is used instead.
$\int_{0}^{n-1}f^*_{z}d(z) = \frac{\sum_1^p\int f^*_{zi}}{s}$
Where _s_ is the number of rarefaction replicates.
_s_ is chosen based on the Silverman's rule of thumb for choosing the bandwidth of a Gaussian kernel density estimator multiplied by 1000 with a result forced to be 100 $\leq p \leq$ 1000 [@silverman1986density].
##### Silverman's rule {#silverman}
$p=\left(\frac{0.9\times \sigma_{m} }{1.34n}\right)^{-1/5}$
With $\sigma_{m}$ being the minimum of the standard deviation and the interquartile range of the distribution.
This allows the rarefaction algorithm to be fast but "fair" and reduces the number of re-sampling the when the distribution is more homogeneous [@silverman1986density].
If the displacement difference is positive, the landmark's variation in the partition is bigger than the overall landmark's variation, if the difference is negative, the variation is smaller.
## Probability of overlap between size differences (Bhattacharyya Coefficient)
The Bhattacharyya Coefficient calculates the probability of overlap of two distributions [@Bhattacharyya; Guillerme2016146].
When it is equal to zero, the probability of overlap of the distributions is also zero, and when it is equal to one, the two distributions are entirely overlapping.
It forms an elegant and easy to compute continuous measurement of the probability of similarity between two distributions.
The coefficient is calculated as the sum of the square root of the relative counts shared in _n_ bins among two distributions.
##### Bhattacharyya Coefficient
$BC=\sum_{i=1}^{n} \sqrt{{\sum{a_i}}\times{\sum{b_i}}}$
Where ${a_i}$ and ${b_i}$ are the number of counts in bin _i_ for the distributions _a_ and _b_ respectively divided by the total number of counts in the distribution _a_ and _b_ respectively.
_n_ was determined using the Silverman's rule of thumb (see equation [above](#silverman)).
We consider two distributions to be significantly similar when their Bhattacharyya Coefficient is $< 0.95$.
Conversely, they are significantly different when their Bhattacharyya Coefficient is $< 0.05$.
Values in between these two threshold just show the probability of overlap between the distributions but are not conclusive to assess the similarity or differences between the distributions.
## Random permutation test
To test whether the landmarks' variation (i.e. the radii between the "maximum" and "minimum" cranium/mandible) one partition is different than the rest of the landmark's variation, we used a kind of permutation test (based on a modification from `ade4::as.randtest` [@thioulouse1997ade]).
This is a pretty intuitive yet powerful test aiming to calculate whether the observed difference in statistic (either the displacement difference or the probability of overlap) is different than the same statistic drawn randomly from the same population (here, the distribution of all the landmark's variation).
First we measured the statistic between the landmark partition of interest and all the other landmarks (including the ones from the partition).
Second, we generated 1000 statistics by randomly sampling the same number of landmarks as in the partition in the whole distributions and compared them again to the full distribution.
This resulted in 1000 null comparisons (i.e. assuming the null hypothesis that the statistic in the partition is the same as the statistic in the total distribution).
We then calculated the _p_ value based on:
##### Permutation _p_-value
$p=\frac{\sum_1^B\left(random_{i} >= observed\right)+1}{B + 1}$
Where _B_ is the number of random draws (1000 bootstrap pseudo-replicates), $random_{i}$ is the $i^{th}$ statistic from the comparison of the $i^{th}$ randomly drawn partition and the distribution and $observed$ is the observed statistic between the partition and the distribution.
An increased number of bootstrap pseudo-replications increases the type I error.
We therefore lowered our threshold for accepting $H_{0}$ to 0.01 instead of the commonly used 0.05.
# Implementation example
This is a running example of the step by step implementation of this test in the working `landmarktest` package.
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools")
if(!require(knitr)) install.packages("knitr")
if(!require(geomorph)) install.packages("geomorph")
if(!require(dispRity)) install.packages("dispRity")
if(!require(landvR)) install_github("TGuillerme/landvR")
library(dispRity)
library(landvR)
source("../Functions/utilities.R")
set.seed(42)
```
## Loading some example dataset
To perform the test on part of the dataset from the analysis, you can directly use the compiled data obtained by running [the data preparation script](https://github.com/TGuillerme/landmark-test/blob/master/Analysis/01-Data_preparation.Rmd).
```{r, eval = FALSE}
## Loading a dataset
load("../Data/Processed/wombat_ursinus.Rda")
## Selecting a partition
data <- land_data$cranium
## Procrustes data
procrustes <- data$procrustes
## Landmark classification
landmarks_groups <- data$landmarkgroups
```
For simplifying this example, we will use the 2D `plethodon` dataset already present in the `geomorph` package.
```{r}
## Loading the dataset
data(plethodon)
## Generating a Procrustes superimposition
procrustes <- gpagen(plethodon$land, print.progress = FALSE)
## Landmark classification
back <- c(1,2,10,11,12)
front <- c(1:12)[-back]
landmarks_groups <- data.frame("landmark" = c(back, front),
"group" = c(rep("back", 5), rep("front", 7)))
```
And we can select the two partitions to test
```{r}
## Partitions
partitions <- list()
for(part in unique(landmarks_groups[,2])) {
partitions[[part]] <- which(landmarks_groups[,2] == part)
}
```
## Selecting the range of landmark variation (max and min specimen)
We can select the "maximum" and "minimum" specimen and their range of variation using the algorithm detailed above (see [here](#varalgorithm)).
This procedure can be compute with the `variation.range` function:
```{r}
## Procrustes variation ranges
variation <- variation.range(procrustes, type = "spherical", what = "radius", return.ID = TRUE)
## The range of variation
variation$range
## The two most extreme specimens' IDs
variation$min.max
```
We can also do the same but only considering the 95% confidence interval (getting rid of any eventual outliers):
```{r}
## Procrustes variation ranges (95% CI)
variation_95 <- variation.range(procrustes, type = "spherical", what = "radius", return.ID = TRUE,
CI = 0.95)
```
## Testing the overall difference in landmark size
For both ranges of variation `variation` and `variation_95` we can now test whether each partitions is significantly different than the rest of the landmarks.
We can test whether the partitions are different (`area.diff`: is the integral of the variation in partition X different than all the landmarks?) and whether they come from the same statistical population (`bhatt.coeff`: is the distribution of the variation in partition X different from the distribution of all the landmarks?).
Since we are going to run the test for multiple partitions, we can wrap it in a `lapply` loop using the `area.diff` and `bhatt.coeff` functions for the tests as follows:
```{r}
## Function for applying the rand tests
lapply.rand.test <- function(partition, data, test, ...) {
rand.test(data[, "radius"], partition, test = test, test.parameter = TRUE, ...)
}
## Size differences
differences <- lapply(partitions, lapply.rand.test, data = variation$range, test = area.diff)
differences_95 <- lapply(partitions, lapply.rand.test, data = variation_95$range, test = area.diff)
## Probabilities of overlap
overlaps <- lapply(partitions, lapply.rand.test, data = variation$range, test = bhatt.coeff)
overlaps_95 <- lapply(partitions, lapply.rand.test, data = variation_95$range, test = bhatt.coeff)
```
> Note that the `area.test` function is slower than `bhatt.coeff` since it has to estimate the distribution function of the landmarks variation to calculate its integral.
This is the equivalent of running the following for each element in `partition`, both the `area.diff` and `bhatt.coeff` tests and the both the `variation` and `variation_95` ranges of variation:
```{r, eval = FALSE}
## Running one test for one partition
one_test <- rand.test(variation[, "radius"], partition[[1]],
test = area.diff, test.parameter = TRUE)
```
### Interpreting the results
We can then display the results as a normal permutation test with a _p_-value correction applied to the results (using the "bonferrroni" correction):
#### The landmark size differences:
```{r, echo = FALSE}
## Size differences
library(knitr)
kable(make.table(differences, "bonferroni"), digits = 5, caption = "Size difference (100% CI)")
kable(make.table(differences_95, "bonferroni"), digits = 5, caption = "Size difference (95% CI)")
```
#### The probability of overlaps:
```{r, echo = FALSE}
## Probability of overlap
kable(make.table(overlaps, "bonferroni"), digits = 5, caption = "Overlap probability (100% CI)")
kable(make.table(overlaps_95, "bonferroni"), digits = 5, caption = "Overlap probability (95% CI)")
```
#### The result plots for the 100% CI:
```{r, fig.width = 6, fig.height = 9, echo = FALSE}
## Plot the size differences
make.plots(differences, type = "displacement difference", add.p = TRUE, correction = "bonferroni")
```
```{r, fig.width = 6, fig.height = 9, echo = FALSE}
## Plot the size differences
make.plots(overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
#### The result plots for the 100% CI:
```{r, fig.width = 6, fig.height = 9, echo = FALSE}
## Plot the size differences
make.plots(differences_95, type = "displacement difference", add.p = TRUE, correction = "bonferroni")
```
```{r, fig.width = 6, fig.height = 9, echo = FALSE}
## Plot the size differences
make.plots(overlaps_95, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
As we can see from the results on the `plethodon` dataset, the range of variation in both partitions of landmarks is not significantly different nor likely to come from an other statistical population.
## References
<file_sep>---
title: "Standard analyses"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(knitr)) install.packages("knitr"); library(knitr)
if(!require(xtable)) install.packages("xtable"); library(xtable)
if(!require(geomorph)) install.packages("geomorph"); library(geomorph)
if(!require(dispRity)) install.packages("dispRity");library(dispRity)
source("../Functions/utilities.R")
set.seed(42)
## Loading and renaming the land_data objects
load("../Data/Processed/wombat.Rda")
AllWombats <- land_data
load("../Data/Processed/wombat_lasiorhinus.Rda")
Lasio <- land_data
load("../Data/Processed/wombat_krefftii.Rda")
NHNW <- land_data
load("../Data/Processed/wombat_latifrons.Rda")
SHNW <- land_data
load("../Data/Processed/wombat_ursinus.Rda")
CW <- land_data
## Read the classifiers
cranium <- read.csv("../Data/Raw/classifier_cranium_wombat.csv")
mandible <- read.csv("../Data/Raw/classifier_mandible_wombat.csv")
## Remove juvenile from mandibles
nhnw_b34 <- which(mandible[,1] == "NHNW_B34")
mandible <- mandible[-nhnw_b34, ]
```
#Separating the classifier file by species
```{r, message = FALSE, warning = FALSE}
## Creating the vectors holding the species names
species <- c("CW", "SHNW", "NHNW")
sp_holders <-c("Common wombat", "SHN wombat", "NHN wombat")
## Assigning the right class to each species (for the cranium)
for (i in 1:length(unique(cranium$Species))) {
## Extracting the class for each species
class <- cranium[cranium$Species == sp_holders[i],]
## Preparing the sp name for giving names to outputs
sp_name <- paste(species[i], deparse(substitute(cranium)), "class", sep = "_")
## Assigning the class to the names
assign(sp_name, class)
}
## Assigning the right class to each species (for the mandible)
for (i in 1:length(unique(mandible$Species))) {
## Extracting the class for each species
class <- mandible[mandible$Species == sp_holders[i],]
## Preparing the sp name for giving names to outputs
sp_name <- paste(species[i], deparse(substitute(mandible)), "class", sep = "_")
## Assigning the class to the names
assign(sp_name, class)
}
```
# Preparing the data
## Checking for shape outliers
The following session evaluates the shape of the outliers
```{r, message = FALSE, warning = FALSE}
## set up the gridpars for plotRefToTarget to be passed to rgl
points <- gridPar(pt.size = 0.7)
```
This following section detects outliers (the specimen beyond the upper and lower quartiles) and then visually checks whether these individuals have any obvious wrongly placed landmarks.
When multiple individuals are outliers, each are checked in turn (replacing `ID` in `X$Y$procrustes$coords[, , ID]` by the specimens' ID; where `X` and `Y` are respectively the species object and the species dataset).
#### The Common wombat
The cranium:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## Plot the procrustes distances from mean for specimens to identify the ones beyond
## the upper/lower quartiles
plotOutliers(CW$cranium$procrustes$coords)
## CW_M11 (individual 14,11 are out)
## Use plotRefToTarget with lollipop graphs to check if outlier has landmark error;
## Replace number according to which individuals have been identified as outliers
plotRefToTarget(CW$cranium$procrustes$consensus, CW$cranium$procrustes$coords[, , 14],
method = "vector", gridPars = points)
## No evidence of landmarking error
```
The mandible:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## Plot the procrustes distances from mean for specimens to identify the ones beyond
## the upper/lower quartiles
plotOutliers(CW$mandible$procrustes$coords)
## individuals 20 and 11 are out
## Use plotRefToTarget with lollipop graphs to check if outlier has landmark error;
## Replace number according to which individuals have been identified as outliers
plotRefToTarget(CW$mandible$procrustes$consensus, CW$mandible$procrustes$coords[, , 20],
method = "vector", gridPars = points)
## No evidence of landmarking error
```
#### The Northern Hairy Nose Wombat
The cranium:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## Plotting the outliers
plotOutliers(NHNW$cranium$procrustes$coords)
## NHNW_JM8466 (individual 21 is out)
## Plotting the outliers
plotRefToTarget(NHNW$cranium$procrustes$consensus, NHNW$cranium$procrustes$coords[, , 21],
method = "vector", gridPars=points)
## No evidence of landmarking error
```
The mandible:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## Plotting the outliers
plotOutliers(NHNW$mandible$procrustes$coords)
## Specimen 11 is out
## Plotting the outliers
plotRefToTarget(NHNW$mandible$procrustes$consensus, NHNW$mandible$procrustes$coords[, , 11],
method = "vector", gridPars = points)
## No evidence of landmarking error
```
#### The Southern Hairy Nose Wombat
The cranium:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## Plotting the outliers
plotOutliers(SHNW$cranium$procrustes$coords)
## 21, 20 and 5 are out)
## Plotting the outliers
plotRefToTarget(SHNW$cranium$procrustes$consensus, NHNW$cranium$procrustes$coords[, , 5],
method = "vector", gridPars = points)
## No evidence of landmarking error
```
The mandible:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## Plotting the outliers
plotOutliers(SHNW$mandible$procrustes$coords)
## No outliers!
```
# disparity comparison betweeen wombat species
```{r, message = FALSE, warning = FALSE}
## Create gdfs with species for the data frames
cranium_gdf <- geomorph.data.frame(coords = AllWombats$cranium$procrustes$coords,
Csize = AllWombats$cranium$procrustes$Csize,
species = as.factor(cranium$Species))
mandible_gdf <- geomorph.data.frame(coords = AllWombats$mandible$procrustes$coords,
Csize = AllWombats$mandible$procrustes$Csize,
species = as.factor(mandible$Species))
## Running the analyses on the gdf objects (Disparity within groups compared to that group's mean)
cranium_disparity <- morphol.disparity(coords ~ species, groups = ~species, iter = 1000, seed = 42,
data = cranium_gdf, print.progress = FALSE)
## Disparity within groups compared to that group's mean
mandible_disparity <- morphol.disparity(coords ~ species, groups = ~species, iter = 1000, seed = 42,
data = mandible_gdf, print.progress = FALSE)
```
And we can display the results as follows:
```{r, echo = FALSE}
## Cranium disparity values
kable(data.frame("Procrustes variance" = cranium_disparity[[1]]), digits = 5, caption = "Cranium disparity (procrustes variance) per groups.")
## Cranium disparity differences
kable(cranium_disparity[[2]], digits = 5, caption = "Cranium pairwise absolute differences between variances between groups.")
## Cranium disparity differences p
kable(cranium_disparity[[3]], digits = 5, caption = "Cranium pairwise absolute differences between variances between groups (p-values).")
## Mandible disparity values
kable(data.frame("Procrustes variance" = mandible_disparity[[1]]), digits = 5, caption = "Mandible disparity (procrustes variance) per groups.")
## Mandible disparity differences
kable(mandible_disparity[[2]], digits = 5, caption = "Mandible pairwise absolute differences between variances between groups.")
## Mandible disparity differences p
kable(mandible_disparity[[3]], digits = 5, caption = "Mandible pairwise absolute differences between variances between groups (p-values).")
```
#Are wombats sexually dimorphic?
## Make the sex subsets
The following analysis don't contain the northern hairy nose wombats because there is no variation in sex assignment in the dataset.
```{r, message = FALSE, warning = FALSE}
## Making the classifiers list
all_data <- list("SHNW" = SHNW, "CW" = CW)
all_classifiers <- list("SHNW" = list("cranium" = SHNW_cranium_class,
"mandible" = SHNW_mandible_class),
"CW" = list("cranium" = CW_cranium_class,
"mandible" = CW_mandible_class))
```
Creating the sex subsets and the centroid size per sex subsets:
```{r}
## Results placeholder
coords_sex_output <- c_size_sex_output <- list()
## Getting the coordinates for specimens with Geolocation
for (i in 1:length(all_data)){
## Result placeholder
list() ->
coords_sex_output[[i]] ->
c_size_sex_output[[i]]
## Getting the coordinates for each classifier
for (k in 1:length(all_classifiers[[i]])){
## Sex coordinates
coords_sex_output[[i]][[k]] <- all_data[[i]][[k]]$procrustes$coords[ , ,
!is.na(all_classifiers[[i]][[k]]$Sex)]
## Sex centroid size
c_size_sex_output[[i]][[k]] <- all_data[[i]][[k]]$procrustes$Csize[
!is.na(all_classifiers[[i]][[k]]$Sex)]
}
## Naming the element
names(all_data[[i]]) ->
names(coords_sex_output[[i]]) ->
names(c_size_sex_output[[i]])
}
names(all_data) ->
names(coords_sex_output) ->
names(c_size_sex_output)
```
Creating the coordinates subsets and the centroid size subsets for geolocation and sex:
```{r}
## Results placeholder
sex_gdfs <- list()
## Creating the geomorph dataframe for both species and datasets
for (i in 1:length(coords_sex_output)){
## Results placeholder
sex_gdfs[[i]] <- list()
for (k in 1:length(all_classifiers[[i]])){
## Sex data frame object
sex_gdfs[[i]][[k]] <- geomorph.data.frame(
coords = coords_sex_output[[i]][[k]],
Csize = c_size_sex_output[[i]][[k]],
Sex= all_classifiers[[i]][[k]]$Sex[!is.na(all_classifiers[[i]][[k]]$Sex)]
)
}
## Naming the elements
names(sex_gdfs[[i]]) <- names(all_data[[i]])
}
names(sex_gdfs) <- names(all_data)
## Making sure the dimension names are correct;requires testthat
#expect_equal(match(dimnames(geo_gdfs$SHNW$cranium$coords)[[3]],names(geo_gdfs$SHNW$cranium$Csize)),
# seq(1:length(names(geo_gdfs$SHNW$cranium$Csize))))
```
## Running procD.lm analyses
We can run the three following linear models for each species and each datasets:
* coordinates ~ sex + centroid size
* centroid size ~ sex
```{r, message = FALSE, warning = FALSE}
## Results placeholder
coord_sex_lm <- csize_sex_lm <- list()
## Running all the linear models
for (i in 1:length(sex_gdfs)){
## Results placeholder
coord_sex_lm[[i]] <- csize_sex_lm[[i]] <- list()
for (k in 1:length(sex_gdfs[[2]])){
## Running the coordinates ~ sex + centroid size models
coord_sex_lm[[i]][[k]] <- procD.lm(coords ~ Sex , print.progress = FALSE,
data = sex_gdfs[[i]][[k]], iter = 1000)
## Running the centroid size ~ sex models
csize_sex_lm[[i]][[k]] <- procD.lm(Csize ~ Sex, print.progress = FALSE,
data = sex_gdfs[[i]][[k]], iter = 1000)
}
## Renaming the models
names(coord_sex_lm[[i]]) -> names(csize_sex_lm[[i]])
}
names(coord_sex_lm) <- names(csize_sex_lm)
```
And we can display them as follows:
```{r, echo = FALSE}
## coordinates ~ sex + centroid size
kable(coord_sex_lm[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes linear model for coordinates as a function of sex and centroid size for the southern hairy nose wombat's cranium.")
kable(coord_sex_lm[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes linear model for coordinates as a function of sex and centroid size for the southern hairy nose wombat's mandible.")
kable(coord_sex_lm[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes linear model for coordinates as a function of sex and centroid size for the common wombat's cranium.")
kable(coord_sex_lm[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes linear model for coordinates as a function of sex and centroid size for the common wombat's mandible.")
## centroid size ~ sex
kable(csize_sex_lm[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes linear model for centroid size as a function of sex for the southern hairy nose wombat's cranium.")
kable(csize_sex_lm[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes linear model for centroid size as a function of sex for the southern hairy nose wombat's mandible.")
kable(csize_sex_lm[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes linear model for centroid size as a function of sex for the common wombat's cranium.")
kable(csize_sex_lm[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes linear model for centroid size as a function of sex for the common wombat's mandible.")
```
# Allometry Analyses
We can run the allometry tests using the `handle.procD.formula` wrapper function:
```{r, message = FALSE, warning = FALSE, result = 'hide'}
## List of all the data
all_data <- list("NHNW" = NHNW, "SHNW" = SHNW, "CW" = CW)
## Placeholder for the results
allom_output <- list()
## Running the allometry tests
for (i in 1:length(all_data)){
for (k in 1:length(all_data[[1]])){
## Result placeholder
allom_output[i][[k]] <- list()
## Procrustes allometry test (wrapper around the procD.allometry function)
allom_output[[i]][[k]] <- handle.procD.formula(coords ~ Csize, all_data[[i]][[k]]$procrustes,
procD.fun = procD.lm, iter = 1000,
print.progress = FALSE)
}
}
## Naming the results
names(allom_output) <- names(all_data)
## Naming the partitions
for(i in 1:length(all_data)) {
names(allom_output[[i]]) <- names(all_data[[i]])
}
```
And we can display them as follows:
```{r, echo = FALSE}
kable(allom_output[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the northern hairy nose wombat's cranium.")
kable(allom_output[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the northern hairy nose wombat's mandible.")
kable(allom_output[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the southern hairy nose wombat's cranium.")
kable(allom_output[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the southern hairy nose wombat's mandible.")
kable(allom_output[[3]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the common wombat's cranium.")
kable(allom_output[[3]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the common wombat's mandible.")
```
#Allometry between species
```{r}
#Cranium
##turn into gdf frame
gdf_cranium <- geomorph.data.frame(coords = AllWombats$cranium$procrustes$coords,
Csize = AllWombats$cranium$procrustes$Csize)
##run analysis
AllomCranium <- procD.lm(coords~Csize, data = gdf, method = "RegScore")
#Create dataset of residuals of allometry for generating shape space without size
allom_cranium <-arrayspecs(AllomCranium$residuals,dim(gdf_cranium$coords)[[1]],3)
cranium_consensus <- AllWombats$cranium$procrustes$consensus
#Add the consensus shape (from the GPA) to residuals if you want to understand the landmark variation in the residuals; this does not affect the analyses though and is just "cosmetic"
Allom_plus_consensus_cran <- allom_cranium + array(cranium_consensus, dim(allom_cranium))
#Mandible
##turn into gdf frame
gdf_mandible <- geomorph.data.frame(coords = AllWombats$mandible$procrustes$coords,
Csize = AllWombats$mandible$procrustes$Csize)
##run analysis
AllomMandible <- procD.lm(coords~Csize, data = gdf_mandible, method = "RegScore")
allom_mandible <-arrayspecs(AllomMandible$residuals,dim(gdf_mandible$coords)[[1]],3)
mandible_consensus <- AllWombats$mandible$procrustes$consensus
Allom_plus_consensus_mand <- allom_mandible + array(mandible_consensus, dim(allom_mandible))
#The same for just the Northerns/Southerns for later presentation
#Cranium
##turn into gdf frame
gdf_cranium <- geomorph.data.frame(coords = Lasio$cranium$procrustes$coords,
Csize = Lasio$cranium$procrustes$Csize)
##run analysis
AllomCranium <- procD.lm(coords~Csize, data = gdf, method = "RegScore")
#Create dataset of residuals of allometry for generating shape space without size
allom_cranium <-arrayspecs(AllomCranium$residuals,dim(gdf_cranium$coords)[[1]],3)
cranium_consensus <- Lasio$cranium$procrustes$consensus
#Add the consensus shape (from the GPA) to residuals if you want to understand the landmark variation in the residuals; this does not affect the analyses though and is just "cosmetic"
Allom_plus_consensus_cran_Lasio <- allom_cranium + array(cranium_consensus, dim(allom_cranium))
#Mandible
##turn into gdf frame
gdf_mandible <- geomorph.data.frame(coords = Lasio$mandible$procrustes$coords,
Csize = Lasio$mandible$procrustes$Csize)
##run analysis
AllomMandible <- procD.lm(coords~Csize, data = gdf_mandible, method = "RegScore")
allom_mandible <-arrayspecs(AllomMandible$residuals,dim(gdf_mandible$coords)[[1]],3)
mandible_consensus <- Lasio$mandible$procrustes$consensus
Allom_plus_consensus_mand_Lasio <- allom_mandible + array(mandible_consensus, dim(allom_mandible))
save(Allom_plus_consensus_cran,Allom_plus_consensus_mand, Allom_plus_consensus_cran_Lasio,Allom_plus_consensus_mand_Lasio,file = "../Data/Processed/Allometry_residuals.rda")
```
## Allometry analysis without the patches
We can also run the allometry analysis on the data without the patches
```{r, message = FALSE, warning = FALSE, result = 'hide'}
## Placeholder for the results
allom_output_no_patch <- list()
## Running the allometry tests
for (i in 1:length(all_data)){
for (k in 1:length(all_data[[1]])){
## Result placeholder
allom_output_no_patch[i][[k]] <- list()
## Procrustes allometry test (wrapper around the procD.allometry function)
allom_output_no_patch[[i]][[k]] <- handle.procD.formula(coords ~ Csize,
all_data[[i]][[k]]$procrustes_no_patches,
procD.fun = procD.lm, iter = 1000,
print.progress = FALSE)
}
}
## Naming the results
names(allom_output_no_patch) <- names(all_data)
## Naming the partitions
for(i in 1:length(all_data)) {
names(allom_output_no_patch[[i]]) <- names(all_data[[i]])
}
```
And we can display them as follows:
```{r, echo = FALSE}
kable(allom_output_no_patch[[1]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the northern hairy nose wombat's cranium (no patches).")
kable(allom_output_no_patch[[1]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the northern hairy nose wombat's mandible (no patches).")
kable(allom_output_no_patch[[2]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the southern hairy nose wombat's cranium (no patches).")
kable(allom_output_no_patch[[2]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the southern hairy nose wombat's mandible (no patches).")
kable(allom_output_no_patch[[3]][[1]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the common wombat's cranium (no patches).")
kable(allom_output_no_patch[[3]][[2]]$aov.table, digits = 3,
caption = "Procrustes ANOVA for size (allometry) for the common wombat's mandible (no patches).")
```
#Allometry between species (without the patches)
```{r}
#Cranium
##turn into gdf frame
gd <- geomorph.data.frame(coords = AllWombats$cranium$procrustes_no_patches$coords,
Csize = AllWombats$cranium$procrustes_no_patches$Csize)
##run analysis
AllomCranium <- procD.lm(coords~Csize, data = gdf, method = "RegScore")
#Mandible
##turn into gdf frame
gdf <- geomorph.data.frame(coords = AllWombats$mandible$procrustes_no_patches$coords,
Csize = AllWombats$mandible$procrustes_no_patches$Csize)
##run analysis
AllomMandible <- procD.lm(coords~Csize, data = gdf, method = "RegScore")
```
# 2-Block Partial Least Squares analysis (2BPLS)
## Partition classifiers according to species
<!-- Full_classifier_Table_ is the tables of mandibular or cranial classifiers (e.g. read.csv("../Data/Raw/classifier_cranium_wombat.csv")); spp is a vector of species (e.g. c("CW", "SHNW", "NHNW")) -->
## Reduce coordinate datasets to only those that have mandibles and crania
```{r, message = FALSE, warning = FALSE}
## Data list
all_data <- list("NHNW" = NHNW, "SHNW" = SHNW, "CW" = CW)
## Classifiers list
all_classifiers <- list(
"NHNW" = list("cranium" = NHNW_cranium_class, "mandible" = NHNW_mandible_class),
"SHNW" = list("cranium" = SHNW_cranium_class, "mandible" = SHNW_mandible_class),
"CW" = list("cranium" = CW_cranium_class, "mandible" = CW_mandible_class)
)
## Checking whether the cranial and mandibular coordinates datasets match
matched_coords <- reduce.check(all_data, all_classifiers)
```
## Run 2BPLS
Depending on processor speed, this can take a while, so we recommend just loading the results which are saved in the `Results` folder.
The results can be run using the following code chunk:
```{r, message = FALSE, warning = FALSE, eval = FALSE}
## 2BPLS for the southern hairy nose wombats
SHNWTBPLS <- two.b.pls(matched_coords[[1]]$SHNW$cranium ,matched_coords[[1]]$SHNW$mandible,
iter = 1000)
save(SHNWTBPLS, file = "../Data/Results/SHNWTBLS.Rda")
## 2BPLS for the northern hairy nose wombats
NHNWTBPLS <- two.b.pls(matched_coords[[1]]$NHNW$cranium ,matched_coords[[1]]$NHNW$mandible,
iter = 1000)
save(NHNWTBPLS, file="../Data/Results/NHNWTBLS.Rda")
## 2BPLS for the common wombats
CWTBPLS <- two.b.pls(matched_coords[[1]]$CW$cranium ,matched_coords[[1]]$CW$mandible,
iter = 1000)
save(CWTBPLS, file="../Data/Results/CWTBLS.Rda")
```
Or directly loaded using this one:
```{r}
## 2BPLS for the southern hairy nose wombats
load("../Data/Results/SHNWTBLS.Rda")
## 2BPLS for the northern hairy nose wombats
load("../Data/Results/CWTBLS.Rda")
## 2BPLS for the common wombats
load("../Data/Results/NHNWTBLS.Rda")
```
## Subsetting data to run correlations of PLS score with csize and allometry
```{r, message = FALSE, warning = FALSE}
## Getting the list of 2BPLS results
all_TBPLS <- list("NHNW" = NHNWTBPLS, "SHNW" = SHNWTBPLS, "CW" = CWTBPLS)
## Placeholder lists
pls_pca_c_size <- TBPLS_scores <- pc_scores <- centroid_size <- pls_pca <- merged_pls <- list()
## Creating the subsets
for (i in 1:length(all_data)){
## Placeholder lists
list() ->
pls_pca_c_size [[i]] ->
TBPLS_scores[[i]] ->
pc_scores[[i]] ->
centroid_size[[i]] ->
pls_pca [[i]] ->
merged_pls[[i]]
## Create data frames for subsequent merging.
for (k in 1:length(all_data$NHNW)){
## TBPLS needs to contain i(species), an address for k (x/yscores as per cranium/mandible, and a
## designation of how long the first singular vector goes, i.e. the species number); the 5+k i
## the "address" of cranial/mandibular scores in the TBPLS data frames
TBPLS_scores[[i]][[k]] <- as.data.frame(all_TBPLS[[i]][[5+k]]
[c(1:length(dimnames(all_TBPLS[[i]][[5+k]])[[1]]))],
row.names = dimnames(all_TBPLS[[i]][[5+k]])[[1]])
## Get the PC scores
pc_scores[[i]][[k]] <- as.data.frame(all_data[[i]][[k]]$ordination$x[,1])
## Get the centroid sizes
centroid_size[[i]][[k]] <- as.data.frame(all_data[[i]][[k]]$procrustes$Csize)
## Combine the pls data
pls_pca[[i]][[k]] <- merge(TBPLS_scores[[i]][[k]], pc_scores[[i]][[k]],
by = "row.names", all.x = TRUE)
## Renaming the rows
row.names(pls_pca[[i]][[k]]) <- pls_pca[[i]][[k]]$Row.names
## Combined the merged PLS
merged_pls[[i]][[k]] <- merge(pls_pca[[i]][[k]], centroid_size[[i]][[k]],
by = "row.names", all.x = TRUE)
## Renaming the rows
row.names(merged_pls[[i]][[k]]) <- merged_pls[[i]][[k]]$Row.names
## Remove the two first columns
merged_pls[[i]][[k]] <- merged_pls[[i]][[k]][,-(1:2)]
## Renaming the columns
colnames(merged_pls[[i]][[k]]) <- c("PLS_Scores", "PC1","Csize")
}
## Add the species names
names(merged_pls)[[i]] <- names(all_data)[[i]]
## Add the dataset name (cranium/mandible)
names(merged_pls[[i]]) <- names(all_data[[1]])
}
```
# Run the linear models of PLS scores with PC1 scores and centroid size
```{r, message = FALSE, warning = FALSE}
## Placeholder lists
pca_pls_cor <- c_size_pls_cor <- list()
##corelating the pls scores with PC1 scores and centroid sizes for each species and mandible/cranium
for (i in 1:length(merged_pls)){
## Placeholders
pca_pls_cor[[i]] <- c_size_pls_cor[[i]] <- list()
##this runs the lm analyses for [1] PC scores and [2] Csize
for (k in 1: length(merged_pls[[1]])){
pca_pls_cor[[i]][[k]] <- list()
##
pca_pls_cor[[i]][[k]][[1]] <- cor.test(
merged_pls[[i]][[k]]$PLS_Scores , merged_pls[[i]][[k]]$PC1
)
##
pca_pls_cor[[i]][[k]][[2]] <- cor.test(
merged_pls[[i]][[k]]$PLS_Scores , merged_pls[[i]][[k]]$Csize
)
}
## Renaming the list elements
names(pca_pls_cor)[[i]] <- names(merged_pls)[[i]]
names(pca_pls_cor[[i]]) <- names(merged_pls[[1]])
names(pca_pls_cor[[i]][[k]]) <- c("pls_pca", "PLS_Csize")
}
```
## SHNW cranial PLS scores are the only ones with no significant correlation of PLS and PC1 scores. Therefore testing this correlation with PC2 as well
```{r}
#Turn cranial PLS scores and PC scores into a data frame for merging
SHNW_cranial_scores <- as.data.frame(SHNWTBPLS$XScores[c(1:19)],
row.names = dimnames(SHNWTBPLS$XScores)[[1]])
SHNWPC2 <- as.data.frame(SHNW$cranium$ordination$x[,2])
#Merge data frames
SHNW_PLS_PC2<-merge(SHNW_cranial_scores,SHNWPC2,by="row.names", all.x=TRUE )
colnames(SHNW_PLS_PC2)=c("Species","PLS_Scores", "PC2")
#run analysis
cor.test(SHNW_PLS_PC2$PLS_Scores, SHNW_PLS_PC2$PC2)
```
<file_sep>#~~~~~~~~~~~
## Converts the tables generated by R (xtable) into a word document
#~~~~~~~~~~~
## Requires: pandoc!
CI=$1
## Generate the LaTeX temp
echo "\documentclass{article}" > table_result.temp
echo "\\\begin{document}" >> table_result.temp
echo "" >> table_result.temp
for tex in *${CI}.tex
do
prefix=$(basename ${tex} _${CI}.tex | sed 's/_/ /g')
echo "\section{${prefix}}" >> table_result.temp
echo "\input{${tex}}" >> table_result.temp
echo "" >> table_result.temp
done
echo "\end{document}" >> table_result.temp
mv table_result.temp table_result.tex
## Convert into docx
pandoc -i table_result.tex -o result_table_${CI}.docx
## Cleaning
rm table_result.tex
<file_sep>---
title: "Landmark region difference (data)"
author: "<NAME>"
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r}
## Loading the libraries (and installing if necessary)
if(!require(geomorph)) install.packages("geomorph")
```
This script reads in the data and saves it in the proper format to be analysed
## Inputs
The data should be stored in `../Data/` in the following format:
Data type | Data set | Species | File format
----------|----------|---------|------------
classifier| cranium|wombat|.csv
landmarkdata | cranium | wombat | .csv
landmarkgroups | mandible | wombat |.csv
## Partitions
### Cranium

Partition name | Colour | ID in landmarkgroups | default order in test | Name in publication
---|---|---|---|---
zygomatic | blue | 1 | 1 | Zygomatic arch
rest | orange | 2 | 2 | Remainders
snout | green | 3 | 3 | Tip of snout
### Mandible

Partition name | Colour | ID in landmarkgroups | default order in test | Name in publication
---|---|---|---|---
back | green | 1 | 3 | Masticatory insertions
front | blue | 2 | 1 | Symphyseal area
rest | orange | 3 | 2 | Remainders
### Data per genus
Includes gpa coordinates (procrustes), landmark partitions (landmarkgroups), and principal component output (ordination)
```{r}
## The chain names; in case there are several species, but it is only one species here
chains <- c("wombat")
## The datasets
datasets <- c("cranium", "mandible")
## Looping through the chains
for(chain in chains) {
## Output list holder
land_data <- list()
## Looping through the datasets
for(dataset in datasets) {
## Read the landmarks groups
land_data[[dataset]][[1]] <- read.csv(paste0("../Data/Raw/landmarkgroups_", dataset, "_",
chain, ".csv"))
## Translating the landmark groups names
if(dataset == "cranium") {
land_data[[dataset]][[1]][,2] <- gsub(1, "zygomatic", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(2, "rest", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(3, "snout", land_data[[dataset]][[1]][,2])
}
if(dataset == "mandible") {
land_data[[dataset]][[1]][,2] <- gsub(1, "back", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(2, "front", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(3, "rest", land_data[[dataset]][[1]][,2])
}
## Read the landmarks
landmarks <- t(read.csv(paste0("../Data/Raw/landmarkdata_", dataset, "_", chain, ".csv"),
header = TRUE, row.names = 1))
## Remove the juvenile NHNW_B34's mandible
if(dataset == "mandible") {
nhnw_b34 <- which(rownames(landmarks) == "NHNW_B34")
landmarks <- landmarks[-nhnw_b34,]
}
## Remove the patches
landmarks_no_patches <- landmarks[, -c(grep("patch", colnames(landmarks)))]
## Remove the patches and curves
landmarks_no_patches_no_curves <- landmarks_no_patches[, -c(grep(" CUR ",
colnames(landmarks_no_patches)))]
## Make into a 3D array
landmarks <- geomorph::arrayspecs(landmarks, k = 3, p = ncol(landmarks)/3)
landmarks_no_patches <- geomorph::arrayspecs(landmarks_no_patches, k = 3,
p = ncol(landmarks_no_patches)/3)
landmarks_no_patches_no_curves <- geomorph::arrayspecs(landmarks_no_patches_no_curves,
k = 3,
p = ncol(landmarks_no_patches_no_curves)/3)
## Running the Procrustes superimposition
land_data[[dataset]][[2]] <- geomorph::gpagen(landmarks)
land_data[[dataset]][[4]] <- geomorph::gpagen(landmarks_no_patches)
land_data[[dataset]][[5]] <- geomorph::gpagen(landmarks_no_patches_no_curves)
## Convert the array in 2D
array_2d <- geomorph::two.d.array(land_data[[dataset]][[2]]$coords)
## measure the tolerance; the below is part of the geomorph "PlotTangentSpace" code
tol <- prcomp(array_2d)$sdev^2
tolerance <- cumsum(tol)/sum(tol)
tolerance <- length(which(tolerance < 1))
if(length(tolerance) < length(tol)){
tolerance <- tolerance + 1
}
tolerance <- max(c(tol[tolerance]/tol[1],0.005))
## Ordinating the data
land_data[[dataset]][[3]] <- prcomp(array_2d, center = TRUE, scale. = FALSE, retx = TRUE,
tol = tolerance)
## Name the elements
names(land_data[[dataset]]) <- c("landmarkgroups",
"procrustes", "ordination",
"procrustes_no_patches",
"procrustes_no_patches_no_curves")
}
## Check if Processed folder exists
if(!dir.exists("../Data/Processed")) {
dir.create("../Data/Processed")
}
## Save the file
save(land_data, file = paste0("../Data/Processed/", chain, ".Rda"))
}
```
### Data per species
```{r}
## Selecting the wombats
chain <- chains[1]
## Getting the species names
species <- c("ursinus", "latifrons", "krefftii", "lasiorhinus")
sp_holders <- c("Common wombat", "SHN wombat", "NHN wombat")
for(sp in 1:length(species)) {
land_data <- list()
for(dataset in datasets) {
## Reading the wombat species
wombat_sp <- read.csv(paste0("../Data/Raw/classifier_", dataset, "_wombat.csv"))
for(spec in 1:length(species[1:3])) {
wombat_sp$Species <- gsub(sp_holders[spec], species[spec],
as.character(wombat_sp$Species))
}
## Read the landmarks groups
land_data[[dataset]][[1]] <- read.csv(paste0("../Data/Raw/landmarkgroups_", dataset, "_",
chain, ".csv"))
## Translating the landmark groups names
if(dataset == "cranium") {
land_data[[dataset]][[1]][,2] <- gsub(1, "zygomatic", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(2, "rest", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(3, "snout", land_data[[dataset]][[1]][,2])
}
if(dataset == "mandible") {
land_data[[dataset]][[1]][,2] <- gsub(1, "back", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(2, "front", land_data[[dataset]][[1]][,2])
land_data[[dataset]][[1]][,2] <- gsub(3, "rest", land_data[[dataset]][[1]][,2])
}
## Read the landmarks
landmarks <- t(read.csv(paste0("../Data/Raw/landmarkdata_", dataset, "_", chain, ".csv"),
header = TRUE, row.names = 1))
## Remove the juvenile NHNW_B34's mandible
if(dataset == "mandible") {
nhnw_b34 <- which(rownames(landmarks) == "NHNW_B34")
landmarks <- landmarks[-nhnw_b34,]
wombat_sp <- wombat_sp[-nhnw_b34,]
}
## Remove the patches
landmarks_no_patches <- landmarks[, -c(grep("patch", colnames(landmarks)))]
## Remove the patches and curves
landmarks_no_patches_no_curves <- landmarks_no_patches[, -c(grep(" CUR ",
colnames(landmarks_no_patches)))]
## Make into a 3D array
landmarks <- geomorph::arrayspecs(landmarks, k = 3, p = ncol(landmarks)/3)
landmarks_no_patches <- geomorph::arrayspecs(landmarks_no_patches, k = 3,
p = ncol(landmarks_no_patches)/3)
landmarks_no_patches_no_curves <- geomorph::arrayspecs(landmarks_no_patches_no_curves,
k = 3,
p = ncol(landmarks_no_patches_no_curves)/3)
## Selecting the subset of species (if sp == 4, select both krefftii and latifrons)
if(sp != 4) {
which_sp <- sp
} else {
which_sp <- c(2,3)
}
landmarks <- landmarks[, , which(wombat_sp$Species %in% species[which_sp])]
landmarks_no_patches <- landmarks_no_patches[, ,
which(wombat_sp$Species %in% species[which_sp])]
landmarks_no_patches_no_curves <- landmarks_no_patches_no_curves[, ,
which(wombat_sp$Species %in% species[which_sp])]
## Running the Procrustes superimposition
land_data[[dataset]][[2]] <- geomorph::gpagen(landmarks)
land_data[[dataset]][[4]] <- geomorph::gpagen(landmarks_no_patches)
land_data[[dataset]][[5]] <- geomorph::gpagen(landmarks_no_patches_no_curves)
## Convert the array in 2D
array_2d <- geomorph::two.d.array(land_data[[dataset]][[2]]$coords)
## measure the tolerance
tol <- prcomp(array_2d)$sdev^2
tolerance <- cumsum(tol)/sum(tol)
tolerance <- length(which(tolerance < 1))
if(length(tolerance) < length(tol)){
tolerance <- tolerance + 1
}
tolerance <- max(c(tol[tolerance]/tol[1],0.005))
## Ordinating the data
land_data[[dataset]][[3]] <- prcomp(array_2d, center = TRUE, scale. = FALSE, retx = TRUE,
tol = tolerance)
## Name the elements
names(land_data[[dataset]]) <- c("landmarkgroups",
"procrustes", "ordination",
"procrustes_no_patches",
"procrustes_no_patches_no_curves")
}
save(land_data, file = paste0("../Data/Processed/", chain, "_", species[sp], ".Rda"))
}
```
<file_sep>---
title: "Landmark region difference"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools")
if(!require(knitr)) install.packages("knitr")
if(!require(xtable)) install.packages("xtable")
if(!require(geomorph)) install.packages("geomorph")
if(!require(dispRity)) install.packages("dispRity")
if(!require(landvR)) install_github("TGuillerme/landvR")
source("../Functions/utilities.R")
set.seed(42)
```
# Results summary
First we'll load the different results:
```{r}
## Loading and saving paths
load_path <- "../Data/Results/"
table_path <- "../Manuscript/Tables/"
figure_path <- "../Manuscript/Figures/"
## Loading the mean results (observed)
mean_results_obs <- summarise.results(CI = "mean", rarefaction = FALSE, rounding = 4)
mean_results_rar <- summarise.results(CI = "mean", rarefaction = TRUE, rounding = 4)
## Loading the extreme results (GPA)
species_results_100_obs_gpa <- summarise.results(CI = 100, rarefaction = FALSE, rounding = 4)
species_results_095_obs_gpa <- summarise.results(CI = 95, rarefaction = FALSE, rounding = 4)
species_results_100_rar_gpa <- summarise.results(CI = 100, rarefaction = TRUE, rounding = 4)
species_results_095_rar_gpa <- summarise.results(CI = 95, rarefaction = TRUE, rounding = 4)
## Loading the extreme results (pc1_extremes)
species_results_100_obs_pc1 <- summarise.results(CI = 100, rarefaction = FALSE, rounding = 4,
result.type = "pc1.extremes")
species_results_095_obs_pc1 <- summarise.results(CI = 95, rarefaction = FALSE, rounding = 4,
result.type = "pc1.extremes")
species_results_100_rar_pc1 <- summarise.results(CI = 100, rarefaction = TRUE, rounding = 4,
result.type = "pc1.extremes")
species_results_095_rar_pc1 <- summarise.results(CI = 95, rarefaction = TRUE, rounding = 4,
result.type = "pc1.extremes")
## Loading the extreme results (hypothetical)
species_results_100_obs_hyp <- summarise.results(CI = 100, rarefaction = FALSE, rounding = 4,
result.type = "pc1.hypothetical")
species_results_095_obs_hyp <- summarise.results(CI = 95, rarefaction = FALSE, rounding = 4,
result.type = "pc1.hypothetical")
species_results_100_rar_hyp <- summarise.results(CI = 100, rarefaction = TRUE, rounding = 4,
result.type = "pc1.hypothetical")
species_results_095_rar_hyp <- summarise.results(CI = 95, rarefaction = TRUE, rounding = 4,
result.type = "pc1.hypothetical")
```
And combine them together into one observed table and one rarefied table:
```{r}
## Combining results
combine.results <- function(table_mean, table_100_gpa, table_095_gpa, table_100_pc1, table_095_pc1,
table_100_hyp, table_095_hyp) {
complete_fable <- rbind(
table_100_hyp[c(9:12),],
table_095_hyp[c(9:12),],
table_100_hyp[c(13:16),],
table_095_hyp[c(13:16),],
table_100_hyp[c(17:20),],
table_095_hyp[c(17:20),],
table_100_pc1[c(9:12),],
table_095_pc1[c(9:12),],
table_100_pc1[c(13:16),],
table_095_pc1[c(13:16),],
table_100_pc1[c(17:20),],
table_095_pc1[c(17:20),],
table_100_gpa[c(9:12),],
table_095_gpa[c(9:12),],
table_100_gpa[c(13:16),],
table_095_gpa[c(13:16),],
table_100_gpa[c(17:20),],
table_095_gpa[c(17:20),],
table_mean[c(1:4),],
table_mean[c(5:8),]
)
complete_fable <- as.data.frame(complete_fable)
## Make the columns numeric!
complete_fable[, -1] <- apply(complete_fable[, -1], 2, as.numeric)
return(complete_fable)
}
## Observed results table
complete_results_obs <- combine.results(table_mean = mean_results_obs,
table_100_gpa = species_results_100_obs_gpa,
table_095_gpa = species_results_095_obs_gpa,
table_100_pc1 = species_results_100_obs_pc1,
table_095_pc1 = species_results_095_obs_pc1,
table_100_hyp = species_results_100_obs_hyp,
table_095_hyp = species_results_095_obs_hyp)
## Rarefied results table
complete_results_rar <- combine.results(mean_results_rar,
species_results_100_rar_gpa,
species_results_095_rar_gpa,
species_results_100_rar_pc1,
species_results_095_rar_pc1,
species_results_100_rar_hyp,
species_results_095_rar_hyp)
```
And from there we can make the latex results tables:
```{r, eval = FALSE}
# ## Partition names
# partitions <- c("Zygomatic Arch", "Tip of snout", "Remainder(C)", "Masticatory insertions",
# "Symphyseal area", "Remainder(M)")
# ## Test names
# test_names <- c("Vombatus vs. Lasiorhinus", "L. krefftii vs. L. latifrons",
# "Lasiorhinus krefftii (100\\%)", "Lasiorhinus krefftii (95\\%)",
# "Lasiorhinus latifrons (100\\%)", "Lasiorhinus latifrons (95\\%)",
# "Vombatus usrinus (100\\%)", "Vombatus usrinus (95\\%)")
# ## The table caption
# caption_table <- "\"diff\" is the difference in landmark length between the ones from the partition
# and all the other. \"overlap\" is the probability of overlap between the distribution of the landmark
# lengths in the partitions and all the other. Because of the number of bootstrap pseudo-replicates
# involved in the test (1000) and the number of tests, we lowered our threshold for rejecting H0 to p
# <= 0.001. Signif. codes: 0 '*' 0.001 ' ' 1"
# ## Compile the latex tables
# xtable.results(complete_results_obs, partitions.names = partitions, test.names = test_names,
# path = table_path, file.name = "landmark_displacement_obs", caption = caption_table)
# xtable.results(complete_results_rar, partitions.names = partitions, test.names = test_names,
# path = table_path, file.name = "landmark_displacement_rar", caption = caption_table)
```
And the finalised fable:
```{r, width = 7.2, height = 4.5}
## Get the y/x labels
xlabs <- c("Zygomatic Arch", "Tip of snout", "Remainder", "Masticatory\nmuscle insertions",
"Symphyseal\narea", "Remainder")
ylabs <- c(
expression(paste("Northern HN", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Southern HN", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Common", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Northern HN", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Southern HN", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Common", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Northern HN", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Southern HN", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("Common", ", 100% CI", sep = "")),
expression(paste("95% CI")),
expression(paste("All wombat means (GPA)")),
expression(paste("Hairy nose means (GPA)"))
)
ylabs2 <- c("hypothetical\nPC1 projection", "PC1\nextremes", "GPA\nextremes")
plot.test.results(data = complete_results_obs, rarefaction = complete_results_rar, p.value = 0.001,
no.rar = c(2,5), xlabs = xlabs, ylabs = ylabs, ylabs2 = ylabs2, digits = 3,
left.pad = 16, ylab.cex = 1.1, hypothesis = c(1,1,-1,1,1,-1), col.hypo = "yellow") #deepskyblue turquoise2 steelblue
```
```{r, echo = FALSE}
pdf(file = "../Manuscript/Figures/landmark_test_results_full.pdf", width = 12, height = 8)
plot.test.results(data = complete_results_obs, rarefaction = complete_results_rar, p.value = 0.001,
no.rar = c(2,5), xlabs = xlabs, ylabs = ylabs, ylabs2 = ylabs2, digits = 3,
left.pad = 12, ylab.cex = 1.1, hypothesis = c(1,1,-1,1,1,-1), col.hypo = "yellow")
dev.off()
```
Non-significant differences are in grey; significant differences that could not be distinguished from the full statistical population (Bhattacharrya Coefficient test _p_-value > 0.01) are in purple; significant differences that are also from a significant statistical population are in green. Squared cells have the same significance levels when rarefied. The displayed values are the difference in landmark variation area in the partition compared to the whole cranium or mandible.
<file_sep>## Examining digitizing error
# Digitizer: <NAME>
# August 2015
library(geomorph)
library(abind)
# Rep1
setwd("E:/Students/Cruise/Paper/rep/R1")
##Cranial
WomCrData <- read.csv("Crania ORIGINAL.csv", header = T, row.names = 1) # Read data
WomCrData <- t(WomCrData) # Transpose rows and columns
WomCrData <- WomCrData[complete.cases(WomCrData),] # Remove any empty rows
Rep1_Cranial <- arrayspecs(WomCrData, k=3, p=ncol(WomCrData)/3) # Make 3D Array
##Mandible
WomMaData <- read.csv("Mandibles ORIGINAL.csv", header = T, row.names = 1)
WomMaData <- t(WomMaData)
WomMaData <- WomMaData[complete.cases(WomMaData),]
Rep1_Mandible <- arrayspecs(WomMaData, k=3, p=ncol(WomMaData)/3)
# Rep2
setwd("E:/Students/Cruise/Paper/rep/R2")
##Cranial
WomCrData <- read.csv("Crania RELANDMARKED.csv", header = T, row.names = 1) # Read data
WomCrData <- t(WomCrData) # Transpose rows and columns
WomCrData <- WomCrData[complete.cases(WomCrData),] # Remove any empty rows
Rep2_Cranial <- arrayspecs(WomCrData, k=3, p=ncol(WomCrData)/3) # Make 3D Array
##Mandible
WomMaData <- read.csv("Mandibles RELANDMARKED.csv", header = T, row.names = 1)
WomMaData <- t(WomMaData)
WomMaData <- WomMaData[complete.cases(WomMaData),]
Rep2_Mandible <- arrayspecs(WomMaData, k=3, p=ncol(WomMaData)/3)
#Check match of names
nCran <- length(dimnames(Rep2_Cranial)[[3]])
nMand <- length(dimnames(Rep2_Mandible)[[3]])
dimnames(Rep2_Cranial)[[3]] == dimnames(Rep1_Cranial)[[3]]
dimnames(Rep2_Mandible)[[3]] == dimnames(Rep1_Mandible)[[3]]
#Concatenate arrays using abind
CranRep <- abind(Rep1_Cranial,Rep2_Cranial)
MandRep <- abind(Rep1_Mandible,Rep2_Mandible)
#Check all is well
plot3d(CranRep[,,3],aspect = FALSE)
# Procrustes of the two sets - there's a warning that row names are not used but that's OK because they have to be duplicates
CranRep_GPA <- gpagen(CranRep)
MandRep_GPA <- gpagen(MandRep)
individuals <- dimnames(CranRep_GPA$coords)[[3]] # name for each pair shouldbe same, so not _1, _2
# create a vector designating specimens to a replicate, 12 each for both datasets
replicate <- c(rep(1, nCran), rep(2, nCran))
# to check your replicates, examine the replicates in a PCA
plotTangentSpace(CranRep_GPA$coords, groups = replicate) # PCA coloured by replicate; looking for pairs in PCA; black is rep2
plotTangentSpace(MandRep_GPA$coords, groups = replicate, label = individuals)
# Look at the outliers
out <- plotOutliers(gpa$coords) # Which specimens are way off?
plotRefToTarget(mshape(gpa$coords), gpa$coords[,,out[1]], method="vector", label = T)
## TEST Examining replicate error
rep.er.Cran <- procD.lm(CranRep_GPA$coords ~ factor(individuals))
((rep.er.Cran$aov.table$MS[1] - rep.er.Cran$aov.table$MS[2])/2) / (rep.er.Cran$aov.table$MS[2] + ((rep.er.Cran$aov.table$MS[1] - rep.er.Cran$aov.table$MS[2])/2))
# Number here should be above 0.9 for good repeatability, although in practice
rep.er.Mand <- procD.lm(MandRep_GPA$coords ~ factor(individuals))
((rep.er.Mand$aov.table$MS[1] - rep.er.Mand$aov.table$MS[2])/2) / (rep.er.Mand$aov.table$MS[2] + ((rep.er.Mand$aov.table$MS[1] - rep.er.Mand$aov.table$MS[2])/2))
<file_sep>---
title: "Testing the variation in landmark position"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
pdf_document:
fig_width: 8
fig_height: 4
---
Loading the packages and the data
```{r}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools")
if(!require(knitr)) install.packages("knitr")
if(!require(geomorph)) install.packages("geomorph")
if(!require(dispRity)) install.packages("dispRity")
if(!require(landvR)) install_github("TGuillerme/landvR")
source("../../../Functions/utilities.R")
set.seed(42)
## Loading a dataset
load("../../../Data/Processed/wombat_ursinus.Rda")
## Selecting a partition
cranium <- land_data$cranium
```
# Step 1: using the PCA to propose a hypothesis
First we can ordinate the data and check the PCA.
```{r, fig.height = 8, width.height = 8}
## Plot the PCA
ordination_space <- plotTangentSpace(land_data$cranium$procrustes$coords)
```
We can then check the variation along the hypothetical PC1 min and PC1 max variation:
```{r}
## Coordinate differences between the PC1 max and min
ordination_var <- coordinates.difference(ordination_space$pc.shapes$PC1min,
ordination_space$pc.shapes$PC1max,
type = "spherical")
```
And plot this difference to make the hypothesis of where do the variation occur the most.
```{r, fig.height = 8, width.height = 8}
## Plotting the coordinate differences between the PC max and min
procrustes.var.plot(ordination_space$pc.shapes$PC1min,
ordination_space$pc.shapes$PC1max,
col = heat.colors, col.val = ordination_var[[1]][, "radius"], magnitude = 1.2)
```
# Step 2: testing this difference in the Procrustes space
Measuring the variation in the Procrustes space
```{r}
## Procrustes variation ranges
procrustes_var <- variation.range(cranium$procrustes, return.ID = TRUE)
```
Applying the test in the zygomatic partition:
```{r}
## Partitions
partitions <- list()
for(part in unique(cranium$landmarkgroups[,2])) {
partitions[[part]] <- which(cranium$landmarkgroups[,2] == part)
}
## Getting the zygomatic partition
random_part <- partitions[[1]]
## Measuring the difference for the zygomatic area
random_area <- rand.test(procrustes_var$range[, "radius"], random_part, test = area.diff,
test.parameter = TRUE)
## Measuring the difference for a zygomatic overlap
random_overlap <- rand.test(procrustes_var$range[, "radius"], random_part, test = bhatt.coeff,
test.parameter = TRUE)
```
And then plot the effective distribution comparisons from the test (plot functions are detailed in the uncompiled Rmd file)
```{r, echo = FALSE}
## Plotting the area difference
plot.area <- function(distribution, X, reference, col) {
par(bty = "n")
plot(NULL, ylim = c(0, 0.01), xlim = c(1, length(X)), xlab = "", ylab = "")
# par(bty = "n")
# plot(NULL, ylim = c(0, 0.01), xlim = c(1, length(observed_draws)), xaxt = 'n', yaxt = 'n', xlab = "n", ylab = "n")
polygon(
x = c(1:length(X), rev(1:length(X))),
y = c(sort(distribution[X], decreasing = TRUE), sort(distribution[reference], decreasing = FALSE)),
col = col[3], border = NA
)
## Add the lines
lines(sort(distribution[X], decreasing = TRUE), col = col[1], lwd = 2)
lines(sort(distribution[reference], decreasing = TRUE), col = col[2], lwd = 2)
}
## Plotting the overlap function
plot.overlap <- function(distribution, X, reference, col){
## Get the distributions
distri_1 <- density(distribution[X])
distri_2 <- density(distribution[reference])
## Get the x coordinates
global_x <- c(distri_1$x, distri_2$x)
x = seq(from = min(global_x), to = max(global_x), length.out = length(distri_1$y))
## Get the y coordinates
y1 = distri_1$y
y2 = distri_2$y
## Empty plot
par(bty = "n")
plot(NULL, xlim = c(-0.001, 0.01), ylim = c(0, 350), xlab = "", ylab = "")
## Plot the polygon
polygon(x, pmin(y1, y2), col = col[3], border = NA)
## Add the lines
lines(x, y1, type = "l", lwd = 2, col = col[1])
lines(x, y2, type = "l", lwd = 2, col = col[2])
}
```
Getting the results (export directly as pdf)
```{r}
## Plot the results
pdf(file = "results_area.pdf")
par(bty = "n")
plot(random_area, main = "results area")
dev.off()
pdf(file = "results_overlap.pdf")
par(bty = "n")
plot(random_overlap, main = "results overlap")
dev.off()
```
And plotting what the test is actually doing (export directly as pdf)
```{r}
## Setting the parameters for plotting the test data
## The data
distribution <- procrustes_var$range[,1]
## The different draws (first is the reference)
observed_draws <- partitions[[1]]
random_draws <- replicate(4, sample(1:length(distribution), length(observed_draws)), simplify = FALSE)
## The colours parameters
colours <- c("purple", "green", "grey") #obs, reference, difference
## Observed difference
## Overlap
pdf(file = "overlap_obs.pdf")
plot.overlap(distribution, observed_draws, reference = random_draws[[1]], col = colours)
dev.off()
## Area
pdf(file = "area_obs.pdf")
plot.area(distribution, observed_draws, reference = random_draws[[1]], col = colours)
dev.off()
## Simulated differences
for(one_plot in 2:4) {
## Overlap
pdf(file = paste0("overlap_simul_0", one_plot-1, ".pdf"))
plot.overlap(distribution, random_draws[[one_plot]], reference = random_draws[[1]], col = colours)
dev.off()
## Area
pdf(file = paste0("area_simul_0", one_plot-1, ".pdf"))
plot.area(distribution, random_draws[[one_plot]], reference = random_draws[[1]], col = colours)
dev.off()
}
```<file_sep>---
title: "Landmark region difference"
author: "<NAME>"
bibliography: references.bib
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools")
if(!require(knitr)) install.packages("knitr")
if(!require(xtable)) install.packages("knitr")
if(!require(geomorph)) install.packages("geomorph")
if(!require(dispRity)) install_github("TGuillerme/dispRity")
if(!require(landvR)) install_github("TGuillerme/landvR")
source("../Functions/utilities.R")
set.seed(42)
```
##### Note for changing the confidence interval values
Search and replace `CI = 1` and `CI100` by respectively `CI = 0.95` and `CI95` for switching from the 95% confidence interval to the 100%.
# Between species
## All species
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- 1
species <- "Wombat"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
## Lasiorhinus genus
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_lasiorhinus"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
#load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_lasiorhinus"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
#load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
# Within species
## Wombat krefftii
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_krefftii"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_krefftii"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
## Wombat latifrons
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_latifrons"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_latifrons"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
## Wombat ursinus
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_ursinus"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_ursinus"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, combine.land = FALSE, CI = 0.95, use.PC.range = TRUE)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
load(file = paste0("../Data/Results/", species, "_", dataset, "_CI95_PC1.Rda"))
caption_diff <- paste0("Results of the area difference random test for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni")
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni")
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_CI95_PC1.pdf"))
```
# Rarefied analysis
## Between species
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- 1
species <- "Wombat"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
## Lasiorhinus genus
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_lasiorhinus"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
#load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_lasiorhinus"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
#load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
# Within species
## Wombat krefftii
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_krefftii"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_krefftii"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
## Wombat latifrons
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_latifrons"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_latifrons"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
## Wombat ursinus
### Cranium
```{r, echo = FALSE, message = FALSE}
counter <- counter + 1
species <- "Wombat_ursinus"
dataset <- "cranium"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
### Mandible
```{r, echo = FALSE, message = FALSE}
species <- "Wombat_ursinus"
dataset <- "mandible"
results <- pipeline.test(species, dataset, "../Data/Processed/", verbose = TRUE, rarefaction = TRUE, CI = 0.95)
save(results, file = paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Results/", species, "_", dataset, "rarefied_CI95_PC1.Rda"))
load(paste0("../Data/Processed/", species, ".Rda"))
results$rarefaction <- min(table(land_data[[dataset]]$landmarkgroups[,2]))
caption_diff <- paste0("Results of the area difference random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
caption_over <- paste0("Results of the overlap probability random test (rarefied - ", results$rarefaction, ") for the ", results$dataset, " of ", translate.name(results$species))
## Get arguments for the partitions naming
part_args <- get.partition.args(dataset)
## Size differences
kable(make.table(results$differences, "bonferroni", partition.args = part_args), digits = 5, caption = caption_diff)
## Probability of overlap
kable(make.table(results$overlaps, "bonferroni", partition.args = part_args), digits = 5, caption = caption_over)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
## xtables for pub
make.xtable(results$differences, "bonferroni", partition.args = part_args, digits = 3, caption = caption_diff, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_difference_rarefied_CI95"))
make.xtable(results$overlaps, "bonferroni", partition.args = part_args, digits = 3, caption = caption_over, path = "../Manuscript/Tables/", label = paste0("0", counter, "_", translate.name(species), "_", dataset, "_overlaps_rarefied_CI95"))
```
#### Area difference
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
#### Bhattacharyya Coefficient
```{r, fig.width = 10, fig.height = 15, echo = FALSE, message = FALSE}
## Plot the size differences
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction)
```
```{r, eval = TRUE, echo = FALSE, print = FALSE, results = 'hide'}
make.plots(results$differences, type = "area difference", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_difference_rarefied_CI95_PC1.pdf"))
make.plots(results$overlaps, type = "Bhattacharyya Coefficient", add.p = TRUE, correction = "bonferroni", rarefaction = TRUE, rare.level = results$rarefaction, path = paste0("../Manuscript/Figures/", species, "_", dataset, "_overlaps_rarefied_CI95_PC1.pdf"))
```
<file_sep>---
title: "Heat map plot of changes"
author: "<NAME>"
date: "`r Sys.Date()`"
output:
html_document:
fig_width: 12
fig_height: 6
---
Some fancy plots for the maximum landmark variation.
## Plots
### Loading the functions
```{r, message = FALSE, warning = FALSE}
## Loading the libraries (and installing if necessary)
if(!require(devtools)) install.packages("devtools"); library(devtools)
if(!require(geomorph)) install.packages("geomorph"); library(geomorph)
if(!require(dispRity)) install.packages("dispRity"); library(dispRity)
if(!require(landvR)) install_github("TGuillerme/landvR") ; library(landvR)
set.seed(42)
```
### Loading the data
```{r}
## Loading a dataset
#loading the below loads objects called land_data, NOT "wombat"
load("../Data/Processed/wombat.Rda")
AllWombats<-land_data
load("../Data/Processed/wombat_lasiorhinus.Rda")
HN<-land_data
load("../Data/Processed/wombat_krefftii.Rda")
NHNW<-land_data
load("../Data/Processed/wombat_latifrons.Rda")
SHNW<-land_data
load("../Data/Processed/wombat_ursinus.Rda")
CW<-land_data
source("../Functions/utilities.R")
```
The "maximum" and "minimum" specimen in procrustes space
```{r}
## Procrustes variation ranges
target=CW$cranium
variation <- variation.range(target$procrustes, return.ID = TRUE)
specimens_min_max <- variation$min.max
procrustes_var <- variation$range[,1]
```
```{r, eval = FALSE}
gridPar = gridPar(pt.bg = "white", pt.size = 0.5)
open3d()
procrustes.var.plot(target$procrustes$coords[, , specimens_min_max[1]],
target$procrustes$coords[, , specimens_min_max[2]],
col = heat.colors, pt.size = 0.8, col.val = procrustes_var, main = "GPA var")
```
Specimens along PC extremes (i.e. not hypothetical specimens, as per warning message)
```{r}
## variation ranges
target=CW$cranium
#HIgest and lowest Pc1 score - specimen closest to PC1 extremes
variation_real <- variation.range(target$procrustes, axis=1, ordination=target$ordination, return.ID = TRUE)
minmax <- variation_real$min.max
#measuring the difference between the two sepcimens selected in variation.real
variation <- coordinates.difference(target$procrustes$coords[,,minmax[1]], target$procrustes$coords[,,minmax[2]], type = "spherical")
open3d()
#Use "variation" to colour the plot exactly according to vector length
procrustes.var.plot(target$procrustes$coords[, , minmax[2]],
target$procrustes$coords[, , minmax[1]],
col = heat.colors, pt.size = 0.8, col.val = variation[[1]][,1],
main="Min-max specimens closes to PC1 extremes")
```
```{r, eval = FALSE}
gridPar = gridPar(pt.bg = "white", pt.size = 0.5)
open3d()
procrustes.var.plot(target$procrustes$coords[, , specimens_min_max[2]],
target$procrustes$coords[, , specimens_min_max[1]],
col = heat.colors, pt.size = 0.8, col.val = variation$range[,1],
main="procrustes.var.plot based actual specimens")
```
#Doing this using hypothetical PC min/max landmarks for the figures in the manuscript. See utilities file for details. Also be aware that the warning message that the returned specimen does not correspond to the PCmin/max specimen but the nearest observed one is INCORRECT in this case becasue we are using the hypothetical configurations as specimens.
```{r, eval = FALSE}
## Craniums
## All wombats
heatplot.PCs(AllWombats$cranium, minfirst=FALSE, 1 )
## Lasiorhinus
heatplot.PCs(HN$cranium, minfirst=TRUE ,1 )
## Vombatus
heatplot.PCs(CW$cranium, minfirst=FALSE,1, main="hypothetical CW PC1")
## Lasihorhinus latifrons
heatplot.PCs(SHNW$cranium, minfirst=TRUE,1)
## Lasihorhinus krefftii
heatplot.PCs(NHNW$cranium, minfirst=TRUE,1)
## Mandibles
## All wombats
heatplot.PCs(AllWombats$mandible, minfirst=FALSE, 1)
## Lasihorhinus
heatplot.PCs(HN$mandible, minfirst=TRUE, 1 )
## Vombatus
heatplot.PCs(CW$mandible, minfirst=FALSE,1)
## Lasihorhinus latifrons
heatplot.PCs(SHNW$mandible, minfirst=TRUE,1)
## Lasihorhinus krefftii
heatplot.PCs(NHNW$mandible, minfirst=TRUE, 1)
```
#In case there are any doubts that the heatplot and "regular" PlotTangentSpace/plotRefToTArget show the same, below is a comparison
```{r}
gridpar=gridPar(pt.size=0.3)
#Run conventional PlotRefToTarget
CWGeomorph=plotTangentSpace(CW$cranium$procrustes$coords)
#Find min/max specimen
which(CWGeomorph$pc.scores[,1] == max(CWGeomorph$pc.scores[,1]))#CW_M22233, number 3
which(CWGeomorph$pc.scores[,1] == min(CWGeomorph$pc.scores[,1]))#CW_M22233, number 14
#also no. 3 and 14 in the coordinates
dimnames(CW$cranium$procrustes$coords)[[3]]
#Plot hypothetical configurations
open3d()
plotRefToTarget(CWGeomorph$pc.shapes$PC1max, CWGeomorph$pc.shapes$PC1min, method="vector",gridPar=gridpar, main="min/max hypothetical specimens on PC1 as determined through PlotTangentSpace")
#Plot actual specimens - they are different!
open3d()
plotRefToTarget( CW$cranium$procrustes$coords[,,3], CW$cranium$procrustes$coords[,,14], method="vector", gridPar=gridpar, main="min/max actual specimens of CW PC1 as determined through plotTangentSpace")
#hypothetical PCs "the old fashioned way" are comparable to the heat plots and running the above code also means that
open3d()
heatplot.PCs(CW$cranium, minfirst=FALSE,1)
```
| 6150b49e670e39af87b49e7695c6a41e32b931c0 | [
"Markdown",
"R",
"RMarkdown",
"Shell"
] | 15 | Markdown | TGuillerme/landmark-test | f8be076f1fa492ab8254ac52c2c72100100339cf | 6f4f0df12dbb5fa5b1065f60e8dc6f7a902c8aff |
refs/heads/master | <repo_name>pligor/anonymizer<file_sep>/resources/screens/d12245cc-1680-458d-89dd-4f0d7fb22724-1518646228006.js
jQuery("#simulation")
.on("click", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .click", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Hotspot_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_204")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-import_csv_2" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_11")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-import_csv_2" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_4")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_5")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_17")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "anonymize_selected" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "export_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "import_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/908bc018-bee5-45de-8a4f-845a2b307d57",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_7")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_23")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mysql_2" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_9")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_62")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimResize",
"parameter": {
"target": [ "#s-Input_8" ],
"width": {
"type": "noresize"
},
"height": {
"type": "exprvalue",
"value": "270"
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Group_29" ],
"top": {
"type": "movebyoffset",
"value": "-286"
},
"left": {
"type": "nomove"
},
"containment": false
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-sql_results" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_63")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimResize",
"parameter": {
"target": [ "#s-Input_9" ],
"width": {
"type": "noresize"
},
"height": {
"type": "exprvalue",
"value": "270"
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-thunder1" ],
"top": {
"type": "movebyoffset",
"value": "-286"
},
"left": {
"type": "nomove"
},
"containment": false
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_18")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "anonymize_selected" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "export_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "import_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimNavigation",
"parameter": {
"target": "screens/908bc018-bee5-45de-8a4f-845a2b307d57",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_11")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_35")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38": {
"attributes": {
"background-color": "#666666",
"background-image": "none",
"border-top-width": "2px",
"border-top-style": "dashed",
"border-top-color": "#CCCCCC",
"border-right-width": "2px",
"border-right-style": "dashed",
"border-right-color": "#CCCCCC",
"border-bottom-width": "2px",
"border-bottom-style": "dashed",
"border-bottom-color": "#CCCCCC",
"border-left-width": "2px",
"border-left-style": "dashed",
"border-left-color": "#CCCCCC",
"border-radius": "14px 14px 14px 14px",
"font-size": "14.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38 span": {
"attributes": {
"color": "#D9D9D9",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "14.0pt",
"font-style": "italic",
"font-weight": "400"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38": {
"attributes-ie": {
"border-top-width": "2px",
"border-top-style": "dashed",
"border-top-color": "#CCCCCC",
"border-right-width": "2px",
"border-right-style": "dashed",
"border-right-color": "#CCCCCC",
"border-bottom-width": "2px",
"border-bottom-style": "dashed",
"border-bottom-color": "#CCCCCC",
"border-left-width": "2px",
"border-left-style": "dashed",
"border-left-color": "#CCCCCC",
"border-radius": "14px 14px 14px 14px",
"-pie-background": "#666666",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_35": {
"attributes": {
"background-color": "#434343",
"background-image": "none",
"border-top-width": "4px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "4px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "4px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "4px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "14px 14px 14px 14px",
"font-size": "14.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_35 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_35 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "14.0pt",
"font-style": "normal",
"font-weight": "400"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_35": {
"attributes-ie": {
"border-top-width": "4px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "4px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "4px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "4px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "14px 14px 14px 14px",
"-pie-background": "#434343",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-raw_structured" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_19")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "anonymize_selected" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "export_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "import_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/908bc018-bee5-45de-8a4f-845a2b307d57",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_12")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d12245cc-1680-458d-89dd-4f0d7fb22724",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_13")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/908bc018-bee5-45de-8a4f-845a2b307d57",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_149")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mysql_1" ],
"transition": "fade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_201")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-import_csv_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_202")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-import_raw_text_1" ],
"transition": "fade"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 100
}
},
"exectype": "parallel",
"delay": 0
},
{
"action": "jimResize",
"parameter": {
"target": [ "#s-progress_bar" ],
"width": {
"type": "exprvalue",
"value": "1336"
},
"height": {
"type": "noresize"
},
"effect": {
"type": "none",
"easing": "linear",
"duration": 10000
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-percent_label" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "1336"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 10000
}
},
"exectype": "parallel",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "struct_load_loop" ],
"value": "1"
},
"exectype": "parallel",
"delay": 0
},
{
"action": "jimRotate",
"parameter": {
"target": [ "#s-Image_65" ],
"angle": {
"type": "rotateby",
"value": "2000"
},
"effect": {
"type": "none",
"easing": "linear",
"duration": 10000
}
},
"exectype": "parallel",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_119")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-select_import_popup" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 200
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("change", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .change", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Input_5")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimGreater",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-db_hostname_label" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_23": {
"attributes": {
"box-shadow": "0px 10px 20px 2px #404040",
"text-shadow": "none",
"font-size": "24.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_23 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_23 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "24.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-db_hostname_label" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_23": {
"attributes": {
"box-shadow": "none",
"text-shadow": "none",
"font-size": "24.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_23 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_23 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "24.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_6")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimGreater",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_6",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-username_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_6",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-username_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_7")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimGreater",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_7",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-password_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_7",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-password_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("focusin", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .focusin", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Input_5")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_5": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "5px",
"border-bottom-style": "solid",
"border-bottom-color": "#434343",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_6")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_6": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "5px",
"border-bottom-style": "solid",
"border-bottom-color": "#434343",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_7")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_7": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "5px",
"border-bottom-style": "solid",
"border-bottom-color": "#434343",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_8")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_8": {
"attributes": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#0088CC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#0088CC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#0088CC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#0088CC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_9")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_9": {
"attributes": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#0088CC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#0088CC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#0088CC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#0088CC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("focusout", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .focusout", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Input_5")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_5": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#666666",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_6")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_6": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#666666",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_7")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_7": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#666666",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_8")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_8": {
"attributes": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_9")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Input_9": {
"attributes": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mouseenter dragenter", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mouseenter", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Image_62")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_62" ],
"top": {
"type": "movebyoffset",
"value": "-5"
},
"left": {
"type": "nomove"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 50
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_62" ],
"top": {
"type": "movebyoffset",
"value": "10"
},
"left": {
"type": "nomove"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 100
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_62" ],
"top": {
"type": "movebyoffset",
"value": "-5"
},
"left": {
"type": "nomove"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 50
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_63")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_63" ],
"top": {
"type": "movebyoffset",
"value": "-5"
},
"left": {
"type": "nomove"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 50
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_63" ],
"top": {
"type": "movebyoffset",
"value": "10"
},
"left": {
"type": "nomove"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 100
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_63" ],
"top": {
"type": "movebyoffset",
"value": "-5"
},
"left": {
"type": "nomove"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 50
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mouseenter dragenter", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mouseenter", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Image_204") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-drag_n_drop_csv_file_background": {
"attributes": {
"background-color": "#999999",
"background-image": "none",
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-drag_n_drop_csv_file_background": {
"attributes-ie": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px",
"-pie-background": "#999999",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_204 > svg": {
"attributes": {
"overlay": "#EFEFEF"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_19": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_19 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_19 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Text_20" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Button_11" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_19" ],
"value": "Drop CSV File in here"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_2") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_122" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_4") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-csv_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_4 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_23": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_23 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_23 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_3") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_5" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_115" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_6") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_8") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_7" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_10") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_12" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_33") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_33": {
"attributes": {
"font-size": "14.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_33 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_33 span": {
"attributes": {
"color": "#434343",
"text-align": "center",
"text-decoration": "underline",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "14.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_149") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mysql_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_149 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_7": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_7 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_7 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_150") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-oracle_sql_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_150 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_8": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_8 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_8 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_151") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-postgre_sql_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_151 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_9": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_9 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_9 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_198") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-excel_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_198 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_10": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_10 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_10 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_197") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-xml_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_197 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_11": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_11 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_11 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_201") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-csv_hover" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_201 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_12": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_12 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_12 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_202") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_1": {
"attributes": {
"background-color": "#D9D9D9",
"background-image": "none",
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_1": {
"attributes-ie": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px",
"-pie-background": "#D9D9D9",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_202 > svg": {
"attributes": {
"overlay": "#666666"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_14": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_14 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Text_14 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Text_15" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Button_10" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_14" ],
"value": "Drop in here"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_119") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Image_119 > svg": {
"attributes": {
"overlay": "#999999"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
}
})
.on("mouseleave dragleave", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .mouseleave", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Image_204")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_2")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_4")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_3")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_6")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_8")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_10")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_33")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_149")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_150")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_151")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_198")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_197")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_201")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_202")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Image_119")) {
jEvent.undoCases(jFirer);
}
})
.on("variablechange.jim", ".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .variablechange", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Text_29")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop") && {
"action": "jimGreater",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"15" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Text_29" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_34")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop") && {
"action": "jimGreater",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"15" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_34" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_35")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop") && {
"action": "jimGreater",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"25" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_35" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_36")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop") && {
"action": "jimGreater",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"50" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_36" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_37")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop") && {
"action": "jimGreater",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"90" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_37" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_38")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"99" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_38" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-extraction_progress_group" ]
},
"exectype": "timed",
"delay": 1000
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-raw_unstructured_dyn_panel" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38": {
"attributes": {
"background-color": "#434343",
"background-image": "none",
"border-top-width": "4px",
"border-top-style": "dashed",
"border-top-color": "#CCCCCC",
"border-right-width": "4px",
"border-right-style": "dashed",
"border-right-color": "#CCCCCC",
"border-bottom-width": "4px",
"border-bottom-style": "dashed",
"border-bottom-color": "#CCCCCC",
"border-left-width": "4px",
"border-left-style": "dashed",
"border-left-color": "#CCCCCC",
"border-radius": "14px 14px 14px 14px",
"font-size": "14.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "14.0pt",
"font-style": "italic",
"font-weight": "400"
}
}
},{
"#s-d12245cc-1680-458d-89dd-4f0d7fb22724 #s-Rectangle_38": {
"attributes-ie": {
"border-top-width": "4px",
"border-top-style": "dashed",
"border-top-color": "#CCCCCC",
"border-right-width": "4px",
"border-right-style": "dashed",
"border-right-color": "#CCCCCC",
"border-bottom-width": "4px",
"border-bottom-style": "dashed",
"border-bottom-color": "#CCCCCC",
"border-left-width": "4px",
"border-left-style": "dashed",
"border-left-color": "#CCCCCC",
"border-radius": "14px 14px 14px 14px",
"-pie-background": "#434343",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-done_import_button_2" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_202")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "struct_load_loop"),
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-percent_label" ],
"value": {
"action": "jimConcat",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"%" ]
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "struct_load_loop" ],
"value": {
"action": "jimMin",
"parameter": [ {
"action": "jimPlus",
"parameter": [ {
"datatype": "variable",
"element": "struct_load_loop"
},"1" ]
},"100" ]
}
},
"exectype": "timed",
"delay": 100
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
});<file_sep>/resources/screens/908bc018-bee5-45de-8a4f-845a2b307d57-1518646228006.js
jQuery("#simulation")
.on("click", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .click", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Hotspot_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Dynamic_Panel_2" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "tabled_linked" ],
"value": "1"
},
"exectype": "parallel",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_82" ]
},
"exectype": "parallel",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_cell_12")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "is_column_selected" ],
"value": {
"action": "jimMod",
"parameter": [ {
"action": "jimPlus",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"1" ]
},"2" ]
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_3")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "is_title_selected" ],
"value": {
"action": "jimMod",
"parameter": [ {
"action": "jimPlus",
"parameter": [ {
"datatype": "variable",
"element": "is_title_selected"
},"1" ]
},"2" ]
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_2")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "anonymizing" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_hotspot_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-anon_op2_hotspot_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "cars_table_anonymized" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_7")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-view_table_data_panel" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "data_preview_enabled" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_178")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-view_table_data_panel" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "data_preview_enabled" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_hotspot")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-anon_op2_hotspot" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "drive_col_anonymized" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_3")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "data_preview_enabled" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("drag", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .drag", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Rectangle_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimMove",
"parameter": {
"target": [ "#s-draggable_table_panel" ],
"top": {
"type": "movewithcursor",
"value": null
},
"left": {
"type": "movewithcursor",
"value": null
},
"containment": true
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("dragend", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .drag", function(event, data) {
jimEvent(event).jimRestoreDrag(jQuery(this));
})
.on("dragend", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .drag", function(event, data) {
jimEvent(event).jimDestroyDrag(jQuery(this));
})
.on("mouseenter dragenter", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .mouseenter", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Hotspot_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_82" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mouseleave dragleave", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .mouseleave", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Hotspot_1") && (jQuery(document.elementFromPoint(event.clientX, event.clientY)).closest("#s-Hotspot_1").length === 0 || jQuery(document.elementFromPoint(event.clientX, event.clientY)).closest("#s-Hotspot_1") !== jFirer)) {
event.stopPropagation();
cases = [
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "tabled_linked"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_82" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Image_82" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mouseenter dragenter", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .mouseenter", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Text_cell_9") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_9": {
"attributes": {
"background-color": "#CCCCCC",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_9": {
"attributes-ie": {
"-pie-background": "#CCCCCC",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_cell_10") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_10": {
"attributes": {
"background-color": "#CCCCCC",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_10": {
"attributes-ie": {
"-pie-background": "#CCCCCC",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_cell_11") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_11": {
"attributes": {
"background-color": "#CCCCCC",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_11": {
"attributes-ie": {
"-pie-background": "#CCCCCC",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_cell_12") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"0" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12": {
"attributes": {
"background-color": "#CCCCCC",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12": {
"attributes-ie": {
"-pie-background": "#CCCCCC",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_cell_13") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_13": {
"attributes": {
"background-color": "#CCCCCC",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_13": {
"attributes-ie": {
"-pie-background": "#CCCCCC",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_3") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_title_selected"
},"0" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3": {
"attributes": {
"background-color": "#CCCCCC",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3": {
"attributes-ie": {
"-pie-background": "#CCCCCC",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_2") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Panel_12": {
"attributes": {
"opacity": "0.99"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Panel_12 .verticalalign": {
"attributes": {
"vertical-align": "top"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Panel_12": {
"attributes-ie": {
"-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=99)",
"filter": "alpha(opacity=99)"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_hotspot_1") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_14": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_14": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_14": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_hover_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_sel_half_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op1_hotspot_1") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_12": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_12": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_12": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_13": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_13": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_13": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op1_hover_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op1_sel_half_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op3_hotspot_1") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_15": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_15": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_15": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_16": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_16": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_16": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op3_hover_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op3_sel_half_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op1_hotspot_1") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_19": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_19": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_19": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_18": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_18": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_18": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op1_hover_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op1_sel_half_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op2_hotspot_1") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_17": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_17": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_17": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op2_hover_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op2_sel_half_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op3_hotspot_1") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_1": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_1": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_1": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_diag_1": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_diag_1": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_diag_1": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op3_hover_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op3_sel_half_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Panel_11") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Image_178 > svg": {
"attributes": {
"overlay": "#434343"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_hotspot") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_6": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_6": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_6": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_hover" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_sel_half" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op1_hotspot") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_4": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_4": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_4": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_5": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_5": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_5": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op1_hover" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op1_sel_half" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op3_hotspot") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_7": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_7": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_7": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_8": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_8": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_8": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op3_hover" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op3_sel_half" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op1_hotspot") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_11": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_11": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_11": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_10": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_10": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_10": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op1_hover" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op1_sel_half" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op2_hotspot") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_9": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_9": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_9": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op2_hover" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op2_sel_half" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op3_hotspot") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_diag": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_diag": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-mask_op3_line_diag": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#666666",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op3_hover" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-mask_op3_sel_half" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_38") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_38": {
"attributes": {
"font-size": "14.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_38 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_38 span": {
"attributes": {
"color": "#434343",
"text-align": "center",
"text-decoration": "underline",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "14.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
}
})
.on("mouseleave dragleave", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .mouseleave", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Text_cell_9")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_cell_10")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_cell_11")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_cell_12")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_cell_13")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Rectangle_3")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_2")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-anon_op2_hotspot_1")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-anon_op1_hotspot_1")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-anon_op3_hotspot_1")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-mask_op1_hotspot_1")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-mask_op2_hotspot_1")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-mask_op3_hotspot_1")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Panel_11")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-anon_op2_hotspot")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-anon_op1_hotspot")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-anon_op3_hotspot")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-mask_op1_hotspot")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-mask_op2_hotspot")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-mask_op3_hotspot")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_38")) {
jEvent.undoCases(jFirer);
}
})
.on("variablechange.jim", ".s-908bc018-bee5-45de-8a4f-845a2b307d57 .variablechange", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Rectangle_22")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_22" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_cell_12")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "is_column_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12": {
"attributes": {
"background-color": "#434343",
"background-image": "none",
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#F3F3F3",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#F3F3F3",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#F3F3F3",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#F3F3F3",
"border-radius": "0px 0px 0px 0px",
"line-height": "14px",
"font-size": "10.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12 span": {
"attributes": {
"color": "#F3F3F3",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "10.0pt",
"font-style": "normal",
"font-weight": "400"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12": {
"attributes-ie": {
"-pie-background": "#434343",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "is_title_selected" ],
"value": "0"
},
"exectype": "parallel",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "is_column_selected"),
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12": {
"attributes": {
"background-color": "transparent",
"background-image": "none",
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#DDDDDD",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#DDDDDD",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px",
"line-height": "14px",
"font-size": "10.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12 span": {
"attributes": {
"color": "#333333",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "10.0pt",
"font-style": "normal",
"font-weight": "400"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_cell_12": {
"attributes-ie": {
"-pie-background": "transparent",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_3")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "is_title_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_title_selected"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3": {
"attributes": {
"background-color": "#434343",
"background-image": "none",
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#F3F3F3",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#F3F3F3",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#F3F3F3",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#F3F3F3",
"border-radius": "1px 1px 1px 1px",
"font-size": "10.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3 span": {
"attributes": {
"color": "#F3F3F3",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "10.0pt",
"font-style": "normal",
"font-weight": "700"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3": {
"attributes-ie": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#F3F3F3",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#F3F3F3",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#F3F3F3",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#F3F3F3",
"border-radius": "1px 1px 1px 1px",
"-pie-background": "#434343",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "is_column_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "is_title_selected"),
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3": {
"attributes": {
"background-color": "#EFEFEF",
"background-image": "none",
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#434343",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#434343",
"border-radius": "1px 1px 0px 0px",
"font-size": "10.0pt",
"font-family": "'Arial',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3 span": {
"attributes": {
"color": "#333333",
"text-align": "center",
"text-decoration": "none",
"font-family": "'Arial',Arial",
"font-size": "10.0pt",
"font-style": "normal",
"font-weight": "700"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_3": {
"attributes-ie": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#434343",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#434343",
"border-radius": "1px 1px 0px 0px",
"-pie-background": "#EFEFEF",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_18")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_18" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": (data.variableTarget === "is_column_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_18": {
"attributes": {
"background-color": "#F3F3F3",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_18": {
"attributes-ie": {
"-pie-background": "#F3F3F3",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "is_column_selected"),
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_18": {
"attributes": {
"background-color": "#434343",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_18": {
"attributes-ie": {
"-pie-background": "#434343",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_26")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_26" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_27")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_27" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_28")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_28" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_29")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_29" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-table_op_panel")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "is_title_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_title_selected"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-table_op_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "is_title_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-empty_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_background_sel_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_background_sel_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_23")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_23": {
"attributes": {
"background-color": "#F3F3F3",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_23": {
"attributes-ie": {
"-pie-background": "#F3F3F3",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_21")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_21": {
"attributes": {
"font-size": "14.0pt",
"font-family": "'OpenSans-Bold',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_21 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "left"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_21 span": {
"attributes": {
"color": "#F3F3F3",
"text-align": "left",
"text-decoration": "none",
"font-family": "'OpenSans-Bold',Arial",
"font-size": "14.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_22")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_22": {
"attributes": {
"font-size": "12.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_22 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "left"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_22 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "left",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "12.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op1_hotspot_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-anon_op1_hotspot_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op3_hotspot_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-anon_op3_hotspot_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op1_hotspot_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-mask_op1_hotspot_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op2_hotspot_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-mask_op2_hotspot_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Radio_button_8")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Radio_button_8" ],
"value": "true"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimEnable",
"parameter": {
"target": [ "#s-Radio_button_8" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Line_14")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimPause",
"parameter": {
"pause": 100
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_14": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_14": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_14": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op3_hotspot_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-mask_op3_hotspot_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_sel_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_sel_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-col_anon_notification_1")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "cars_table_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "cars_table_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-col_anon_notification_1" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-col_op_panel")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "is_title_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_title_selected"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-table_op_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "is_title_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-empty_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": (data.variableTarget === "is_column_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_column_selected"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-col_op_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "is_column_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "is_title_selected"
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-empty_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_background_sel")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_background_sel" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_6")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_6": {
"attributes": {
"background-color": "#F3F3F3",
"background-image": "none"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Rectangle_6": {
"attributes-ie": {
"-pie-background": "#F3F3F3",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_10")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_10": {
"attributes": {
"font-size": "14.0pt",
"font-family": "'OpenSans-Bold',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_10 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "left"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_10 span": {
"attributes": {
"color": "#F3F3F3",
"text-align": "left",
"text-decoration": "none",
"font-family": "'OpenSans-Bold',Arial",
"font-size": "14.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_12")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_12": {
"attributes": {
"font-size": "12.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_12 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "left"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Text_12 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "left",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "12.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op1_hotspot")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-anon_op1_hotspot" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op3_hotspot")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-anon_op3_hotspot" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op1_hotspot")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-mask_op1_hotspot" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op2_hotspot")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-mask_op2_hotspot" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Radio_button_2")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Radio_button_2" ],
"value": "true"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimEnable",
"parameter": {
"target": [ "#s-Radio_button_2" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Line_6")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimPause",
"parameter": {
"pause": 100
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_6": {
"attributes": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_6": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-908bc018-bee5-45de-8a4f-845a2b307d57 #s-Line_6": {
"attributes-ie": {
"border-top-width": "6px",
"border-top-style": "solid",
"border-top-color": "#434343",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-mask_op3_hotspot")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-mask_op3_hotspot" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-anon_op2_sel")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anon_op2_sel" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-col_anon_notification")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-col_anon_notification" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_10")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "drive_col_anonymized") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "drive_col_anonymized"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_10" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Panel_4")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "data_preview_enabled") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "data_preview_enabled"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Dynamic_Panel_1" ]
},
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "data_preview_enabled"),
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_1" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-table_op_panel" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Panel_13")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-anonymizing_panel" ],
"effect": {
"type": "fade",
"easing": "linear",
"duration": 100
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_5")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
},
"actions": [
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_5" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "50"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 1500
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_5" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "-100"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 3000
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_5" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "100"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 3000
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_5" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "-100"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 3000
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimMove",
"parameter": {
"target": [ "#s-Image_5" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "100"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 2900
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_41")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"100" ]
},
"actions": [
{
"action": "jimPause",
"parameter": {
"pause": 1000
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimNavigation",
"parameter": {
"target": "screens/1a88b7e7-1f05-465e-a350-0751f24b3532",
"transition": "fade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Panel_14")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
},
"actions": [
{
"action": "jimPause",
"parameter": {
"pause": 100
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "anonymizing" ],
"value": {
"action": "jimPlus",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-progress_fore")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
},
"actions": [
{
"action": "jimResize",
"parameter": {
"target": [ "#s-progress_fore" ],
"width": {
"type": "exprvalue",
"value": "1340"
},
"height": {
"type": "noresize"
},
"effect": {
"type": "none",
"easing": "linear",
"duration": 13400
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-percent_anoning_text")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-percent_anoning_text" ],
"value": {
"action": "jimConcat",
"parameter": [ {
"action": "jimMin",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"100" ]
},"%" ]
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": (data.variableTarget === "anonymizing") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "anonymizing"
},"1" ]
},
"actions": [
{
"action": "jimMove",
"parameter": {
"target": [ "#s-percent_anoning_text" ],
"top": {
"type": "nomove"
},
"left": {
"type": "movebyoffset",
"value": "1340"
},
"containment": false,
"effect": {
"type": "none",
"easing": "linear",
"duration": 13400
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
});<file_sep>/resources/lookup-1518646228006.js
(function(window, undefined) {
var dictionary = {
"908bc018-bee5-45de-8a4f-845a2b307d57": "Anonymize",
"d12245cc-1680-458d-89dd-4f0d7fb22724": "Import",
"d9ca8466-7e3b-487b-ae33-bfaada00a071": "Metrics",
"3f01b028-1fc4-4900-aa2d-745006f7b56d": "Export",
"1a88b7e7-1f05-465e-a350-0751f24b3532": "Anonymized",
"f39803f7-df02-4169-93eb-7547fb8c961a": "default_template",
"e73b655d-d3ec-4dcc-a55c-6e0293422bde": "960 grid - 16 columns",
"ef07b413-721c-418e-81b1-33a7ed533245": "960 grid - 12 columns",
"f894517a-70e0-41df-9cec-b257ca85088c": "test_template",
"a5fc2ec3-eea7-4702-950b-351b09bf10c9": "testing",
"bb8abf58-f55e-472d-af05-a7d1bb0cc014": "default"
};
var uriRE = /^(\/#)?(screens|templates|masters|scenarios)\/(.*)(\.html)?/;
window.lookUpURL = function(fragment) {
var matches = uriRE.exec(fragment || "") || [],
folder = matches[2] || "",
canvas = matches[3] || "",
name, url;
if(dictionary.hasOwnProperty(canvas)) { /* search by name */
url = folder + "/" + canvas;
}
return url;
};
window.lookUpName = function(fragment) {
var matches = uriRE.exec(fragment || "") || [],
folder = matches[2] || "",
canvas = matches[3] || "",
name, canvasName;
if(dictionary.hasOwnProperty(canvas)) { /* search by name */
canvasName = dictionary[canvas];
}
return canvasName;
};
})(window);<file_sep>/resources/simulationdata-1518646228006.js
function initData() {
jimData.variables["tabled_linked"] = "0";
jimData.variables["anonymize_selected"] = "0";
jimData.variables["cars_table_anonymized"] = "0";
jimData.variables["exporting"] = "0";
jimData.variables["import_selected"] = "1";
jimData.variables["anim_direction"] = "1";
jimData.variables["anonymizing"] = "0";
jimData.variables["drive_col_anonymized"] = "0";
jimData.variables["export_selected"] = "0";
jimData.variables["is_title_selected"] = "0";
jimData.variables["struct_load_loop"] = "0";
jimData.variables["which_export_selected"] = "-1";
jimData.variables["is_column_selected"] = "0";
jimData.variables["var_db_hostname"] = "";
jimData.variables["data_preview_enabled"] = "0";
jimData.isInitialized = true;
}<file_sep>/resources/screens/3f01b028-1fc4-4900-aa2d-745006f7b56d-1518646228006.js
jQuery("#simulation")
.on("click", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .click", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Button_1")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "exporting" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_204")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_37" ],
"value": "C:\\docs\\custom_destination.txt"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "-1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_11")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_37" ],
"value": "C:\\docs\\custom_destination.txt"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "-1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_23")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimNotEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
},"db.mycompany.com:3636" ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_5" ],
"value": {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-after_setting_db" ],
"transition": "fade"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "-1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
},"db.mycompany.com:3636" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Dynamic_Panel_4" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_3")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Dynamic_Panel_4" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Button_2")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
},"db.mycompany.com:3636" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_173" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_5" ],
"value": {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
}
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-after_setting_db" ],
"transition": "fade"
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "-1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_11")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimNotEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"1" ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "1"
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "-1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_10")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimNotEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"0" ]
},
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "0"
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimSetValue",
"parameter": {
"variable": [ "which_export_selected" ],
"value": "-1"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_12")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d12245cc-1680-458d-89dd-4f0d7fb22724",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_13")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/908bc018-bee5-45de-8a4f-845a2b307d57",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_14")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/3f01b028-1fc4-4900-aa2d-745006f7b56d",
"transition": "slideandfade"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_15")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d9ca8466-7e3b-487b-ae33-bfaada00a071"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_12")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimNavigation",
"parameter": {
"target": "screens/d12245cc-1680-458d-89dd-4f0d7fb22724"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("change", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .change", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Input_5")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimGreater",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-db_hostname_label" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_23": {
"attributes": {
"box-shadow": "0px 10px 20px 2px #404040",
"text-shadow": "none",
"font-size": "24.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_23 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_23 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "24.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-db_hostname_label" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_23": {
"attributes": {
"box-shadow": "none",
"text-shadow": "none",
"font-size": "24.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_23 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_23 span": {
"attributes": {
"color": "#666666",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "24.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_5",
"property": "jimGetValue"
},"db.mycompany.com:3636" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Image_172" ],
"effect": {
"type": "shake",
"duration": 500
}
},
"exectype": "serial",
"delay": 0
}
]
},
{
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Image_172" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_6")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimGreater",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_6",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-username_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_6",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-username_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_7")) {
cases = [
{
"blocks": [
{
"condition": {
"action": "jimGreater",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_7",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-password_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": {
"action": "jimEquals",
"parameter": [ {
"action": "jimCount",
"parameter": [ {
"datatype": "property",
"target": "#s-Input_7",
"property": "jimGetValue"
} ]
},"0" ]
},
"actions": [
{
"action": "jimHide",
"parameter": {
"target": [ "#s-password_label" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("focusin", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .focusin", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Input_5")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Input_5": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "5px",
"border-bottom-style": "solid",
"border-bottom-color": "#434343",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_6")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Input_6": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "5px",
"border-bottom-style": "solid",
"border-bottom-color": "#434343",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_7")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Input_7": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "5px",
"border-bottom-style": "solid",
"border-bottom-color": "#434343",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("focusout", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .focusout", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-Input_5")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Input_5": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#666666",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_6")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Input_6": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#666666",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Input_7")) {
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Input_7": {
"attributes": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#666666",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
})
.on("mouseenter dragenter", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .mouseenter", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Image_204") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-drag_n_drop_csv_file_background": {
"attributes": {
"background-color": "#999999",
"background-image": "none",
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-drag_n_drop_csv_file_background": {
"attributes-ie": {
"border-top-width": "0px",
"border-top-style": "none",
"border-top-color": "#000000",
"border-right-width": "0px",
"border-right-style": "none",
"border-right-color": "#000000",
"border-bottom-width": "0px",
"border-bottom-style": "none",
"border-bottom-color": "#000000",
"border-left-width": "0px",
"border-left-style": "none",
"border-left-color": "#000000",
"border-radius": "0px 0px 0px 0px",
"-pie-background": "#999999",
"-pie-poll": "false"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Image_204 > svg": {
"attributes": {
"overlay": "#EFEFEF"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_19": {
"attributes": {
"font-size": "18.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_19 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_19 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "center",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "18.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Text_20" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimHide",
"parameter": {
"target": [ "#s-Button_11" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimSetValue",
"parameter": {
"target": [ "#s-Text_19" ],
"value": "Drop CSV File in here"
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Text_8") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_8": {
"attributes": {
"font-size": "14.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_8 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "center"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_8 span": {
"attributes": {
"color": "#434343",
"text-align": "center",
"text-decoration": "underline",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "14.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Hotspot_15") && jFirer.has(event.relatedTarget).length === 0) {
event.backupState = true;
event.target = jFirer;
cases = [
{
"blocks": [
{
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_2": {
"attributes": {
"font-size": "14.0pt",
"font-family": "'OpenSans-Regular',Arial"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_2 .valign": {
"attributes": {
"vertical-align": "middle",
"text-align": "left"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Text_2 span": {
"attributes": {
"color": "#EFEFEF",
"text-align": "left",
"text-decoration": "none",
"font-family": "'OpenSans-Regular',Arial",
"font-size": "14.0pt"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Image_21 > svg": {
"attributes": {
"overlay": "#EFEFEF"
}
}
} ],
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Rectangle_40" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
jEvent.launchCases(cases);
}
})
.on("mouseleave dragleave", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .mouseleave", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getDirectEventFirer(this);
if(jFirer.is("#s-Image_204")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Text_8")) {
jEvent.undoCases(jFirer);
} else if(jFirer.is("#s-Hotspot_15")) {
jEvent.undoCases(jFirer);
}
})
.on("variablechange.jim", ".s-3f01b028-1fc4-4900-aa2d-745006f7b56d .variablechange", function(event, data) {
var jEvent, jFirer, cases;
if(data === undefined) { data = event; }
jEvent = jimEvent(event);
jFirer = jEvent.getEventFirer();
if(jFirer.is("#s-export_ready")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "which_export_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"-1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-export_ready" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
},
{
"blocks": [
{
"condition": (data.variableTarget === "exporting") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "exporting"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-exporting" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-export_csv")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "which_export_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"0" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-export_csv" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Image_65")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "exporting"),
"actions": [
{
"action": "jimRotate",
"parameter": {
"target": [ "#s-Image_65" ],
"angle": {
"type": "rotateto",
"value": "1600"
},
"effect": {
"type": "none",
"easing": "linear",
"duration": 10000
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-export_mysql")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "which_export_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-export_mysql" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_41")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "which_export_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"1" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_41": {
"attributes": {
"border-top-width": "3px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "3px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "3px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px",
"box-shadow": "0px 0px 10px 0px #000000",
"text-shadow": "none"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_41": {
"attributes-ie": {
"border-top-width": "3px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "3px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "3px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "which_export_selected"),
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_41": {
"attributes": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px",
"box-shadow": "none",
"text-shadow": "none"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_41": {
"attributes-ie": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Rectangle_32")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "which_export_selected") && {
"action": "jimEquals",
"parameter": [ {
"datatype": "variable",
"element": "which_export_selected"
},"0" ]
},
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_32": {
"attributes": {
"border-top-width": "3px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "3px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "3px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px",
"box-shadow": "0px 0px 10px 0px #000000",
"text-shadow": "none"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_32": {
"attributes-ie": {
"border-top-width": "3px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "3px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "3px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "3px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
},
{
"condition": (data.variableTarget === "which_export_selected"),
"actions": [
{
"action": "jimChangeStyle",
"parameter": [ {
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_32": {
"attributes": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px",
"box-shadow": "none",
"text-shadow": "none"
}
}
},{
"#s-3f01b028-1fc4-4900-aa2d-745006f7b56d #s-Rectangle_32": {
"attributes-ie": {
"border-top-width": "1px",
"border-top-style": "solid",
"border-top-color": "#CCCCCC",
"border-right-width": "1px",
"border-right-style": "solid",
"border-right-color": "#CCCCCC",
"border-bottom-width": "1px",
"border-bottom-style": "solid",
"border-bottom-color": "#CCCCCC",
"border-left-width": "1px",
"border-left-style": "solid",
"border-left-color": "#CCCCCC",
"border-radius": "0px 0px 0px 0px"
}
}
} ],
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-progbar_csv_inner")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "exporting") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "exporting"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-progbar_csv" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimResize",
"parameter": {
"target": [ "#s-progbar_csv_inner" ],
"width": {
"type": "exprvalue",
"value": "467"
},
"height": {
"type": "noresize"
},
"effect": {
"type": "none",
"easing": "linear",
"duration": 7000
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-progbar_sql_inner")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "exporting") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "exporting"
},"1" ]
},
"actions": [
{
"action": "jimShow",
"parameter": {
"target": [ "#s-progbar_sql" ]
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimResize",
"parameter": {
"target": [ "#s-progbar_sql_inner" ],
"width": {
"type": "exprvalue",
"value": "467"
},
"height": {
"type": "noresize"
},
"effect": {
"type": "none",
"easing": "easeOutSine",
"duration": 10000
}
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Panel_3")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "exporting") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "exporting"
},"1" ]
},
"actions": [
{
"action": "jimPause",
"parameter": {
"pause": 7000
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Dynamic_Panel_5" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
} else if(jFirer.is("#s-Panel_4")) {
cases = [
{
"blocks": [
{
"condition": (data.variableTarget === "exporting") && {
"action": "jimGreaterOrEquals",
"parameter": [ {
"datatype": "variable",
"element": "exporting"
},"1" ]
},
"actions": [
{
"action": "jimPause",
"parameter": {
"pause": 10100
},
"exectype": "serial",
"delay": 0
},
{
"action": "jimShow",
"parameter": {
"target": [ "#s-Dynamic_Panel_6" ]
},
"exectype": "serial",
"delay": 0
}
]
}
],
"exectype": "serial",
"delay": 0
}
];
event.data = data;
jEvent.launchCases(cases);
}
}); | 0ce4915069128bf6baa4bbe8232edc7143046ec4 | [
"JavaScript"
] | 5 | JavaScript | pligor/anonymizer | 54c7f1ce871e0633efaf4f368a30d13ac819ac30 | 2cefed53c61eb38fec1daca70a308a9b8d1bd9ac |
refs/heads/master | <repo_name>mayfield/pendulum<file_sep>/build-wheels.sh
#!/bin/bash
PYTHON_VERSIONS="cp27-cp27m cp35-cp35m"
echo "Compile wheels"
for PYTHON in ${PYTHON_VERSIONS}; do
/opt/python/${PYTHON}/bin/pip install -r /io/wheels-requirements.txt
/opt/python/${PYTHON}/bin/pip wheel /io/ -w /io/wheelhouse/
done
echo "Bundle external shared libraries into the wheels"
for whl in /io/wheelhouse/*.whl; do
auditwheel repair $whl -w /io/wheelhouse/
done
echo "Install packages and test"
for PYTHON in ${PYTHON_VERSIONS}; do
/opt/python/${PYTHON}/bin/pip install pendulum --no-index -f /io/wheelhouse
find ./io/tests | grep -E "(__pycache__|\.pyc$)" | xargs rm -rf
/opt/python/${PYTHON}/bin/py.test /io/tests
find ./io/tests | grep -E "(__pycache__|\.pyc$)" | xargs rm -rf
done
| bb613b9eb6f5279b25908515d1e17d4dff68186b | [
"Shell"
] | 1 | Shell | mayfield/pendulum | bd7e9531bda35c45ddf794138c9967d9454209d4 | eb0b9c66f89a5d164446e728b8f8bc8e8d7f47d9 |
refs/heads/master | <repo_name>zmabunda/swingy<file_sep>/Swingy/src/main/java/com/swingy/model/player/Character.java
package com.swingy.model.player;
import com.swingy.model.artifact.Defense;
import com.swingy.model.artifact.Weapons;
public class Character {
public int hp;
public int level;
public int exp;
public Hero name;
public Weapons attack;
public Defense defense;
public HeroClass heroClass;
}
<file_sep>/Swingy/src/main/java/com/swingy/view/InterfaceGui.java
package com.swingy.view;
import com.swingy.controller.aid.AppSwingy;
public interface InterfaceGui {
public void theGui(AppSwingy.GuiChoice cntrl);
}
<file_sep>/Swingy/src/main/java/com/swingy/view/Gui.java
package com.swingy.view;
import com.swingy.controller.aid.AppSwingy;
import com.swingy.model.player.HeroClass;
import javax.swing.*;
import java.awt.*;
public class Gui implements InterfaceGui{
JFrame window;
public JPanel titlePanel;
public JPanel startButton;
public JLabel titleLabel, createHeroLable, selectHeroLable, errorMsgLable,errorMsgLable1, heroStatsLable;
JButton pressStart;
Font titleFont = new Font("Times new Roman", Font.ITALIC, 45);
Font normalFont = new Font("Times new Roman", Font.PLAIN, 25);
public JPanel instructiontext;
public JPanel btnPanel;
public JLabel errLable;
public JPanel choicePanel, createHeroPanel, selectHeroPanel, errorMsg, heroStatsPanel ;
public JPanel artifactPanel, errorMsgPalnel1;
public JLabel hitPont;
public JLabel weapon;
public JLabel level;
public JLabel exp;
public JLabel heroClass1;
public JLabel name;
public JLabel defense1;
public JPanel errPanel;
JButton choice1, choice2, choice3, choice4;
JTextArea textArea;
public JTextField heroNameText = new JTextField();
public JRadioButton heroClassRadio;
public JButton submit, playGame;
public void theGui(AppSwingy.GuiChoice cntrl) {
HeroClass rBtn = new HeroClass();
//Window
window = new JFrame();
window.setSize(800, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null);
//TitlePanel
titlePanel = new JPanel();
titlePanel.setBounds(100, 100, 500, 100);
titlePanel.setBackground(Color.black);
//TitleLable
titleLabel = new JLabel("Welcome to Swingy");
titleLabel.setForeground(Color.white);
titleLabel.setFont(titleFont);
titlePanel.add(titleLabel);
//startButton
startButton = new JPanel();
startButton.setBounds(200, 400, 300, 100);
startButton.setBackground(Color.black);
//pressStart button
pressStart = new JButton("START");
pressStart.setForeground(Color.BLACK);
pressStart.setFont(normalFont);
pressStart.setFocusPainted(false);
startButton.add(pressStart);
pressStart.addActionListener(cntrl);
pressStart.setActionCommand("start");
///////////////////////////////
window.add(titlePanel);
window.add(startButton);
window.setVisible(true);
//create hero window.
instructiontext = new JPanel();
instructiontext.setBounds(200, 200, 700, 70);
instructiontext.setBackground(Color.black);
window.add(instructiontext);
textArea = new JTextArea("[Create or Select a hero !!]");
textArea.setBounds(100, 100, 600, 250);
textArea.setForeground(Color.WHITE);
textArea.setBackground(Color.black);
textArea.setFont(normalFont);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
instructiontext.add(textArea);
//choice button panel
choicePanel = new JPanel();
choicePanel.setBounds(250, 350, 300, 140);
choicePanel.setBackground(Color.black);
choicePanel.setLayout(new GridLayout(4, 1));
window.add(choicePanel);
///////////////////
choice1 = new JButton("create hero");
choice1.setBackground(Color.black);
choice1.setForeground(Color.black);
choice1.setFont(normalFont);
choice1.setFocusPainted(false);
choicePanel.add(choice1);
choice1.addActionListener(cntrl);
choice1.setActionCommand("c1");
choice2 = new JButton("Select Hero");
choice2.setBackground(Color.black);
choice2.setForeground(Color.black);
choice2.setFont(normalFont);
choice2.setFocusPainted(false);
choicePanel.add(choice2);
choice2.addActionListener(cntrl);
choice2.setActionCommand("c2");
choice3 = new JButton("Switch to console");
choice3.setBackground(Color.black);
choice3.setForeground(Color.BLACK);
choice3.setFont(normalFont);
choice3.setFocusPainted(false);
choicePanel.add(choice3);
choice3.addActionListener(cntrl);
choice3.setActionCommand("c3");
choice4 = new JButton("Quit Game");
choice4.setBackground(Color.black);
choice4.setForeground(Color.black);
choice4.setFont(normalFont);
choice4.setFocusPainted(false);
choicePanel.add(choice4);
choice4.addActionListener(cntrl);
choice4.setActionCommand("c4");
//////////////////////////////////////////////
artifactPanel = new JPanel();
artifactPanel.setBounds(100, 15, 700, 150);
artifactPanel.setBackground(Color.black);
artifactPanel.setLayout(new GridLayout(4, 4));
window.add(artifactPanel);
hitPont = new JLabel("hitPoints");
hitPont.setFont(normalFont);
hitPont.setForeground(Color.white);
artifactPanel.add(hitPont);
weapon = new JLabel("Weapon");
weapon.setFont(normalFont);
weapon.setForeground(Color.white);
artifactPanel.add(weapon);
level = new JLabel("level");
level.setFont(normalFont);
level.setForeground(Color.white);
artifactPanel.add(level);
exp = new JLabel("exp");
exp.setFont(normalFont);
exp.setForeground(Color.white);
artifactPanel.add(exp);
heroClass1 = new JLabel("HeroClass");
heroClass1.setFont(normalFont);
heroClass1.setForeground(Color.white);
artifactPanel.add(heroClass1);
name = new JLabel("name");
name.setFont(normalFont);
name.setForeground(Color.white);
artifactPanel.add(name);
defense1 = new JLabel("defense");
defense1.setFont(normalFont);
defense1.setForeground(Color.white);
artifactPanel.add(defense1);
///////////////////////////////////////////////////////
createHeroPanel = new JPanel();
createHeroPanel.setBounds(150, 100, 350, 200);
createHeroPanel.setBackground(Color.black);
createHeroPanel.setLayout(new GridLayout(4, 1));
window.add(createHeroPanel);
createHeroLable = new JLabel("Create a hero(input hero name)");
createHeroLable.setFont(normalFont);
createHeroLable.setForeground(Color.white);
createHeroPanel.add(createHeroLable);
heroNameText.setFont(normalFont);
createHeroPanel.add(heroNameText);
heroClassRadio = new JRadioButton("Class Name: "+ rBtn.classname);
heroClassRadio.setFont(normalFont);
heroClassRadio.setForeground(Color.white);
heroClassRadio.addActionListener(cntrl);
heroClassRadio.setActionCommand("rBtn");
createHeroPanel.add(heroClassRadio);
submit = new JButton("Submit ");
submit.setSize(50,50);
submit.setFont(normalFont);
submit.setForeground(Color.black);
submit.addActionListener(cntrl);
submit.setActionCommand("play");
createHeroPanel.add(submit);
//////////////////////////////////////////////
errorMsg = new JPanel();
errorMsg.setBounds(90, 15, 350, 200);
errorMsg.setBackground(Color.black);
errorMsg.setLayout(new GridLayout(4, 1));
window.add(errorMsg);
errorMsgLable = new JLabel("please select a hero type!!");
errorMsgLable.setFont(normalFont);
errorMsgLable.setForeground(Color.red);
errorMsg.add(errorMsgLable);
selectHeroPanel = new JPanel();
selectHeroPanel.setBounds(90, 15, 350, 200);
selectHeroPanel.setBackground(Color.black);
selectHeroPanel.setLayout(new GridLayout(4, 1));
window.add(selectHeroPanel);
selectHeroLable = new JLabel(heroNameText.getText());
selectHeroLable.setFont(normalFont);
selectHeroLable.setForeground(Color.red);
selectHeroPanel.add(selectHeroLable);
heroStatsPanel = new JPanel();
heroStatsPanel.setBounds(10, 250, 800, 100);
heroStatsPanel.setBackground(Color.black);
//heroStatsPanel.setLayout(new GridLayout(1, 1));
window.add(heroStatsPanel);
heroStatsLable = new JLabel("You've now created your hero follow the given instructions to play..");
heroStatsLable.setFont(normalFont);
heroStatsLable.setForeground(Color.yellow);
heroStatsLable.setLayout(new GridLayout(4, 2));
heroStatsPanel.add(heroStatsLable);
//lableBtn = new JLabel();
btnPanel = new JPanel();
btnPanel.setBounds(200, 400, 300, 100);
btnPanel.setBackground(Color.black);
window.add(btnPanel);
playGame = new JButton("Play");
playGame.setFont(normalFont);
//playGame.setBounds(10, 450, 800, 300);
playGame.setForeground(Color.black);
playGame.addActionListener(cntrl);
playGame.setActionCommand("Go");
btnPanel.add(playGame);
errPanel = new JPanel();
errPanel.setBounds(90, 35, 350, 200);
errPanel.setBackground(Color.black);
errPanel.setLayout(new GridLayout(4, 1));
window.add(errPanel);
errLable = new JLabel("You have to create a hero first!!");
errLable.setFont(normalFont);
errLable.setForeground(Color.red);
errPanel.add(errLable);
}
}
<file_sep>/Swingy/src/main/java/com/swingy/Storage.java
package com.swingy;
import com.swingy.view.Gui;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Storage extends Gui {
public void dataBase(String name) throws IOException {
File outFile = new File("file.txt");
FileOutputStream outFileStream = new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
outStream.println(name);
outStream.close();
}
}
<file_sep>/Swingy/src/main/java/com/swingy/controller/aid/HeroControl.java
package com.swingy.controller.aid;
import javax.swing.*;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class HeroControl extends JComponent {
public int x;
public int y;
public int dimensions;
HeroControl(int size){
this.dimensions = size;
this.x = 250;
this.y = 200;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.PINK);
g.drawRect(x, y,dimensions, dimensions);
g.fillRect(x, y,dimensions, dimensions);
g.setColor(Color.BLACK);
g.drawRect(15,20, 550,500);
g.setColor(Color.red);
g.drawOval(500,400,50,60);
g.fillOval(500,400,50,60);
g.setColor(Color.red);
g.drawOval(20,40,50,60);
g.fillOval(20,40,50,60);
g.setColor(Color.red);
g.drawOval(20,40,50,60);
g.fillOval(20,420,50,60);
g.setColor(Color.red);
g.drawOval(20,40,50,60);
g.fillOval(400,20,50,60);
g.setColor(Color.red);
g.drawOval(40,200,50,60);
g.fillOval(40,200,50,60);
g.setColor(Color.red);
g.drawOval(500,200,50,60);
g.fillOval(500,200,50,60);
g.setColor(Color.black);
g.drawOval(300,400,50,60);
g.fillOval(300,400,50,60);
g.setColor(Color.black);
g.drawOval(250,40,50,60);
g.fillOval(250,40,50,60);
}
void moveRight(){
this.x += 15;
repaint();
}
void moveLeft(){
this.x -= 15;
repaint();
}
void moveDown(){
this.y += 15;
repaint();
}
void moveUp(){
this.y -= 15;
repaint();
}
}
| bc92c248528fa9d0684a95105287494545d2e8ba | [
"Java"
] | 5 | Java | zmabunda/swingy | 53dc8cefd43481e6d2e4a85ff18ec3128b01e883 | 17fc8273a86fe71aee018621a12ba302bec7b57c |
refs/heads/master | <file_sep>prnt ("new featur love");<file_sep>prnt ("console git start");<file_sep><?php
/* webserver AMPPS
* редактор кода phpStorm
*/
define ("CONSTANT", "12345");
$a = 10;
$b = 11.12;
$c = true;
$d = "1 lesson";
//1
echo $a;
echo $b;
echo $c;
echo $d;
echo CONSTANT;
echo "<br>";
//2
echo "$a";
echo "$b";
echo "$c";
echo "$d";
echo "CONSTANT";
echo "<br>";
//3
echo '$a';
echo '$b';
echo '$c';
echo '$d';
echo 'CONSTANT';
echo "<br>";
//4
$str1= "Славная осень! Здоровый, ядреный <br>";
$str2= "Воздух усталые силы бодрит;<br>";
$str3= "Лед неокрепший на речке студеной<br>";
$str4= "Словно как тающий сахар лежит.<br>";
$str5= "<u>Н. <NAME></u><br>";
echo $str1;
echo $str2;
echo $str3;
echo $str4;
echo $str5;
//5
echo $str1 . $str2 . $str3 . $str4 . $str5;
//6
$sum= $a+$d;
echo $sum. "<br>";
//7
echo "false xor false = ".(false xor false)."<br>";
echo "false xor true = ".(false xor true)."<br>";
echo "true xor false = ".(true xor false)."<br>";
echo "true xor true = ".(true xor true)."<br>";
//8
$x=10;
$y=15;
$x+= $y;
$y= $x-$y;
$x= $x-$y;
?>
| 4c7c38f12ca53822b8d4b6f0f7695f2d161edf73 | [
"PHP"
] | 3 | PHP | umbsse/git-test | 5417e969ddc2b021709ad4870acaf79704520576 | a39833d7e31dc47ad5607b8b127723fa260ca4c1 |
refs/heads/master | <file_sep># Reddit Comment Analysis
## Overview
The purpose of the project was to get experience handling large amount of data. The project invovled over 50 millions reddit comments. Technolgies and frameworks such as MongoDB, SQL, Amazon Web Services and Databricks were used in the analysis of the data. Machine learning tasks were also performed on the data. The comment text was used as in the input into the model, certain methods such as Feature Hashing were utilized in order to optimize the implementation. All machine learning was supervised learning and involved a mix or regression and classification problems.
The Dataset can be found here: https://www.reddit.com/r/datasets/comments/3bxlg7/i_have_every_publicly_available_reddit_comment/
## Background
Reddit is a massive online community wherein users can post content into content-specific sub-communities called ‘subreddits’ to be viewed by others within and without the subreddit. Users can ‘upvote’ or ‘downvote’ posts to shift their rankings on the website and in this way as a community dictate which posts are more easily seen by the wider community and which are not.
Users can also comment on and discuss posted content under a chosen pseudonym in each post’s ‘thread’ and comments can also be upvoted or downvoted as well as ‘gilded’ to show the community’s reaction to them. Reddit also uses other metrics to score comments such as ‘controversiality’ and ‘distinguished’.
A dataset containing all comments made on Reddit in January 2015 was released by a Reddit user, detailing for each comment; the sub-reddit it belongs to, the user who posted it, the number of upvotes and downvotes it received as well as other information as will be shown in the MongoDB section of this report.
## Objectives
Given this dataset, a lot can be learned about the nature of online communication and various data handling tools can be used to process the data. This project will focus on the use of databases, specifically the MongoDB noSQL query language, and word processing to come to an understanding of the dynamics of the Reddit online community and how the way people communicate online leads to different reactions from the community.
Specific tasks have been selected to implement various tools and are as follows:
Data Exploration:
* Set up a MongoDB database for the dataset
* Use Spark to extract information about the dataset
* Use SQL and Databricks to create visualizations
Machine Learning and Featurization Tasks:
* Compare Feature Hashing vs Bag of Words representation
* Determine if words are a good predictor of the score of the comment
* Determine if score is a good predictor of gilded comments
* Train a classifier to match comments to certain subreddits
Cluster Tasks:
* Create a multi node cluster on Databricks or Amazon Web Services (EMR or EC2) to run Spark tasks
* Perform computations and machine learning tasks on all the data efficiently
The full report can be found here: https://github.com/brydenfogelman/reddit-comment-analysis/blob/master/reddit-comment-analysis-report.pdf
<file_sep>#bzip2 -d reddit_database.dz2
N=17000000
f=open("reddit_database")
f2=open("new_database", "w+")
for i in range(N):
line=f.next().strip()
f2.write(line)
f.close()
f2.close()
<file_sep>import bz2
import json
import time
import boto.ec2
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.ml import Pipeline
from pyspark.ml.feature import * # CountVectorizer, Tokenizer, RegexTokenizer, HashingTF
from pyspark.ml.regression import * # RandomForestRegressor, LinearRegression, DecisionTreeRegressor
from pyspark.ml.evaluation import RegressionEvaluator
def timeit(method):
'''
Decorator to time functions.
'''
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r took %2.2f sec\n' % \
(method.__name__, te-ts)
return result
return timed
@timeit
def load_data(filename, test=True, mb=1):
'''
Returns either the a DataFrame containing all the tweets or a test DataFrame containing numTest comments.
@params:
test - boolean, if True return test DataFrame
mb - the number of megabytes to load from the data set
'''
# # load compressed file
# comments_file = bz2.BZ2File(filename, "r")
# # convert the megabytes to bytes
# size = mb * (1024 ** 2)
# # load a test dataset of size mb
# if test:
# # create RDD using string returned by reading the comments file
# # specify bytesize of file to read
# commentRDD = sc.parallelize(comments_file.readlines(size))
# # read RDD as json and convert to a DataFrame
# df = spark.read.json(commentRDD)
# # load full dataset
# else:
df = spark.read.json(filename)
# return a new DataFrame that doesn't contain deleted comments
return df.filter("body != '[deleted]'")
if __name__ == "__main__":
"""
Loading DF
"""
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
sc = spark.sparkContext
sc._jsc.hadoopConfiguration().set("fs.s3a.awsAccessKeyId", "<KEY>")
sc._jsc.hadoopConfiguration().set("fs.s3a.awsSecretAccessKey", "<KEY>")
# filename = 'RC_2015-01.bz2'
filename = 's3a://big-data-project-bryden-fogelman/RC_2015-01.bz2'
# load the comments into a DataFrame
commentDF = load_data(filename)
# commentDF = spark.read.json(filename)
# Display comments and information
print "Snippet of Comment DataFrame:"
commentDF.select('id', 'body', 'ups', 'downs', 'gilded', 'subreddit').show(5)
print "Column names of comment DataFrame:"
print commentDF.columns
print "\nThe total number of comments: %s (deleted comments removed)" % commentDF.count()
# sc.stop()
| e0b0b1d0c341b62b6fc191ff597656d9830ad37d | [
"Markdown",
"Python"
] | 3 | Markdown | brydenfogelman/reddit-comment-analysis | b056a5fb21fdd5659cacfd8ab217f9babc19fec2 | ba5812ea562e766ec1bed091a08a865032a39527 |
refs/heads/master | <repo_name>mramakrishnan-chwy/sys6018-competition-titanic<file_sep>/README.md
# Kaggle---Titanic-Machine-Learning-from-Disaster
Using data mining techniques to predict the probability of a person surviving from Titanic disaster
<file_sep>/Titanic_predictions_Data_Mining.R
######## TITANIC PREDICTION - KAGGLE ###########
rm(list = ls())
#Calling the required libraries for the operations
library(dplyr)
library(glmnet) # For cross validation and regularization (ridge and lasso) using glm models
## Setting the wroking directors
path = "C:\\Users\\arvra\\Documents\\UVa files\\Classes\\Fall_18\\Data Mining\\Kaggle competitions\\Titanic\\"
setwd(path)
#Reading the train and test data
train_data <- read.csv(dir()[grep("train",dir())])
test_data <- read.csv(dir()[grep("test",dir())])
############################# FEATURE ENGINEERING ########################################################3
#### Function to extract the first and last name with the intials
initial_fn <- function(train_data){
train_data$Last_name <- as.character(lapply(strsplit(as.character(train_data$Name), ", "),function(x)x[[1]]))
name_2 <- as.character(lapply(strsplit(as.character(train_data$Name), ", "),function(x)x[[2]]))
# strsplit for '.' (dot) can be used in two ways. 1) [.] 2) //.
train_data$Initial <- as.character(lapply(strsplit(name_2, "[.] "), function(x)x[[1]]))
train_data$First_name <- as.character(lapply(strsplit(name_2, "[.] "), function(x)x[[2]]))
return(train_data)
}
## Function to pre-preprocess - add Age and features like name title and others
data_pre_processing <- function(data_input)
{
train_data_1 <- data_input
#Creating features for the names
train_data_1 <- initial_fn(train_data_1)
# Creating extra features based on the title (initials)
# Changing the initial values to 4 consistent values
Mr.val <- c("Capt", "Col", "Don", "Jonkheer","Major","Rev", "Sir")
Mrs.val <- c("Lady", "Ms", "the Countess", "Mme", "Mlle","Dona")
train_data_1$title_form <- ""
train_data_1$title_form <- ifelse(train_data_1$Initial %in% Mr.val, "Mr",
ifelse(train_data_1$Initial %in% Mrs.val, "Mrs",
ifelse(train_data_1$Initial %in% "Dr" & train_data_1$Sex == "male", "Mr",
ifelse(train_data_1$Initial %in% "Dr" & train_data_1$Sex == "female", "Mrs",train_data_1$Initial))))
# Imputing the Fare column based on the analysis
# The value has been manually written as 13 since it is the average Fare for 3rd class passengers which is the only missing value
if(nrow(train_data_1[is.na(train_data_1$Fare),])>0)
{
train_data_1[is.na(train_data_1$Fare),]$Fare <- 13
}
####### Creating a sub-model - to predict the missing values of age instead of imputing the age values with the mean value
age.fit <- glm(Age ~ poly(SibSp,2)+poly(Parch,2)+poly(Fare,2)+title_form+poly(Pclass,2)+Sex,
data= train_data_1[!is.na(train_data_1$Age),])
###Imputing the age column with the model created for age
train_data_1[is.na(train_data_1$Age),]$Age <- round(predict(age.fit, train_data_1[is.na(train_data_1$Age),]))
#Setting the minimum age as 1
train_data_1$Age <- ifelse(train_data_1$Age < 0 , 1 , train_data_1$Age)
# CREATING ADDITIONAL FEATURES ########
#Feature to check if the individual is Single or Married
train_data_1$single_or_not <- as.factor(ifelse(train_data_1$SibSp == 0 & train_data_1$Parch == 0, 1, 0) )
#Feature to check if the individual is a Single Woman
train_data_1$single_lady <- as.factor( ifelse(as.numeric(train_data_1$single_or_not) & train_data_1$Sex == "female" , 1, 0) )
#Feature to check if the family size is greater than 3
train_data_1$family_big <- as.factor( ifelse(train_data_1$SibSp + train_data_1$Parch + 1 > 3, 1, 0) )
#Feature to get the size of the family
train_data_1$family_size <- as.numeric( train_data_1$SibSp + train_data_1$Parch + 1 )
#Feature to check if the individual is a mother
train_data_1$Mother <- as.factor(ifelse(train_data_1$Age > 18 & train_data_1$Parch == 1 & train_data_1$title == "Mrs", 1, 0))
#Feature to check if the individual is a minor
train_data_1$Minor <- as.factor(ifelse(train_data_1$Age <= 18 & train_data_1$Parch == 1, 1, 0))
#Removing the Name variable
train_data_1$Name <- NULL
#Creating squres of the following variables
train_data_1$Age_2 <- (train_data_1$Age)^2
train_data_1$SibSp_2 <- (train_data_1$SibSp)^2
train_data_1$Parch_2 <- (train_data_1$Parch)^2
train_data_1$Fare_2 <- (train_data_1$Fare)^2
#Removing unnecessary variabes
train_data_1$Name <- NULL
train_data_1$Ticket <- NULL
train_data_1$Last_name <- NULL
train_data_1$Cabin <- NULL
train_data_1$Initial <- NULL
train_data_1$First_name <- NULL
train_data_1$Pclass <- as.factor( train_data_1$Pclass )
return(train_data_1)
}
##Calling the pre-precessing function to impute Age and add various new features
train_data_1 <- data_pre_processing(train_data)
train_data_1$Survived <- as.factor( train_data_1$Survived ) #Converting Survived to factor data type
##Calling the pre-precessing function to impute Age and add various new features for TEST dataset
test_data_1 <- data_pre_processing(test_data)
test.fit.glm <- glm(Survived ~ . -PassengerId, data = train_data_1, family = binomial)
###Function to calculate the accuracy
acc_fn <- function(train_data1,fit){
pred = round(predict(fit, train_data1, type = "response"),0)
t_val = train_data1$Survived
true_val = as.numeric(summary(t_val == pred)[["TRUE"]])
#print(true_val)
#print(length(t_val))
acc = 100*(true_val / length(t_val))
return(acc)
}
acc_fn(train_data_1,test.fit.glm)
#[1] 83.95062
test_data_1$Survived <- 0
test_data_1$EmbarkedC <- ifelse(test_data_1$Embarked == "C",1,0)
train_data_2 <- train_data_1
test_data_2 <- test_data_1
##Creating one-hot vectors for the embarked locations S,Q and C
train_data_2$S <- as.factor(ifelse(train_data_2$Embarked == "S",1,0))
train_data_2$Q <- as.factor(ifelse(train_data_2$Embarked == "Q",1,0))
train_data_2$C <- as.factor(ifelse(train_data_2$Embarked == "C",1,0))
test_data_2$S <- as.factor(ifelse(test_data_2$Embarked == "S",1,0))
test_data_2$Q <- as.factor(ifelse(test_data_2$Embarked == "Q",1,0))
test_data_2$C <- as.factor(ifelse(test_data_2$Embarked == "C",1,0))
#### Function to normalize the values
scale_fn <- function(data_frame, columns)
{
for (i in columns){
print(i)
a <- diff(range(data_frame[[i]]))
b <- mean(data_frame[[i]])
value <- (data_frame[[i]] - b )/a
data_frame[[i]] <- value
}
return(data_frame)
}
### Calling the scaling function for training and test dataset
train_data_2 <- scale_fn(train_data_2,c("Age","Age_2","Fare","Fare_2"))
test_data_2 <- scale_fn(test_data_2,c("Age","Age_2","Fare","Fare_2"))
train_data_2$Embarked <- NULL
test_data_2$Embarked <- NULL
test_data_2$EmbarkedC <- NULL
combined_data_2 <- rbind(train_data_2,test_data_2)
combined_data_matrix = model.matrix(Survived ~ . - PassengerId, combined_data_2 ) [,-1]
#Creating the matrix for train and testdataset
x = combined_data_matrix[1:nrow(train_data_2),]
x1 = combined_data_matrix[(nrow(train_data_2)+1):nrow(combined_data_matrix),]
y = as.numeric(train_data_1$Survived)
### Running glm with cross validation
cv.ridge.fit2 = cv.glmnet(x,y, alpha = 1)
# Here you can use the CV set for prediction as it gives the best model with best value of 'lambda'
true_value <- table(round(predict(cv.ridge.fit2, x)) == y)[["TRUE"]]
acc = 100*(true_value / length(y))
print(acc)
y <- test_data$PassengerId
head(test_data)
submission <- data.frame(PassengerId = test_data$PassengerId,Survived = round(predict(cv.ridge.fit2, x1, type = "response")))
submission$X1 <- ifelse(submission$X1 == 2,1,0)
names(submission)[names(submission)=="X1"] <- "Survived"
write.csv(submission, "Titanic_sub_Data_Mining.csv",row.names = FALSE)
######################################################################################### | 484c7f9a6798196578287865375d172df25a37ed | [
"Markdown",
"R"
] | 2 | Markdown | mramakrishnan-chwy/sys6018-competition-titanic | a6c39a5f30854c74a79b5274c43bfa58344b3af7 | 062cc756d2edc97e8511591205283017b9deed9f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.