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 | <repo_name>ExxxxT/lab7<file_sep>/src/lab/StackR.java
package lab;
import java.util.Scanner;
import java.util.Stack;
public class StackR {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<Integer> firstHand = new Stack<>();
Stack<Integer> secondHand = new Stack<>();
for(int i = 0; i < 5; i++) {
firstHand.push(scanner.nextInt());
}
for(int i = 0; i < 5; i++) {
secondHand.push(scanner.nextInt());
}
int count = 0;
while (count < 106 && !firstHand.isEmpty() && !secondHand.isEmpty()) {
Integer val1 = firstHand.pop();
Integer val2 = secondHand.pop();
int comp = val1.compareTo(val2);
if (val1 == 9 && val2 == 0) {
comp = -1;
}
if (val2 == 9 && val1 == 0) {
comp = 1;
}
if (comp == 1) {
firstHand.add(0, val1);
firstHand.add(0, val2);
}
else if(comp == -1) {
secondHand.add(0, val2);
secondHand.add(0, val1);
}
printOut(firstHand);
printOut(secondHand);
System.out.println('\n');
count++;
}
if(count == 106)
System.out.println("botva");
else if(firstHand.isEmpty()) {
System.out.println("second " + count);
}
else {
System.out.println("first " + count);
}
}
private static void printOut(Stack<Integer> hand) {
String res = "[ ";
for(Object x: hand)
res += x.toString() + ", ";
res = res.substring(0, res.length() - 2);
System.out.println(res + " ]");
}
} | 26f6cc92e8b033c94149723c05b293fa31292073 | [
"Java"
] | 1 | Java | ExxxxT/lab7 | c749918d4b6de2b8de2500c0e24e61e903a4b657 | 3f0327f863f5e489455efd5db55bfce6ba00e38f |
refs/heads/master | <repo_name>juancarestre/servelesspythonwithlayers<file_sep>/app/f5/app.py
import sys, os
sys.path.append('./app/')
from shared.dorequest import doreq
from numpy import array
def lambda_handler(event, context):
# TODO implement
r = doreq(f'{os.environ["POKEMON_API_URL"]}blastoise')
print(r)<file_sep>/Dockerfile
FROM python:3-alpine3.8
# docker container run --rm -it serverlessbuilder sh -c "source .venv/bin/activate && serverless invoke local --function pikachu" | jq
ENV ALPINE_MIRROR "http://dl-cdn.alpinelinux.org/alpine"
RUN echo "${ALPINE_MIRROR}/edge/main" >> /etc/apk/repositories
RUN apk add --no-cache nodejs-current --repository="http://dl-cdn.alpinelinux.org/alpine/edge/community"
RUN node --version
RUN apk update && apk upgrade \
&& apk add bash curl make \
&& rm -rf /var/cache/apk/*
RUN apk add npm==7.15.0-r0
RUN npm install -g serverless
RUN pip install awscli
WORKDIR /tmp
COPY ./ /tmp
RUN python -m venv .venv
RUN source .venv/bin/activate && pip install --upgrade pip
RUN source .venv/bin/activate && pip install wheel
RUN aws configure set default.region us-east-1 && \
aws configure set aws_access_key_id 'DUMMY_ACCESS_KEY' && \
aws configure set aws_secret_access_key 'DUMMY_SECRET_KEY'
RUN source .venv/bin/activate && pip install -r app/shared_requeriments.txt
RUN rm -r app/python
RUN npm install --save
<file_sep>/app/f1/handler.py
import sys, os
sys.path.append('./app/')
from shared.dorequest import doreq
def lambda_handler(event, context):
# TODO implement
r = doreq(f'{os.environ["POKEMON_API_URL"]}ditto')
print(r)
return r
<file_sep>/app/shared/dorequest.py
import requests
def doreq(url):
r = requests.get(url)
return r.json()<file_sep>/app/f1/test_handler.py
from app.f1.handler import lambda_handler
import os
def test_handler():
os.environ['POKEMON_API_URL'] = 'https://pokeapi.co/api/v2/pokemon/'
assert lambda_handler(True, True) | 9a3b651fa6d38697de6047b4412966ddcb3e259e | [
"Python",
"Dockerfile"
] | 5 | Python | juancarestre/servelesspythonwithlayers | f77236cf025c53001352308bcdcaf0ef4084acbf | 80b30b5fbc4462bd59d80f989b237e60af6e2d9c |
refs/heads/master | <repo_name>langliang/wcpy<file_sep>/wordcount.py
# *-*coding:utf8*-*
import sys
import os
import re
import pygal # 使用pygal来进行数据可视化
from optparse import OptionParser as OP
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 构造OptionParser对象
usage = "usage: %prog [options] arg1 arg2..."
parser = OP(usage)
# 往OptionParser对象中添加Options
parser.add_option('-l', '--line',
dest='lines',
action='store_true',
default=False,
help='counts lines only'
)
parser.add_option('-c', '--chars',
dest='chars',
action='store_true',
default=False,
help='counts chars only'
)
parser.add_option('-w', '--words',
dest='words',
action='store_true',
default=False,
help='counts words only'
)
parser.add_option('-a', '--another',
dest='more',
action='store_true',
default=False,
help='use for counting the numbers of comment lines,empty lines and char line'
)
# 如果使用-g参数,会保存相关数据到SVG文件
parser.add_option('-g', '--graph',
dest='graph',
action='store_true',
default=False,
help='use for describing data by graph.svg'
)
# 调用optionparser的解析函数
(options, args) = parser.parse_args()
"""判断路径是否正确,是否目录,或者多个文件"""
def is_not_dir(files):
if not os.path.exists(files):
sys.stderr.write("%s No such file or directory\n" % files)
return 0
if os.path.isdir(files):
sys.stderr.write("%s Is a directory\n" % files)
return 1
return 2
# 显示行数,字符数,单词数
def show_data(ll, cc, ww, cl, sl, chl):
global sum_l
global sum_c
global sum_w
global sum_comment
global sum_space
global sum_char_line
sum_l += ll
sum_c += cc
sum_w += ww
sum_char_line += chl
sum_space += sl
sum_comment += cl
if not (options.words or options.lines or options.chars):
print(ll)
print(ww)
print(cc)
if options.words:
print(ww)
if options.lines:
print(ll)
if options.chars:
print(cc)
if options.more:
print("the number of comment lines is:", cl)
print("the number of empty lines is:", sl)
print("the number of char lines is:", chl)
if options.graph:
# 列表用以构造svg图
x_list_arg = ['lines number', 'words number', 'chars number', 'comment lines number', 'empty lines number',
'chars lines number']
y_list_arg = [ll, ww, cc, cl, sl, chl]
use_pygal(x_list_arg, y_list_arg, svg_name='word_count.svg')
# 可视化
def use_pygal(x_list, y_list, svg_name):
# 设置风格
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()
my_config.show_legend = False
# 坐标旋转25度
my_config.x_label_rotation = 25
my_config.title_font_size = 24
# x,y轴坐标大小
my_config.label_font_size = 16
# 主坐标大小
my_config.major_label_font_size = 18
my_config.show_y_guides = True
# 设置width 充分利用浏览器界面
my_config.width = 1000
# 使用pygal绘制直方图
chart = pygal.Bar(my_config, style=my_style)
chart.title = "source file's data of wordcount"
chart.x_labels = x_list
chart.add('', y_list)
# 保存svg图
chart.render_to_file(svg_name)
# 读取文件
def read_files(files):
file_list = []
for file in files:
judge = is_not_dir(file)
if judge == 2:
# use the function of with open to automatically open and close files
read_file(file)
elif judge == 1:
for item in os.listdir(file):
item_path = os.path.join(file, item)
file_list.append(item_path)
read_files(file_list)
else:
continue
if len(files) > 1: # 如果有多个文件,则输出总数
print('the total number is:')
show_data(sum_l, sum_c, sum_w, sum_comment, sum_space, sum_char_line)
# 读取单个文件
def read_file(file):
with open(file, 'r') as f:
l = 0
c = 0
w = 0
comment_lines = 0
space_lines = 0
char_lines = 0
for line in f.readlines():
l += 1
c += len(line.strip())
# 统计单词数
match_list = re.findall('[a-zA-Z]+', line.lower())
w += len(match_list)
# to judge if a line is a comment line
line = line.strip()
if line.startswith("#") or line.startswith(r'"""') or line.endswith("#") or line.endswith(r'"""'):
comment_lines += 1
elif not line:
space_lines += 1
else:
char_lines += 1
print('the current file is: %s' % f)
l -= 1
# 打印数据
show_data(l, c, w, comment_lines, space_lines, char_lines)
# 使用列表返回以便于测试
return list([l, comment_lines, space_lines, char_lines])
sum_comment = 0
sum_space = 0
sum_char_line = 0
sum_l = 0
sum_w = 0
sum_c = 0
def begins():
read_files(args)
begins()
<file_sep>/test_wc.py
# *-*coding:utf8*-*
import unittest
from wordcount import *
class TestWc(unittest.TestCase):
"""unittest for wc.py"""
def test_is_not_dir(self):
self.assertEqual(0, is_not_dir(r"/home/hd"))
self.assertEqual(1, is_not_dir(r"/home/"))
self.assertEqual(2, is_not_dir(r"/home/hduser/wc.py"))
def test_use_pygal(self):
use_pygal([1, 2, 3], [4, 5, 6], "test.svg")
self.assertEqual(2, is_not_dir("test.svg"))
def test_read_file(self):
self.assertEqual([11, 4, 2, 6], read_file("/home/hduser/fortest.py"))
if __name__ == '__main__':
unittest.main()
| 53eded33f178718731eccbf16a3efd4132dca97c | [
"Python"
] | 2 | Python | langliang/wcpy | 33e7b51bc1816c1035a7bc16755cb21b14a1de6d | 87b035c8b8ae8c2654a1ebc52c562fc70959a3c3 |
refs/heads/master | <repo_name>KrissDrawing/Pantry<file_sep>/src/components/modal/Modal.js
import React from "react";
import ProductForm from "components/Forms/ProductForm";
import styles from "./Modal.module.scss";
const Modal = ({ add }) => (
<div className={styles.wrapper}>
<ProductForm add />
</div>
);
export default Modal;
<file_sep>/src/components/Forms/ProductForm.js
import React from "react";
import AppContext from "context";
import Input from "components/input/Input";
import Button from "components/button/Button";
import Radio from "./FormRadio";
import firebase from "firebase";
import styles from "./ProductForm.module.scss";
import { v4 as uuidv4 } from "uuid";
const categories = {
uncattegorized: "uncattegorized",
beverage: "beverage",
alcohol: "alcohol",
};
class ProductForm extends React.Component {
state = {
name: "",
amount: "",
limit: "",
category: categories.uncattegorized,
uid: "",
};
handleInputChange = (e) => {
e.preventDefault();
this.setState({
[e.target.name]: e.target.value,
});
};
editedProductState = (items) => {
if (!this.props.add) {
const item = items.find((x) => x.id == this.props.match.params["id"]);
console.log(item);
this.setState({
name: item.name,
amount: item.amount,
limit: item.limit,
category: categories.uncattegorized,
uid: item.uid,
});
}
};
submitFirebase = (e) => {
e.preventDefault();
firebase
.firestore()
.collection("products")
.add(this.state)
.then(
this.setState({
name: "",
amount: "",
limit: "",
category: categories.uncattegorized,
})
);
};
editFirebase = (e, id) => {
e.preventDefault();
firebase
.firestore()
.collection("products")
.doc(id)
.set(this.state)
.then(
this.setState({
name: "",
amount: "",
limit: "",
category: categories.uncattegorized,
})
);
};
resetForm = () => {
this.setState({
name: "",
amount: "",
limit: "",
category: categories.uncattegorized,
});
};
setUid = () => {
this.setState({
uid: uuidv4(),
});
};
componentDidMount() {
if (!this.props.add) {
let value = this.context;
this.editedProductState(value.products);
}
}
render() {
const { category } = this.state;
const { add } = this.props;
return (
<AppContext.Consumer>
{(context) => (
<form
className={styles.wrapper}
autoComplete="off"
onSubmit={(e) => {
// (context.addProduct(e, this.state);
add
? this.submitFirebase(e)
: this.editFirebase(e, this.props.match.params["id"]);
}}
>
{/* <Radio
id={categories.beverage}
checked={category === categories.beverage}
changeFn={() => this.handleRadioButtonChange(categories.beverage)}
>
Article
</Radio> */}
<Input
onChange={this.handleInputChange}
value={this.state.name}
name="name"
label="Product name"
type="text"
></Input>
<div className={styles.amountLimit}>
<Input
onChange={this.handleInputChange}
value={this.state.amount}
name="amount"
label="Amount"
type="number"
min={0}
step={1}
></Input>
<Input
onChange={this.handleInputChange}
value={this.state.limit}
name="limit"
label="Limit"
type="number"
min={0}
step={1}
></Input>
</div>
{/* <Input
onChange={this.handleInputChange}
value={this.state.title}
label="Product name"
></Input> */}
<Button onClick={this.setUid} type="submit">
{add ? "Add Item" : "Edit Item"}
</Button>
</form>
)}
</AppContext.Consumer>
);
}
}
ProductForm.contextType = AppContext;
export default ProductForm;
<file_sep>/src/components/header/Navigation.js
import React from "react";
import { NavLink } from "react-router-dom";
import styles from "./Navigation.module.scss";
const Navigation = (props) => {
return (
<nav>
{console.log(props)}
<ul className={styles.wrapper}>
<li className={styles.navItem}>
<NavLink
exact
className={styles.navItemList}
activeClassName={styles.navItemListActive}
to="/"
>
Home
</NavLink>
</li>
<li className={styles.navItem}>
<NavLink
exact
className={styles.navItemList}
activeClassName={styles.navItemListActive}
to="/add"
>
Add
</NavLink>
</li>
<li className={styles.navItem}>
<NavLink
exact
className={styles.navItemList}
activeClassName={styles.navItemListActive}
to="/cart"
>
Cart
</NavLink>
</li>
</ul>
</nav>
);
};
export default Navigation;
<file_sep>/src/views/ShopCartView.js
import React from "react";
import CardList from "components/card/CardList";
const ShopCartView = ({ products }) => {
return (
<>
<CardList products={products} cart />
</>
);
};
export default ShopCartView;
<file_sep>/src/components/card/CardList.js
import React from "react";
import Card from "./Card";
import styles from "./CardList.module.scss";
const CardList = ({ products, cart }) => {
const filteredProducts = cart
? products.filter((item) => +item.amount < +item.limit)
: products;
return (
<>
{filteredProducts.length === 0 ? (
<h2 className={styles.empty}>nothing here</h2>
) : (
<ul className={styles.wrapper}>
{filteredProducts.map((product) => (
<Card key={product.uid} {...product} />
))}
</ul>
)}
</>
);
};
export default CardList;
<file_sep>/src/components/header/HeaderNavigation.js
import React from "react";
import { NavLink } from "react-router-dom";
import Navigation from "./Navigation";
import styles from "./HeaderNavigation.module.scss";
const HeaderNavigation = () => {
return (
// <ul>
// <li className={styles.navItem}>
<header className={styles.wrapper}>
<div></div>
<Navigation />
<NavLink
className={styles.navItemList}
activeClassName={styles.navItemListActive}
to="edit"
>
Settings
</NavLink>
</header>
// </li>
// </ul>
);
};
export default HeaderNavigation;
<file_sep>/src/firebase.js
// import firebase from "firebase";
// import "firebase/firestore";
import * as firebase from "firebase/app";
import "firebase/firestore";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "pantry-31aed.firebaseapp.com",
databaseURL: "https://pantry-31aed.firebaseio.com",
projectId: "pantry-31aed",
storageBucket: "pantry-31aed.appspot.com",
messagingSenderId: "1001179315869",
appId: "1:1001179315869:web:9c5ad5801d1349d4f79e74",
measurementId: "G-PGPQR5JWM5",
};
firebase.initializeApp(firebaseConfig);
export default firebase;
<file_sep>/src/views/EditView.js
import React from "react";
const EditView = () => {
return <h1>Widok edycji</h1>;
};
export default EditView;
| 4b3ec2421b5970795823c5b3fb5721cf63272939 | [
"JavaScript"
] | 8 | JavaScript | KrissDrawing/Pantry | 891b31c2e981d51d85130b2486a01acb4f09c1f9 | b298caa1dec0222322513e6644e9b63172cd76c9 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# ---------------------------------------------------------------------
# Print a CHANGES file in GitHub Flavored Markdown
#
# Sample call:
# ghchanges -m 3.2 -o GENI-NSF -r geni-portal > changes.md
#
# ---------------------------------------------------------------------
import argparse
import json
import re
import sys
import time
import urllib
import urllib2
from distutils.version import StrictVersion
class GitHubService(object):
base_url = 'https://api.github.com/repos'
def __init__(self):
pass
def get_next_link(self, response):
"""Extract the link to the next set of issues.
The GitHub API returns 30 issues at a time. The response
headers include a link to the next 'page' of issues. Extract
it and return it. Return None if no next link is present.
The link header is a comma-separated list of links:
'<https://api.github.com/...>; rel="next", <URL>; rel="last"'
"""
result = None
link_header = response.headers.getheader('link')
if link_header:
links = [l.strip() for l in link_header.split(',')]
p = re.compile('^<(.*)>; rel="(.*)"$')
for link in links:
m = p.match(link)
if m and m.group(2) == 'next':
result = m.group(1)
break
return result
class GitHubMilestoneService(GitHubService):
def __init__(self):
pass
def get(self, owner, repo, milestone, **kwargs):
"""Get all milestones matching parameters. Specify parameters
using arbitrary keyword arguments. For instance, state=all or
state=closed.
"""
url = '%s/%s/%s/milestones' % (self.base_url, owner, repo)
if kwargs:
query_string = urllib.urlencode(kwargs)
url = url + '?' + query_string
while url:
response = urllib2.urlopen(url)
url = self.get_next_link(response)
raw = response.read()
milestones = json.loads(raw)
found = None
for m in milestones:
title = m['title']
if title == milestone:
found = Milestone(owner, repo, m)
return found
def all(self, owner, repo, **kwargs):
"""Get all milestones matching parameters. Specify parameters
using arbitrary keyword arguments. For instance, state=all or
state=closed.
"""
url = '%s/%s/%s/milestones' % (self.base_url, owner, repo)
if kwargs:
query_string = urllib.urlencode(kwargs)
url = url + '?' + query_string
result = []
while url:
response = urllib2.urlopen(url)
url = self.get_next_link(response)
raw = response.read()
milestones = json.loads(raw)
result.extend([Milestone(owner, repo, m)
for m in milestones])
return result
class GitHubIssueService(GitHubService):
def __init__(self):
pass
def get(self, owner, repo, milestone, **kwargs):
"""Get all issues for the given milestone. Specify parameters
using arbitrary keyword arguments. For instance, state=all or
state=closed.
"""
url = '%s/%s/%s/issues' % (self.base_url, owner, repo)
kwargs['milestone'] = milestone.number
query_string = urllib.urlencode(kwargs)
url = url + '?' + query_string
result = []
while url:
response = urllib2.urlopen(url)
url = self.get_next_link(response)
raw = response.read()
issues = json.loads(raw)
result.extend([Issue(owner, repo, json_data)
for json_data in issues])
return result
class GitHubObject(object):
def __init__(self, owner, repo, json_data):
self.data = json_data
self.owner = owner
self.repo = repo
class Issue(GitHubObject):
@property
def title(self):
return self.data['title']
@property
def number(self):
return self.data['number']
@property
def html_url(self):
return self.data['html_url']
@property
def is_pull_request(self):
return 'pull_request' in self.data
def md_string(self):
prefix = ''
if self.is_pull_request:
prefix = 'PR '
format = '%s (%s[#%d](%s))'
return format % (self.title, prefix, self.number, self.html_url)
class Milestone(GitHubObject):
@property
def number(self):
return self.data['number']
@property
def title(self):
return self.data['title']
def issues(self):
ghis = GitHubIssueService()
return ghis.get(self.owner, self.repo, self, state='all')
def __cmp__(self, other):
if hasattr(self, 'version') and hasattr(other, 'version'):
return self.version.__cmp__(other.version)
else:
return self.title.__cmp__(other.title)
def print_header(hdr, level=1):
print '#' * level,
print hdr
def print_changes_1(milestone, all_issues):
# print header
# print issues
# print pull requests
issues = []
pull_requests = []
for i in all_issues:
if i.is_pull_request:
pull_requests.append(i)
else:
issues.append(i)
hdr = "Release %s" % (milestone.title)
print_header(hdr, 1)
print
print_header("Issues Closed", 2)
print
if issues:
for i in issues:
print "* %s" % (i.md_string())
else:
print "* None"
if pull_requests:
print
print_header("Pull Requests Merged", 2)
print
for p in pull_requests:
print "* %s" % (p.md_string())
def do_stuff(milestone, owner, repo):
# Find the milestone
ghms = GitHubMilestoneService()
m = ghms.get(owner, repo, milestone, state='all')
if not m:
print 'Milestone %s not found' % (milestone)
sys.exit(1)
print_changes_1(m, m.issues())
return
issues = m.issues()
# Print milestone header
print milestone
print '-' * len(milestone)
print
# Print bullets for each issue and pull request
for i in issues:
if i.is_pull_request:
continue
print ' * %s' % (i.md_string())
def parse_args(args):
parser = argparse.ArgumentParser(description='Generate changes file.')
parser.add_argument('-m', '--milestone', metavar='MILESTONE',
help='a milestone name')
parser.add_argument('-o', '--owner', metavar='OWNER',
help='GitHub repository owner')
parser.add_argument('-r', '--repository', metavar='REPO',
help='GitHub repository')
return parser.parse_args()
def sem_ver_filter(milestone):
try:
milestone.version = StrictVersion(milestone.title)
return True
except:
return False
def full_changes(args):
ghms = GitHubMilestoneService()
milestones = ghms.all(args.owner, args.repository, state='closed')
milestones = [m for m in milestones if sem_ver_filter(m)]
milestones = sorted(milestones)
milestones.reverse()
for m in milestones:
print_changes_1(m, m.issues())
print ""
time.sleep(300)
def main(argv=None):
if argv is None:
argv = sys.argv
args = parse_args(argv)
# Need to validate arguments or put good defaults in place
# Actually, since they are required, make them so in argparse
# by not making them "options".
if True:
do_stuff(args.milestone, args.owner, args.repository)
else:
full_changes(args)
if __name__ == "__main__":
sys.exit(main())
<file_sep># incubator
Miscellaneous works in progress
<file_sep>To run the alpha "playbook" `alpha.yml`:
```shell
ansible-playbook -i "localhost," -c local alpha.yml
```
<file_sep>#!/usr/bin/env python
# ----------------------------------------------------------------------
# Parse the GENI Portal map data and print a comma separated values
# (CSV) file containing unique entries. The output format is aggregate
# name, longitude, latitude. The resulting file can be loaded into
# Microsoft Excel.
# ----------------------------------------------------------------------
import urllib2
import json
MAP_DATA = 'https://portal.geni.net/common/map/current.json'
url = MAP_DATA
f = urllib2.urlopen(url)
all = f.read()
f.close()
jdat = json.loads(all)
feat = jdat['features']
rows = set()
for x in feat:
loc = x['geometry']['coordinates']
lon = loc[0]
lat = loc[1]
props = x['properties']
name = props['am']
rows.add("%s, %s, %s" % (name, lon, lat))
print("Name, Longitude, Latitude")
for r in rows:
print r
| 262b909b7e9b7e524859f2e4f81fbb8065bc902b | [
"Markdown",
"Python"
] | 4 | Python | tcmitchell/incubator | 8a89919246a789521b082e736b25fb3a486741a1 | 7018aff1d8b01fb12910f2aea7221a21de0bbe99 |
refs/heads/master | <repo_name>ericmhuntley/scrapers<file_sep>/rockefeller_2015.py
from bs4 import BeautifulSoup as bs
import requests
import csv
import re
grantee = []
location = []
amount = []
purpose = []
url = "https://www.rockefellerfoundation.org/2015-grantees/"
def get_grantees(url_in):
r = requests.get(url_in)
soup = bs(r.text, "html.parser")
for hr in soup.find_all("hr"):
grantee_p = hr.next_sibling.next_sibling
if grantee_p.get_text() == '\xa0':
grantee_p = grantee_p.next_sibling.next_sibling
location_p = grantee_p.next_sibling.next_sibling
amount_p = location_p.next_sibling.next_sibling
purpose_p = amount_p.next_sibling.next_sibling
grantee.append(grantee_p.get_text().replace("Grantee:","").replace("Organization:","").strip().replace("\u2013","-").replace("\u2019","\'"))
location.append(location_p.get_text().replace("Location:","").replace("<br/>","").strip().replace("\u2013","-").replace("\u2019","\'"))
amount.append(int(amount_p.get_text().replace("Amount:","").replace("$","").replace(",","").replace("<br/>","").strip().replace("\u2013","-").replace("\u2019","\'")))
purpose.append(purpose_p.get_text().replace("Purpose:","").replace("<br/>","").strip().replace("\u2013","-").replace("\u2019","\'").replace("\u201d","\"").replace("\u201c","\""))
return {"grantee": grantee,
"location": location,
"amount": amount,
"purpose": purpose
}
grantees = get_grantees(url)
data = []
data.append(grantee,location,amount,purpose)
print(data)
| a0d791bb43d9e688e45b28f0d50e46af2462f5f8 | [
"Python"
] | 1 | Python | ericmhuntley/scrapers | b320afbf05bbd4f7200ed77523d4fe4a4ebdf9b7 | 039825064da7b0ba7aa1820b8ab383d0eda65d8c |
refs/heads/master | <file_sep>import flask
from flask import jsonify, request
from dao.movie_dao import MovieDao
app = flask.Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return "<h1>My first REST API</h1>"
@app.route('/movies', methods=['GET'])
def get_all_movies():
return jsonify(MovieDao.select_all())
@app.route('/movies/<id>', methods=['GET'])
def get_movie_by_id(id):
return jsonify(MovieDao.select(id))
@app.route('/movies', methods=['POST'])
def insert_movie():
json = request.json
id = MovieDao.insert(json)
result = {"id": id}
return jsonify(result)
@app.route('/movies/<id>', methods=['PUT'])
def update_movie(id):
json = request.json
result = MovieDao.update(json, id)
return jsonify(result)
@app.route('/movies/<id>', methods=['DELETE'])
def delete_movie(id):
result = MovieDao.delete(id)
return jsonify(result)
if __name__ == '__main__':
app.config["DEBUG"] = True
app.run()
<file_sep>#súbor dao/db.py
import sys, os, psycopg2
from psycopg2 import pool
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
def get_db(key=None):
return getattr(get_db, 'pool').getconn(key)
def put_db(conn, key=None):
conn.commit()
getattr(get_db, 'pool').putconn(conn, key=key)
try:
setattr(get_db, 'pool', psycopg2.pool.ThreadedConnectionPool(1, 20, os.getenv("DB")))
print('Initialized db')
except psycopg2.OperationalError as e:
print(e)
sys.exit(0)<file_sep># súbor dao/movie_dao.py
from .db import get_db, put_db
from threading import Thread
from time import sleep
class MovieDao:
@staticmethod
def select_all():
db = get_db()
cursor = db.cursor()
cursor.execute("SELECT * FROM d_movie")
result = cursor.fetchall()
cursor.close()
put_db(db)
return result
@staticmethod
def select(id):
db = get_db()
cursor = db.cursor()
cursor.execute("SELECT * FROM d_movie WHERE id = %s", (id,))
result = cursor.fetchall()
cursor.close()
put_db(db)
return result
@staticmethod
def insert(json):
db = get_db()
cursor = db.cursor()
cursor.execute("INSERT INTO d_movie VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s) RETURNING id",
(json["name"], json["description"], json["duration"], json["release_date"], json["state"], json["price"], json["version"],))
result = cursor.fetchone()[0]
cursor.close()
put_db(db)
return result
@staticmethod
def update(json, id):
db = get_db()
cursor = db.cursor()
cursor.execute("UPDATE d_movie SET name = %s, description = %s, duration = %s, release_date = %s, state = %s, price = %s, version = %s WHERE id = %s RETURNING *",
(json["name"], json["description"], json["duration"], json["release_date"], json["state"], json["price"], json["version"], id,))
result = cursor.fetchone()
cursor.close()
put_db(db)
return result
@staticmethod
def delete(id):
db = get_db()
cursor = db.cursor()
cursor.execute("DELETE FROM d_movie WHERE id = %s RETURNING id", (id,))
result = cursor.fetchone()
cursor.close()
put_db(db)
return result
<file_sep># simple-flask-app
1. pip install -r dependencies.txt
2. python server.py
<file_sep>import unittest
from server import app
class TestExample(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
app.testing = True
self.app = app.test_client()
pass
def test_equal_numbers_ok(self):
self.assertEqual(2, 2)
def test_main_page(self):
response = self.app.get('/', follow_redirects=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, b"<h1>My first REST API</h1>")
if __name__ == '__main__':
unittest.main()
<file_sep>flask
psycopg2
python-dotenv
nose2 | 68693c3f86f6723c1aeda721ef353f67071d19b8 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | danecsvk/simple-flask-app | 8ea043f6fcc2e78f90c5db592f943e9536be0b59 | 6f14ce899cf86e9ccabc6c8d6538978280524569 |
refs/heads/master | <file_sep>package com.qsoa.admin.pojo;
public class AdminInfo {
private Integer id;
private String username;
private String password;
private Long phone;
private String createBy;
private Long createDate;
private String updateBy;
private Long updateDate;
private String salt;
public AdminInfo() {
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Long getCreateDate() {
return createDate;
}
public void setCreateDate(Long createDate) {
this.createDate = createDate;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Long getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Long updateDate) {
this.updateDate = updateDate;
}
}
<file_sep>package com.qsoa.system.util;
import java.util.Random;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RandomUtil {
/**
* 随机生成验证码
* @param digit 位数 至少是1位数
*/
private static Logger logger = LoggerFactory.getLogger(Random.class);
public static StringBuffer getVerificationCode(int digit){
if(digit <= 0){
logger.warn("未生成验证码的原因:输入位数小于等于0",digit);
return null;
}
StringBuffer verificationCode = new StringBuffer(digit);
String[][] _verificationCode = new String[digit][10];
for(int i=0;i<digit;i++){
int length = _verificationCode[i].length;
for(int j=0;j<length;j++){
_verificationCode[i][j] = String.valueOf((int)(1+Math.random()*9));
}
}
for(int i=0;i<digit;i++){
int suiji = (int)(1+Math.random()*9);
verificationCode.append(_verificationCode[i][suiji]);
}
return verificationCode;
}
/**
* 生成uuid
*
* @return
*/
public static String uuid(boolean is32bit) {
String result = UUID.randomUUID().toString();
if (is32bit) {
result = result.replaceAll("-", "");
}
return result;
}
/**
* 生成加密盐
*
* @return
*/
public static String makeSalt() {
String[] salts = { "qwertyuiopasdfghjklzxcvbnm", "QWERTYUIOPLKJHGFDSAZXCVBNM", "1234567890",
"~!@#$%^&*()_+{}|:?><.,;'][" };
int saltLen = 16;
char[] chrs = new char[saltLen];
// 从左边生成4位盐值
for (int i = 0; i < salts.length; i++) {
int index = (int) (Math.random() * salts.length);
chrs[i] = salts[i].charAt(index);
}
// 从右边生成补偿盐值
for (int i = salts.length; i < saltLen; i++) {
int arrInd = (int) (Math.random() * salts.length);
int saltInd = (int) (Math.random() * salts[arrInd].length());
chrs[i] = salts[arrInd].charAt(saltInd);
}
for (int i = 0; i < 1000; i++) {
int indx1 = (int) (Math.random() * saltLen);
int indx2 = (int) (Math.random() * saltLen);
if (indx1 == indx2) {
continue;
}
char temp = chrs[indx1];
chrs[indx1] = chrs[indx2];
chrs[indx2] = temp;
}
return new String(chrs);
}
public static void main(String[] args) {
System.out.println(getVerificationCode(4));
}
}
<file_sep>package com.qsoa.system.response;
import java.util.Map;
public class Response {
private static Response response;
private int status;
private int code;
private String message;
private Map<String, Object> data;
public Response() {
// TODO Auto-generated constructor stub
}
public static Response getResponse() {
if (response == null) {
response = new Response();
}
return response;
}
public static Response getResponse(int status,int code,String message,Map<String, Object> data) {
Response response = new Response();
response.status = status;
response.code = code;
response.message = message;
response.data = data;
return response;
}
public static Response success(int status,int code) {
return getResponse(status,code, "成功", null);
}
public static Response success(Map<String, Object> data) {
return getResponse(200,200,"成功",data);
}
public static Response success(int status,int code,String message) {
return getResponse(status,code,message,null);
}
public static Response success(String message,Map<String, Object> data) {
return getResponse(200,200, message, data);
}
public static Response error() {
return getResponse(500,500, "失败", null);
}
public static Response error(int status,int code,String message) {
return getResponse(status,code, message, null);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
public static void setResponse(Response response) {
Response.response = response;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qsoa</groupId>
<artifactId>qsoa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>qsoa</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring boot 核心启动器 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
<!-- spring boot 配置处理器 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
<!-- spring mvc -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
<!--MySQL连接 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!--mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--spring整合mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--alibaba json格式转换和数据源配置 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.59</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!-- 日志管理 -->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--访问第三方接口jar -->
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!--添加redis支持 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>
<file_sep>#Tue Sep 03 17:08:45 CST 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.9.0.v20180906-0745
<file_sep>/*
Navicat MySQL Data Transfer
Source Server : 本地连接
Source Server Version : 50721
Source Host : localhost:3306
Source Database : qsoa
Target Server Type : MYSQL
Target Server Version : 50721
File Encoding : 65001
Date: 2019-09-01 09:50:27
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for admin_info
-- ----------------------------
DROP TABLE IF EXISTS `admin_info`;
CREATE TABLE `admin_info` (
`id` bigint(10) NOT NULL,
`username` varchar(50) NOT NULL COMMENT '姓名',
`password` varchar(50) NOT NULL COMMENT '密码',
`phone` bigint(50) NOT NULL,
`create_by` varchar(10) NOT NULL,
`create_date` bigint(15) NOT NULL,
`update_by` varchar(10) NOT NULL,
`update_date` bigint(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<file_sep>package com.qsoa.admin.servier;
import com.qsoa.admin.pojo.AdminInfo;
public interface AdminService {
int insert(AdminInfo admininfo);
boolean checkInfo(String username,String password);
boolean setPassword(String password,Integer id);
AdminInfo getAdminInfoByUsernameAndPassword(String username,String password);
}
| 7b1c58189fe0bf87b6f07458a81d68986a40e15f | [
"Java",
"Maven POM",
"SQL",
"INI"
] | 7 | Java | Theshy439/houduan | 6a2309faf1cd58f6f3eb4d382811937e32968d08 | 45007d3465cef5c889417fde13044513ea05c462 |
refs/heads/master | <repo_name>SU-I-KA/Dynamic-Slider-ReactJS<file_sep>/src/App.js
import React, {useState, useEffect} from 'react';
import './App.css';
import {FaQuoteRight} from 'react-icons/fa';
import {FiChevronLeft, FiChevronRight} from 'react-icons/fi';
import data from './data';
function App() {
const [people, setPeople] = useState(data);
const [index, setIndex] = useState(0);
useEffect(()=>{
const lastPerson = people.length - 1;
if(index < 0){
setIndex(lastPerson);
}
if(index > lastPerson){
setIndex(0);
}
},[index, people])
useEffect(()=>{
let slide = setInterval(()=>{setIndex(index + 1);}, 3000);
return ()=>clearInterval(slide);
},[index])
return (
<div className='container'>
<div className='title'>
<h1><span>/</span>reviews</h1>
</div>
<div className='slider-container'>
{
people.map((person, personIndex)=>{
const {id, image, name, title, quote} = person;
let position = 'next-slide';
if(index === personIndex){
position='active-slide';
}
if((personIndex === index - 1) || (index === 0 && personIndex === people.length - 1)){
position='last-slide';
}
return(
<div className={`slider-body ${position}`} key={id}>
<img className='image' src={image} alt={name} />
<div className='name'>{name}</div>
<div className='job'>{title}</div>
<div className='text'>{quote}</div>
<FaQuoteRight className='quote' />
</div>
)
})
}
<button className='prev-btn' onClick={()=>setIndex(index-1)}>
<FiChevronLeft />
</button>
<button className='next-btn' onClick={()=>setIndex(index+1)}>
<FiChevronRight />
</button>
</div>
</div>
);
}
export default App;
| 682f8d56f9e1ce81b91a1a8d72d663819071b038 | [
"JavaScript"
] | 1 | JavaScript | SU-I-KA/Dynamic-Slider-ReactJS | 04f40a3f0d3b37a5c49e468daadd5e3919df72e7 | 0a386bb2ee4db00e0ed588b5eb70fab5cd711bc4 |
refs/heads/master | <repo_name>whoisbma/primus-test<file_sep>/server/websocket.js
'use strict';
const Primus = require('primus');
const http = require('http');
const transformers = {
WEBSOCKETS: 'websockets',
ENGINEIO: 'engine.io',
SOCKJS: 'sockjs'
};
class WebsocketServer {
constructor(app, port) {
this.onConnection = this.onConnection.bind(this);
this.onDisconnection = this.onDisconnection.bind(this);
const server = http.createServer(app);
this.primus = new Primus(server, {
transformer: transformers.WEBSOCKETS,
pathname: '/',
pingInterval: false
});
this.primus.on('connection', this.onConnection);
this.primus.on('disconnection', this.onDisconnection);
this.startServer(app, server, port);
}
startServer(app, server, port) {
server.listen(port, function() {
console.log("websocket server listening on port " + port);
});
if (process.env.NODE_ENV === 'development') {
app.get('/primus.js', (req, res) => {
res.send(this.primus.library());
});
}
if (process.env.NODE_ENV === 'production') {
this.primus.save(__dirname + '/../client/primus.js');
}
}
onConnection(spark) {
console.log("got connection");
spark.on('data', this.onData.bind(this, spark));
}
onDisconnection(spark) {
console.log("connection lost");
}
onData(spark, data) {
console.log("server got data:", data);
}
}
module.exports = WebsocketServer;<file_sep>/server/index.js
'use strict';
const express = require('express');
const path = require('path');
const cors = require('cors');
const WebsocketServer = require('./websocket.js');
const app = express();
let websocketServer = new WebsocketServer(app, 1234);
app.use(express.static(path.join(__dirname, '../client')));
app.use(cors());
app.listen(8080, function() {
console.log("express server listening on port 8080");
});
setInterval(function() {
websocketServer.primus.write("hello from server");
}, 3000); | be1337bc9227a13ed00bcd2badb19caa8363f749 | [
"JavaScript"
] | 2 | JavaScript | whoisbma/primus-test | e049d694d8678f37d901ef225be3a7fcf967e523 | 5fdad5a840f9c015efababbef72e5e3302dd262d |
refs/heads/master | <file_sep>var rpio = require('rpio');
var sleep = require('sleep');
rpio.open(11, rpio.OUTPUT, rpio.HIGH);
sleep.sleep(1);
rpio.open(11, rpio.OUTPUT, rpio.LOW);
sleep.sleep(1);
rpio.open(11, rpio.OUTPUT, rpio.HIGH);
sleep.sleep(1);
rpio.open(11, rpio.OUTPUT, rpio.LOW);
sleep.sleep(1);
rpio.open(11, rpio.OUTPUT, rpio.HIGH);
sleep.sleep(1);
rpio.open(11, rpio.OUTPUT, rpio.LOW);
<file_sep>var rpio = require('rpio');
var queueUrl = "https://sqs.eu-central-1.amazonaws.com/064138081926/Ampel";
const Consumer = require('sqs-consumer');
const app = Consumer.create({
queueUrl: queueUrl,
handleMessage: (message, done) => {
// do some work with `message`
console.log('received:' + message.Body);
var command = message.Body.toLowerCase();
if (command == 'red') {
rpio.open(11, rpio.OUTPUT, rpio.HIGH);
}
else {
rpio.open(11, rpio.OUTPUT, rpio.LOW);
}
done();
}
});
app.on('error', (err) => {
console.log(err.message);
});
app.start(); | 969f3cf2394736431c1043e289dfc7fae490d62d | [
"JavaScript"
] | 2 | JavaScript | tobitux/ampel | 593d34b977f4183082730ca1185cd5e18465929f | 01f797c30566912d5de633dac179ec3e7f624f85 |
refs/heads/master | <repo_name>lcia-lab/heroku-buildpack-poppler<file_sep>/bin/detect
#!/usr/bin/env bash
# bin/detect <build-dir>
echo "Poppler" && exit 0
<file_sep>/bin/compile
#!/usr/bin/env bash
export PATH=:/usr/local/bin:$PATH
BUILD_DIR=$1
BIN_DIR=$(cd "$(dirname "$0")"; pwd) # absolute path
VENDOR_DIR="$BIN_DIR/../vendor"
echo $VENDOR_DIR
POPPLER_DATA_HOME="$VENDOR_DIR/poppler-data"
POPPLER_DATA_DIR="$VENDOR_DIR/poppler-data-0.4.9"
POPPLER_HOME="$VENDOR_DIR/poppler"
POPPLER_DIR="$VENDOR_DIR/poppler-0.83.0/"
cd $VENDOR_DIR
echo "Installing poppler data"
tar -xvzf "$VENDOR_DIR/poppler-data-0.4.9.tar.gz"
cd $POPPLER_DATA_DIR
make prefix="$VENDOR_DIR" install
cd $VENDOR_DIR
echo "Installing poppler"
tar Jxfv "$VENDOR_DIR/poppler-0.83.0.tar.xz"
cd $POPPLER_DIR \
&& cmake . -DCMAKE_INSTALL_PREFIX="$VENDOR_DIR" -DCMAKE_BUILD_TYPE=release \
&& make \
&& make install
PROFILE_PATH="$BUILD_DIR/.profile.d/poppler.sh"
mkdir -p $(dirname $PROFILE_PATH)
echo 'export PATH="$PATH:$HOME/vendor/poppler/bin"' >> $PROFILE_PATH
echo 'export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HOME/vendor/poppler/lib"' >> $PROFILE_PATH
echo "-----> DONE"
| e7d340d70a821f5462fb52238cca1f246639ef92 | [
"Shell"
] | 2 | Shell | lcia-lab/heroku-buildpack-poppler | 6c321edd9cef830f448a7ae174312969362fb1a8 | 01418cc7a9b0d88cbabb0294a697c4785546ecc7 |
refs/heads/master | <repo_name>suppersentai/project_HK_5<file_sep>/SellManage/DAO/showInforDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using MODEL;
using System.Data;
namespace DAO
{
public class showInforDAO
{
public static DataTable takeListType()
{
String sql = "select * from loaisanpham ";
DataTable dtableType = ConnectDAO.getDataTable(sql);
if (dtableType.Rows.Count == 0)
{
MessageBox.Show("base base loaisanpham null ");
return null;
}
return dtableType;
}
public static DataTable takeListSize()
{
String sql = "select (size) from SANPHAM group by size order by size;";
DataTable dtableSize = ConnectDAO.getDataTable(sql);
if (dtableSize.Rows.Count == 0)
{
return null;
}
return dtableSize;
}
public static DataTable takeListColor()
{
String sql = "select (mausac) from SANPHAM group by mausac order by mausac;";
DataTable dtable = ConnectDAO.getDataTable(sql);
if (dtable.Rows.Count == 0)
{
return null;
}
return dtable;
}
public static DataTable getListProduct()
{
List<product> list = new List<product>();
string sql = "select SANPHAM.idSp ,SANPHAM.tenSp,LOAISANPHAM.tenLoai,SANPHAM.size,SANPHAM.mausac,giaban,SANPHAM.doituongsudung,SANPHAM.note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap; ";
DataTable dtableProduct = ConnectDAO.getDataTable(sql);
return dtableProduct;
}
public static DataTable filterCombox(int idLoai)
{
DataTable data = null;
string sql = "select SANPHAM.idSp ,SANPHAM.tenSp,LOAISANPHAM.tenLoai,SANPHAM.size,SANPHAM.mausac,giaban,SANPHAM.doituongsudung,SANPHAM.note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and idloaisanpham='"+idLoai+"'; ";
data = ConnectDAO.getDataTable(sql);
return data;
}
}
}
<file_sep>/SellManage/DAO/payDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MODEL;
namespace DAO
{
public class payDAO
{
public static bool payAndInsertBill(bill bil)
{
string sql = "insert into HOADON values('" + bil.IdBill + "',N'" + bil.IdStaff + "','" + CONST.customer.Id + "','" + bil.DayOfSell.ToString("yyyy/MM/dd") + "','" + bil.TotalMoney + "')";
if (ConnectDAO.queryNonQuery(sql))
return true;
//Console.WriteLine("HOA DON");
//Console.WriteLine(" ma HOA DON" + bil.IdBill);
//Console.WriteLine("id nhan vien" + bil.IdStaff);
//Console.WriteLine("id n kHach" + CONST.customer.Id);
//Console.WriteLine("Ngay ban" + bil.DayOfSell);
//Console.WriteLine("tong tien" + bil.TotalMoney);
return false;
}
public static bool payAndInsertDetailBill(DataGridView dgv, bill bil)
{
MessageBox.Show("Toan 3");
bool check = false; ;
int i = 0;
for (i = 0; i < dgv.Rows.Count; i++)
{
check = false;
detailBill detaiBill = new detailBill();
detaiBill.IdBill = bil.IdBill;
detaiBill.IdProduct = int.Parse(dgv.Rows[i].Cells["idsp"].Value.ToString());
detaiBill.Price = int.Parse(dgv.Rows[i].Cells["giaban"].Value.ToString());
detaiBill.Quantity = int.Parse(dgv.Rows[i].Cells["soluong"].Value.ToString());
string sql = "insert into CHITIETHOADON values('" + detaiBill.IdBill + "','" + detaiBill.IdProduct + "','" + detaiBill.Price + "','" + detaiBill.Quantity + "')";
if (ConnectDAO.queryNonQuery(sql))
check = true;
if (!check)
{
break;
}
//Console.WriteLine("chi tuet HOA DON");
//Console.WriteLine(" ma ct HOA DON" + detaiBill.IdBill);
//Console.WriteLine(" id san pham" + detaiBill.IdProduct);
//Console.WriteLine("gia" + detaiBill.Price);
//Console.WriteLine("sol luong" + detaiBill.Quantity);
}
return check;
}
public static bool insertCustomerDAO(customer cus)
{
Console.WriteLine(cus.Name);
Console.WriteLine(cus.Address );
Console.WriteLine(cus.Phone);
Console.WriteLine(cus.Gender);
string sql = "insert into khachhang values('',N'" + cus.Name + "',N'" + cus.Address + "',N'" + cus.Phone + "',N'" + cus.Gender + "')";
if (ConnectDAO.queryNonQuery(sql))
return true;
return false;
}
}
}
<file_sep>/SellManage/VIEW/formMain-LAPTOP-8FFN7941.cs
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 Controller;
using System.Windows.Forms;
namespace VIEW
{
public partial class formMain : Form
{
public formMain()
{
InitializeComponent();
}
private void panel3_Paint(object sender, PaintEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
private void formMain_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult di = MessageBox.Show("Bạn Chắc Chắc Muốn thoát Không", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (di == DialogResult.Cancel){
e.Cancel = true;
}
else
{
Environment.Exit(1);
// Application.Exit();
}
}
private void đăngXuấtToolStripMenuItem_Click(object sender, EventArgs e)
{
new LOGIN().Visible = true; this.Visible = false;
}
private void formMain_Load(object sender, EventArgs e)
{
Controller.showInforProcesss.showTypeOnCombox(sell_cbType);
Controller.showInforProcesss.showSizeOnCombox(sell_cbSize);
//sell_dataGrid.DataSource = Controller.showInforProcesss.getListProductProsess();
}
}
}
<file_sep>/SellManage/VIEW/use_NhanVien.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Controller;
using MODEL;
using Controller.NhanVien;
namespace VIEW
{
public partial class use_NhanVien : UserControl
{
public use_NhanVien()
{
InitializeComponent();
}
private void use_NhanVien_Load(object sender, EventArgs e)
{
loadUserNhanVien();
}
private void loadUserNhanVien()
{
accountProcess nvProcess = new accountProcess();
nvProcess.getAllStaff(nv_dgvNV);
}
}
}
<file_sep>/SellManage/Controller/showInforProcesss.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DAO;
using MODEL;
using System.Data;
using System.Collections;
namespace Controller
{
public class showInforProcesss
{
#region Hiển thị thông tin và chưc năng lọc trong combobox
public static void showTypeOnCombox(ComboBox cbType)
{
DataTable datable = new DataTable();
//show combobox type
datable = DAO.showInforDAO.takeListType();
DataRow row = datable.NewRow();
row["tenLoai"] = " Tất cả";
row["idLoai"] = 0;
datable.Rows.Add(row);
DataView daView = datable.DefaultView;
daView.Sort = "idloai ASC";
cbType.DataSource = datable;
cbType.DisplayMember = "tenloai";
cbType.ValueMember = "idLoai";
}
public static void showSizeOnCombox(ComboBox combox)
{
DataTable datable = new DataTable();
//show combobox SIZE
datable = DAO.showInforDAO.takeListSize();
DataRow row = datable.NewRow();
row["size"] = " Tất cả";
datable.Rows.Add(row);
DataView daView = datable.DefaultView;
daView.Sort = "size ASC";
combox.DataSource = datable;
combox.DisplayMember = "size";
combox.ValueMember = "size";
}
public static void showColorOnCombox(ComboBox combox)
{
DataTable datable = new DataTable();
//show combobox color
datable = DAO.showInforDAO.takeListColor();
DataRow row = datable.NewRow();
row["mausac"] = " Tất cả";
datable.Rows.Add(row);
DataView daView = datable.DefaultView;
daView.Sort = "mausac ASC";
combox.DataSource = datable;
combox.DisplayMember = "mausac";
combox.ValueMember = "Mausac";
}
public static DataTable filterComboxValues(int idLoai)
{
//lọc giá giá trị khi thay đổi selectedIndex
DataTable dataView = DAO.showInforDAO.filterCombox(idLoai);
return dataView;
}
#endregion
public static DataTable getListProductProsess()
{
return DAO.showInforDAO.getListProduct();
}
public void bindigToObject()
{
}
}
//public class sortListById : IComparer
//{ so sanh doi tượng bằng giá trị propeties
// public int Compare(object a, object b)
// {
// typeProduct typeProduct = a as typeProduct;
// typeProduct typeProduct2 = b as typeProduct;
// return typeProduct.Id.CompareTo(typeProduct2.Id);
// }
//}
}
<file_sep>/SellManage/VIEW/test.cs
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;
using System.Threading;
namespace VIEW
{
public partial class test : Form
{
public test()
{
InitializeComponent();
}
private void test_Load(object sender, EventArgs e)
{
timer1.Start();
}
public void runTime()
{
//Thread.Sleep(950); MessageBox.Show(h + "---" + p + "--" + s);
}
private void timer1_Tick(object sender, EventArgs e)
{
System.Timers.Timer t = sender as System.Timers.Timer;
string h = DateTime.Now.TimeOfDay.Hours.ToString();
string p = DateTime.Now.TimeOfDay.Minutes.ToString();
string s = DateTime.Now.TimeOfDay.Seconds.ToString();
lbTimeNow.Text = h + " : " + p + " : " + s;
}
}
}
<file_sep>/SellManage/MODEL/bill.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MODEL
{
public class bill
{
int idBill;
int idStaff;
int idCustomer;
DateTime dayOfSell;
int totalMoney;
List<detailBill> detail;
public bill()
{
// detail.
}
public int IdBill { get => idBill; set => idBill = value; }
public int IdStaff { get => idStaff; set => idStaff = value; }
public int IdCustomer { get => idCustomer; set => idCustomer = value; }
public DateTime DayOfSell { get => dayOfSell; set => dayOfSell = value; }
public int TotalMoney { get => totalMoney; set => totalMoney = value; }
}
}
<file_sep>/SellManage/VIEW/formMain.cs
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;
using MODEL;
using Controller;
namespace VIEW
{
public partial class formMain : Form
{
bool billStatus = false;
private fillterDataComBoxPROCESS fill;
DataTable tableCurent;//List product ddang show tren data grid
bool check = false;// dùng để tránh chạy sk valuechange khi đổ data vào combox
DataTable tableProductFull;//List product chua tat ca product from database
public formMain()
{
InitializeComponent();
}
private void đăngXuấtToolStripMenuItem_Click(object sender, EventArgs e)
{// event log out
new LOGIN().Visible = true;
this.Visible = false;
}
private void formMain_FormClosing(object sender, FormClosingEventArgs e)
{// event Close Form
DialogResult di = MessageBox.Show("Bạn Chắc Chắc Muốn thoát Không", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (di == DialogResult.Cancel)
{
e.Cancel = true;
}
else
{
Environment.Exit(1);
// Application.Exit();
}
}
private void formMain_Load(object sender, EventArgs e)
{//event LoadForm First
tableProductFull = Controller.showInforProcesss.getListProductProsess();
sell_dataGrid.DataSource = tableProductFull;
//đặt header
sell_dataGrid.Columns["idSP"].HeaderText = "Mã";
sell_dataGrid.Columns["TenSP"].HeaderText = "Tên sản phẩm";
sell_dataGrid.Columns["tenloai"].HeaderText = "Loại";
sell_dataGrid.Columns["size"].HeaderText = "Size";
sell_dataGrid.Columns["mausac"].HeaderText = "Màu sắc";
sell_dataGrid.Columns["giaban"].HeaderText = "Giá Bán";
sell_dataGrid.Columns["doituongsudung"].HeaderText = "Phái";
sell_dataGrid.Columns["note"].HeaderText = "note";
// add colum button
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
Button b = new Button();
btn.HeaderText = "Click";
btn.Name = "button";
btn.Text = "Add";
btn.Width = 80;
btn.UseColumnTextForButtonValue = true;
sell_dataGrid.Columns.Add(btn);
// //đặt kích thước width
sell_dataGrid.Columns["idSP"].Width = 60;
sell_dataGrid.Columns["size"].Width = 60;
sell_dataGrid.Columns["doituongsudung"].Width = 60;
sell_dataGrid.Columns["button"].Width = 80;
// // show infor on 3 combobox
Controller.showInforProcesss.showTypeOnCombox(sell_cbType);
Controller.showInforProcesss.showSizeOnCombox(sell_cbSize);
Controller.showInforProcesss.showColorOnCombox(sell_cbColor);
//// sell_cbPrice.SelectedIndex = 0;
tableCurent = (DataTable)sell_dataGrid.DataSource;
check = true;
MessageBox.Show(billStatus.ToString());
if (!billStatus)
{
changeReadOnllytextBoxCustomew(!billStatus);
}
else
{
changeReadOnllytextBoxCustomew(!billStatus);
}
}
#region combobox change value
private void sell_cbType_SelectedValueChanged(object sender, EventArgs e)
{// event combobox type
//ShowIInfo();
ComboBox com = sender as ComboBox;
if (check == true)
if (sell_cbSize.SelectedIndex == 0 && sell_cbColor.SelectedIndex == 0)
{
tableProductFull = Controller.showInforProcesss.getListProductProsess();
if (com.SelectedIndex == 0)
{
sell_dataGrid.DataSource = tableProductFull;
}
else
{
tableCurent = Controller.showInforProcesss.filterComboxValues(Convert.ToInt32(com.SelectedValue));
sell_dataGrid.DataSource = tableCurent;
}
}
else
{
ShowIInfo(com);
}
}
private void sell_cbSize_SelectedValueChanged_1(object sender, EventArgs e)
{// event combobox size
ComboBox com = sender as ComboBox;
if (check == true)
if (sell_cbType.SelectedIndex == 0 && sell_cbColor.SelectedIndex == 0)
{
tableProductFull = Controller.showInforProcesss.getListProductProsess();
if (com.SelectedIndex == 0)
{
tableCurent = tableProductFull;
sell_dataGrid.DataSource = tableCurent;
}
else
{
DataTable oldDataCurent = tableCurent;
DataView daview = oldDataCurent.DefaultView;
daview.RowFilter = "size = '" + com.SelectedValue.ToString() + "'";
sell_dataGrid.DataSource = tableCurent;
}
}
else
{
ShowIInfo(com);
}
}
#endregion
private void sell_cbColor_SelectedValueChanged(object sender, EventArgs e)
{// event combobox màu
ComboBox com = sender as ComboBox;
if (check == true)
if (sell_cbType.SelectedIndex == 0 && sell_cbSize.SelectedIndex == 0)
{
tableProductFull = Controller.showInforProcesss.getListProductProsess();
if (com.SelectedIndex == 0)
{
sell_dataGrid.DataSource = tableProductFull;
}
else
{
// DataTable oldDataCurent = (DataTable)sell_dataGrid.DataSource;
DataView daview = tableCurent.DefaultView;
daview.RowFilter = "mausac = '" + com.SelectedValue.ToString() + "'";
sell_dataGrid.DataSource = tableCurent;
}
}
else
{
ShowIInfo(com);
}
}
public void ShowIInfo(ComboBox com)
{//set datagrid = tất cả san pham
string size = null, color = null;
int idType = Convert.ToInt32(sell_cbType.SelectedValue);
if (sell_cbSize.SelectedIndex != 0)
{
size = sell_cbSize.SelectedValue.ToString();
}
if (sell_cbColor.SelectedIndex != 0)
{
color = sell_cbColor.SelectedValue.ToString();
}
fill = new fillterDataComBoxPROCESS();
DataTable data = fill.fillterTypeCombox(size, idType, color);
sell_dataGrid.DataSource = data;
}
public bool checkAllSelecedIsZero()
{// kiểm tra xem tất cả các value index có phải = 0
if (sell_cbType.SelectedIndex == 0 && sell_cbSize.SelectedIndex == 0 && sell_cbColor.SelectedIndex == 0)
{
return true;
}
return false;
}
private void button1_Click_1(object sender, EventArgs e)
{// button tất cả: show all product
sell_cbType.SelectedIndex = 0;
sell_cbSize.SelectedIndex = 0;
sell_cbColor.SelectedIndex = 0;
}
private void sell_dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{// event datagridview main
var dgvBtn = (DataGridView)sender;
if (CONST.checkCreatedBill)
if (dgvBtn.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
{//nếu là column button
Controller.showBill.showDgvBill(sell_dataGrid, sell_dgvBill);
sell_txtTotaPricelBill.Text = Controller.showBill.getTotalPriceInDgvBill(sell_dgvBill).ToString();
}
else
{
MessageBox.Show("Bạn Chưa tạo hóa đơn !", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void sell_txtResetBill_Click(object sender, EventArgs e)
{
reset();
}
private void button8_Click(object sender, EventArgs e)
{
}
private void sell_txtCreateBill_Click(object sender, EventArgs e)
{
billStatus = true;
changeBackColorBillStatus();
billStatus = true;
CONST.checkCreatedBill = true;
// hiển thị các textbox tên nhân viên ,,id hóaddonw
int idBill = Controller.getData.getIdBill();
sell_txtIdHd.Text = idBill.ToString();
sell_txtNameStaff.Text = CONST.currenAcount.Name;
DateTime dateOfsell = DateTime.Now;
Color mau = Color.PeachPuff;
changeBackColorEnoughInfoCustomer(mau);
}
private void sell_dgvBill_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
}
public bool checkInvalidWhenPay()
{
if (!sell_txtNameCus.Equals(""))
{
if (sell_txtPhoneCus.Text.Length < 1 || sell_txtPhoneCus.Text.Length > 10)
{
return false;
}
else
{
if (!sell_txtAddressCus.Equals(""))
if (sell_genderCusBoy.Checked == true || sell_genderCusGirl.Checked == true)
if (sell_dgvBill.Rows.Count >= 0)
return true;
}
}
return false;
}
private String getGenderCus()
{
if (sell_genderCusBoy.Checked)
return sell_genderCusBoy.Text;
else return sell_genderCusGirl.Text;
}
private void sell_btnPay_Click(object sender, EventArgs e)
{
if (checkInvalidWhenPay())
{
if (CONST.customer == null)
{
customer cus = new customer();
cus.Name = sell_txtNameCus.Text;
cus.Address = sell_txtAddressCus.Text;
cus.Phone = sell_txtPhoneCus.Text;
cus.Gender = getGenderCus();
CONST.customer = cus;
Controller.payProcess.insertNewCustomer(cus); //insert to databbase. luc nay chua co ID
Controller.payProcess.getCustomerIfExist(cus.Phone);//lay laij khach hang vua insert de lay ca ID
MessageBox.Show("TAI KHOAN CHUA TON TAI");
}
if (sell_dgvBill.Rows.Count >= 1)
{
MessageBox.Show("TAI KHOAN dA TON TAI");
MessageBox.Show("Chưattt", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
bill bil = new bill();
bil.IdBill = int.Parse(sell_txtIdHd.Text);
bil.IdStaff = CONST.currenAcount.Id;
bil.IdCustomer = CONST.customer.Id;
// bil.DayOfSell = Convert.ToDateTime( sell_txtDayOfSell.Text,'yyyy/MM/dd');
bil.DayOfSell = sell_dateOfSell.Value.Date;
MessageBox.Show(bil.DayOfSell.ToString());
bil.TotalMoney = int.Parse(sell_txtTotaPricelBill.Text.ToString());
Controller.payProcess.createBill(sell_dgvBill, bil);
MessageBox.Show("Tạo Hóa Đơn Thành Công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
reset();
billStatus = false;
changeBackColorBillStatus();
changeReadOnllytextBoxCustomew(!billStatus);
}
else
{
MessageBox.Show("Chưa có sản phẩm", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Thông tin không hợp lệ");
}
CONST.customer = null;
}
private void changeBackColorBillStatus()
{
if (billStatus)
{
sell_panTopCus.BackColor = Color.LightGreen;
}
else
{
sell_panTopCus.BackColor = Color.Red;
}
}
private void sell_txtPhoneCus_TextChanged(object sender, EventArgs e)
{
TextBox text = sender as TextBox;
if (text.Text.Length == 10)
{
Controller.payProcess.getCustomerIfExist(text.Text);
if (CONST.customer != null)
{
sell_txtAddressCus.Text = CONST.customer.Address;
sell_txtPhoneCus.Text = CONST.customer.Phone;
if (CONST.customer.Gender.Equals("Nam"))
{
sell_genderCusBoy.Checked = true;
}
else
{
sell_genderCusGirl.Checked = true;
}
sell_txtNameCus.Text = CONST.customer.Name;
sell_panInfoCustome.BackColor = Color.LightGreen;
Color mau = Color.LightGreen;
changeBackColorEnoughInfoCustomer(mau);
MessageBox.Show("CONST != NULL");
}
else
{
MessageBox.Show("CONST = NULL");
changeReadOnllytextBoxCustomew(!billStatus);
}
}
}
private void changeReadOnllytextBoxCustomew(bool value)
{
sell_txtAddressCus.ReadOnly = value;
sell_txtNameCus.ReadOnly = value;
}
private void changeBackColorEnoughInfoCustomer(Color mau)
{
// if (sell_txtNameCus.Text.Length > 0)
// if (sell_txtPhoneCus.Text.Length > 0)
// if (sell_txtGenderCus.Text.Length > 0)
sell_panInfoCustome.BackColor = mau;
}
void reset()
{
sell_txtTotaPricelBill.Text = "";
sell_txtNameCus.Text = "";
sell_txtPhoneCus.Text = "";
sell_txtAddressCus.Text = "";
sell_dgvBill.Rows.Clear();
Color mau = Color.PeachPuff;
changeBackColorEnoughInfoCustomer(mau);
}
private void button2_Click(object sender, EventArgs e)
{
// button chuyen sang quan li doanh thu
}
private void button2_Click_1(object sender, EventArgs e)
{
Main_panMain.Controls.Clear();
use_KhachHang kh = new use_KhachHang();
refontsive(kh);
Main_panMain.Controls.Add(kh);
}
private void btn_sell_Click(object sender, EventArgs e)
{
Main_panMain.Controls.Clear();
Main_panMain.Controls.Add(pan_sell);
}
private void button3_Click(object sender, EventArgs e)
{
Main_panMain.Controls.Clear();
use_NhanVien nv = new use_NhanVien();
refontsive(nv);
Main_panMain.Controls.Add(nv);
}
public void refontsive(UserControl nv)
{
nv.Anchor = AnchorStyles.Left;
nv.Anchor = AnchorStyles.Right;
nv.Dock = DockStyle.Fill;
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
}
}
<file_sep>/SellManage/Controller/NhanVien/accountProcess.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows.Forms;
namespace Controller.NhanVien
{
public class accountProcess
{
public void getAllStaff(DataGridView dgv)
{
DataTable data = DAO.userDAO.getAllStaff();
dgv.DataSource = data;
dgv.Columns["idnv"].HeaderText = "Mã";
dgv.Columns["tennv"].HeaderText = "Họ Tên";
dgv.Columns["PhoneNV"].HeaderText = "Số điện thoại";
dgv.Columns["NgaySinhNV"].HeaderText = "Ngày Sinh";
dgv.Columns["DiaChiNV"].HeaderText = "Địa Chỉ";
dgv.Columns["LuongNV"].HeaderText = "Lương";
dgv.Columns["NgayVaoLam"].HeaderText = "ngày vào làm";
dgv.Columns["GioiTinhNV"].HeaderText = "Giới Tính";
//dgv.Columns["NgaySinhNV"].Visible = false;
//dgv.Columns["DiaChiNV"].Visible = false;
//dgv.Columns["NgayVaoLam"].Visible = false;
dgv.Columns["idnv"].Width = 30;
dgv.Columns["LuongNV"].DefaultCellStyle.Format = "# ###";
dgv.Columns["LuongNV"].Width =60;
dgv.Columns["GioiTinhNV"].Width = 30;
dgv.Columns["tennv"].Width = 120;
dgv.Columns["DiaChiNV"].Width = 150;
dgv.Columns["NgayVaoLam"].Width = 70;
dgv.Columns["NgaySinhNV"].Width = 70;
}
}
}
<file_sep>/SellManage/Controller/loginProcess.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using System.Text.RegularExpressions;
using System.Data;
using System.Windows.Forms;
namespace Controller
{
public class loginProcess
{
public bool checkInvalid(String name, String password)
{
string regex = "\\w{6,30}";
Regex.IsMatch(name, regex);
if (Regex.IsMatch(name, regex) || Regex.IsMatch(password, regex)) {
return true;
}
return false;
}
public bool checkExistAccount(String name, String password)
{
if (DAO.userDAO.checkExistAccount(name,password))
return true;
return false;
}
public static staff getAccount(String name, String password)
{
DataTable data = DAO.userDAO.getAccount(name,password);
staff st = new staff();
st.Id = Convert.ToInt32( data.Rows[0]["idnv"].ToString());
st.Name = data.Rows[0]["tennv"].ToString();
st.UserName = data.Rows[0]["username"].ToString();
st.Password= data.Rows[0]["pass"].ToString();
st.CheckAdmin= Convert.ToInt32(data.Rows[0]["checkadmin"].ToString());
return st;
}
}
}
<file_sep>/SellManage/Controller/fillterDataComBoxPROCESS.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows.Forms;
namespace Controller
{
public class fillterDataComBoxPROCESS
{
public DataTable fillterTypeCombox(String size, int idType, string color)
{
String sql = null;
DataTable data = null;
//if (idType == 0)
//{
// sql = "select SANPHAM.idSp ,SANPHAM.tenSp,LOAISANPHAM.tenLoai,SANPHAM.size,SANPHAM.mausac,giaban,SANPHAM.doituongsudung,SANPHAM.note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and mausac='" + color + "' size='" + size + "'; ";
//}
if (idType == 0)
{
if (color != null && size == null)
{
sql = "select idSp ,tenSp,tenLoai,size,mausac,giaban,doituongsudung,note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and mausac='" + color + "'; ";
MessageBox.Show("th1");
}
else
if (size != null && color == null)
{
sql = "select idSp ,tenSp,tenLoai,size,mausac,giaban,doituongsudung,note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and size='" + size + "'; ";
MessageBox.Show("th2");
}
else
{
sql = "select idSp ,tenSp,tenLoai,size,SANPHAM.mausac,giaban,doituongsudung,note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and size='" + size + "' and mausac='" + color + "'; ";
MessageBox.Show("th3");
}
} else
{
if (size != null && color == null)
{
sql = "select idSp ,tenSp,tenLoai,size,mausac,giaban,doituongsudung,SANPHAM.note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and idloaisanpham='" + idType + "' and size='" + size + "' ; ";
MessageBox.Show("th4");
} else if (size == null && color != null)
{
sql = "select SANPHAM.idSp ,SANPHAM.tenSp,LOAISANPHAM.tenLoai,SANPHAM.size,SANPHAM.mausac,giaban,SANPHAM.doituongsudung,SANPHAM.note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and idloaisanpham='" + idType + "' and mausac='" + color + "' ; ";
MessageBox.Show("th5");
}
else if (size != null && color != null)
{
sql = "select idSp ,tenSp,tenLoai,size,mausac,giaban,doituongsudung,note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and idloaisanpham='" + idType + "'and mausac='" + color + "' and size='" + size + "' ; ";
MessageBox.Show("ca 3 khac null");
}
else
{
sql = "select idSp ,tenSp,tenLoai,size,mausac,giaban,doituongsudung,note from SANPHAM, LOAISANPHAM ,HoaDonNhapHang,nhacungcap where SANPHAM.idLOAISANPHAM = LOAISANPHAM.idLoai and sanpham.idSP=hoadonnhaphang.IdSanPham and NHACUNGCAP.IdNCC= sanpham.IdNhaCungCap and idloaisanpham='" + idType + "' ; ";
}
}
data = DAO.ConnectDAO.getDataTable(sql);
return data;
}
}
}
<file_sep>/SellManage/DAO/ConnectDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data;
namespace DAO
{
public class ConnectDAO
{
static String stringConnect = "Data Source = localhost;Database = quanlibanhang; port = 3306;User Id=root;password=;charset=utf8;";
//public static MySqlConnection getConnect()
//{
// MySqlConnection conn = new MySqlConnection();
// try
// {
// String stringConnect = "Data Source = localhost;Database = quanlibanhang; port = 3306;User Id=root;password=";
// conn = new MySqlConnection(stringConnect);
// conn.Open();
// }
// catch (MySqlException ex)
// {
// MessageBox.Show(ex.StackTrace +"\n Error connect in getConnect()");
// }
// return conn;
//}
public static DataTable getDataTable(String stringQuery)
{
using (MySqlConnection conn = new MySqlConnection(stringConnect))
{
conn.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter(stringQuery, conn);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
conn.Close();
return dataTable;
}
}
public static bool queryNonQuery(String stringQuery)
{
MySqlConnection conn = null;
try
{
using ( conn = new MySqlConnection(stringConnect))
{
conn.Open();
MySqlCommand command = new MySqlCommand(stringQuery, conn);
if(command.ExecuteNonQuery()>=1)
// conn.Close();
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace + "\n ChungToan Say connectDAO/queryNonQuery");
}
finally
{
conn.Close();
}
return false;
}
public static int getDataIDBill(String stringQuery)
{
using (MySqlConnection conn = new MySqlConnection(stringConnect))
{
conn.Open();
MySqlCommand com = new MySqlCommand(stringQuery, conn);
MySqlDataReader adapter = com.ExecuteReader();
adapter.Read();
int num = Convert.ToInt32(adapter[0].ToString());
conn.Close();
return num ;
}
}
}
}
<file_sep>/SellManage/MODEL/typeProduct.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MODEL
{
public class typeProduct
{
string id;
string name;
public string Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
}
}
<file_sep>/SellManage/VIEW/LOGIN.cs
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;
using Controller;
using MODEL;
namespace VIEW
{
public partial class LOGIN : Form
{
public LOGIN()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
loginProcess log = new loginProcess();
if (log.checkInvalid(log_txtUser.Text, log_txtPas.Text))
{
if (log.checkExistAccount(log_txtUser.Text, log_txtPas.Text))
{
new formMain().Visible=true;
this.Visible = false;
staff st = Controller.loginProcess.getAccount(log_txtUser.Text, log_txtPas.Text);
CONST.currenAcount = st;
}
else
{
MessageBox.Show("không tồng tai", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("Sai tên đăng nhập hoặc mật khẩu", "Thông Báo", MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
private void LOGIN_FormClosing(object sender, FormClosingEventArgs e)
{
//Environment.Exit(1);
Application.Exit();
}
}
}
<file_sep>/SellManage/MODEL/product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MODEL
{
public class product
{
#region propeties
private int id;
private string name;
private string supplier;
private String size;
private string color;
private double outPrice;
private string type;
private string note;
private string tag;
public int Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
public double OutPrice { get => outPrice; set => outPrice = value; }
public string Type { get => type; set => type = value; }
public string Color { get => color; set => color = value; }
public string Size { get => size; set => size = value; }
public string Supplies { get => supplier; set => supplier = value; }
public string Note { get => note; set => note = value; }
public string Tag { get => tag; set => tag = value; }
#endregion
#region method
#endregion
}
}
<file_sep>/SellManage/DAO/userDAO.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace DAO
{
public class userDAO
{
public static bool checkExistAccount(String name, String pass)
{
String sql = "select * from acount where userName='"+name+"' and pass='"+pass+"'";
DataTable da = ConnectDAO.getDataTable(sql);
if(da.Rows.Count>0)
return true;
return false;
}
public static DataTable getAccount(String name, String pass)
{
String sql = "select nhanvien.idnv,tennv,username,pass,checkadmin from nhanvien ,acount where username='" +name+"' and pass='"+pass+"'";
DataTable data =DAO.ConnectDAO.getDataTable(sql);
return data;
}
public static DataTable getAllStaff()
{
String sql = "select * from nhanvien";
DataTable data = DAO.ConnectDAO.getDataTable(sql);
return data;
}
}
}
<file_sep>/SellManage/Controller/payProcess.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MODEL;
using System.Data;
namespace Controller
{
public class payProcess
{
public static void createBill(DataGridView dgvBil,bill bil)
{
if(DAO.payDAO.payAndInsertBill(bil))
if (DAO.payDAO.payAndInsertDetailBill(dgvBil, bil))
{
MessageBox.Show("ok");
}
}
public static void getCustomerIfExist(string phoneCustomer)
{
string sql = "select * from khachhang where phonekh='" + phoneCustomer + "'";
DataTable data = DAO.ConnectDAO.getDataTable(sql);
if (data.Rows.Count >= 1)
{
CONST.customer = new customer();
MessageBox.Show(data.Rows[0]["idkh"].ToString());
CONST.customer.Id = int.Parse(data.Rows[0]["idkh"].ToString());
CONST.customer.Name= data.Rows[0]["TenKH"].ToString();
CONST.customer.Address= data.Rows[0]["DiaChiKH"].ToString();
CONST.customer.Phone= data.Rows[0]["PhoneKH"].ToString();
CONST.customer.Gender= data.Rows[0]["GioiTinhKH"].ToString();
}
else
{
CONST.customer = null;
}
}
public static void insertNewCustomer( customer cus)
{
DAO.payDAO.insertCustomerDAO(cus);
}
}
}
<file_sep>/sqlMain.sql
/*
*/
drop database quanlibanhang;
create database quanlibanhang;
use quanlibanhang;
/* ---- table Loai san pham--------------------------------*/
create table LOAISANPHAM(
IdLoai int not null ,
TenLoai nvarchar(100)
);
alter table LOAISANPHAM
add constraint fk_LoaiSP primary key (IdLoai);
alter table LOAISANPHAM
modify column IdLoai int auto_increment;
alter table LOAISANPHAM
auto_increment = 1;
insert into LOAISANPHAM(tenloai)
values ('Quần');
insert into LOAISANPHAM(tenloai)
values ('Áo');
insert into LOAISANPHAM(tenloai)
values ('Giày');
insert into LOAISANPHAM(tenloai)
values ('Dép');
insert into LOAISANPHAM (tenloai)
values ('Áo Khoác');
select * from LOAISANPHAM ;
/*-----------select * from LOAISANPHAM ;----------------------------------------------------*/
/* ---- table Nhan vien--------------------------------*/
create table NHANVIEN(
IdNV int not null ,
TenNV nvarchar(59),
PhoneNV char(10) unique,
NgaySinhNV date ,
DiaChiNV nvarchar(100),
LuongNV int,
NgayVaoLam date ,
GioiTinhNV nvarchar(4)
);
alter table NHANVIEN
add constraint fk_NhanVien primary key (IdNV);
alter table NHANVIEN
modify column IdNV int auto_increment;
alter table NHANVIEN
auto_increment = 1;
insert into NHANVIEN
VALUES('','Trương CHung TOàn','0333216635','1996/05/14','long bình - biên hòa - đồng nai',100000,'2018/12/12','Nam');
insert into NHANVIEN
VALUES('','<NAME>','0333236635','1996/05/14','long bình - biên hòa - đồng nai',100000,'2018/12/12','Nam');
/*---------------------------------------------------------------*/
/* ---- table ACOUNT --------------------------------*/
create table ACOUNT(
idNV int,
userName char(40) unique,
pass char(30),#
checkAdmin tinyint
);
alter table ACOUNT
add constraint fk_acount foreign key (idnv)references NHANVIEN(idnv);
insert into acount values(1,'chungtoan','gaotoan',1);
/* ---- table Khach Hang--------------------------------*/
create table KHACHHANG(
IdKH int not null ,
TenKH nvarchar(100),
DiaChiKH nvarchar(100),
PhoneKH char(10),
GioiTinhKH nvarchar(4)
);
alter table KHACHHANG
add constraint fk_KhachHang primary key (IdKH);
alter table KHACHHANG
modify column IdKH int auto_increment;
alter table KHACHHANG
auto_increment = 1;
insert into KHACHHANG
values ('','khách hàng 1 ','thanh hoa',2333335553,'nữ');
insert into KHACHHANG
values ('','khách hàng 2 ','thanh hoa',2335335553,'Nam');
insert into KHACHHANG
values ('','khách hàng 3 ','thanh hoa',2333777553,'nữ');
/*---------------------------------------------------------------*/
/* ---- table Nha cung cap--------------------------------*/
create table NHACUNGCAP(
IdNCC int not null ,
TenNCC nvarchar(100),
DiaChiNCC nvarchar(200),
PhoneNCC char(19) unique
);
alter table NHACUNGCAP
add constraint fk_NhaCungCap primary key (IdNCC);
alter table NHACUNGCAP
modify column IdNCC int auto_increment;
alter table NHACUNGCAP
auto_increment = 1;
insert into NHACUNGCAP
values ('','Nha cung cấp 1 ','Biên hòa đồng nai',0156453333);
insert into NHACUNGCAP
values ('','Nha cung cấp 2 ','Biên hòa đồng nai',0156453334);
/*----------select * from NHACUNGCAP;-----------------------------------------------------*/
/* ---- table san pham--------------------------------*/
create table SANPHAM(
IdSP int not null ,
TenSP nvarchar(100),
IdNhaCungCap int ,
IdLoaiSanPham int,
Size char(4),
MauSac nvarchar(15),
TongSoLuongSP int,
DoiTuongSuDung nvarchar(4),
note nvarchar(500)
);
alter table SANPHAM
add constraint Pk_SanPham primary key (IdSP);
alter table SANPHAM
add constraint fk_NhaCungCap foreign key (IdNhaCungCap) references NHACUNGCAP(IdNCC);
alter table SANPHAM
add constraint fk_LoaiSanPham foreign key (IdLoaiSanPham) references LOAISANPHAM(IdLoai);
alter table SANPHAM
modify column IdSP int auto_increment;
alter table SANPHAM
auto_increment = 1;
insert into SANPHAM
values ('','Áo ba lỗ ',1,2,'32','red',100,'nữ','');
insert into SANPHAM
values ('','Áo thun ',1,2,'34','green',100,'nam','');
insert into SANPHAM
values ('','Quần jean ',1,1,'34','blue',100,'nữ','');
insert into SANPHAM
values ('','Áo lửng ',1,1,'32','white',100,'nam','');
insert into SANPHAM
values ('','bitit hunter ',1,3,'26','red',100,'nữ','');
insert into SANPHAM
values ('','giày bóng ',1,3,'41','green',100,'nam','');
insert into SANPHAM
values ('','dép lê',1,4,'42','blue',100,'nữ','');
insert into SANPHAM
values ('','dép tông xẹp tông',1,4,'45','red',100,'nam','');
insert into SANPHAM
values ('','Áo Khoác nỉ ',1,5,'33','white',100,'nữ','');
insert into SANPHAM
values ('','Áo khoác da ',1,5,'32','brow',100,'nam','');
/*---------------------------------------------------------------*/
/* ---- table hoa don --------------------------------*/
create table HOADON(
IdHD int not null ,
IdNhanVien int,
IdKhachHang int,
NgayLapHD date,
TongTien int
);
alter table HOADON
add constraint fk_HoaDon primary key (IdHD);
alter table HOADON
add constraint fk_IdNhanVien foreign key (IdNhanVien) references NHANVIEN(IdNV);
alter table HOADON
add constraint fk_IdKhachHang foreign key (IdKhachHang) references KHACHHANG(IdKH);
alter table HOADON
modify column IdHD int auto_increment;
alter table HOADON
auto_increment = 1;
/*---------------------------------------------------------------*/
/* ---- table Chi tiet hoa don--------------------------------*/
create table CHITIETHOADON(
IdHoaDon int not null ,
IDSanPham int,
GiaBan double,
SoLuong int
);
alter table CHITIETHOADON
add constraint fk_IdHoaDon foreign key (IdHoaDon) references HOADON(IdHD);
alter table CHITIETHOADON
add constraint fk_IdSanPham foreign key (IDSanPham) references SANPHAM(IdSP);
use quanlibanhang;
select Max(idhd) from hoadon;
/*---------------------------------------------------------------*/
/* ---- table Nhap Nhap Hang--------------------------------*/
create table HoaDonNhapHang(
IdHoaDonNhap int not null ,
IdNhaCungCap int ,
IdSanPham int,
SoLuong int,
DonGia double ,
GiaBan double not null ,
NgayNhap date
);
alter table HoaDonNhapHang
add constraint pk_HoaDonNhap primary key (IdHoaDonNhap);
alter table HoaDonNhapHang
add constraint fk_IdNhaCungCap foreign key (IdNhaCungCap) references NHACUNGCAP(IdNCC);
alter table HoaDonNhapHang
add constraint fk_IdSanPhams foreign key (IdSanPham) references SANPHAM(IdSP);
alter table HoaDonNhapHang
modify column IdHoaDonNhap int auto_increment;
alter table HoaDonNhapHang
auto_increment = 1;
insert into hoadonnhaphang
values ('',1 ,1,100,10000,20000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,2,100,10000,60000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,3,100,10000,30000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,4,100,10000,40000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,5,100,10000,50000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,6,100,10000,20000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,7,100,10000,60000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,8,100,10000,30000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,9,100,10000,40000,'2018,2,11');
insert into hoadonnhaphang
values ('',1 ,10,100,10000,50000,'2018,2,11');
/*---------------------------------------------------------------*/
/*---------------------------------------------------------------*/
INSERT INTO HOADON
values('',1,1,'2018/8/8',160000);
INSERT INTO HOADON
values('',2,2,'2018/8/8',60000);
INSERT INTO HOADON
values('',1,2,'2018/8/8',40000);
INSERT INTO HOADON
values('',1,2,'2018/8/8',40000);
INSERT INTO HOADON
values('',1,2,'2018/8/8','');
use quanlibanhang;
INSERT INTO CHITIETHOADON
VALUES(1,1,20000,2);
INSERT INTO CHITIETHOADON
VALUES(1,2,60000,2);
INSERT INTO CHITIETHOADON
VALUES(2,3,30000,2);
INSERT INTO CHITIETHOADON
VALUES(3,4,40000,1);
INSERT INTO CHITIETHOADON
VALUES(5,4,'10000',2);
use quanlibanhang;
select * from HOADON;
select * from CHITIETHoadon;
select * from khachhang;
/*------------------- KHU VỰC TEST QUERY--------------------------------------------*/
insert into khachhang values('','truong taon','bien',,'" + cus.Phone + "','" + cus.Gender + "');
insert into HOADON values('34',1,2,'2018/4/3 ','100000');
insert into HOADON values('','" + bil.IdStaff + "','" + CONST.customer.Id + "','" + bil.DayOfSell + "','" + bil.TotalMoney + "');
<file_sep>/SellManage/Controller/showBill.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows.Forms;
namespace Controller
{
public class showBill
{
static DataTable table = null;
static int sttDgvBill = 1;
public static void showDgvBill(DataGridView sell_dataGrid, DataGridView sell_dgvBill)
{
// show thông tin trên datagridbill khi click button Add
table = (DataTable)sell_dgvBill.DataSource;
int indexRow = sell_dataGrid.CurrentCell.RowIndex;// lấy chỉ số hàng đk chọn
DataGridViewRow row = new DataGridViewRow();
row = sell_dataGrid.Rows[indexRow];
int ma = (int)row.Cells["idsp"].Value;
string ten = row.Cells["tensp"].Value.ToString();
string dongia = row.Cells["giaban"].Value.ToString();
int tien = 0;
if (sell_dgvBill.Rows.Count != 0)
{
int i;
bool tontai = false;
for (i = 0; i < sell_dgvBill.Rows.Count; i++)
{
int a = (int)sell_dgvBill.Rows[i].Cells["idsp"].Value;
if (a == ma)
{
int soluong = Convert.ToInt32(sell_dgvBill.Rows[i].Cells[4].Value.ToString());
soluong++;
sell_dgvBill.Rows[i].Cells[4].Value = soluong;
tien = Convert.ToInt32(sell_dgvBill.Rows[i].Cells[3].Value.ToString());
tien *= soluong;
sell_dgvBill.Rows[i].Cells[5].Value = tien;
tontai = true;
break;
}
}
if (!tontai)
{
sell_dgvBill.Rows.Add(sttDgvBill, ma, ten, dongia, 1, dongia);
sttDgvBill++;
}
}
else
{
MessageBox.Show("o444k");
sell_dgvBill.Rows.Add(sttDgvBill, ma, ten, dongia, 1, dongia);
sttDgvBill++;
table = (DataTable)sell_dgvBill.DataSource;
}
}
public static bool checkRowExist(DataGridView table, int ma)
{// kiểm tra giá hàng đang thêm đã tồn tại trong dgvBill chưa
if (table.Rows.Count != 0)
for (int i = 0; i < table.Rows.Count; i++)
{
int a = (int)table.Rows[i].Cells[1].Value;
if (a == ma)
return true;
}
return false;
}
public static int getTotalPriceInDgvBill(DataGridView sell_dgvBill)
{// lấy tổng tiền cả hóa đơn
table = (DataTable)sell_dgvBill.DataSource;
int tongtien = 0;
if (sell_dgvBill.Rows.Count != 0)
for (int i = 0; i < sell_dgvBill.Rows.Count; i++)
{
tongtien += Convert.ToInt32(sell_dgvBill.Rows[i].Cells[5].Value.ToString());
}
return tongtien;
}
}
public class getData
{
public static int getIdBill()
{
String query = "select Max(idhd) from hoadon";
return DAO.ConnectDAO.getDataIDBill(query) + 1;
}
}
}
<file_sep>/SellManage/MODEL/detailBill.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MODEL
{
public class detailBill
{
int idBill;
int idProduct;
String nameProduct;
int quantity;
int price;
bill bills;
public int IdBill { get => idBill; set => idBill = value; }
public int IdProduct { get => idProduct; set => idProduct = value; }
public int Quantity { get => quantity; set => quantity = value; }
public int Price { get => price; set => price = value; }
public string NameProduct { get => nameProduct; set => nameProduct = value; }
}
}
<file_sep>/SellManage/MODEL/CONST.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MODEL
{
public class CONST
{
public static staff currenAcount;
public static bool checkCreatedBill = false;
public static customer customer = new customer();
// public staff CurrenAcount { get => currenAcount; set => currenAcount = value; }
}
}
<file_sep>/SellManage/MODEL/customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MODEL
{
public class customer
{
int id;
string name;
string address;
string phone;
string gender;
public int Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
public string Phone { get => phone; set => phone = value; }
public string Address { get => address; set => address = value; }
public string Gender { get => gender; set => gender = value; }
}
}
| ed1072a1bdd92fd06cbfe4a3fd52638d3258a8f6 | [
"C#",
"SQL"
] | 22 | C# | suppersentai/project_HK_5 | 677b31523e3b5b2341b2bd4ed852d818fb39f253 | 6c0e62e9677a68c19acfba35a4d127d8131fbf72 |
refs/heads/master | <file_sep>const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "twitter-eea49.firebaseapp.com",
databaseURL: "https://twitter-eea49.firebaseio.com",
projectId: "twitter-eea49",
storageBucket: "twitter-eea49.appspot.com",
messagingSenderId: "92511051399",
appId: "1:92511051399:web:1782d6c570c02003f42222"
};
export default firebaseConfig | 0048dc900d890cb9ecab06d99dc1ae0ba73c3508 | [
"JavaScript"
] | 1 | JavaScript | thomasgui06110/twitcoders | 83d5c3489ec75f354b736520033cd334ef5d948e | 4dca86228b46fa1bdf8a41474075e8de723d2716 |
refs/heads/master | <repo_name>Jankowski-J/python-utils<file_sep>/README.md
# python-utils
Simple utilites scripts for common tasks in Python
This repository contains some scripts for common tasks, that I've been dealing with then using python.
<file_sep>/stdin/console_controller.py
import threading
import time
NOOP_LAMBDA = (lambda: None)
class InputThread(threading.Thread):
last_user_input = None
input_callback = None
input_prompt = ""
def __init__(self, input_callback=None, input_prompt=""):
threading.Thread.__init__(self)
if input_callback is None:
input_callback = NOOP_LAMBDA
self.input_callback = input_callback
self.input_prompt = input_prompt
def run(self):
while True:
self.last_user_input = input(self.input_prompt)
self.input_callback(self.last_user_input)
def stop(self):
self.stop()
class WasdController:
w_callback = None
s_callback = None
a_callback = None
d_callback = None
input_thread = None
def __init__(self, w=NOOP_LAMBDA, s=NOOP_LAMBDA, a=NOOP_LAMBDA, d=NOOP_LAMBDA):
self.w_callback = w
self.s_callback = s
self.a_callback = a
self.d_callback = d
self.callback_dict = {
"w": self.w_callback,
"s": self.s_callback,
"a": self.a_callback,
"d": self.d_callback
}
self.keys = self.callback_dict.keys()
self.input_thread = InputThread(input_callback=(lambda x: self._handle_input(x)))
def _handle_input(self, input_string):
first_letter = input_string.lower()
if first_letter in self.keys:
callback = self.callback_dict[first_letter]
callback()
def stop(self):
self.input_thread.stop()
def start(self):
self.input_thread.start()
ctrl = WasdController()
ctrl.start()
while True:
time.sleep(1)
| 97413aa96af31bc14f240e134bb07be632628bdf | [
"Markdown",
"Python"
] | 2 | Markdown | Jankowski-J/python-utils | 2d0df9855924e58ba89d13977543cb5035dd6ab9 | b8c8eedb902eb62d58e44e69e3ca05f9284f6b21 |
refs/heads/master | <repo_name>JoseAMF/StrongSchool<file_sep>/src/app/pages/web-site/testimonial/testimonial.component.html
<div class="background">
<h2 class="text-white text-center pt-5">Testimonials</h2>
<hr class="divider mx-auto my-4" />
<div class="vertical-align">
<div class="custom-container mx-auto">
<div class="box">
<div class="content">
<img src="assets/Images/Quotes.png" alt="" class="quote">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Id maiores ipsum libero illo assumenda consequatur!</p>
<img src="assets/Images/user1.jpg" alt="" class="user">
<h3><NAME></h3>
</div>
</div>
<div class="box">
<div class="content">
<img src="assets/Images/Quotes.png" alt="" class="quote">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Id maiores ipsum libero illo assumenda consequatur!</p>
<img src="assets/Images/user2.jpg" alt="" class="user">
<h3><NAME></h3>
</div>
</div>
<div class="box">
<div class="content">
<img src="assets/Images/Quotes.png" alt="" class="quote">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Id maiores ipsum libero illo assumenda consequatur!</p>
<img src="assets/Images/user3.jpg" alt="" class="user">
<h3><NAME></h3>
</div>
</div>
</div>
</div>
</div>
<file_sep>/src/app/pages/web-site/nav-bar/nav-bar.component.ts
import { DOCUMENT } from '@angular/common';
import { ChangeDetectorRef, Component, Inject, Input, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit, OnDestroy {
collapsed = true;
hideNav = false;
currentPosition;
@Input() Home;
@Input() AboutUs;
@Input() Testimonial;
@Input() Contato;
constructor(@Inject(DOCUMENT) private document: Document, private ref: ChangeDetectorRef) {
// Adiciona um Listener para o evento de scroll na página inteira
this.document.addEventListener('scroll', this.onContentScrolled.bind(this));
}
ngOnDestroy() {
// Remove o Listener
this.document.removeEventListener('scroll', this.onContentScrolled);
}
onContentScrolled(e) {
const scroll = window.pageYOffset;
if (scroll > this.currentPosition) {
this.hideNav = true;
this.collapsed = true;
} else {
this.hideNav = false;
}
this.currentPosition = scroll;
this.ref.detectChanges();
}
ngOnInit(): void {
}
}
<file_sep>/src/app/pages/web-site/web-site.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { WebSiteRoutingModule } from './web-site-routing.module';
import { AboutUsComponent } from './about-us/about-us.component';
import { CarouselComponent } from './carousel/carousel.component';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { TestimonialComponent } from './testimonial/testimonial.component';
import { HomePageComponent } from './home-page/home-page.component';
import { ContactComponent } from './contact/contact.component';
@NgModule({
declarations: [AboutUsComponent, CarouselComponent, NavBarComponent, TestimonialComponent, HomePageComponent, ContactComponent],
imports: [
CommonModule,
WebSiteRoutingModule
]
})
export class WebSiteModule { }
<file_sep>/src/app/pages/erp/erp.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ERPRoutingModule } from './erp-routing.module';
@NgModule({
declarations: [],
imports: [
CommonModule,
ERPRoutingModule
]
})
export class ERPModule { }
| 39f23e6a1c2adcb1dc14c84cd3bc009f981005d5 | [
"TypeScript",
"HTML"
] | 4 | HTML | JoseAMF/StrongSchool | 13e93a15b14653eda9496adb28198a3b9334f888 | eabbf70dcfd20cdb2a375ba566791dbd3ea5fa80 |
refs/heads/master | <repo_name>LiammCodes/liams-discord-bot<file_sep>/TwitchNotifier.js
require('dotenv').config()
const TwitchAPI = require('node-twitch').default
const { MessageEmbed, Channel } = require('discord.js')
module.exports = class TwitchNotifier {
constructor(client, twitchName) {
this.client = client
this.twitchName = twitchName
// different channel for my stream notifications
if (this.twitchName === "liama6") {
this.CHANNEL_ID = process.env.DISCORD_NOTIFICATIONS_ID
} else {
this.CHANNEL_ID = process.env.DISCORD_SELF_PROMOS_ID
}
// initialize twitch api
this.twitch = new TwitchAPI({
client_id: process.env.TWITCH_CLIENT,
client_secret: process.env.TWITCH_SECRET
})
// twitch live flag
this.lastStatus = false
this.currentStatus = false
this.offlineCount = 5
}
// Function to send notification when live
async send_embed(data) {
const notifChannel = this.client.channels.cache.find(channel => channel.id === this.CHANNEL_ID)
console.log(`Live Status: ${this.currentStatus} \n Response: ${data} \n Offline Count: ${this.offlineCount}`)
console.log(` Start Time: ${data.started_at} \n ImageURL: ${data.getThumbnailUrl({width: 1600, height: 900})}`)
// send live notification
if (this.currentStatus === true && this.lastStatus === false && data != undefined){
let live_time = new Date(data.started_at).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', timeZone: 'Canada/Eastern', timeZoneName: 'short'})
let user = await this.twitch.getUsers(this.twitchName).then(async d => { return d.data[0] })
let game_title = ""
if (data.game_id != undefined){
game_title = await this.twitch.getGames(data.game_id).then(async d => { return d.data[0].name })
} else {
game_title = "nothing"
}
const liveNotificationMsg = new MessageEmbed()
.setColor('#FF3854')
.setTitle(`${data.title}`)
.setURL(`https://twitch.tv/${user.login}`)
.setDescription(`${user.display_name} is now live on Twitch!`)
.setThumbnail(`${user.profile_image_url}`)
.addFields(
{ name: 'Start time:', value: `${live_time}`, inline: true },
{ name: 'Playing', value: `${game_title}`, inline: true },
)
.setImage(`${data.getThumbnailUrl({width: 1920, height: 1080})}`)
.setTimestamp()
notifChannel.send({
content: '@everyone',
embeds: [liveNotificationMsg]
})
}
}
async run() {
await this.twitch.getStreams({
channel: this.twitchName
})
.then(async data => {
const response = data.data[0]
// Manage response memory
if (response !== undefined) {
// channel is live
if (response.type === "live") {
if (this.currentStatus === false && this.lastStatus === false) {
this.lastStatus = this.currentStatus
this.currentStatus = true
}
this.offlineCount = 0
// channel is offline
} else {
if (this.currentStatus === true && this.lastStatus === true && this.offlineCount > 4) {
this.currentStatus = false
this.lastStatus = false
this.offlineCount = 0
}
this.offlineCount++
}
// send notification
this.send_embed(response)
this.lastStatus = this.currentStatus
// channel is also offline
} else {
if (this.currentStatus === true && this.lastStatus === true && this.offlineCount > 4) {
this.currentStatus = false
this.lastStatus = false
this.offlineCount = 0
} else if (this.offlineCount < 5){
this.offlineCount++
}
}
console.log(`Name: ${this.twitchName} \n Live: ${this.currentStatus} \n Offline count: ${this.offlineCount}`)
})
}
start() {
this.interval = setInterval(() => {this.run()}, 15000)
}
stop() {
clearInterval(this.interval)
}
} | 78ce6f58f98adadbe98d1665de00745dca804f42 | [
"JavaScript"
] | 1 | JavaScript | LiammCodes/liams-discord-bot | d72548d80244b3e782449a99d6e243b88ce90236 | a57d48a433750d1d6845cb8acb1ae5237e25a5c1 |
refs/heads/master | <file_sep>## Various projects related to master thesis
<file_sep>import sys
# This script tries to determine a list of libraries used by an app based on a
# list of imports made by it in the form of __sorted__ new-line- or space-separated
# list of package names (or, generally, anything which can be put after
# "import" statement in java).
# The algorithm to obtain a list of unique libraries is quite simple.
# It iterates over package names and calculates a distance between current and
# previous package name. The distance is simply a number of package name
# segments identical in both package names, counting from the beginning.
# If the distance is less than 2 (i.e. package names differ already on second
# segment) the current package name is assumed to belong to different library
# and is printed.
# calculates similarity as a number of package name segments
# equal in both package names, counting from beginning
def calculate_similarity(a, b):
sim = 0
for i in range(0, min(len(a), len(b))):
if a[i] == b[i]:
sim += 1
else:
break
return sim
# takes string which is a sorted list of imported classes
def process(imports_str):
imports_list = imports_str.replace("\n", " ").split(" ")
print "Read %d entries" % len(imports_list)
imports_list = [x.split(".") for x in imports_list]
if len(imports_list) < 2:
return
current_a = imports_list[0]
last_similarity = len(current_a)
for i in range(1, len(imports_list)):
current_b = imports_list[i]
similarity = calculate_similarity(current_a, current_b)
if similarity < 2:
# current_b represents next library
print ".".join(current_a[:last_similarity])
last_similarity = len(current_b)
else:
last_similarity = similarity
current_a = current_b
def main():
input_str = sys.stdin.read()
process(input_str)
if __name__ == "__main__":
main()
<file_sep>#!/bin/bash
# The script which downloads source code of apps from fdroid repository.
# Takes as argument a file with a list of entries in the form of
# <package_name>:<version_code>
if [[ "$#" -ne 1 ]]; then
echo "Usage: $0 <pkg_names_list_file>"
exit 0
fi
RED='\033[0;31m'
NC='\033[0m'
while read p
do
echo -e "${RED}Invoking fdroid scanner $p${NC}"
fdroid scanner $p
done < $1
<file_sep>import sys
import os
import glob
import re
import fnmatch
main_build_gradle_patch = """
// PITest support
buildscript {
repositories {
mavenLocal()
}
dependencies {
classpath 'pl.droidsonroids.gradle:gradle-pitest-plugin:%s'
}
}
"""
module_build_gradle_patch = """
// PITest support
apply plugin: 'pl.droidsonroids.pitest'
pitest {
pitestVersion = "2.2.1337"
targetClasses = ['%s.*']
targetTests = ['%s.*']
mutators = ['EXPERIMENTAL_ALWAYS_TRUE_HOSTNAME_VERIFIER',
'EXPERIMENTAL_ALWAYS_TRUSTING_TRUST_MANAGER',
'EXPERIMENTAL_VULNERABLE_SSL_CONTEXT_PROTOCOL',
'EXPERIMENTAL_HTTPS_TO_HTTP']
}
"""
def find_package_name(path):
found_files = []
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, "AndroidManifest.xml"):
found_files.append(os.path.join(root, filename))
if len(found_files) == 0:
print "[-] find_package_name: Unable to find AndroidManifest.xml"
return None
if len(found_files) > 1:
print "[!] find_package_name: More than one AndroidManifest.xml"
# try every AndroidManifest.xml found, except these, which path contains '/build/'.
# Such manifests usually contain applicationId instead of 'real' packageId.
for manifest in found_files:
if "/build/" in manifest:
continue
# read AndroidManifest.xml and find package name
with open(manifest, "r") as f:
xml = f.read()
result = re.search("package=\"(\S+)\"", xml)
if result:
package_name = result.group(1)
print "[*] find_package_name: Found package name: %s" % package_name
return package_name
else:
print "[-] find_package_name: Couldn't find package name in %s" % manifest
print "[-] find_package_name: Couldn't find package name in any of manifest files"
return None
def make_file_copy(file_path):
copy_path = file_path + ".cpy"
if os.path.exists(file_path):
if not os.path.exists(copy_path):
os.rename(file_path, copy_path)
else:
print "[*] make_file_copy: %s already exists" % copy_path
return copy_path
else:
print "[-] make_file_copy: %s does not exist" % file_path
return None
return copy_path
def do_patch(root_dir):
print "[*] Root dir: %s" % root_dir
everything_succeeded = True
package_name = find_package_name(root_dir)
if not package_name:
print "[-] Unable to get package name, exiting"
return 2
# 1. Modify root build.gradle file
build_gradle_path = os.path.join(root_dir, "build.gradle")
build_gradle_cpy_path = make_file_copy(build_gradle_path)
if not build_gradle_cpy_path:
print "[-] Unable to do a file copy, exiting"
return 2
build_gradle = open(build_gradle_cpy_path, "r")
buildscript = build_gradle.read()
build_gradle.close()
# determine PITest plugin version needed. Find 'com.android.tools.build:gradle:x.x.x'
# If the version is 3.x.x or above, use plugin version 0.1.4, otherwise choose version
# 0.0.11
gradle_plugin_version = "0.0.11"
gradle_dependency = re.search("com.android.tools.build:gradle:([0-9])", buildscript)
if gradle_dependency:
if gradle_dependency.group(1) == "3":
gradle_plugin_version = "0.1.4"
elif gradle_dependency.group(1) != "2":
print "[!] Unknown main version of gradle: %s" % gradle_dependency.group(1)
everything_succeeded = False
else:
print "[!] Unable to determine gradle version"
everything_succeeded = False
print "[*] Using gradle plugin version %s" % gradle_plugin_version
# add additional repository mavenLocal() and gradle plugin dependency
buildscript += main_build_gradle_patch % gradle_plugin_version
# check if android {} block is present in file. If it is, than there is
# a big chance that it is old-style build.gradle structure with everything
# in one file. In such case, add also the patch as for module build.gradle files
if re.search("android[\s]+{", buildscript):
print "[*] Found android {} block in root build.gradle; appending module patch"
buildscript += module_build_gradle_patch % (package_name, package_name)
print "[+] Patching root build.gradle (%s)" % build_gradle_path
new_build_gradle = open(build_gradle_path, "w")
new_build_gradle.write(buildscript)
new_build_gradle.close()
# 2. Find build.gradle files in modules and append PITest config to them
for module_build_gradle in glob.glob(os.path.join(root_dir, "*/build.gradle")):
print "[*] Found module script: %s" % module_build_gradle
copy = make_file_copy(module_build_gradle)
if copy:
build_gradle = open(copy, "r")
buildscript = build_gradle.read()
build_gradle.close()
# add PITest config
buildscript += module_build_gradle_patch % (package_name, package_name)
print "[+] Patching module build.gradle (%s)" % module_build_gradle
new_build_gradle = open(module_build_gradle, "w")
new_build_gradle.write(buildscript)
new_build_gradle.close()
else:
print "[!] Unable to do a file copy, skipping!"
everything_succeeded = False
if everything_succeeded:
print "[+] All done"
return 0
else:
print "[+] Finished, but some tasks failed"
return 1
if __name__ == '__main__':
res = 0
if len(sys.argv) > 1:
res = do_patch(sys.argv[1])
else:
res = do_patch(os.getcwd())
sys.exit(res)
<file_sep>#!/bin/bash
# This script takes a directory of Android apps (each app in different subdirectory)
# and, for each of them, tries to obtain a list of external libs that they use.
# It does that by grepping all the java source files for "import ..." lines, sorting them,
# removing repeating lines and submitting the resulting list to a python script. That
# script then tries to determine a list of libraries used (see determine_libs.py source
# code).
# Note: this script assumes 1 parameter will be given: a directory which contains
# subdirectories which are roots for source code of Android apps. It also assumes
# that these subdirectories' names will be package names of corresponding apps.
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <dir_with_apps>"
exit 1
fi
WORKING_DIR=$1
echo "Working dir is $WORKING_DIR"
for dir in $WORKING_DIR/*/ ; do
echo "[.] Processing $dir"
package_name=$(basename $dir)
# echo "[.] Package name is $package_name"
# get unique imports, filter out java.*, android.* and package_name.* packages
# and remove "import" and semicolons from lines
# todo: dots in $package_name may have impact on regex
imports=$(egrep -rh --include=*.java "^import " $dir | sort -u \
| egrep -v "^import (static )?(java|android|$package_name)\..*" \
| sed 's/import static //;s/import //;s/;//')
echo "[.] Running libs determinator..."
# determine unique libraries
uniq_libs=$(echo $imports | python determine_libs.py)
echo "$uniq_libs"
echo ""
done
| df2836962db0481d1722e4620be635403f6108b9 | [
"Markdown",
"Python",
"Shell"
] | 5 | Markdown | kkieczka/mgr | d6d215ddc54492398d36b11059e00397c852c995 | 174fa659a368656026898f440a9bc20fc9a0fcf8 |
refs/heads/master | <repo_name>ming3000/go_by_example<file_sep>/atomic_counters/atomic_add.go
package main
import (
"sync"
"sync/atomic"
"runtime"
"fmt"
)
var counter int64
var wg sync.WaitGroup
func incCounter() {
defer wg.Done()
for count := 0; count < 2; count++ {
atomic.AddInt64(&counter, 1)
runtime.Gosched()
}
}
func main() {
wg.Add(2)
go incCounter()
go incCounter()
wg.Wait()
fmt.Println("final counter:", counter)
}
<file_sep>/README.md
# go_by_example
go_by_example
<file_sep>/line_filters/line_filters.go
package main
import (
"os"
"bufio"
"fmt"
"strings"
)
func main() {
f, err := os.Open("_data/test_read_lines.txt")
if err != nil {
panic(err)
}
defer f.Close()
myScanner := bufio.NewScanner(f)
for myScanner.Scan() {
lineText := myScanner.Text()
fmt.Println(lineText)
lineByte := myScanner.Bytes()
fmt.Println(lineByte)
fmt.Println(strings.Repeat("-", 50))
}
if err = myScanner.Err(); err != nil {
panic(err)
}
}
<file_sep>/constants/constants.go
package main
import "fmt"
const g_s string = "the global constant"
func main() {
fmt.Println(g_s)
const l_s = "the local constant"
fmt.Println(l_s)
}
<file_sep>/goroutines/goroutines.go
package main
import (
"sync"
"fmt"
"strings"
)
var wGroup sync.WaitGroup
func init() {
wGroup.Add(2)
}
func main() {
go testRoutine("test routine 1")
go testRoutine("test routine 2")
wGroup.Wait()
fmt.Println(strings.Repeat(">", 50))
fmt.Println("main meet the end")
}
func testRoutine(from string) {
defer wGroup.Done()
for i := 0; i < 10; i++ {
fmt.Println(from, ": ", i)
}
}
<file_sep>/panic/panic.go
package main
import "fmt"
func main() {
panic("a panic happen")
// won't execute
fmt.Println("lalala")
}
<file_sep>/exit/exit.go
package main
import (
"fmt"
"os"
)
func testDefer() {
defer fmt.Println("can you see me")
}
func main() {
testDefer()
// won't be print
defer fmt.Println("you can't see me")
os.Exit(233)
}
<file_sep>/reading_files/reading_files.go
package main
import (
"fmt"
"strings"
"io/ioutil"
"os"
"bufio"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func main() {
data, err := ioutil.ReadFile("_data/test_read.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))
fmt.Println(strings.Repeat(">", 50))
f, err := os.Open("_data/test_read.txt")
if err != nil {
panic(err)
}
defer f.Close()
byte1 := make([]byte, 5)
count1, _ := f.Read(byte1)
fmt.Printf("read: %d bytes, strings is: %s \n", count1, string(byte1))
fmt.Println(strings.Repeat(">", 50))
offset2, _ := f.Seek(6, 0)
byte2 := make([]byte, 10)
count2, _ := f.Read(byte2)
fmt.Printf("read %d bytes @ %d: %s \n", count2, offset2, byte2)
// reset the offset pointer
offset3, _ := f.Seek(0, 0)
byte3 := make([]byte, 10)
count3, _ := f.Read(byte3)
fmt.Printf("read %d bytes @ %d: %s \n", count3, offset3, byte3)
fmt.Println(strings.Repeat(">", 50))
// buf io
bufedFile := bufio.NewReader(f)
byte4, _ := bufedFile.Peek(10)
fmt.Println("bufed read 10, byte:", byte4)
fmt.Println("bufed read 10, string:", string(byte4))
fmt.Println(strings.Repeat(">", 50))
}
<file_sep>/variables/variables.go
package main
import (
"fmt"
"strings"
)
func main() {
var a string = "initial"
var b int = 3
fmt.Println(a, b)
fmt.Println(strings.Repeat("-", 30))
var aa string
var bb int
fmt.Println(aa, bb)
fmt.Println(strings.Repeat("-", 30))
var c, d int = 1, 2
fmt.Println(c, d)
var cc, dd = 33, "ss"
fmt.Println(cc, dd)
fmt.Println(strings.Repeat("-", 30))
var e = true
var f = 3.14
fmt.Println(e, f)
fmt.Println(strings.Repeat("-", 30))
x := "short"
y := false
fmt.Println(x, y)
fmt.Println(strings.Repeat("-", 30))
}
<file_sep>/non_blocking_channel_operations/block_tx.go
package main
import (
"fmt"
"time"
)
func main() {
msg := make(chan string, 1)
go func() {
time.Sleep(time.Second * 3)
fmt.Println("routine,", <-msg)
}()
for i := 0; i < 2; i++ {
msg <- "hahaha"
fmt.Printf("main, the %d times tx\n", i)
}
}
<file_sep>/sha1_hashes/sha1_hashes.go
package main
import (
"crypto/sha1"
"fmt"
)
func main() {
str1 := "this is a test str, first"
str2 := "this is a test str, second"
mSha1 := sha1.New()
mSha1.Write([]byte(str1))
ret1 := mSha1.Sum(nil)
fmt.Printf("raw ret:%s, hex ret:%x \n", ret1, ret1)
mSha1.Write([]byte(str2))
ret2 := mSha1.Sum(nil)
fmt.Printf("raw ret:%s, hex ret:%x \n", ret2, ret2)
}<file_sep>/if_else/if_else.go
package main
import "fmt"
func main() {
flag := false
if flag {
fmt.Println("is true")
} else {
fmt.Println("is false")
}
name := "golang"
if name == "golang" {
fmt.Println("name is", name)
}
if num := 1; num < 0 {
fmt.Println(num, " is small than 0")
} else {
fmt.Println(num, " is big than 0")
}
}
<file_sep>/slices/slices.go
package main
import (
"fmt"
"strings"
)
func main() {
a := make([]string, 5)
b := []string{"go", "python", "javascript"}
fmt.Println(a, b)
fmt.Println(len(a), len(b))
fmt.Println(strings.Repeat("-", 10))
a[0] = "flask"
a[1] = "gin"
a[2] = "express"
fmt.Println("a:", a)
fmt.Println(strings.Repeat("-", 10))
// notice the len, a[3], a[4] is default value
a = append(a, "django")
fmt.Println("a:", a)
fmt.Println("len a:", len(a))
fmt.Println(strings.Repeat("-", 10))
a = append(a, "yii", "laravel")
fmt.Println("a:", a)
fmt.Println("len a:", len(a))
fmt.Println(strings.Repeat("-", 10))
c := make([]string, len(a))
copy(c, a)
fmt.Println("copy a:", c)
fmt.Println(strings.Repeat("-", 10))
l := a[3:5]
fmt.Println("notice, l, 3:5", l)
l = a[3:6]
fmt.Println("l, 3:6", l)
l = a[:6]
fmt.Println("l, :6", l)
l = a[5:]
fmt.Println("l, 5:", l)
fmt.Println(strings.Repeat("-", 10))
}
<file_sep>/url_parsing/url_parsing.go
package main
import (
"net/url"
"fmt"
"strings"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func myParser(urlStr string) {
urlDst, err := url.Parse(urlStr)
if err != nil {
panic(err)
}
fmt.Println(urlDst.Scheme)
fmt.Println(urlDst.Host)
fmt.Println(urlDst.Path)
fmt.Println(urlDst.Fragment)
line()
fmt.Println(urlDst.User)
fmt.Println(urlDst.User.Username())
fmt.Println(urlDst.User.Password())
line()
fmt.Println(urlDst.RawQuery)
m, _ := url.ParseQuery(urlDst.RawQuery)
fmt.Println(m)
}
func main() {
pgs := "postgres://user:pass@host.com:5432/path?k=v#f"
myParser(pgs)
fmt.Println(strings.Repeat(">", 50))
mgs := "mongodb://db1.example.net:27017,db2.example.net:2500/test_db/?replicaSet=test"
myParser(mgs)
fmt.Println(strings.Repeat(">", 50))
mons := "mongodb://admin:123456@localhost/test_db/?_id=111"
myParser(mons)
}
<file_sep>/time_formatting_parsing/time_formatting_parsing.go
package main
import (
"fmt"
"strings"
"time"
"reflect"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func main() {
t := time.Now()
tStr := fmt.Sprintf("string_datetime:%d_%02d_%02d__%02d:%02d:%02d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
fmt.Println(tStr)
line()
fmt.Printf("current_date:%d_%02d_%02d \n",
t.Year(), t.Month(), t.Day())
fmt.Printf("current_time:%02d:%02d:%02d \n",
t.Hour(), t.Minute(), t.Second())
fmt.Printf("current_datetime:%d_%02d_%02d__%02d:%02d:%02d \n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
line()
fmt.Println(t.Format(time.ANSIC))
fmt.Println(t.Format(time.RFC3339))
line()
// second must be 0x format, can not be xx format
fmt.Println(t.Format("2006-01-02 15:30:02"))
fmt.Println(t.Format("2006-01-02 15:30:20"))
fmt.Println(t.Format("2006-01-02T15:03"))
line()
pt, err := time.Parse(time.RFC3339, "2018-05-03T09:10:30+08:00")
if err != nil {
panic(err)
}
fmt.Println(reflect.TypeOf(pt), pt)
line()
// the layout must be 2006-01-02 15:04:05, others wont be affected
pt, err = time.Parse("2006-01-02 15:04:05", "2018-05-03 09:18:30")
if err != nil {
panic(err)
}
fmt.Println(reflect.TypeOf(pt), pt)
line()
pt, err = time.Parse("2006-01-02", "2018-06-23")
if err != nil {
panic(err)
}
fmt.Println(reflect.TypeOf(pt), pt)
line()
// anyway, the layout must be the day of "2006 01 02"
pt, err = time.Parse("2006_01_02", "2018_06_23")
if err != nil {
panic(err)
}
fmt.Println(reflect.TypeOf(pt), pt)
line()
pt, err = time.Parse("2006_01_02_15_04_05", "2018_06_23_09_30_02")
if err != nil {
panic(err)
}
fmt.Println(reflect.TypeOf(pt), pt)
line()
}
<file_sep>/for/for.go
package main
import (
"fmt"
"bufio"
"os"
"strings"
)
func main() {
i := 1
for i < 3 {
fmt.Println(i)
i++
}
for j := 5; j < 10; j++ {
fmt.Println(j)
}
inputReader := bufio.NewReader(os.Stdin)
for {
fmt.Println("typein >>>")
in, _ := inputReader.ReadString('\n')
in = strings.Trim(in, "\n")
if in == "exit" {
break
}
fmt.Println("input: ", in)
}
}
<file_sep>/number_parsing/number_parsing.go
package main
import (
"fmt"
"strings"
"strconv"
"reflect"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func main() {
i, _ := strconv.ParseInt("123", 0, 64)
fmt.Println(reflect.TypeOf(i), i)
// bitsize useless
i, _ = strconv.ParseInt("567",0, 32)
fmt.Println(reflect.TypeOf(i), i)
line()
// base is 8, 10, 16, 0 is auto detect
i, _ = strconv.ParseInt("0xFF",0, 64)
fmt.Println(reflect.TypeOf(i), i)
i, _ = strconv.ParseInt("123", 16, 64)
fmt.Println(reflect.TypeOf(i), i)
i, _ = strconv.ParseInt("0xFF", 10, 64)
fmt.Println(reflect.TypeOf(i), i)
line()
// bitsize is 32, 64
f, _ := strconv.ParseFloat("3.14", 64)
fmt.Println(reflect.TypeOf(f), f)
b, _ := strconv.ParseBool("false")
fmt.Println(reflect.TypeOf(b), b)
line()
// shortcut
v, e := strconv.Atoi("999")
fmt.Println(v, e)
v, e = strconv.Atoi("diango")
fmt.Println(v, e)
line()
}
<file_sep>/variadic_functions/variadic_functions.go
package main
import (
"fmt"
"strings"
)
func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
fmt.Println("input:", nums)
fmt.Println("result:", total)
fmt.Println(strings.Repeat("-", 10))
return total
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4, 5}
sum(nums...)
}
<file_sep>/channels/channels.go
package main
import (
"sync"
"fmt"
)
var wGroup sync.WaitGroup
func init() {
wGroup.Add(1)
}
func main() {
msgs := make(chan string)
go testChannel(msgs)
back := <- msgs
fmt.Println("rx message:", back)
wGroup.Wait()
fmt.Println("main meet the end")
}
func testChannel(ch chan string) {
fmt.Println("a new routine start")
defer wGroup.Done()
ch <- "ping ping ping"
}
<file_sep>/errors/errors.go
package main
import (
"errors"
"fmt"
"strings"
)
// ------------------------------------
func errorCmd(cmd string) (string, error) {
if cmd == "error" {
return cmd, errors.New("i love the way you lie")
}
return cmd, nil
}
// ------------------------------------
type myError struct {
code int
message string
}
func (e * myError) Error() string {
return fmt.Sprintf("error code: %d, error message: %s", e.code, e.message)
}
func errorCmd2(cmd string) (string , error) {
if cmd == "error" {
errObj := myError{code:500, message:"pressure, pushing down on me"}
return cmd, &errObj
}
return cmd, nil
}
// ------------------------------------
func main() {
_, err := errorCmd("haha")
if err != nil {
fmt.Println("errorCmd return error:", err)
} else {
fmt.Println("errorCmd return no error")
}
fmt.Println(strings.Repeat("-", 20))
// best practice
if _, err = errorCmd("error"); err != nil {
fmt.Println("errorCmd return error:", err)
} else {
fmt.Println("errorCmd return no error")
}
fmt.Println(strings.Repeat("-", 20))
_, err = errorCmd2("haha")
if err != nil {
fmt.Println("errorCmd2 return error:", err)
} else {
fmt.Println("errorCmd2 return no error")
}
fmt.Println(strings.Repeat("-", 20))
// best practice
if _, err = errorCmd2("error"); err != nil {
fmt.Println("errorCmd2 return error:", err)
} else {
fmt.Println("errorCmd2 return no error")
}
fmt.Println(strings.Repeat("-", 20))
}
<file_sep>/pointers/pointers.go
package main
import "fmt"
func zeroValue(iValue int) {
iValue = 0
}
func zeroPtr(iPtr *int) {
*iPtr = 0
}
func main() {
i := 1
fmt.Println("initial, value:", i)
fmt.Println("pointer, value:", &i)
zeroValue(i)
fmt.Println("after zeroValue, value:", i)
zeroPtr(&i)
fmt.Println("after zeroPtr, value:", i)
}
<file_sep>/epoch/epoch.go
package main
import (
"time"
"fmt"
)
func main() {
now := time.Now()
fmt.Println(now)
secs := now.Unix()
fmt.Println(secs)
day := time.Unix(secs, 0)
fmt.Println(day)
}
<file_sep>/non_blocking_channel_operations/non_block_rx.go
package main
import (
"time"
"fmt"
)
func main() {
msg := make(chan string)
go func() {
time.Sleep(time.Second * 5)
msg <- "head"
}()
select {
case res := <-msg:
fmt.Println("main rx: ", res)
default:
fmt.Println("default, no block")
}
}
<file_sep>/environment_variables/environment_variables.go
package main
import (
"os"
"fmt"
"strings"
)
func main() {
os.Setenv("foo", "233")
ret := os.Getenv("foo")
fmt.Println("env foo:", ret)
ret = os.Getenv("bar")
fmt.Println("env bar:", ret)
fmt.Println(strings.Repeat(">", 50))
for _, value := range os.Environ() {
valuePair := strings.Split(value, "=")
fmt.Println("env:", valuePair[0])
}
fmt.Println(strings.Repeat(">", 50))
}
<file_sep>/multiple_return_values/multiple_return_values.go
package main
import "fmt"
func vals(a int, b int) (int, int) {
return a, b
}
func main() {
a, b := vals(3, 5)
fmt.Println("return value:", a, b)
_, c := vals(7, 11)
fmt.Println("return value:", c)
}
<file_sep>/worker_pools/worker_pools.go
package main
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, rets chan<- string) {
for j := range jobs {
fmt.Println("worker:", id, "processing job:", j)
time.Sleep(time.Second)
rets <- fmt.Sprintf("result of the job %d", j)
}
}
func main() {
jobs := make(chan int, 100)
rets := make(chan string, 100)
for w :=0; w < 3; w++ {
go worker(w, jobs, rets)
}
for j := 0; j < 10; j++ {
jobs <- j
}
close(jobs)
for a := 0; a < 10; a++ {
ret := <- rets
fmt.Println(ret)
}
}
<file_sep>/sorting/sorting.go
package main
import (
"sort"
"fmt"
)
func main() {
// 就地排序,改变原有序列,无返回值
strs := []string{"e", "a", "g", "k"}
sort.Strings(strs)
fmt.Println(strs)
ints := []int{98, 1, 33, 5, 76}
sort.Ints(ints)
fmt.Println(ints)
}
<file_sep>/range/range.go
package main
import (
"fmt"
)
func main() {
arrayNums := [3]int{1, 2, 3}
for _, num := range arrayNums {
fmt.Print(num, ",")
}
fmt.Println()
sliceNums := []int{5, 6, 7}
for i, num := range sliceNums {
fmt.Printf("index %d is %d, ", i, num)
}
fmt.Println()
mapNums := map[string]string{"a": "python", "b": "golang", "c": "node.js"}
for k, v := range mapNums {
fmt.Printf("key %s is %s, ", k, v)
}
fmt.Println()
for i, c := range "node.js" {
fmt.Println(i, c)
}
}
<file_sep>/structs/structs.go
package main
import (
"fmt"
"strings"
)
type person struct {
name string
age int
}
func main() {
var one person
fmt.Println("one: ", one)
one = person{name:"alice", age:30}
fmt.Println("one: ", one)
one = person{name:"fred"}
fmt.Println("one: ", one)
one = person{"jack", 20}
fmt.Println("one: ", one)
one = person{"pool", 35}
fmt.Println("one.name: ", one.name)
one.name = "dead pool"
fmt.Println("one.name: ", one.name)
fmt.Println(strings.Repeat("-", 10))
two := &person{name:"ant", age:30}
fmt.Println("two: ", two)
fmt.Println("two.name: ", two.name)
two.name = "<NAME>"
fmt.Println("two.name: ", two.name)
}
<file_sep>/non_blocking_channel_operations/non_block_tx.go
package main
import (
"fmt"
"time"
)
func main() {
msg := make(chan string, 1)
go func() {
time.Sleep(time.Second * 3)
fmt.Println("routine,", <-msg)
}()
for i := 0; i < 2; i++ {
select {
case msg <- "hahaha":
fmt.Printf("main, the %d times tx\n", i)
default:
fmt.Println("default, no block")
}
}
}
<file_sep>/writing_files/writing_files.go
package main
import (
"fmt"
"strings"
"io/ioutil"
"os"
"bufio"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func main() {
data1 := []byte("hello golang\n")
err := ioutil.WriteFile("_data/test_write_1.txt",
data1, 0644)
if err != nil {
panic(err)
}
f, err := os.Create("_data/test_write_2.txt")
if err != nil {
panic(err)
}
defer f.Close()
data2 := []byte("my blood gets heavy when you are here...\n")
count2, _ := f.Write(data2)
fmt.Printf("write %d bytes \n", count2)
// notice the \n here
count3, _ := f.WriteString("i can't turn my soul, when you are here...\n")
fmt.Printf("write %d bytes \n", count3)
// sync
f.Sync()
bufFile := bufio.NewWriter(f)
count4, _ := bufFile.WriteString("everything gone...\n")
fmt.Printf("write %d bytes \n", count4)
// flush
bufFile.Flush()
}
<file_sep>/channel_synchronization/channel_synchronization.go
package main
import (
"fmt"
"time"
)
func main() {
flagChan := make(chan bool)
go workerRoutine(flagChan)
ret := <-flagChan
if ret {
fmt.Println("work done")
} else {
fmt.Println("work delay")
}
fmt.Println("main meet the end")
}
func workerRoutine(ch chan bool) {
fmt.Println("worker routine start working...")
time.Sleep(time.Second * 5)
fmt.Println("worker routine done work...")
ch <- true
}
<file_sep>/random_numbers/random_numbers.go
package main
import (
"math/rand"
"fmt"
"time"
"strings"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func main() {
var randNum int
randNum = rand.Int()
fmt.Println(randNum)
randNum = rand.Intn(100)
fmt.Println(randNum)
randNum = rand.Intn(10)
fmt.Println(randNum)
line()
var randFloat float64
randFloat = rand.Float64()
fmt.Println(randFloat)
randFloat = rand.Float64()
fmt.Println(randFloat)
line()
src1 := rand.NewSource(42)
gen1 := rand.New(src1)
fmt.Println(gen1.Intn(10), gen1.Intn(10))
// so the same source, generate the same rand num
src2 := rand.NewSource(42)
gen2 := rand.New(src2)
fmt.Println(gen2.Intn(10), gen2.Intn(10))
line()
//use a variable source, will generate the variable num
newSrc1 := rand.NewSource(time.Now().UnixNano())
newGen1 := rand.New(newSrc1)
fmt.Println(newGen1.Intn(10), newGen1.Intn(10))
//use a variable source, will generate the variable num
newSrc2 := rand.NewSource(time.Now().UnixNano())
newGen2 := rand.New(newSrc2)
fmt.Println(newGen2.Intn(10), newGen2.Intn(10))
line()
}
<file_sep>/json/json.go
package main
import (
"encoding/json"
"fmt"
"strings"
"os"
)
type Book struct {
Name string `json:"the_book_name"`
Authors []string `json:"the_author_list"`
}
type User struct {
Name string
Age int
phone string
}
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func marshals() {
jBool, _ := json.Marshal(true)
fmt.Println(string(jBool))
jInt, _ := json.Marshal(3)
fmt.Println(string(jInt))
jStr, _ := json.Marshal("golang")
fmt.Println(string(jStr))
line()
jSlice, _ := json.Marshal([]string{"python", "golang", "node.js"})
fmt.Println(string(jSlice))
jMap, _ := json.Marshal(map[string]int{"apple": 5, "lettuce": 7})
fmt.Println(string(jMap))
line()
objBook := Book{
Name: "Node.js Design Patterns",
Authors: []string{"<NAME>", "<NAME>", "冯康", " 孙光金", " 丁全"},
}
retBook, _ := json.Marshal(objBook)
fmt.Println(string(retBook))
objUser := &User{
Name: "kafka",
Age: 30,
// won't be marshaled
phone: "15623093333",
}
retUser, _ := json.Marshal(objUser)
fmt.Println(string(retUser))
}
func userUnMarshals() {
by := []byte(`{"Name": "json", "Age": 50}`)
var obj map[string]interface{}
if err := json.Unmarshal(by, &obj); err != nil {
panic(err)
}
fmt.Println(obj)
name := obj["Name"].(string)
// must be float64, can not be int...
age := obj["Age"].(float64)
fmt.Printf("result, Name is %s, Age is %f \n", name, age)
line()
userStr := `{"Name": "wwj", "Age": 31}`
userObj := User{}
err := json.Unmarshal([]byte(userStr), &userObj)
if err != nil {
panic(err)
}
fmt.Println(userObj)
fmt.Printf("user name is:%s, age is:%d", userObj.Name, userObj.Age)
}
func bookUnMarshal() {
by := []byte(`{"name": "go in action", "authors": ["<NAME>", "<NAME>", "<NAME>"]}`)
var obj map[string]interface{}
if err := json.Unmarshal(by, &obj); err != nil {
panic(err)
}
fmt.Println(obj)
name := obj["name"].(string)
fmt.Println("name:", name)
tempStr := obj["authors"].([]interface{})
author1 := tempStr[0].(string)
fmt.Println("first author:", author1)
author2 := tempStr[1].(string)
fmt.Println("second author:", author2)
line()
// TODO, watch out of this! both two are wrong!
//bookStr := `{"name": "go in action", "authors": ["<NAME>", "<NAME>", "<NAME>"]}`
//bookStr := `{"Name": "go in action", "Authors": ["<NAME>", "<NAME>", "<NAME>"]}`
bookStr := `{"the_book_name": "go in action", "the_author_list": ["<NAME>", "<NAME>", "<NAME>"]}`
bookObj := Book{}
if err := json.Unmarshal([]byte(bookStr), &bookObj); err != nil {
panic(err)
}
fmt.Println(bookObj)
fmt.Println("name:", bookObj.Name)
fmt.Println("authors:", bookObj.Authors)
}
func jsonCode() {
enc := json.NewEncoder(os.Stdout)
data := map[string]int{"apple": 5, "orange": 6}
enc.Encode(data)
user := User{Name:"wwj", Age:666}
enc.Encode(user)
}
func main() {
//marshals()
//userUnMarshals()
//bookUnMarshal()
jsonCode()
}
<file_sep>/select/select_loop.go
package main
import (
"time"
"fmt"
)
// select,如果有default子句,则执行该子句
// 如果没有default子句,select将阻塞,直到某个通道返回
// 如果有多个case可以运行,select会随机选出一个执行。其他不会执行
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(time.Second * 5)
c1 <- "first chan"
}()
go func() {
time.Sleep(time.Second * 1)
c2 <- "second chan"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <- c1:
fmt.Println("rx: ", msg1)
case msg2 := <- c2:
fmt.Println("rx: ", msg2)
}
}
}
<file_sep>/string_functions/string_functions.go
package main
import (
"fmt"
"strings"
)
func line() {
fmt.Println(strings.Repeat("-", 30))
}
func main() {
fmt.Println("len:", len("hello"))
line()
fmt.Println("Char:", "hello"[1])
line()
fmt.Println("Count:", strings.Count("rabbitmq redis kafka", "r"))
fmt.Println("Count:", strings.Count("rabbitmq redis kafka", "f"))
line()
fmt.Println("Contains:", strings.Contains("go in action", "ac"))
fmt.Println("Index:", strings.Index("golang", "la"))
line()
fmt.Println("HasPrefix:", strings.HasPrefix("mongodb", "mon"))
fmt.Println("HasSuffix:", strings.HasSuffix("redis", "os"))
line()
fmt.Println("Join:", strings.Join([]string{"a", "b", "c"}, "###"))
fmt.Println("Split:", strings.Split("2018-06-22-17-40", "-"))
line()
fmt.Println("ToUpper:", strings.ToUpper("mysql"))
fmt.Println("ToLower:", strings.ToLower("MongoDB"))
line()
fmt.Println(strings.Repeat("ha", 10))
line()
fmt.Println("Replace:", strings.Replace("fooobar", "o", "a", 1))
// If n < 0, there is no limit on the number of replacements.
fmt.Println("Replace:", strings.Replace("fooobar", "o", "a", -1))
line()
}
<file_sep>/range_over_channels/range_over_channels.go
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
wg.Add(1)
queue := make(chan string, 5)
queue <- "one"
queue <- "two"
queue <- "three"
close(queue)
go func() {
defer wg.Done()
for elem := range queue {
fmt.Println(elem)
}
}()
wg.Wait()
}
<file_sep>/maps/maps.go
package main
import (
"fmt"
"strings"
)
func main() {
m := make(map[string]int)
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println(m, n)
fmt.Println(len(m), len(n))
fmt.Println(strings.Repeat("-", 10))
m["k1"] = 3
m["k2"] = 7
m["k3"] = 10
fmt.Println("m:", m)
fmt.Println("len m:", len(m))
fmt.Println(strings.Repeat("-", 10))
delete(m, "k2")
fmt.Println("m:", m)
fmt.Println("len m:", len(m))
fmt.Println(strings.Repeat("-", 10))
v, i := m["k3"]
fmt.Println(v, i)
v, i = m["k2"]
fmt.Println(v, i)
fmt.Println(strings.Repeat("-", 10))
}
<file_sep>/channel_buffering/channel_buffering.go
package main
import (
"fmt"
"sync"
)
var wGroup sync.WaitGroup
func init() {
wGroup.Add(1)
}
func main() {
msgs := make(chan string, 2)
go testRoutine(msgs)
fmt.Println("start rx")
rx1 := <-msgs
rx2 := <-msgs
fmt.Println("after rx 1:", rx1)
fmt.Println("after rx 2:", rx2)
wGroup.Wait()
fmt.Println("main meet the end")
}
func testRoutine(ch chan string) {
defer wGroup.Done()
fmt.Println("a new routine start")
ch <- "ping ping"
ch <- "bang bang"
}
<file_sep>/mutexes/mutexes.go
package main
import (
"sync"
"fmt"
"time"
)
func main() {
songs := make([]string, 0)
wg := sync.WaitGroup{}
var mutex = &sync.Mutex{}
wg.Add(30)
for i := 0; i < 30; i++ {
go func(id int) {
defer wg.Done()
mutex.Lock()
ret := fmt.Sprintf("routine %d enter,", id)
songs = append(songs, ret)
fmt.Println(ret)
time.Sleep(time.Second)
mutex.Unlock()
}(i)
}
wg.Wait()
mutex.Lock()
fmt.Println("main enter")
fmt.Println(songs)
mutex.Unlock()
}
<file_sep>/arrays/arrays.go
package main
import (
"fmt"
"strings"
)
func main() {
var a [5]int
var b [3]bool
fmt.Println("array a:", a)
fmt.Println("array b:", b)
fmt.Println(strings.Repeat("-", 10))
a[3] = 3
fmt.Println("array a all:", a)
fmt.Println("array a one:", a[3])
fmt.Println(strings.Repeat("-", 10))
fmt.Println("array a len:", len(a))
fmt.Println("array b len:", len(b))
fmt.Println(strings.Repeat("-", 10))
var c [3]string = [3]string{"python", "go", "javascript"}
fmt.Println("array c:", c)
fmt.Println(strings.Repeat("-", 10))
}
<file_sep>/timeouts/timeouts.go
package main
import (
"time"
"fmt"
)
func main() {
ch1 := make(chan string)
go func() {
time.Sleep(time.Second * 5)
ch1 <- "result 1"
}()
select {
case res1 := <-ch1:
fmt.Println("rx: ", res1)
case <-time.After(time.Second * 2):
fmt.Println("2 second, timeout...")
}
// -------------------------
ch2 := make(chan string)
go func () {
time.Sleep(time.Second * 2)
ch2 <- "result 2"
}()
select {
case res2 := <- ch2:
fmt.Println("rx: ", res2)
case <-time.After(time.Second * 5):
fmt.Println("5 second, timeout...")
}
}
<file_sep>/channel_directions/channel_directions.go
package main
import (
"fmt"
"time"
)
func badEcho(in <-chan string) {
// invalid operation: in <- "bad bad",
// send to receive-only type <-chan string
in <- "bad bad"
}
func testEcho(in <-chan string, out chan<- string) {
inStr := <-in
fmt.Println("routine rx:", inStr)
out <- inStr
}
func main() {
inChan := make(chan string)
outChan := make(chan string)
go testEcho(outChan, inChan)
fmt.Println("main tx a message")
outChan <- "All of the dust and dirt in the ground at some point"
time.Sleep(time.Second * 2)
backMsg := <- inChan
fmt.Println("main rx a message: " + backMsg)
badChan := make(chan string)
go badEcho(badChan)
}
<file_sep>/non_blocking_channel_operations/non_block_mutil_rx.go
package main
import (
"time"
"fmt"
)
func main() {
someChan := make(chan string)
otherChan := make(chan string)
go func() {
time.Sleep(time.Second * 3)
someChan <- "some text"
}()
go func() {
time.Sleep(time.Second * 5)
otherChan <- "other text"
}()
select {
case res1 := <-someChan:
fmt.Println("some chan,", res1)
case res2 := <-otherChan:
fmt.Println("other chan,", res2)
default:
fmt.Println("default, no block")
}
}
<file_sep>/closures/closures.go
package main
import (
"fmt"
"strings"
)
func intSeq() (func() int) {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
nextInt := intSeq()
fmt.Println("the next int:", nextInt())
fmt.Println("the next int:", nextInt())
fmt.Println("the next int:", nextInt())
fmt.Println(strings.Repeat("-", 10))
newInt := intSeq()
fmt.Println("the new int:", newInt())
fmt.Println("the new int:", newInt())
fmt.Println("the new int:", newInt())
fmt.Println(strings.Repeat("-", 10))
}
<file_sep>/time/time.go
package main
import (
"time"
"fmt"
)
func main() {
now := time.Now()
fmt.Println(now)
fmt.Println(now.Year(), now.Month(), now.Day())
fmt.Println(now.Hour(), now.Minute(), now.Second())
fmt.Println(now.Location())
fmt.Println(now.Weekday())
sometime := time.Date(2009, 7, 20,
20, 30, 50,
651387237,
time.UTC)
fmt.Println(sometime)
tomorrow := now.Add(24 * time.Hour + 10 * time.Minute + 30 * time.Second)
fmt.Println(tomorrow)
fmt.Println(tomorrow.Before(now))
fmt.Println(tomorrow.After(now))
fmt.Println(tomorrow.Equal(now))
diff := tomorrow.Sub(now)
fmt.Println(diff)
fmt.Println(diff.Hours(), diff.Minutes(), diff.Seconds())
// Duration is the same as int64
var dela time.Duration = 60 * 60 * time.Second
next := now.Add(dela)
fmt.Println(next)
}
<file_sep>/functions/functions.go
package main
import "fmt"
func plus(a int, b int) int {
return a + b
}
func main() {
ret := plus(3, 5)
fmt.Println("result of plus is ", ret)
}
<file_sep>/string_formatting/string_formatting.go
package main
import (
"fmt"
"strings"
"os"
)
type point struct {
x int
y int
}
func strFormat() {
fmt.Println(strings.Repeat("-", 30))
s := fmt.Sprintf("you like %s, i like %s.", "java", "golang")
fmt.Println(s)
fmt.Println(strings.Repeat("-", 30))
}
func fileFormat() {
fmt.Println(strings.Repeat("-", 30))
fmt.Fprintf(os.Stdout, "aways %s sky! \n", "blue")
f, _ := os.Create("_data/string_formatting")
defer f.Close()
fmt.Fprintf(f, "aways %s sky! \n", "blue")
fmt.Println(strings.Repeat("-", 30))
}
func main() {
p := point{3, 7}
fmt.Printf("%v \n", p)
fmt.Printf("%+v \n", p)
fmt.Printf("%#v \n", p)
fmt.Printf("%T \n", p)
fmt.Printf("%p \n", &p)
fmt.Printf("the bool %t \n", true)
fmt.Printf("the bool %t \n", false)
fmt.Printf("%d \n", 123)
fmt.Printf("%b \n", 7)
fmt.Printf("%x \n", 456)
fmt.Printf("%c \n", 33)
fmt.Printf("%f \n", 78.9)
fmt.Printf("the %s \n", "way you lie")
strFormat()
fileFormat()
}
| 216752c27b831bf6d4ae9c869f28b256d96ce1f2 | [
"Markdown",
"Go"
] | 48 | Go | ming3000/go_by_example | f233f35bc98c8b5c9f265e4f577cbda092f009c8 | 6bfc933b361a30afa3e8df0722d2fb64d78413e5 |
refs/heads/master | <repo_name>lefeuvre/ESP32<file_sep>/esp32.ino
#include <WiFi.h>
#include "ESPAsyncWebServer.h"
#include "SPIFFS.h"
const char* ssid = "OICore-ESP32-AP";
const char* password = "<PASSWORD>";
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
AsyncWebServer server(80);
String cmd_led = "LED_NONE";
String cmd_stor[4] = {"HIGH", "HIGH", "HIGH", "HIGH"};
String etor_state[4] = {"-", "-", "-", "-"};
String an_value[2] = {"-", "-"};
String processor(const String& var){
if (var == "LED_NONE" && cmd_led == "LED_NONE")
return "selected";
else if (var == "LED_RED" && cmd_led == "LED_RED")
return "selected";
else if (var == "LED_GREEN" && cmd_led == "LED_GREEN")
return "selected";
else if (var == "LED_YELLOW" && cmd_led == "LED_YELLOW")
return "selected";
else if (var == "LED_BLUE" && cmd_led == "LED_BLUE")
return "selected";
else if (var == "LED_PURPLE" && cmd_led == "LED_PURPLE")
return "selected";
else if (var == "LED_CYAN" && cmd_led == "LED_CYAN")
return "selected";
else if (var == "LED_WHITE" && cmd_led == "LED_WHITE")
return "selected";
else if (var == "STOR1_HIGH" && cmd_stor[0] == "STOR1_HIGH")
return "selected";
else if (var == "STOR1_LOW" && cmd_stor[0] == "STOR1_LOW")
return "selected";
else if (var == "STOR2_HIGH" && cmd_stor[1] == "STOR2_HIGH")
return "selected";
else if (var == "STOR2_LOW" && cmd_stor[1] == "STOR2_LOW")
return "selected";
else if (var == "STOR3_HIGH" && cmd_stor[2] == "STOR3_HIGH")
return "selected";
else if (var == "STOR3_LOW" && cmd_stor[2] == "STOR3_LOW")
return "selected";
else if (var == "STOR4_HIGH" && cmd_stor[3] == "STOR4_HIGH")
return "selected";
else if (var == "STOR4_LOW" && cmd_stor[3] == "STOR4_LOW")
return "selected";
else if (var == "ETOR1_STATE")
return etor_state[0];
else if (var == "ETOR2_STATE")
return etor_state[1];
else if (var == "ETOR3_STATE")
return etor_state[2];
else if (var == "ETOR4_STATE")
return etor_state[3];
else if (var == "AN1_VALUE")
return an_value[0];
else if (var == "AN2_VALUE")
return an_value[1];
else
return String();
}
uint16_t calculChecksum(uint8_t* buf, uint8_t len) {
uint16_t checksum = 0;
if (buf != NULL) {
for (int i=0; i<len; i++) {
checksum += buf[i];
}
}
return checksum;
}
void setup() {
Serial.begin(115200);
SPIFFS.begin(true);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html", String(), false, processor);
});
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/style.css", "text/css");
});
server.on("/act", HTTP_GET, [](AsyncWebServerRequest *request){
String cmd, val;
uint8_t buf[12] = {0};
size_t len = 12;
uint16_t crc;
if (request->hasParam("c")) {
cmd = request->getParam("c")->value();
}
if (cmd == "LED_NONE") {
cmd_led = "LED_NONE";
buf[2] = 0x14;
buf[6] = 0x00;
buf[9] = 0x01;
}
else if (cmd == "LED_RED") {
cmd_led = "LED_RED";
buf[2] = 0x14;
buf[6] = 0x01;
buf[9] = 0x01;
}
else if (cmd == "LED_GREEN") {
cmd_led = "LED_GREEN";
buf[2] = 0x14;
buf[6] = 0x02;
buf[9] = 0x01;
}
else if (cmd == "LED_YELLOW") {
cmd_led = "LED_YELLOW";
buf[2] = 0x14;
buf[6] = 0x03;
buf[9] = 0x01;
}
else if (cmd == "LED_BLUE") {
cmd_led = "LED_BLUE";
buf[2] = 0x14;
buf[6] = 0x04;
buf[9] = 0x01;
}
else if (cmd == "LED_PURPLE") {
cmd_led = "LED_PURPLE";
buf[2] = 0x14;
buf[6] = 0x05;
buf[9] = 0x01;
}
else if (cmd == "LED_CYAN") {
cmd_led = "LED_CYAN";
buf[2] = 0x14;
buf[6] = 0x06;
buf[9] = 0x01;
}
else if (cmd == "LED_WHITE") {
cmd_led = "LED_WHITE";
buf[2] = 0x14;
buf[6] = 0x07;
buf[9] = 0x01;
}
else if (cmd == "STOR1_HIGH") {
cmd_stor[0] = "STOR1_HIGH";
buf[2] = 0x31;
buf[5] = 0x00;
buf[9] = 0x01;
}
else if (cmd == "STOR1_LOW") {
cmd_stor[0] = "STOR1_LOW";
buf[2] = 0x31;
buf[5] = 0x00;
buf[9] = 0x00;
}
else if (cmd == "STOR2_HIGH") {
cmd_stor[1] = "STOR2_HIGH";
buf[2] = 0x31;
buf[5] = 0x01;
buf[9] = 0x01;
}
else if (cmd == "STOR2_LOW") {
cmd_stor[1] = "STOR2_LOW";
buf[2] = 0x31;
buf[5] = 0x01;
buf[9] = 0x00;
}
else if (cmd == "STOR3_HIGH") {
cmd_stor[2] = "STOR3_HIGH";
buf[2] = 0x31;
buf[5] = 0x02;
buf[9] = 0x01;
}
else if (cmd == "STOR3_LOW") {
cmd_stor[2] = "STOR3_LOW";
buf[2] = 0x31;
buf[5] = 0x02;
buf[9] = 0x00;
}
else if (cmd == "STOR4_HIGH") {
cmd_stor[3] = "STOR4_HIGH";
buf[2] = 0x31;
buf[5] = 0x03;
buf[9] = 0x01;
}
else if (cmd == "STOR4_LOW") {
cmd_stor[3] = "STOR4_LOW";
buf[2] = 0x31;
buf[5] = 0x03;
buf[9] = 0x00;
}
else if (cmd == "SEND") {
if (request->hasParam("v")) {
val = request->getParam("v")->value();
}
if (val.length() == 16) {
byte tmp[17] = {0};
val.getBytes(tmp, 17);
// Convert String to uint8_t array
for (int i=0; i<8; i++) {
if (tmp[i*2] >= 48 && tmp[i*2] <= 57) {
buf[i+2] |= (uint8_t)((tmp[i*2] - 48) << 4);
}
else if (tmp[i*2] >= 65 && tmp[i*2] <= 70) {
buf[i+2] |= (uint8_t)((tmp[i*2] - 55) << 4);
}
if (tmp[(i*2)+1] >= 48 && tmp[(i*2)+1] <= 57) {
buf[i+2] |= (uint8_t)(tmp[(i*2)+1] - 48);
}
else if (tmp[(i*2)+1] >= 65 && tmp[(i*2)+1] <= 70) {
buf[i+2] |= (uint8_t)(tmp[(i*2)+1] - 55);
}
}
}
}
request->send(SPIFFS, "/index.html", String(), false, processor);
// Add checksum and heading
crc = calculChecksum(buf, len);
buf[10] = (uint8_t)((crc & 0xFF00) >> 8);
buf[11] = (uint8_t)(crc & 0x00FF);
buf[0] = 0x4F;
buf[1] = 0x49;
Serial.write(buf, len);
});
server.begin();
}
void loop(){
uint8_t tmp[8] = {0};
while (Serial.available()) {
if (Serial.read() == 0x4F) {
if (Serial.read() == 0x49) {
for (int i=0; i<8; i++) {
tmp[i] = Serial.read();
}
if (calculChecksum(tmp, 8) == ((Serial.read() << 8) | Serial.read())) {
// PROCESS_SEND_DATA
if (tmp[0] == 0x36) {
if (tmp[3] == 0x00 && tmp[7] == 0x00) {
etor_state[0] = "LOW";
}
else if (tmp[3] == 0x00 && tmp[7] == 0x01) {
etor_state[0] = "HIGH";
}
else if (tmp[3] == 0x01 && tmp[7] == 0x00) {
etor_state[1] = "LOW";
}
else if (tmp[3] == 0x01 && tmp[7] == 0x01) {
etor_state[1] = "HIGH";
}
else if (tmp[3] == 0x02 && tmp[7] == 0x00) {
etor_state[2] = "LOW";
}
else if (tmp[3] == 0x02 && tmp[7] == 0x01) {
etor_state[2] = "HIGH";
}
else if (tmp[3] == 0x03 && tmp[7] == 0x00) {
etor_state[3] = "LOW";
}
else if (tmp[3] == 0x03 && tmp[7] == 0x01) {
etor_state[3] = "HIGH";
}
else if (tmp[3] == 0x0B) {
an_value[0] = String((tmp[4] << 24) | (tmp[5] << 16) | (tmp[6] << 8) | tmp[7]);
}
else if (tmp[3] == 0x0C) {
an_value[1] = String((tmp[4] << 24) | (tmp[5] << 16) | (tmp[6] << 8) | tmp[7]);
}
}
}
}
}
}
}
<file_sep>/README.md
# ESP32
Installing ESP32 Add-on in Arduino IDE:
1 - File -> Preferences
2 - Enter https://dl.espressif.com/dl/package_esp32_index.json into the “Additional Board Manager URLs”
3 - Tools > Board > Boards Manager…
4 - Search for ESP32 and press install button for the "ESP32 by Espressif Systems" | 17edf816a655fb78d0886ca0e2036b8908ff6a61 | [
"Markdown",
"C++"
] | 2 | C++ | lefeuvre/ESP32 | c752a158a7aca027bdfde195ef914e4ec9245b0d | 1589ea0d797a00191aa7fbf1c043c2e0afef52f7 |
refs/heads/master | <file_sep>// Philips Hue remote API configuration
var clientId = "your_meethue_clientid";
var clientSecret = "your_meethue_clientsecret";
//******************************************************
//** START set ajax content-type and configuration **
//******************************************************
var axios = require("axios");
var base64 = require("base-64");
var Wappsto = require("wapp-api");
var wappsto = new Wappsto();
let wappstoConsole = require("wapp-api/console");
wappstoConsole.start();
var wStream;
var networkRepliers;
var dataPromise = new Promise(function(resolve, reject) {
wappsto.get("data", {}, {
expand: 1,
subscribe: true,
success: function(col) {
let data = col.first();
wStream = wappsto.wStream;
wStream.subscribe('/extsync');
resolve(data);
},
error: function() {
}
});
});
var networkPromise = new Promise(function(resolve, reject) {
networkRepliers = {
resolve,
reject
};
initializeNetwork();
});
Promise.all([dataPromise, networkPromise]).then(function(result) {
console.log("STARTING THE APP");
let data = result[0];
let network = result[1];
start(data, network);
});
function initializeNetwork() {
wappsto.get("network", {}, {
expand: 5,
subscribe: true,
success: function(col) {
if (col.length > 0) {
networkRepliers.resolve(col.first());
} else {
createNetwork();
}
},
error: function() {
console.log("error getting network");
}
});
}
function createNetwork() {
let network = new wappsto.models.Network({
name: "hue network"
});
network.save({}, {
subscribe: true,
success: function() {
networkRepliers.resolve(network);
},
error: function() {
}
});
}
function start(data, network) {
var statusMessage = {
"error_create_token": "Failed to create access token",
"error_get_bridge_data": "Failed to get Hue Bridge data.",
"error_create_config": "Failed to create configuration.",
"error_create_user": "Failed to log in.",
"success_update_wappsto_data": "Success! Hue Bridge was updated in Wappsto",
"error_update_wappsto_data": "Failed to update Wappsto data.",
"error_get_bridge_config": "Failed to get Bridge configuration.",
"please_login": "Please log in.",
"no_permission": "Requires permission to enable webhook and create data.",
"logging_in": "Logging in...",
"processing": "Processing..."
};
//** the uniqueID should be something like gatewayId or serial number, something unique that you get from the user **
var username = data.get("username");
var bridgeId = data.get("bridgeId");
var token = data.get("token") && data.get("token").access_token;
//** refresh variable to know when we receive a stream if we should refresh background or not **
var refresh = data.get("refresh");
//** adding bridgeId and token listeners**
data.on("stream:message", function(model, newData) {
if (refresh != newData.refresh) {
console.log("refreshing");
refresh = newData.refresh;
switch (appState) {
case "processing":
case "getting_token":
updateData({
"status": statusMessage.processing
});
break;
case "error_login":
updateData({
"status": statusMessage.please_login
});
break;
case "error_refresh_token":
refreshToken();
break;
default:
validateAndCreate();
break;
}
}
});
//** baseUrl is the SERVICE that you are going to use for external requests (proxy thing, ask Tsvetomir) **
var baseUrl = "http://rest-service/external/meethue/";
var hueHeader = {
'Content-type': 'application/json',
'Accept': 'application/json',
'X-Session': process.env.sessionID
};
axios.defaults.headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'X-Session': process.env.sessionID
};
//****************************************************
//** END set ajax content-type and configuration **
//****************************************************
var appState = "error_login";
var pendingValueStatus = [];
var deleteTimeout;
var toCreate = false;
var validating = false;
var models = wappsto.models;
var destroyDevices = function(toDestroy) {
if (toDestroy.length > 0) {
if (deleteTimeout) {
clearTimeout(deleteTimeout);
}
network.get("device").destroy({
url: "/services/network/" + network.get("meta.id") + "/device?" + $.param({
id: toDestroy
}),
error: function(model, response) {
if (response.status != 404 && response.status != 410) {
deleteTimeout = setTimeout(function() {
destroyDevices(toDestroy);
}, 30 * 1000);
}
}
});
}
};
var updateData = function(obj) {
//check if object different than data attributes
data.set(obj);
data.save(obj, {
patch: true
});
};
var getBridgeConfig = function() {
axios({
url: baseUrl + "bridge/" + username + "/config",
headers: hueHeader,
method: "GET",
dataType: "json",
contentType: "application/json"
})
.then(function({ data }) {
network.set({
"name": data.name + " - " + data.bridgeid
});
updateData({
"username": username,
"bridgeId": data.bridgeid
});
if (bridgeId != data.bridgeid) {
bridgeId = data.bridgeid;
destroyDevices(network.get("device").map(e => e.get("meta.id")));
}
validateAndCreate();
})
.catch(function() {
appState = "error_login";
updateData({
"status": statusMessage.error_get_bridge_config
});
});
};
var createHueUser = function() {
axios({
url: baseUrl + "bridge",
headers: hueHeader,
method: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"devicetype": "wappsto-qa"
})
})
.then(function({ data }) {
username = data[0].success.username;
getBridgeConfig();
})
.catch(function() {
appState = "error_login";
updateData({
"status": statusMessage.error_create_user
});
});
};
var createHueConfig = function() {
axios({
url: baseUrl + "bridge/0/config",
headers: hueHeader,
method: "PUT",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"linkbutton": true
})
})
.then(function() {
createHueUser();
})
.catch(function(error) {
appState = "error_login";
updateData({
"status": statusMessage.error_create_config
});
});
};
var refreshTokenExpireTime;
var refreshTimeout;
var refreshToken = function() {
console.log("refreshing token");
if (refreshTimeout) {
clearTimeout(refreshTimeout);
}
if ((new Date()).getTime() < refreshTokenExpireTime) {
axios({
url: baseUrl + "oauth2/refresh?grant_type=refresh_token",
method: "POST",
headers: {
Authorization: 'Basic ' + base64.encode(clientId + ":" + clientSecret)
},
data: {
refreshToken: data.get("token").refresh_token
}
})
.then(function({ data }) {
token = data.access_token;
updateData({
"token": data
});
addTokenRefresh(data);
hueHeader.Authorization = "Bearer " + token;
createHueConfig();
console.log("success refresh token");
})
.catch(function(response) {
console.log("error refresh token: ", response);
if (appState != "error_refresh_token") {
appState = "error_refresh_token";
updateData({
"status": statusMessage.error_create_token
});
}
refreshTimeout = setTimeout(function() {
console.log("adding token refresh interval every 30 sec");
refreshToken();
}, 1000 * 30);
});
} else {
appState = "error_login";
updateData({
"status": statusMessage.please_login
});
}
};
function addTokenRefresh(response) {
console.log("adding token refresh timeout");
refreshTokenExpireTime = (new Date()).getTime() + (response.refresh_token_expires_in * 1000);
refreshTimeout = setTimeout(function() {
refreshToken();
}, response.access_token_expires_in * 1000);
}
var getToken = function(code) {
console.log("getting token");
axios({
url: baseUrl + "oauth2/token?grant_type=authorization_code&code=" + code,
method: "POST",
headers: {
Authorization: 'Basic ' + base64.encode(clientId + ":" + clientSecret)
}
})
.then(function({ data }) {
token = data.access_token;
updateData({
"token": data
});
addTokenRefresh(data);
hueHeader.Authorization = "Bearer " + token;
createHueConfig();
})
.catch(function(error) {
appState = "error_login";
updateData({
"status": statusMessage.error_create_token
});
});
};
//** adding login listener **
wStream.on("message", function(e) {
try {
let data = JSON.parse(e.data);
data.forEach(function(message){
if (message.meta_object.type == "extsync" && !message.extsync.uri.endsWith("/console")) {
var query = JSON.parse(message.extsync.body);
query = query.search;
query = query.split("&");
var queryObj = {};
for (var i = 0; i < query.length; i++) {
var str = query[i].split("=");
queryObj[str[0]] = str[1];
}
updateData({
"status": statusMessage.logging_in
});
appState = "getting_token";
getToken(queryObj.code);
}
});
} catch (error) {
console.log(error);
}
});
//uses getUrl variable to make the request
function validateAndCreate() {
if (appState != "processing" && bridgeId && username && token) {
appState = "processing";
var requestData = getRequestData("get");
axios({
headers: hueHeader,
url: baseUrl + requestData.url,
method: requestData.method,
data: requestData.body
})
.then(function({ data }) {
toCreate = false;
parseData(data);
removeOldDevices(data);
if (toCreate) {
var options = {
subscribe: true,
success: function() {
appState = "success_update_wappsto_data";
updateData({
"status": statusMessage.success_update_wappsto_data
});
clearPendingValueStatus();
addValueListeners(network);
},
error: function() {
appState = "error_update_wappsto_data";
updateData({
"status": statusMessage.error_update_wappsto_data
});
}
};
network.save({}, options);
} else {
appState = "success_update_wappsto_data";
updateData({
"status": statusMessage.success_update_wappsto_data
});
addValueListeners(network);
}
})
.catch(function(error) {
var status;
if (error.response && error.response.data && error.response.data.fault && error.response.data.fault.detail && error.response.data.fault.detail.errorcode == "keymanagement.service.invalid_access_token") {
appState = "error_login";
status = statusMessage.please_login;
} else {
appState = "error_get_bridge_data";
status = statusMessage.error_get_bridge_data;
}
updateData({
"status": status
});
console.log("failed to get bridge data");
});
}
}
//create a device using data
function createDevice(data) {
var device = new models.Device();
device.set(data);
return device;
}
//create a value and state using data, data should contain stateData attribute {stateData: "my_val"}
function createValue(device, data) {
var value = new models.Value();
value.set(data);
setDataType(data.name, value);
data = convertToWappstoData(data.name, data.stateData);
createPermissionState(value, data);
return value;
}
//create states using permission
function createPermissionState(value, data) {
switch (value.get("permission")) {
case "r":
createState(value, "Report", data);
break;
case "w":
createState(value, "Control", data);
break;
case "rw":
createState(value, "Control", data);
createState(value, "Report", data);
break;
default:
break;
}
}
//create a state and add it to valueModel
function createState(valueModel, type, data) {
var state = new models.State();
state.set("type", type);
state.set("data", data + "");
var timestamp = new Date().toISOString();
state.set("timestamp", timestamp + "");
valueModel.get("state").push(state);
}
//change device status to "ok"
function clearPendingValueStatus() {
pendingValueStatus.forEach(function(value) {
value.save({
"status": "ok"
}, {
patch: true
});
});
}
//add listeners to all the controlStates and fire "postRequest" function whenever we receive a stream event from the control value
function addValueListeners(network) {
//adding network destroy listener
var onNetworkDestroy = function() {
wStream.unsubscribe(network);
validateAndCreate();
};
network.off("destroy", onNetworkDestroy);
network.on("destroy", onNetworkDestroy);
//adding listeners to value and state
network.get("device").forEach(function(device) {
device.get("value").forEach(function(value) {
//adding value status listener
var onValueMessage = function(model, data) {
if (data.status === "update") {
value.save({
"status": "pending"
}, {
patch: true
});
pendingValueStatus.push(value);
validateAndCreate();
}
};
value.off("stream:message", onValueMessage);
value.on("stream:message", onValueMessage);
//adding control value data change listener
var controlState = value.get("state").findWhere({
"type": "Control"
});
if (controlState) {
var onControlMessage = function(model, data) {
data = data.data + "";
console.log("controlState data changed to: " + data);
postRequest(controlState, data);
};
controlState.off("stream:message", onControlMessage);
controlState.on("stream:message", onControlMessage);
}
});
});
}
//update report state on the server
function saveStateData(state, data) {
var reportState;
if (state.get("type") == "Report") {
reportState = state;
} else {
state.set("data", data);
reportState = state.parent().get("state").findWhere({
"type": "Report"
});
}
if (reportState) {
var timestamp = new Date().toISOString();
reportState.save({
"data": data + "",
timestamp: timestamp + ""
}, {
patch: true
});
}
}
//send request to post url
function postRequest(state, data) {
var convData = convertData(state, data);
console.log("sending " + convData);
var parsedData;
try {
parsedData = JSON.parse(convData);
} catch (e) {
parsedData = convData;
}
var requestData = getRequestData("update", state, parsedData);
axios({
headers: hueHeader,
dataType: "json",
contentType: "application/json",
url: baseUrl + requestData.url,
method: requestData.method,
data: JSON.stringify(requestData.body)
})
.then(function(response) {
if (response.data[0] && response.data[0].hasOwnProperty("success")) {
saveStateData(state, data);
}
})
.catch(function(error) {
console.log("failed to update state: " + state.get("meta.id") + " - of value: " + state.parent().get("meta.id") + " - " + state.parent().get("name"));
});
}
//*************************************************************************************************
//** return the url, method, and body for the request **
//** by default, get is used to get the data, and update used to update **
//*************************************************************************************************
function getRequestData(type, state, newData) {
var url, method, body;
switch (type) {
case "get":
url = "bridge/" + username + "/lights";
method = "GET";
break;
case "update":
var value = state.parent();
var device = value.parent();
url = "bridge/" + username + "/lights/" + device.get("product") + "/state";
method = "PUT";
body = {};
body[value.get("name")] = newData;
break;
default:
break;
}
return {
url: url,
method: method,
body: body
};
}
//********************************************************************************************************
//** TO CHANGE!!! here you are going to create your devices, values and states **
//** if you want to create/update the network, set toCreate to true(toCreate = true) **
//** this function will be called each time you call "validateAndCreate" function and try to parse data,**
//** so update your network here each and everytime you find a new data **
//** don't forget to add the new data to the network/device... **
//********************************************************************************************************
function parseData(data) {
for (let id in data) {
let light = data[id];
var device = network.get("device").findWhere({
"serial": light.uniqueid
});
if (!device) {
toCreate = true;
var deviceObj = {
"name": light.name,
"type": light.type,
"serial": light.uniqueid,
"manufacturer": light.manufacturername,
"communication": "always",
"protocol": "hue",
"included": "1",
"product": id
};
device = createDevice(deviceObj);
for (let key in light.state) {
let lightVal = light.state[key];
var valueObj = {
"name": key,
"type": deviceObj.type,
"permission": "rw",
"status": "ok",
"stateData": lightVal //this will be state.data
};
var value = createValue(device, valueObj);
device.get("value").push(value);
}
network.get("device").push(device);
} else {
for (let key in light.state) {
let lightVal = light.state[key];
var val = device.get("value").findWhere({
name: key
});
if (val) {
var reportState = val.get("state").findWhere({
type: "Report"
});
if (reportState) {
var newData = convertToWappstoData(key, lightVal);
if (reportState.get("data") != newData) {
saveStateData(reportState, newData);
}
}
}
}
}
}
}
//remove devices that are not in bridge anymore
function removeOldDevices(data) {
var hueIds = [];
for (let key in data) {
hueIds.push(data[key].uniqueid);
}
var toDelete = [];
network.get("device").each(function(device) {
if (hueIds.indexOf(device.get("serial")) == -1) {
toDelete.add(device.get("meta.id"));
}
});
destroyDevices(toDelete);
}
//*************************************************************************************
//** TO CHANGE if needed!!! this function will be called each time we are going to send a request to the device, so if your device accept true/false and in "setDataType" function you changed it to integer, here you shoud change it back to Boolean
//*************************************************************************************
function convertData(state, data) {
var value = state.parent();
if (value.attributes.hasOwnProperty("number")) {
data = parseFloat(data);
var number = value.get("number");
var min = parseFloat(number.min);
var max = parseFloat(number.max);
if (max - min === 1) {
if (data === min) {
data = false;
} else {
data = true;
}
}
}
return data;
}
//************************************************************************************
//** TO CHANGE(don't change the default case)!!! set value dataType and update data **
//** in this function, you should change the raw received data to the wanted data **
//************************************************************************************
function setDataType(valueName, valueModel) {
switch (valueName) {
case "on":
case "reachable":
valueModel.set("number", {
min: 0,
max: 1,
step: 1,
unit: "int"
});
break;
case "bri":
case "sat":
valueModel.set("number", {
min: 0,
max: 255,
step: 1,
unit: "int"
});
break;
case "hue":
valueModel.set("number", {
min: 0,
max: 65535,
step: 1,
unit: "int"
});
break;
default:
valueModel.set("string", {
max: 99
});
break;
}
}
function convertToWappstoData(valueName, stateData) {
switch (valueName) {
case "on":
case "reachable":
if (stateData) {
stateData = "1";
} else {
stateData = "0";
}
break;
case "xy":
stateData = stateData + "";
break;
default:
stateData = JSON.stringify(stateData) + "";
break;
}
return stateData;
}
if (bridgeId && token && username) {
hueHeader.Authorization = "Bearer " + token;
validateAndCreate();
}
}
<file_sep># Pumpkin example application
Pumpkin device example code: https://github.com/Wappsto/IoT_RapidPrototyping/tree/master/example_code/pumpkin
<file_sep>// Functions used in the conversion process
// Create and return a network with the name Fitbit
const createNetwork = wappstoInstance => {
if (wappstoInstance) {
let newNetwork = new wappstoInstance.models.Network();
newNetwork.set("name", "Fitbit");
return newNetwork;
}
return null;
};
// Create and return a device
const createDevice = (wappstoInstance, deviceType) => {
if (wappstoInstance && deviceType) {
let newDevice = new wappstoInstance.models.Device();
switch (deviceType.toLowerCase()) {
case "activity":
newDevice.set("name", "Activity");
newDevice.set("description", "Device representing Fitbit activities");
break;
case "sleep stages":
newDevice.set("name", "Sleep stages");
newDevice.set("description", "Device representing Fitbit sleep stages");
break;
}
newDevice.set("manufacturer", "Fitbit Converter");
newDevice.set("version", "1.0");
newDevice.set("product", "FitbitCharge3");
return newDevice;
}
return null;
};
// Create and return a value based on its value type
const createValue = (wappstoInstance, valueType, valueData) => {
if (wappstoInstance && valueType && valueData) {
let newValue = new wappstoInstance.models.Value();
let stateData, reportState;
switch (valueType.toLowerCase()) {
case "calories":
newValue.set("name", "Calories burned");
newValue.set("type", "energy");
newValue.set("permission", "r");
newValue.set("status", "ok");
newValue.set("number", {
max: 4000,
min: 0,
step: 1,
unit: "cal"
});
stateData = valueData.summary.calories ? valueData.summary.calories : "0";
reportState = createState(wappstoInstance, "Report", stateData);
break;
case "floors":
newValue.set("name", "Floors");
newValue.set("type", "count");
newValue.set("permission", "r");
newValue.set("status", "ok");
newValue.set("number", {
max: 1000,
min: 0,
step: 1,
unit: ""
});
stateData = valueData.summary.floors ? valueData.summary.floors : "0";
reportState = createState(wappstoInstance, "Report", stateData);
break;
case "heart rate":
newValue.set("name", "Resting heart rate");
newValue.set("type", "frequency");
newValue.set("permission", "r");
newValue.set("status", "ok");
newValue.set("number", {
max: 250,
min: 30,
step: 1,
unit: "bpm"
});
stateData = valueData.summary.restingHeartRate;
reportState = createState(wappstoInstance, "Report", stateData);
break;
case "sleep":
let name = valueData.level;
if(name === "wake") {
name = "awake"
}
newValue.set("name", name === "rem" ? name.toUpperCase() : name.replace(/^./, name[0].toUpperCase()));
newValue.set("type", "time");
newValue.set("permission", "r");
newValue.set("status", "ok");
newValue.set("string", {
encoding: "",
max: 100000
});
stateData = valueData.dateTime ? valueData.dateTime : "0";
reportState = createState(wappstoInstance, "Report", stateData);
break;
case "steps":
newValue.set("name", "Steps");
newValue.set("type", "count");
newValue.set("permission", "r");
newValue.set("status", "ok");
newValue.set("number", {
max: 100000,
min: 0,
step: 1,
unit: ""
});
stateData = valueData.summary.steps;
reportState = createState(wappstoInstance, "Report", stateData);
break;
case "water":
newValue.set("name", "Water");
newValue.set("type", valueType);
newValue.set("permission", "r");
newValue.set("status", "ok");
newValue.set("number", {
max: 100000,
min: 0,
step: 1,
unit: "litre"
});
stateData = valueData.length > 0 ? valueData.summary.water : "0";
reportState = createState(wappstoInstance, "Report", stateData);
break;
}
newValue.get("state").push(reportState);
return newValue;
}
return null;
};
// Create and return a state
const createState = (wappstoInstance, stateType, data) => {
if (wappstoInstance && stateType && data) {
let newState = new wappstoInstance.models.State();
let timestamp = new Date().toISOString();
newState.set("type", stateType);
newState.set("data", data.toString());
newState.set("timestamp", timestamp);
return newState;
}
return null;
};
module.exports = {
createNetwork: createNetwork,
createDevice: createDevice,
createValue: createValue,
createState: createState
};
<file_sep>let wappsto = new Wappsto();
console.log("Wapp Started");
let network;
// this function creates a PERMISSION REQUEST to the user who installs it. In this specific permission request it is required to retrieve 1 Network taht has a name "Smart Home Simulator"
wappsto.get("network", {"name":"Smart Home Simulator"}, {
expand: 4,
quantity:1,
success: networkCollection => {
// You will always receive a collection of models. In this case you will only need one (which is first)
network = networkCollection.first();
console.log("This is your network in foreground", network);
},
error: (networkCollection, response) => {
console.log("Something went wrong");
}
}
);
<file_sep>let wappsto = new Wappsto();
console.log("Wapp Started");
<file_sep>// Implementing the OAuth 2.0 Authorization Code Grant Flow
const axios = require("axios");
const base64 = require("base-64");
const qs = require("qs");
const clientID = "your_clientID";
const clientSecret = "your_clientSecret";
const redirect_uri = "https://light.wappsto.com/third_auth/callback.html";
const authUrl = "https://api.fitbit.com/oauth2/token";
const authHeader = {
Authorization: "Basic " + base64.encode(clientID + ":" + clientSecret),
"Content-Type": "application/x-www-form-urlencoded"
};
const getAccessToken = authcode => {
return axios({
url: authUrl,
method: "post",
headers: authHeader,
data: qs.stringify({
client_id: clientID,
grant_type: "authorization_code",
redirect_uri: redirect_uri,
code: authcode
})
});
};
const getRefreshToken = refreshToken => {
return axios({
url: authUrl,
method: "post",
headers: authHeader,
data: qs.stringify({
grant_type: "refresh_token",
refresh_token: refreshToken
})
});
};
const getTokenState = tokenToIntrospect => {
return axios({
url: "https://api.fitbit.com/1.1/oauth2/introspect",
method: "post",
headers: {
Authorization: `Bearer ${tokenToIntrospect}`,
"Content-Type": "application/x-www-form-urlencoded"
},
data: qs.stringify({
token: tokenToIntrospect
})
});
};
module.exports = {
getAccessToken: getAccessToken,
getRefreshToken: getRefreshToken,
getTokenState: getTokenState
};
<file_sep>let Wappsto = require("wapp-api");
let wappsto = new Wappsto();
let wappstoConsole = require("wapp-api/console");
wappstoConsole.start(); // to start sending logs
var network;
// this function creates a PERMISSION REQUEST to the user who installs this wapp.
//In this specific permission request it is required to retrieve 1 Network that has a name: "Smart Home Simulator"
wappsto.get("network", {"name":"Smart Home Simulator"}, {
expand: 4,
quantity:1,
success: networkCollection => {
// You will always receive a collection of models. In this case you will only need one (which is first)
network = networkCollection.first();
console.log("This is your network in background", network);
},
error: (networkCollection, response) => {
console.log("Something went wrong");
}
}
);
<file_sep># Smart Watch Converter
## Introduction
This application allows you to connect your Fitbit account and convert your data into the Wappsto Unified Data Model (UDM). It makes use of the [Fitbit Web API](https://dev.fitbit.com/build/reference/web-api/), as well as the [Wappsto API](https://developer.wappsto.com/), which is made for developing creative IoT solutions.
## How to get started
To get started with using this Wapp you need the following:
* A Fitbit account - you can signup for one at the official [Fitbit website](https://www.fitbit.com/signup)
* A Wappsto account
* A Fitbit Smart watch device
### Setup
1. Go to this [link](https://dev.fitbit.com/apps/new) and register your own application. This enables you to get your own **client ID** and **client secret**. In the field *Callback URL* input https://light.wappsto.com/third_auth/callback.html
2. Login into your Wappsto account and create a new Wapp using the files in this GitHub repository.
3. Navigate to the *foreground* folder and edit the **index.js** file by replacing the placeholder value for clientID with your own client ID.
4. Navigate to the *background* folder and edit the **auth.js** file by replacing the placeholder values for clientID and clientSecret with your own credentials.
5. Run the Wapp, then enable extsync when prompted and allow Wappsto permission to store data in your account .
<file_sep>let wappsto = new Wappsto();
let device, city;
getDevice();
$(document).ready(function () {
$("#networkName").text(networkInfo.name);
$("#integratedValues").html(createValueDescription);
});
function updateStatusMessage(status) {
$("#status").show().addClass(status.type);
console.log(status);
$("#statusMessage").html(status.message);
setTimeout(function(){ $("#status").hide(); }, 4000);
}
function createValueDescription(){
var list = "",
unit = "";
$.each(networkInfo.device[0].value, function(key, value) {
if(value.unit){
unit = "(" + value.unit + ")";
} else if (value.encoding){
unit = "(" + value.encoding + ")";
}
list += "<li><strong>" + value.name + "</strong> " + unit + " - " + value.description + "</li>";
});
return list;
}
// creating event listener that makes requests on city change
function addValueListener() {
console.log("add listener for device");
var townReportState = device.get("value").findWhere({name:"city"}).get("state").findWhere({type:"Report"});
townReportState.on("change", function(model, data){
$("#currentWeather").html(currentValueList());
});
}
function setCurrentLocation(){
var name = $("#currentLocation").val();
if(name){
if(device){
var timestamp = new Date().toISOString();
var controlState = device.get("value").findWhere({"name": "city"}).get("state").findWhere({"type":"Control"});
controlState.save({
"data": name,
"timestamp": timestamp + ""
}, {
patch: true,
error: function(){
console.log("An error occured when sending requesting data.");
}
});
} else {
updateStatusMessage({message:"Something went wrong. Please try again.", type:"error"});
getDevice();
}
} else{
updateStatusMessage({message:"enter city name", type:"error"});
}
}
function getDevice(){
wappsto.get('device', {name: "Current Weather"}, {
expand: 5,
subscribe: true,
success: (deviceCollection) => {
device = deviceCollection.first();
if (device && device.get('value') && device.get('value').length !== 0) {
$("#currentWeather").html(currentValueList());
addValueListener();
} else {
updateStatusMessage({
type: "error",
message: "Network Was not created. Please accept permission."
});
wappsto.wStream.subscribe("/network");
wappsto.wStream.on("message", event => {
try{
message = JSON.parse(event.data);
message.forEach(m => {
if(m.meta_object.type === "network" && m.event === "create"){
getDevice();
}
});
}catch(e){
console.log(e);
}
});
}
},
error: (networkCollection, response) => {
updateStatusMessage({
type: "error",
message: "Network Was not created. Please accept permission."
});
}
});
}
function currentValueList(){
var list = "",
data = "";
$.each(device.get("value").models, function(key, value) {
var unit = "";
if(value.get("number")){
unit = value.get("number").unit;
}
data = value.get("state").findWhere({"type":"Report"}).get("data");
if(value.get("type") === "timestamp"){
var timestamp = data;
data = new Date(0);
data.setUTCSeconds(timestamp);
}
list += "<li>" + value.get("name") + ": <strong id='"+value.get("name")+"Data'>" + data + "</strong> " + unit + "</li>";
});
return list;
}<file_sep># Hue converter example application
Hue converter is an application that imports all your hue bridge's devices to Wappsto.
# How to use the code:
In order for this application to work, you have to go to [meethue developer website](https://developers.meethue.com/my-apps/) and create your remote application.
Fill the empty fields and set the **callback** url to: https://light.wappsto.com/third_auth/callback.html
After creating your meethue application, you will get a **ClientId** and **ClientSecret** back.
Use your data in your app(foreground/index.js and background/main.js).
<file_sep>// Functions used to make api calls to the Fitbit Web API using an access token
const axios = require("axios");
const getActivities = accessToken => {
return axios({
url: "https://api.fitbit.com/1/user/-/activities/date/today.json",
headers: {
Authorization: `Bearer ${accessToken}`
}
});
};
const getFood = accessToken => {
return axios({
url: `https://api.fitbit.com/1.2/user/-/foods/log/date/${formatCurrentDate()}.json`,
headers: {
Authorization: `Bearer ${accessToken}`
}
});
};
const getSleep = accessToken => {
return axios({
url: `https://api.fitbit.com/1.2/user/-/sleep/date/${formatCurrentDate()}.json`,
headers: {
Authorization: `Bearer ${accessToken}`
}
});
};
// Return current date in the yyyy-mm-dd format
const formatCurrentDate = () => {
let currentDate = new Date();
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1 <= 9 ? `0${currentDate.getMonth() + 1}` : currentDate.getMonth() + 1;
let day = currentDate.getDate() <= 9 ? `0${currentDate.getDate()}` : currentDate.getDate();
let formattedDate = `${year}-${month}-${day}`;
return formattedDate;
};
module.exports = {
getActivities: getActivities,
getFood: getFood,
getSleep: getSleep,
formatCurrentDate: formatCurrentDate
};
<file_sep><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/wapp-api@latest/browser/wapp-api.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="index.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<article>
<h1>Philips HUE Light Converter</h1>
<section>
<h4>Complete the following steps to connect your HUE Bridge</h4>
<ul>
<li>
<p>Log in to your Meet hue account and allow this wapp to get the access token.</p>
<a id="login" class="button" href="#" onclick="openLoginPage()">Log in</a>
</li>
<li><p>Accept permission requests in Wappsto:</p>
<ul>
<li><p>to save Hue Bridge data under your wappsto account.</p></li>
<li><p>to create a webhook (external synchronisation) with Meet Hue.</p></li>
</ul>
</li>
</ul>
</section>
<section>
<h4>Background app:</h4>
<p>Here you can see the <b>status</b> of the background tasks.</p>
<p class="callout secondary" id="statusId">Waiting for permissions.</p>
<p>If for some reason background app have crashed, or stuck, you can try the restart button.</p>
<button class="button" onclick="refreshBackground()">Restart Background</button>
</section>
</article>
</body>
</html>
<file_sep>// get device
var camera = network.get("device").findWhere({
"name": pumpkinConfig.device.camera.name
});
// get value
var cameraVal = camera.get("value").findWhere({
"name": pumpkinConfig.device.camera.valueName
});
//get Report state
var cameraReport = cameraVal.get("state").findWhere({
"type": "Report"
});
function takePicture() {
// save camera value with the status "update" to take picture. When using patch, ":id" and ":type" of the value is required.
cameraVal.save({
':type': cameraVal.get(':type'),
':id': cameraVal.get(':id'),
status: "update"
}, {
patch: true
});
}
function updateNose(){
// show last picture taken by pumpkin camera
$("input[type='image']").attr("src", cameraReport.get("data"));
}
$(document).ready(function () {
// update DOM element when page is loaded
updateNose();
// on "nose" click call takePicture function
$("#nose").on("click", takePicture);
});
// listen to device value 'Report' state data changes
cameraReport.on("change:data", function () {
updateNose();
});
<file_sep>const Wappsto = require("wapp-api");
const axios = require("axios");
const auth = require("./auth");
const fitbit = require("./fitbit");
const util = require("./util");
const wappsto = new Wappsto();
const wappStatus = {
warning_login_required: "Please login to Fitbit account",
success_convert_data: "Succesfully converted Fitbit data to Wappsto UDM",
warning_convert_data: "Starting the conversion process..",
error_convert_data: "Error converting Fitbit data to Wappsto UDM",
success_retrieve_data: "Succesfully retrieved Fitbit Network",
error_retrieve_data: "Error retrieving Fitbit Network",
success_update_data: "Succesfully updated Fitbit Network",
error_update_data: "Error updating Fitbit Network"
};
let updateTimer;
// 5 minutes
let updateTimeInterval = 300000;
let data, network;
const dataPromise = new Promise((resolve, reject) => {
wappsto
.get("data", {}, { expand: 1, subscribe: true })
.then(collection => {
resolve(collection.first());
})
.catch(error => {
console.log(`Error getting Wappsto data: ${error}`);
});
});
const networkPromise = new Promise((resolve, reject) => {
wappsto
.get("network", {}, { expand: 5, subscribe: true })
.then(collection => {
resolve(collection.find({ name: "Fitbit" }));
})
.catch(error => {
console.log(`Error getting Fitbit network: ${error}`);
});
});
Promise.all([dataPromise, networkPromise])
.then(result => {
data = result[0];
network = result[1];
startWapp();
})
.catch(error => {
console.log(`Error occured: ${error}`);
});
const startWapp = () => {
if (network) {
setUpdateTimer();
updateWappstoData({ status_message: wappStatus.success_retrieve_data });
} else {
updateWappstoData({ status_message: wappStatus.warning_login_required });
// waiting for the access token to be saved
data.on("change:accessToken", () => {
// ensuring that the conversion process takes place only once
if (!network && data.get("accessToken")) {
convertToWappstoUDM();
}
});
}
// declare and init stream
const wStream = wappsto.wStream;
// subscribe to extsync
wStream.subscribe("/extsync");
// add stream listener
wStream.on("message", event => {
try {
let streamdata = JSON.parse(event.data);
streamdata.forEach(message => {
if (message.meta_object.type === "extsync") {
let query = JSON.parse(message.extsync.body);
let queryObj = {};
if (query) {
query = query.search;
if (query) {
query = query.split("&");
for (let i = 0; i < query.length; i++) {
let str = query[i].split("=");
queryObj[str[0]] = str[1];
}
}
}
if (queryObj.code) {
auth
.getAccessToken(queryObj.code)
.then(response => {
data.save(
{
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token
},
{
patch: true,
error: () => {
console.log("Error saving access tokens..");
}
}
);
})
.catch(error => {
console.log(`Could not get access token: ${error}`);
});
}
}
});
} catch (error) {
console.log(`Error occured: ${error}`);
}
});
};
// Convert Fitbit data to Wappsto UDM
const convertToWappstoUDM = () => {
updateWappstoData({ status_message: wappStatus.warning_convert_data });
// Create network
network = util.createNetwork(wappsto);
// Create activity device
let activityDevice = util.createDevice(wappsto, "Activity");
// Create sleep stage device
let sleepStageDevice = util.createDevice(wappsto, "Sleep stages");
// Wait for all the needed Fitbit data to be delivered
axios
.all([
fitbit.getActivities(data.get("accessToken")),
fitbit.getFood(data.get("accessToken")),
fitbit.getSleep(data.get("accessToken"))
])
.then(
axios.spread((fitbitActivities, fitbitFood, fitbitSleep) => {
const allowedValueTypes = ["calories", "floors", "heart rate", "sleep", "steps", "water"];
// Create values based on the allowed value types and Fitbit data
allowedValueTypes.forEach(valueType => {
let valueToAdd;
// Value type is used to assign the right Fitbit data to the coresponding value
switch (valueType) {
case "calories":
valueToAdd = util.createValue(wappsto, valueType, fitbitFood.data);
break;
case "floors":
valueToAdd = util.createValue(wappsto, valueType, fitbitActivities.data);
break;
case "heart rate":
valueToAdd = util.createValue(wappsto, valueType, fitbitActivities.data);
break;
case "sleep":
let sleepData = fitbitSleep.data.sleep[0].levels.data;
// Create sleep values of type Awake, Light, REM and Deep
for (let i = 0; i < sleepData.length; i++) {
let sleepStage = formatSleepStage(sleepData[i].level);
// Ensuring that no duplicate sleep values are created
let foundSleepValue = sleepStageDevice.get("value").find({ name: sleepStage });
// If the sleep value is not found then create it and add it to the Sleep stage device
if (!foundSleepValue) {
let sleepValueToAdd = util.createValue(wappsto, valueType, sleepData[i]);
if (sleepStageDevice) {
if (sleepValueToAdd) {
sleepStageDevice.get("value").push(sleepValueToAdd);
}
}
}
}
break;
case "steps":
valueToAdd = util.createValue(wappsto, valueType, fitbitActivities.data);
break;
case "water":
valueToAdd = util.createValue(wappsto, valueType, fitbitFood.data);
break;
}
// Add new values to Activity device
if (activityDevice) {
if (valueToAdd) {
activityDevice.get("value").push(valueToAdd);
}
}
});
if (activityDevice && sleepStageDevice) {
// Add devices to network
network.get("device").push(activityDevice);
network.get("device").push(sleepStageDevice);
// Save the new Fitbit Network
saveNetwork();
}
})
)
.catch(error => {
console.log(`Error getting Fitbit data: ${error}`);
updateWappstoData({ status_message: wappStatus.error_convert_data });
});
};
const formatSleepStage = sleepStage => {
if(sleepStage === "wake") {
sleepStage = "awake";
}
if (sleepStage === "rem") {
sleepStage = sleepStage.toUpperCase();
} else {
sleepStage = sleepStage.replace(/^./, sleepStage[0].toUpperCase());
}
return sleepStage;
};
// Timer used to update report states
const setUpdateTimer = () => {
if (updateTimer) {
clearInterval(updateTimer);
}
updateTimer = setInterval(() => {
updateReportStates();
}, updateTimeInterval);
};
// Update value report states
const updateReportStates = () => {
let activityDeviceValues = network
.get("device")
.at(0)
.get("value");
let sleepStageDeviceValues = network
.get("device")
.at(1)
.get("value");
axios
.all([
fitbit.getActivities(data.get("accessToken")),
fitbit.getFood(data.get("accessToken")),
fitbit.getSleep(data.get("accessToken"))
])
.then(
axios.spread((fitbitActivities, fitbitFood, fitbitSleep) => {
const allowedValueTypes = ["calories", "floors", "heart rate", "sleep", "steps", "water"];
allowedValueTypes.forEach(valueType => {
let valueToUpdate;
let reportState;
let newReportData;
switch (valueType) {
case "calories":
valueToUpdate = activityDeviceValues.find({
name: "Calories burned"
});
reportState = valueToUpdate.get("state").find({ type: "Report" });
newReportData = fitbitFood.data.summary.calories ? fitbitFood.data.summary.calories : "0";
break;
case "floors":
valueToUpdate = activityDeviceValues.find({
name: "Floors"
});
reportState = valueToUpdate.get("state").find({ type: "Report" });
newReportData = fitbitActivities.data.summary.floors ? fitbitActivities.data.summary.floors : "0";
break;
case "heart rate":
valueToUpdate = activityDeviceValues.find({
name: "Resting heart rate"
});
reportState = valueToUpdate.get("state").find({ type: "Report" });
newReportData = fitbitActivities.data.summary.restingHeartRate
? fitbitActivities.data.summary.restingHeartRate
: "NO_DATA";
break;
case "sleep":
let sleepData = fitbitSleep.data.sleep[0] ? fitbitSleep.data.sleep[0].levels.data : [];
// Start and current date are used to get logs
// Start date is the date from three days ago
let startDate = new Date(new Date().setDate(new Date().getDate() - 3)).toISOString();
// Current date is now
let currentDate = new Date().toISOString();
if (sleepData.length > 0) {
for (let i = 0; i < sleepData.length; i++) {
let sleepStage = formatSleepStage(sleepData[i].level);
let sleepValueToUpdate = sleepStageDeviceValues.find({
name: sleepStage
});
let sleepReportState = sleepValueToUpdate.get("state").find({ type: "Report" });
let newSleepReportData = sleepData[i].dateTime;
// To properly update sleep values, new data is compared to current report data and historical data to avoid inserting duplicates
sleepReportState.getLogs({
query: `start=${startDate}&end=${currentDate}&limit=3600`,
success: (model, response, XHRResponse) => {
let sleepLogs = response.data;
if (sleepReportState.get("data") !== newSleepReportData) {
if (sleepLogs.length > 0) {
let found = false;
for (let i = 0; i < sleepLogs.length; i++) {
let sleepLogData = sleepLogs[i].data;
if (sleepLogData === newSleepReportData) {
found = true;
}
}
if (!found) {
sleepReportState.save({ data: newSleepReportData }, { patch: true });
}
} else {
sleepReportState.save({ data: newSleepReportData }, { patch: true });
}
}
},
error: (model, XHRResponse) => {
console.log("Could not get logs..");
}
});
}
}
break;
case "steps":
valueToUpdate = activityDeviceValues.find({ name: "Steps" });
reportState = valueToUpdate.get("state").find({ type: "Report" });
newReportData = fitbitActivities.data.summary.steps ? fitbitActivities.data.summary.steps : "NO_DATA";
break;
case "water":
valueToUpdate = activityDeviceValues.find({ name: "Water" });
reportState = valueToUpdate.get("state").find({ type: "Report" });
newReportData = fitbitFood.data.summary.water ? fitbitFood.data.summary.water : "0";
break;
}
if (valueType !== "sleep" && reportState.get("data") !== newReportData.toString()) {
reportState.save({ data: newReportData.toString() }, { patch: true });
}
});
setUpdateTimer();
updateWappstoData({ status_message: wappStatus.success_update_data });
})
)
.catch(error => {
if (error.response && error.response.status === 401) {
auth
.getRefreshToken(data.get("refreshToken"))
.then(response => {
data.save(
{
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token
},
{
patch: true,
success: () => {
// try to update again
updateReportStates();
},
error: () => {
console.log("error saving tokens..");
}
}
);
})
.catch(error => {
console.log("error refreshing tokens..");
});
}
console.log(`Error updating Fitbit network: ${error}`);
updateWappstoData({ status_message: wappStatus.error_update_data });
});
};
// Save data to Wappsto Data
const updateWappstoData = dataToUpdate => {
data.set(dataToUpdate);
data.save(dataToUpdate, {
patch: true,
error: () => {
console.log("Error saving Wappsto data..");
}
});
};
// Save network
const saveNetwork = () => {
network.save(
{},
{
success: () => {
updateWappstoData({ status_message: wappStatus.success_convert_data });
// Update to fill in log data of sleep values
updateReportStates();
},
error: error => {
console.log(`Error saving Fitbit network: ${error}`);
updateWappstoData({ status_message: wappStatus.error_convert_data });
}
}
);
};
| 31e89fcde785db387141716220e88a854f8ca0b3 | [
"JavaScript",
"HTML",
"Markdown"
] | 14 | JavaScript | Seluxit/IoTappStore | a5aa2e61eaf48932a7f87e5b225e402b9fd0c568 | 1072b3e9483a3ba94862f6ba68579dc22ad9b73b |
refs/heads/develop | <repo_name>Lyumih/pocket-combats-trade<file_sep>/back/app.js
// подключение express
const express = require("express");
// создаем объект приложения
const app = express();
app.use(express.static(__dirname + "/build"))
// определяем обработчик для маршрута "/"
app.get("/", function (request, response) {
// отправляем ответ
response.send("<h2>Привет Express!</h2>");
});
// начинаем прослушивать подключения на 5000 порту
let port = process.env.PORT || 5000
app.listen(port); | f7e1a535952c66e4a2ea70769074f4dcffcc942a | [
"JavaScript"
] | 1 | JavaScript | Lyumih/pocket-combats-trade | b9b18ce3afe2dfd18e1f882d19f4e16e662966e3 | d4d38c0ee2770d067dc449a94f4a737def5eeefa |
refs/heads/master | <file_sep>import pbundler
pbundler.PBundler.setup()
import sys
import PIL # actually pillow
print(repr(PIL))
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['CheeseshopSource']
import os
import pkg_resources
import xmlrpclib
from . import PBundlerException
from .util import PBDownloader
class CheeseshopSource(object):
def __init__(self, url):
self.url = url
if self.url.endswith('/'):
self.url = self.url[:-1]
def _src(self):
return xmlrpclib.ServerProxy(self.url, xmlrpclib.Transport())
def available_versions(self, cheese):
versions = self._src().package_releases(cheese.name, True)
return versions
def requires(self, cheese):
d = self._src().release_data(cheese.name, cheese.exact_version)
return d["requires"]
def download(self, cheese, target_path):
urls = self._src().release_urls(cheese.name, cheese.exact_version)
filename = None
url = None
remote_digest = None
for urlinfo in urls:
if urlinfo['packagetype'] != 'sdist':
continue
filename = urlinfo['filename']
url = urlinfo['url']
remote_digest = urlinfo['md5_digest']
break
if not url:
print(repr(urls))
raise PBundlerException("Did not find an sdist for %s %s on %s" % (cheese.name, cheese.exact_version, self.url))
target_file = os.path.join(target_path, filename)
PBDownloader.download_checked(url, target_file, remote_digest)
return target_file
class FilesystemSource(object):
def __init__(self, path):
self.path = os.path.expanduser(path)
def available_versions(self, cheese):
dists = pkg_resources.find_distributions(self.path, only=True)
return [dist.version for dist in dists]
def get_distribution(self, cheese):
dists = pkg_resources.find_distributions(self.path, only=True)
return [dist for dist in dists][0]
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['Cheesefile', 'Cheese', 'CHEESEFILE', 'CHEESEFILE_LOCK']
import os
from contextlib import contextmanager
import pkg_resources
from . import PBundlerException
from .dsl import DslRunner
from .sources import CheeseshopSource
CHEESEFILE = 'Cheesefile'
CHEESEFILE_LOCK = 'Cheesefile.lock'
class Cheese(object):
"""A package. A distribution. A requirement. A cheese.
Whatever you want to call it.
"""
def __init__(self, name, version_req, platform=None, path=None, source=None):
self.name = name
self.version_req = version_req
self.platform = platform
self.path = path
self.source = source
self.dist = None
self._requirements = None
@classmethod
def from_requirement(cls, req):
version = ','.join([op + ver for (op, ver) in req.specs])
if version == '':
version = None
return cls(req.project_name, version, None, None)
def applies_to(self, platform):
if self.platform is None:
return True
return (self.platform == platform)
def is_exact_version(self):
return self.version_req.startswith('==')
@property
def exact_version(self):
"""Returns the version number, without an operator. If the operator
was not '==', an Exception is raised."""
if not self.is_exact_version():
raise Exception("Cheese %s didn't have an exact version (%s)" %
(self.name, self.version_req))
return self.version_req[2:]
def use_from(self, version, source):
self.version_req = '==' + version
self.source = source
def use_dist(self, dist):
self.dist = dist
def requirement(self):
"""Return pkg_resources.Requirement matching this object."""
version = self.version_req
if version is None:
version = ''
else:
if not ('>' in version or '<' in version or '=' in version):
version = '==' + version
return pkg_resources.Requirement.parse(self.name + version)
@property
def requirements(self):
assert(self.dist is not None)
if self._requirements is None:
self._requirements = [Cheese.from_requirement(dep) for dep in self.dist.requires()]
return self._requirements
class CheesefileContext(object):
"""DSL Context class. All methods not starting with an underscore
are exposed to the Cheesefile."""
def __init__(self):
self.sources = []
self.groups = {}
with self.group('default'):
pass
def __str__(self):
s = []
for source in self.sources:
s.append('source(%r)' % source)
s.append('')
for name, group in self.groups.items():
indent = ' '
if name == 'default':
indent = ''
else:
s.append('with group(%r):' % name)
for egg in group:
s.append(indent + ('%r' % (egg,)))
s.append('')
return "\n".join(s)
def source(self, name_or_url):
if name_or_url == 'pypi':
name_or_url = 'http://pypi.python.org/pypi'
self.sources.append(CheeseshopSource(name_or_url))
@contextmanager
def group(self, name):
self.current_group = name
self.groups[name] = self.groups.get(name, [])
yield
self.current_group = 'default'
def req(self, name, version=None, platform=None, path=None):
self.groups[self.current_group].append(
Cheese(name, version, platform, path)
)
class Cheesefile(object):
"""Parses and holds Cheesefiles."""
def __init__(self, path):
self.path = path
@classmethod
def generate_empty_file(cls, path):
filepath = os.path.join(path, CHEESEFILE)
if os.path.exists(filepath):
raise PBundlerException("Cowardly refusing, as %s already exists here." %
(CHEESEFILE,))
print("Writing new %s to %s" % (CHEESEFILE, filepath))
with open(filepath, "w") as f:
f.write("# PBundler Cheesefile\n")
f.write("\n")
f.write("source(\"pypi\")\n")
f.write("\n")
f.write("# req(\"Flask\")\n")
f.write("\n")
def parse(self):
runner = DslRunner(CheesefileContext)
ctx = runner.execfile(self.path)
for attr, val in ctx.__dict__.items():
self.__setattr__(attr, val)
def collect(self, groups, platform):
collection = {}
groups = [group for name, group in self.groups.iteritems() if name in groups]
for pkgs in groups:
for pkg in pkgs:
if pkg.applies_to(platform):
collection[pkg.name] = pkg
return collection
class CheesefileLockContext(object):
"""DSL Context class. All methods not starting with an underscore
are exposed to the Cheesefile.lock."""
def __init__(self):
self.cheesefile_data = []
self.from_source_data = {}
@contextmanager
def from_source(self, url):
self.from_source_data[url] = []
self.current_req_context = self.from_source_data[url]
yield
self.current_req_context = None
@contextmanager
def Cheesefile(self):
self.current_req_context = self.cheesefile_data
yield
self.current_req_context = None
def req(self, name, version, platform=None, path=None):
req = Cheese(name, version, platform, path)
self.current_req_context.append(req)
@contextmanager
def resolved_req(self, name, version):
prev_req_context = self.current_req_context
solved_req = Cheese(name, version)
self.current_req_context = solved_req.requirements
yield
self.current_req_context = prev_req_context
self.current_req_context.append(solved_req)
class CheesefileLock(object):
"""Parses and holds Cheesefile.locks."""
def __init__(self, path):
self.path = path
def parse(self):
runner = DslRunner(CheesefileLockContext)
ctx = runner.execfile(self.path)
for attr, val in ctx.__dict__.items():
self.__setattr__(attr, val)
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['PBundlerException']
class PBundlerException(Exception):
pass
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['PBFile', 'PBDownloader', 'PBArchive']
import os
from hashlib import md5
from urllib2 import Request, urlopen
import subprocess
import shutil
import pkg_resources
from . import PBundlerException
# Utility functions. Not for public consumption.
# If you need some of these exposed, please talk to us.
class PBFile(object):
@staticmethod
def read(path, filename):
try:
with open(os.path.join(path, filename), 'r') as f:
return f.read()
except:
return None
@staticmethod
def find_upwards(fn, root=os.path.realpath(os.curdir)):
if os.path.exists(os.path.join(root, fn)):
return root
up = os.path.abspath(os.path.join(root, '..'))
if up == root:
return None
return PBFile.find_upwards(fn, up)
@staticmethod
def ensure_dir(path):
if not os.path.exists(path):
os.makedirs(path)
@staticmethod
def md5_digest(path):
digest = md5()
with file(path, 'rb') as f:
digest.update(f.read())
return digest.hexdigest()
class PBDownloader(object):
@classmethod
def download_checked(cls, url, target_file, expected_digest):
if os.path.exists(target_file):
# file already exists, see if we can use it.
if PBFile.md5_digest(target_file) == expected_digest:
# local file is ok
return
else:
os.unlink(target_file)
user_agent = ("pbunder/%s " % (cls.my_version) +
"(http://github.com/zeha/pbundler/issues)")
try:
req = Request(url)
req.add_header("User-Agent", user_agent)
req.add_header("Accept", "*/*")
with file(target_file, 'wb') as f:
sock = urlopen(req)
try:
f.write(sock.read())
finally:
sock.close()
except Exception as ex:
raise PBundlerException("Downloading %s failed (%s)" % (url, ex))
local_digest = PBFile.md5_digest(target_file)
if local_digest != expected_digest:
os.unlink(target_file)
msg = ("Downloading %s failed (MD5 Digest %s did not match expected %s)" %
(url, local_digest, expected_digest))
raise PBundlerException(msg)
else:
# local file is ok
return
try:
PBDownloader.my_version = pkg_resources.get_distribution('pbundler').version
except:
PBDownloader.my_version = 'DEV'
class PBArchive(object):
def __init__(self, path):
self.path = path
self.filetype = os.path.splitext(path)[1][1:]
if self.filetype in ['tgz', 'gz', 'bz2', 'xz']:
self.filetype = 'tar'
if self.filetype not in ['zip', 'tar']:
raise PBundlerException("Unsupported Archive file: %s" % (self.path))
def unpack(self, destination):
if os.path.exists(destination):
shutil.rmtree(destination)
PBFile.ensure_dir(destination)
# FIXME: implement this stuff in pure python
if self.filetype == 'zip':
subprocess.call(['unzip', '-q', self.path, '-d', destination])
elif self.filetype == 'tar':
subprocess.call(['tar', 'xf', self.path, '-C', destination])
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['PyPath']
import ctypes
import sys
import pkg_resources
class PyPath:
@staticmethod
def builtin_path():
"""Consumes the C API Py_GetPath function to return the path
built into the Python interpreter.
This already takes care of PYTHONPATH.
Note: actually Py_GetPath dynamically computes the path on
the first call (which happens during startup).
"""
Py_GetPath = ctypes.pythonapi.Py_GetPath
if sys.version_info[0] >= 3:
# Unicode
Py_GetPath.restype = ctypes.c_wchar_p
else:
Py_GetPath.restype = ctypes.c_char_p
return Py_GetPath().split(':')
@staticmethod
def path_for_pkg_name(pkg_name):
pkgs = [pkg for pkg in pkg_resources.working_set
if pkg.project_name == pkg_name]
if len(pkgs) == 0:
return None
return pkgs[0].location
@classmethod
def bundler_path(cls):
"""Returns the path to PBundler itself."""
return cls.path_for_pkg_name("pbundler")
@classmethod
def clean_path(cls):
"""Return a list containing the builtin_path and bundler_path.
Before replacing sys.path with this, realize that sys.path[0]
will be missing from this list.
"""
path = [cls.bundler_path()] + cls.builtin_path()
return path
@classmethod
def replace_sys_path(cls, new_path):
for path in sys.path[:]:
sys.path.remove(path)
sys.path.extend(new_path)
PyPath.initial_sys_path_0 = sys.path[0]
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['run']
import PBundler
import traceback
import sys
import code
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
# readline magically hooks into code.InteractiveConsole somehow.
# don't ask.
def run():
"""minimal interpreter, mostly for debugging purposes."""
console = code.InteractiveConsole()
console.interact("PBundler REPL on Python" + str(sys.version))
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['Bundle']
import os
import sys
from . import PBundlerException
from .util import PBFile
from .pypath import PyPath
from .cheesefile import Cheesefile, CheesefileLock, Cheese, CHEESEFILE, CHEESEFILE_LOCK
from .sources import FilesystemSource
from .localstore import LocalStore
class Bundle:
def __init__(self, path):
self.path = path
self.current_platform = 'cpython'
self.cheesefile = Cheesefile(os.path.join(self.path, CHEESEFILE))
self.cheesefile.parse()
cheesefile_lock_path = os.path.join(self.path, CHEESEFILE_LOCK)
if os.path.exists(cheesefile_lock_path):
self.cheesefile_lock = CheesefileLock(cheesefile_lock_path)
self.cheesefile_lock.parse()
else:
self.cheesefile_lock = None
self.localstore = LocalStore()
@classmethod
def load(cls, path=None):
"""Preferred constructor."""
if path is None:
path = PBFile.find_upwards(CHEESEFILE)
if path is None:
message = ("Could not find %s in path from here to " +
"filesystem root.") % (CHEESEFILE)
raise PBundlerException(message)
return cls(path)
def validate_requirements(self):
self.calculate_requirements()
pass
def _add_new_dep(self, dep):
cheese = Cheese.from_requirement(dep)
existing = self.required.get(cheese.name)
if existing:
# FIXME: check if we're compatible
return None
self.required[cheese.name] = cheese
return cheese
def _resolve_deps(self):
for pkg in self.required.values():
if pkg.source or pkg.dist:
# don't touch packages where we already know a source (& version)
continue
if pkg.path:
source = FilesystemSource(pkg.path)
available_versions = source.available_versions(pkg)
if len(available_versions) == 0:
raise PBundlerException("Package %s is not available in %r" % (pkg.name, pkg.path))
if len(available_versions) != 1:
raise PBundlerException("Package %s has multiple versions in %r" % (pkg.name, pkg.path))
version = available_versions[0]
pkg.use_from(version, source)
else:
req = pkg.requirement()
for source in self.cheesefile.sources:
for version in source.available_versions(pkg):
if version in req:
pkg.use_from(version, source)
break
if pkg.source is None:
raise PBundlerException("Package %s %s is not available on any sources." % (pkg.name, pkg.version_req))
new_deps = []
for pkg in self.required.values():
if pkg.dist:
# don't touch packages where we already have a (s)dist
continue
if pkg.path:
# FIXME: not really the truth
dist = pkg.source.get_distribution(pkg.source)
print("Using %s %s from %s" % (pkg.name, pkg.exact_version, pkg.path))
else:
dist = self.localstore.get(pkg)
if dist:
print("Using %s %s" % (pkg.name, pkg.exact_version))
else:
# download and unpack
dist = self.localstore.prepare(pkg, pkg.source)
pkg.use_dist(dist)
for dep in dist.requires():
new_deps.append(self._add_new_dep(dep))
# super ugly:
new_deps = list(set(new_deps))
if None in new_deps:
new_deps.remove(None)
return new_deps
def install(self, groups):
self.required = self.cheesefile.collect(groups, self.current_platform)
while True:
new_deps = self._resolve_deps()
if len(new_deps) == 0:
# done resolving!
break
for pkg in self.required.values():
if getattr(pkg.dist, 'is_sdist', False) is True:
dist = self.localstore.install(pkg, pkg.dist)
pkg.use_dist(dist) # mark as installed
self._write_cheesefile_lock()
print("Your bundle is complete.")
def _write_cheesefile_lock(self):
# TODO: file format is wrong. at least we must consider groups,
# and we shouldn't rewrite the entire file (think groups, platforms).
# TODO: write source to lockfile.
with file(os.path.join(self.path, CHEESEFILE_LOCK), 'wt') as lockfile:
indent = ' '*4
lockfile.write("with Cheesefile():\n")
for pkg in self.cheesefile.collect(['default'], self.current_platform).itervalues():
lockfile.write(indent+"req(%r, %r, path=%r)\n" % (pkg.name, pkg.exact_version, pkg.path))
lockfile.write(indent+"pass\n")
lockfile.write("\n")
for source in self.cheesefile.sources:
lockfile.write("with from_source(%r):\n" % (source.url))
for name, pkg in self.required.items():
# ignore ourselves and our dependencies (which should
# only ever be distribute).
if name in ['pbundler','distribute']:
continue
if pkg.source != source:
continue
lockfile.write(indent+"with resolved_req(%r, %r):\n" % (pkg.name, pkg.exact_version))
for dep in pkg.requirements:
lockfile.write(indent+indent+"req(%r, %r)\n" % (dep.name, dep.version_req))
lockfile.write(indent+indent+"pass\n")
lockfile.write(indent+"pass\n")
def _check_sys_modules_is_clean(self):
# TODO: Possibly remove this when resolver/activation development is done.
unclean = []
for name, module in sys.modules.iteritems():
source = getattr(module, '__file__', None)
if source is None or name == '__main__':
continue
in_path = False
for path in sys.path:
if source.startswith(path):
in_path = True
break
if in_path:
continue
unclean.append('%s from %s' % (name, source))
if len(unclean) > 0:
raise PBundlerException("sys.modules contains foreign modules: %s" % ','.join(unclean))
def load_cheese(self):
if getattr(self, 'required', None) is None:
# while we don't have a lockfile reader:
self.install(['default'])
#raise PBundlerException("Your bundle is not installed.")
def enable(self, groups):
# TODO: remove groups from method sig
self.load_cheese()
# reset import path
new_path = [sys.path[0]]
new_path.extend(PyPath.clean_path())
PyPath.replace_sys_path(new_path)
enabled_path = []
for pkg in self.required.values():
pkg.dist.activate(enabled_path)
new_path = [sys.path[0]]
new_path.extend(enabled_path)
new_path.extend(PyPath.clean_path())
PyPath.replace_sys_path(new_path)
self._check_sys_modules_is_clean()
def exec_enabled(self, command):
# We don't actually need all the cheese loaded, but it's great to
# fail fast.
self.load_cheese()
import pkg_resources
dist = pkg_resources.get_distribution('pbundler')
activation_path = os.path.join(dist.location, 'pbundler', 'activation')
os.putenv('PYTHONPATH', activation_path)
os.putenv('PBUNDLER_CHEESEFILE', self.cheesefile.path)
os.execvp(command[0], command)
def get_cheese(self, name, default=None):
self.load_cheese()
return self.required.get(name, default)
<file_sep>from __future__ import print_function
import traceback
try:
import pbundler
pbundler.PBundler.setup()
except:
print("E: Exception in pbundler activation code.")
print("")
print("Please report this to the pbundler developers:")
print(" http://github.com/zeha/pbundler/issues")
print("")
traceback.print_exc()
print("")
<file_sep>Python Bundler
==============
Simplifies virtualenv and pip usage.
Aims to be compatible with all existing projects already carrying a "requirements.txt" in their source.
Inspired by http://gembundler.com/
Howto
-----
* easy\_install pbundler
* cd into your project path
* Run pbundle. It will install your project's dependencies into a fresh virtualenv.
To run commands with the activated virtualenv:
pbundle exec bash -c 'echo "I am activated. virtualenv: $VIRTUAL_ENV"'
Or, for python programs:
pbundle py ./debug.py
If you don't have a requirements.txt yet but have an existing project, try this:
pip freeze > requirements.txt
If you start fresh, try this for a project setup:
mkdir myproject && cd myproject
git init
pbundle init
Instructions you can give your users:
git clone git://github.com/you/yourproject.git
easy_install pbundler
pbundle
If you rather like pip, and you're sure your users already have pip:
git clone git://github.com/you/yourproject.git
pip install pbundler
pbundle
Making python scripts automatically use pbundle py
--------------------------------------------------
Replace the shebang with "/usr/bin/env pbundle-py". Example:
#!/usr/bin/env pbundle-py
import sys
print sys.path
WSGI/Unicorn example
--------------------
start-unicorn.sh:
#!/bin/bash
cd /srv/app/flaskr
PYTHONPATH=/srv/app/wsgi exec pbundle exec gunicorn -w 5 -b 127.0.0.1:4000 -n flaskrprod flaskr:app
Custom environment variables
----------------------------
If you need to set custom ENV variables for the executed commands in your local copy, do this:
echo "DJANGO_SETTINGS_MODULE='mysite.settings'" >> .pbundle/environment.py
TODO
----
* Build inventory from what is installed, instead of requirements.last file
* Handle failed egg installs
* Really remove all no longer needed packages from virtualenv
* Reorganize library code
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['PBCli', 'pbcli', 'pbpy']
import os
import sys
import traceback
import pbundler
USAGE = """
pbundle Copyright 2012,2013 <NAME>
pbundle Usage:
pbundle [install] - Install the packages from Cheesefile
pbundle update - Update dependencies to their latest versions
pbundle init - Create a basic Cheesefile
pbundle exec program - Run "program" in activated environment
pbundle console - Start an interactive activated python session
To auto-enable your scripts, use "#!/usr/bin/env pbundle-py" as the
shebang line. Alternatively:
require pbundler
pbundler.PBundler.setup()
Website: https://github.com/zeha/pbundler
Report bugs: https://github.com/zeha/pbundler/issues
"""
class PBCli():
def __init__(self):
self._bundle = None
@property
def bundle(self):
if not self._bundle:
self._bundle = pbundler.PBundler.load_bundle()
return self._bundle
def handle_args(self, argv):
args = argv[1:]
command = "install"
if args:
command = args.pop(0)
if command in ['--help', '-h']:
command = 'help'
if command == '--version':
command = 'version'
if 'cmd_' + command in PBCli.__dict__:
return PBCli.__dict__['cmd_' + command](self, args)
else:
raise pbundler.PBundlerException("Could not find command \"%s\"." %
(command,))
def run(self, argv):
try:
return self.handle_args(argv)
except pbundler.PBundlerException as ex:
print("E:", str(ex))
return 1
except Exception as ex:
print("E: Internal error in pbundler:")
print(" ", ex)
traceback.print_exc()
return 120
def cmd_help(self, args):
print(USAGE.strip())
def cmd_init(self, args):
path = os.getcwd()
if len(args) > 0:
path = os.path.abspath(args[0])
pbundler.cheesefile.Cheesefile.generate_empty_file(path)
def cmd_install(self, args):
self.bundle.install(['default'])
def cmd_update(self, args):
self.bundle.update()
def cmd_exec(self, args):
return self.bundle.exec_enabled(args)
def cmd_console(self, args):
plain = False
for arg in args[:]:
if arg == '--':
args.pop(0)
break
elif arg == '--plain':
args.pop(0)
plain = True
else:
break
command = [sys.executable]
if not plain:
# If ipython is part of the bundle, use it.
for shell_name in ['ipython']:
shell = self.bundle.get_cheese(shell_name)
if not shell:
continue
# FIXME: need a way to look this path up.
command = [os.path.join(shell.dist.location, "..", "bin", shell_name)]
command.extend(args)
return self.bundle.exec_enabled(command)
def cmd_repl(self, args):
#self.bundle.validate_requirements()
import pbundler.repl
pbundler.repl.run()
def cmd_version(self, args):
import pkg_resources
dist = pkg_resources.get_distribution('pbundler')
print(dist)
return 0
def pbcli():
sys.exit(PBCli().run(sys.argv))
def pbpy():
argv = [sys.argv[0], "console", "--plain", "--"] + sys.argv[1:]
sys.exit(PBCli().run(argv))
<file_sep>from __future__ import absolute_import
__all__ = ['PBundler']
from .exceptions import *
from .bundle import Bundle
from .cli import PBCli
class PBundler(object):
"""Public API"""
@classmethod
def load_bundle(cls, path=None):
"""Load a bundle from path and return it. Does not modify the
current environment."""
return Bundle.load(path)
@classmethod
def setup(cls, path=None, groups=None):
"""Load a bundle from path and activate it in the current
environment.
Returns the bundle."""
bundle = Bundle.load(path)
if groups is None:
groups = 'default'
bundle.enable(groups)
return bundle
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['DslRunner']
class DslRunner(object):
"""Runs Python code in the context of a class.
Public methods will be exposed to the DSL code.
"""
def __init__(self, contextclass):
self.contextclass = contextclass
def make_context(self):
ctx = self.contextclass()
ctxmap = {}
method_names = [fun for fun in ctx.__class__.__dict__ if not fun.startswith('_')]
methods = ctx.__class__.__dict__
def method_caller(fun):
unbound = methods[fun]
def wrapped(*args, **kw):
args = (ctx,) + args
return unbound(*args, **kw)
return wrapped
for fun in method_names:
ctxmap[fun] = method_caller(fun)
return (ctx, ctxmap)
def execfile(self, filename):
ctx, ctxmap = self.make_context()
execfile(filename, {}, ctxmap)
return ctx
<file_sep>from __future__ import print_function
from __future__ import absolute_import
__all__ = ['LocalStore']
import os
import platform
import pkg_resources
import glob
import subprocess
import sys
import tempfile
from . import PBundlerException
from .util import PBFile, PBArchive
class LocalStore(object):
def __init__(self, path=None):
if path is None:
if os.getenv('PBUNDLER_STORE'):
self.path = os.getenv('PBUNDLER_STORE')
else:
self.path = os.path.expanduser('~/.cache/pbundler/')
else:
self.path = path
PBFile.ensure_dir(self.path)
self._temp_path = None
self.python_name = ('%s-%s' % (platform.python_implementation(),
('.'.join(platform.python_version_tuple()[:-1]))))
@property
def cache_path(self):
path = os.path.join(self.path, 'cache')
PBFile.ensure_dir(path)
return path
@property
def temp_path(self):
if not self._temp_path:
self._temp_path = tempfile.mkdtemp(prefix='pbundle')
return self._temp_path
def get(self, cheese):
lib_path = self.path_for(cheese, 'lib')
if os.path.exists(lib_path):
dists = [d for d in pkg_resources.find_distributions(lib_path, only=True)]
if len(dists) == 1:
return dists[0]
return None
def path_for(self, cheese, sub=None):
path = [self.path, 'cheese', self.python_name,
'%s-%s' % (cheese.name, cheese.exact_version)]
if sub is not None:
path.append(sub)
return os.path.join(*path)
def prepare(self, cheese, source):
"""Download and unpack the cheese."""
print("Downloading %s %s..." % (cheese.name, cheese.exact_version))
# path we use to install _from_
source_path = os.path.join(self.temp_path, cheese.name, cheese.exact_version)
sdist_filepath = source.download(cheese, self.cache_path)
PBArchive(sdist_filepath).unpack(source_path)
# FIXME: ugly hack to get the unpacked dir.
# actually we should say unpack(..., strip_first_dir=True)
source_path = glob.glob(source_path + '/*')[0]
return UnpackedSdist(source_path)
def install(self, cheese, unpackedsdist):
print("Installing %s %s..." % (cheese.name, cheese.exact_version))
cheese_path = self.path_for(cheese)
lib_path = self.path_for(cheese, 'lib')
PBFile.ensure_dir(lib_path)
unpackedsdist.run_setup_py(['install',
'--root', cheese_path,
'--install-lib', 'lib',
'--install-scripts', 'bin'], {'PYTHONPATH': lib_path}, "Installing")
return self.get(cheese)
class UnpackedSdist(object):
def __init__(self, path):
self.path = path
self.is_sdist = True
def requires(self):
self.run_setup_py(['egg_info'], {}, "Preparing", raise_on_fail=False)
egg_info_path = glob.glob(self.path + '/*.egg-info')
if not egg_info_path:
return []
requires_path = os.path.join(egg_info_path[0], 'requires.txt')
if not os.path.exists(requires_path):
return []
requires_raw = []
with file(requires_path, 'rt') as f:
requires_raw = f.readlines()
# requires.txt MAY contain sections, and we ignore all of them except
# the unnamed section.
sections = [line for line in requires_raw if line.startswith('[')]
if sections:
requires_raw = requires_raw[0:requires_raw.index(sections[0])]
else:
requires_raw = requires_raw
return [req for req in pkg_resources.parse_requirements(requires_raw)]
def run_setup_py(self, args, envvars, step, raise_on_fail=True):
setup_cwd = self.path
cmd = [sys.executable, 'setup.py'] + args
env = dict(os.environ)
if envvars:
env.update(envvars)
with tempfile.NamedTemporaryFile() as logfile:
proc = subprocess.Popen(cmd,
cwd=setup_cwd,
close_fds=True,
stdin=subprocess.PIPE,
stdout=logfile,
stderr=subprocess.STDOUT,
env=env)
proc.stdin.close()
rv = proc.wait()
if rv != 0 and raise_on_fail:
logfile.seek(0, os.SEEK_SET)
print(logfile.read())
msg = ("%s failed with exit code %d. Source files have been" +
" left in %r for you to examine.\nCommand line was: %s") % (
step, rv, setup_cwd, cmd)
raise PBundlerException(msg)
<file_sep>PHILOSOPHY
==========
* Don't bother with Packages that can't be bothered to have a full cheeseshop record.
* Don't bother with complex version requirements in Cheesefile.
* Don't bother with getting stuff 100% right.
* Bother with an (internal) API.
Notes
=====
A note on binary distributions
------------------------------
While the initial version will probably not support them, we very likely want to allow this.
A note on cheeseshops
---------------------
The official PyPI is a beast: it has four different ways offering data access, none of them supporting the same set of features.
The initial version will probably only support cheeseshops with an XMLRPC interface. Depending on what else happens, we might need to expand on this support.
<file_sep>#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
extra = {
'install_requires': ['distribute']
}
if sys.version_info >= (3,):
extra['use_2to3'] = False
setup(
name="pbundler",
version="0.8.0a0",
packages=find_packages(),
zip_safe=False,
entry_points={
'console_scripts': [
'pbundle = pbundler.cli:pbcli',
'pbundle-py = pbundler.cli:pbpy',
],
},
# metadata for upload to PyPI
author="<NAME>",
author_email="<EMAIL>",
description="Bundler for Python",
license="MIT",
keywords="bundler bundle pbundler pbundle dependency dependencies management virtualenv pip packages",
url="http://github.com/zeha/pbundler/",
download_url="https://github.com/zeha/pbundler/downloads",
**extra
)
| 8b3f36c6b14b43fc8c1d2da5b42a1535d3541ce1 | [
"Markdown",
"Python"
] | 16 | Python | zeha/pbundler | 01a45bde68e0e76042d845343a22f3cdfcda7cee | 34a8245bc9d4dbcfbbc8242f413c316fc22cebb0 |
refs/heads/master | <repo_name>eron93br/opendsp<file_sep>/wavsig/readme.md
# WavSig
WavSig is a open-source signal generator for Arduino UNO and AVR Microcontrollers.
WavSig is based on MCP4921 Digital to Analog converter from Microchip
# Usage
# Waveform Generator with Arduino DUE
https://www.arduino.cc/en/Tutorial/DueSimpleWaveformGenerator
<file_sep>/mikroplot/readme.md
MikroPlot to plot data from Arduino!
# MikroPlot
O MirkoPlot é um programa desenvolvido pelo pessoal da MikroElektronika para plotar em tempo real dados vindos da serial do Arduino, via comunicação serial! O link para o download é https://libstock.mikroe.com/projects/view/1937/mikroplot-data-visualization-tool
# openDSP e MikroPlot
O objetivo do uso do MikroPlot é para plotar em tempo real os resultados de filtros digitais aplicados usando o MCU/plataforma Arduino.
O código exemplo pode ser encontrado.
<file_sep>/MCP3201.ino
#include <SPI.h>
const int chipSelectPinADC = 6;
unsigned int result = 0;
byte inByte = 0;
int saida;
const int PIN_CS = 7;
const int GAIN_1 = 0x1;
const int GAIN_2 = 0x0;
void setup()
{
Serial.begin(9600);
pinMode(PIN_CS, OUTPUT);
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV4);
pinMode(chipSelectPinADC, OUTPUT);
digitalWrite(chipSelectPinADC, HIGH);
}
void analog_to_digital()
{
digitalWrite(chipSelectPinADC, LOW);
result = SPI.transfer(0x00);
result = result << 8;
inByte = SPI.transfer(0x00);
result = result | inByte;
digitalWrite(chipSelectPinADC, HIGH);
result = result >> 1;
result = result & 0b0000111111111111;
}
void digital_to_analog(unsigned int val)
{
saida = val;
byte lowByte = (val & 0xff) ;
byte highByte = ((val >> 8) & 0xff) | 0x10;
//PORTB &= 0xfb; // baixo
SPI.transfer(highByte);
SPI.transfer(lowByte);
//PORTB |= 0x4; // alto
}
void loop()
{
analog_to_digital();
digital_to_analog(result);
}
<file_sep>/MCP3201/readme.md
readme file to write about MCP3201
<file_sep>/README.md
# opendsp
Codes for DSP in MUCs and FPGAs
The objectiv of OpenDSP is share codes related to Digital Signal Processing (DSP) on Microcontrollers and FPGAs.
If you want to contribute, please fell free to contact me (<EMAIL>)
<file_sep>/SPI_MCP3201_DUE.ino
#include <SPI.h>
unsigned int result = 0;
byte inByte = 0;
byte byteOne = 0; //Initialize an 8 bit variable to read the first byte from the MCP3201
byte byteTwo = 0;
int saida;
const int GAIN_1 = 0x1;
const int GAIN_2 = 0x0;
void setup()
{
Serial.begin(9600);
// ADC SETUP
// CS PIN USED IS 10!
SPI.begin(10); //Initialize the bus for a device on pin 4
SPI.setDataMode(10,1); //Set SPI data mode to 1
SPI.setBitOrder(10, MSBFIRST); //Expect the most significant bit first, apply rule only to pin 10
SPI.setClockDivider(10, 52); //Set clock divider on pin 10 to 42 (84 MHz / 42 = 2 MHz SPI bus speed)
//digitalWrite(ADC, HIGH); // DAC SETUP
// DAC SETUP
// CS PIN USED IS 4!
SPI.begin(4);
SPI.setDataMode(4,1);
//Initialize the bus for a device on pin 10
SPI.setBitOrder(4, MSBFIRST); //Expect the most significant bit first, apply rule only to pin 10
}
int analog_to_digital()
{
byteOne = SPI.transfer(10, 0x00, SPI_CONTINUE); //Read the first byte from the MCP3201, keep CS active LOW for the next byte to transfer
byteTwo = SPI.transfer(10, 0x00, SPI_LAST); //Read the second byte, take CS pin 10 HIGH to disable the MCP3201
result = byteOne; //Store the first byte into the result variable
result = result << 8; //Shift the first byte left 8 bits.
result = result | byteTwo; //Combine the two bytes into a 16 bit word (stored in a 32 bit variable) using OR function
result = result >> 1; //Shift the bits in the word to the right 1 places. Bit 0 from MCP3201 is blank data.
result = result & 0b00000000000000000000111111111111; //Bit mask the first 20 bits using the AND function. We only want to look at the last 12 bits
//Serial.print( "entrada: ");
//Serial.print( result );
return result;
}
void digital_to_analog(unsigned int val)
{
Serial.print(" -- OUT:");
Serial.println(val);
byte b0 = (val & 0x000000ff) ;
byte b1 = ((val >> 8) & 0x000000ff) | 0x00000010;
//Serial.println(b1);
//digitalWrite(4,LOW);
SPI.transfer(4, b1, SPI_CONTINUE);
SPI.transfer(4, b0);
//digitalWrite(4,HIGH);
}
int sinal=0;
void loop()
{
sinal = analog_to_digital();
//Serial.println(sinal);
digital_to_analog(sinal);
//delay(400);
}
<file_sep>/mikroplot/example.ino
int EEG_Value;
float mytime = 0;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(57200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB
}
Serial.println("START");
}
// the loop routine runs over and over again forever:
void loop() {
int EEG_Value = analogRead(A0);
Serial.print(EEG_Value);
Serial.print(",");
Serial.println(mytime);
mytime = mytime + 3.90;
delay(3900);
}
| d4d312ff2a20a89115e4f1cd81aebad7c191bb09 | [
"Markdown",
"C++"
] | 7 | Markdown | eron93br/opendsp | b47dd9d96ce72393d7f797feac7b4bf5d81e047b | 640c008c24af95f608ac58a1aa1054166aebe704 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
double** ler(const char *nomeArq, int *d)
{
int i, j, dim;
double **M, a;
FILE *arq;
arq = fopen(nomeArq, "r");
i = fscanf(arq,"%d",&dim);
M = malloc( dim*sizeof(double *));
for( i = 0 ; i < dim ; i++ )
M[i] = (double *) malloc((dim+1)*sizeof(double));
i=j=0;
while (fscanf(arq,"%lf",&a) != EOF)
{
M[i][j] = a;
j++;
if (j == dim+1)
{
j = 0;
i++;
}
}
*d=dim;
return M;
}
void imprime(double **M, int var)
{
int i, j;
for(i=0;i<var;i++)
{
for(j=0;j<var+1;j++)
printf("%.0lf\t",M[i][j]);
puts("");
}
}
void triangsup(double **M, int dim)
{
int i, j, k;
double lamb;
i=j=0;
puts("\nMatriz triangularizada:");
for(j=0; j<dim; j++)
{
for(i=j; i<dim-1; i++)
{
lamb=M[i+1][j]/M[j][j];
for(k=j; k<dim+1; k++)
{
M[i+1][k] = M[i+1][k] - (lamb)*M[j][k];
}
}
}
}
void subsreversa (double **M, double *raizes, int dim)
{
int i, j;
double soma=0;
for(i=dim-1; i>=0; i--)
{
raizes[i] = M[i][dim];
for(j=dim; j>=i+1; j--)
raizes[i]-=M[i][j]*raizes[j];
raizes[i]/=M[i][i];
}
}
main(int argc, char **argv) {
double **M;
double *raizes;
int i, dim;
M=ler(argv[1], &dim);
imprime(M,dim);
triangsup(M,dim);
imprime(M,dim);
raizes = malloc(dim*sizeof(double));
subsreversa(M,raizes,dim);
puts("Raizes\n\n");
for(i=0; i<dim; i++)
printf("x%d = %5.2lf\t", i, raizes[i]);
printf("\n\n");
}
| 74f6da6966fa4fdf6777a04224b077e2ac660006 | [
"C"
] | 1 | C | lucasthiago/Metodo-Gauss | 1fdf140f8a3082ddde326fc6ce3844214ba05eb7 | f3af8b783d1ee6f7cc7c6f88bd488eb0179316d4 |
refs/heads/master | <repo_name>ajmagnus/Test-Repo<file_sep>/ConsoleApplication1/Sample-Test1/test.cpp
#include "pch.h"
#include <string>
#include "../ConsoleApplication1/Message.h"
TEST(TestCaseName, TestName) {
EXPECT_EQ(1, 1);
EXPECT_TRUE(true);
}
TEST(testMessage, test1) {
Message testClass;
std::string answer = "Hello World!";
std::string output = testClass.print();
EXPECT_TRUE(answer.compare(output));
}<file_sep>/ConsoleApplication1/NativeTestHelloWorld/unittest1.cpp
#include "stdafx.h"
#include "CppUnitTest.h"
#include "../ConsoleApplication1/Message.h"
#include <string>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace NativeTestHelloWorld
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
Message mess;
std::string line = "Hello World!";
Assert::AreEqual(line, mess.print());
}
};
}<file_sep>/ConsoleApplication1/Sample-Test2/test.cpp
#include "pch.h"
#include "../ConsoleApplication1/Message.h"
#include <iostream>
TEST(TestCaseName, TestName) {
EXPECT_EQ(1, 1);
EXPECT_TRUE(true);
}
TEST(HelloWorldTest, test1) {
std::string output;
std::string answer;
Message source = Message::Message();
output = source.print();
answer = "Hello World!";
EXPECT_EQ(output, answer);
}
<file_sep>/ConsoleApplication1/ConsoleApplication1/Message.h
#pragma once
#include <string>
class Message
{
public:
Message();
~Message();
std::string print();
};
<file_sep>/ConsoleApplication1/TestHelloWorld/test.cpp
#include "pch.h"
#include <string>
#include "../ConsoleApplication1/Message.h"
TEST(MessageTest, ReturnMessage) {
ASSERT_TRUE(0 == 0);
}
TEST(TestMessage, Return) {
Message source;
std::string answer = "Hello World!";
std::string output = source.print();
ASSERT_TRUE(answer.compare(output));
}<file_sep>/ConsoleApplication1/ConsoleApplication1/Message.cpp
#include "pch.h"
#include "Message.h"
#include <string>
Message::Message()
{
}
Message::~Message()
{
}
std::string Message::print()
{
return "Hello World!";
}
| e5a53660a1cfcde8df657ac7f07b1f02f2e2029d | [
"C++"
] | 6 | C++ | ajmagnus/Test-Repo | 7e07efc20f3fd02e5d69a6ffe363aa21200b91e2 | 3959569a3cc6473fc4195a3a95cb377efd4ef521 |
refs/heads/master | <repo_name>artursharypau/filtering-task<file_sep>/FilteringTask/Obj.cs
namespace FilteringTask
{
class Obj
{
public int Id { get; set; }
}
}
<file_sep>/FilteringTask/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace FilteringTask
{
class Program
{
static void Main(string[] args)
{
IList<Obj> collection = new List<Obj>()
{
new Obj() { Id = 1 },
new Obj() { Id = 2 },
new Obj() { Id = 3 },
};
// Method 1
var obj1 = collection.Where(x => x.Id == 2);
foreach (var o in obj1)
{
Console.WriteLine(o.Id);
}
// Method 2
var obj2 = from x in collection
where x.Id == 3
select x;
foreach (var o in obj2)
{
Console.WriteLine(o.Id);
}
// Method 3
foreach (var o in collection)
{
if (o.Id == 2)
{
Console.WriteLine(o.Id);
}
}
// Method 4
var obj4 = collection.First(x => x.Id == 3);
Console.WriteLine(obj4.Id);
// Method 5
var obj5 = collection.FirstOrDefault(x => x.Id == 3);
Console.WriteLine(obj5.Id);
// Method 6
var obj6 = collection.Last(x => x.Id == 1);
Console.WriteLine(obj6.Id);
// Method 7
var obj7 = collection.LastOrDefault(x => x.Id == 1);
Console.WriteLine(obj7.Id);
}
}
}
| 586cd6075cb53547a33f90852ee73650127f6524 | [
"C#"
] | 2 | C# | artursharypau/filtering-task | 56c9fd537f777014790a5e657e09c8492886eada | 646ac2b20a2059e39f8c282e80591bb26e652c42 |
refs/heads/master | <repo_name>fcccode/WMI<file_sep>/structures.h
#pragma once
#include <string>
using namespace std;
struct PRODUCT
{
wstring name;
wstring id;
wstring version;
wstring publisher;
};
struct PROCESS
{
wstring caption;
wstring id;
wstring path;
wstring handles;
};
struct SERVICE
{
wstring name;
wstring id;
wstring start;
wstring state;
wstring status;
};
struct LOGICALDISK
{
wstring id;
wstring type;
wstring freespace;
wstring size;
};
struct PROCESSOR
{
wstring caption;
wstring id;
wstring manufacturer;
wstring speed;
wstring name;
wstring socket;
};
struct BIOS
{
wstring biosversion;
wstring manufacturer;
wstring name;
wstring number;
wstring version;
};
struct HARDDRIVE
{
wstring parts;
wstring id;
wstring model;
wstring size;
wstring caption;
};
struct OS
{
wstring dir;
wstring id;
wstring caption;
wstring number;
wstring version;
};
struct ANTIPRODUCT
{
wstring name;
wstring guid;
wstring exepath;
wstring time;
};
struct FIREWALL
{
wstring guid;
wstring exepath;
wstring time;
};<file_sep>/client.cpp
#define _CRT_SECURE_NO_WARNINGS
#define _WIN32_DCOM
#define UNICODE
#include <iostream>
#include <comutil.h>
#include <atlbase.h>
#include <tchar.h>
#include <Wbemidl.h>
#include <vector>
#include <comdef.h>
#include <wincred.h>
#include <strsafe.h>
#include "structures.h"
#pragma comment(lib, "comsuppw.lib")
#pragma comment(lib, "Wbemuuid.lib")
#pragma comment(lib, "credui.lib")
using namespace std;
IWbemLocator *pLoc = NULL;
IWbemServices *pSvc = NULL;
wchar_t ipAddr[CREDUI_MAX_USERNAME_LENGTH + 1];
wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 };
wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH + 1] = { 0 };
wchar_t pszDomain[CREDUI_MAX_USERNAME_LENGTH + 1];
wchar_t pszUserName[CREDUI_MAX_USERNAME_LENGTH + 1];
wchar_t pszAuthority[CREDUI_MAX_USERNAME_LENGTH + 1];
COAUTHIDENTITY *userAcct = NULL;
COAUTHIDENTITY authIdent;
void unInitialize()
{
if (pSvc != NULL)
{
pSvc->Release();
pSvc = NULL;
}
if (pLoc != NULL)
{
pLoc->Release();
pLoc = NULL;
}
}
wstring WmiQueryValue(IWbemClassObject* pclsObj, LPCWSTR szName)
{
wstring value = L"0";
if (pclsObj != NULL && szName != NULL)
{
VARIANT vtProp;
HRESULT hr = pclsObj->Get(szName, 0, &vtProp, 0, 0);
if (SUCCEEDED(hr))
{
if (vtProp.vt == VT_BSTR && ::SysStringLen(vtProp.bstrVal) > 0)
{
value = vtProp.bstrVal;
}
else
{
value = std::to_wstring(vtProp.intVal);
}
}
}
return value;
}
void WmiGetSpecialValues(PRODUCT* el, IWbemClassObject* pclsObj)
{
//wcout << L"Name: " << WmiQueryValue(pclsObj, L"Name") << endl;
wcout << L"ID: " << WmiQueryValue(pclsObj, L"IdentifyingNumber") << endl;
wcout << L"Version: " << WmiQueryValue(pclsObj, L"Version") << endl;
wcout << L"Vendor: " << WmiQueryValue(pclsObj, L"Vendor") << endl;
}
void WmiGetSpecialValues(PROCESS* el, IWbemClassObject* pclsObj)
{
wcout << L"Caption: " << WmiQueryValue(pclsObj, L"Caption") << endl;
wcout << L"ProcessId: " << WmiQueryValue(pclsObj, L"ProcessId") << endl;
wcout << L"ExecutablePath: " << WmiQueryValue(pclsObj, L"ExecutablePath") << endl;
wcout << L"HandleCount: " << WmiQueryValue(pclsObj, L"HandleCount") << endl;
}
void WmiGetSpecialValues(SERVICE* el, IWbemClassObject* pclsObj)
{
wcout << L"Name: " << WmiQueryValue(pclsObj, L"Name") << endl;
wcout << L"ProcessId: " << WmiQueryValue(pclsObj, L"ProcessId") << endl;
wcout << L"StartMode: " << WmiQueryValue(pclsObj, L"StartMode") << endl;
wcout << L"State: " << WmiQueryValue(pclsObj, L"State") << endl;
wcout << L"Status: " << WmiQueryValue(pclsObj, L"Status") << endl;
}
void WmiGetSpecialValues(LOGICALDISK* el, IWbemClassObject* pclsObj)
{
wcout << L"DeviceId: " << WmiQueryValue(pclsObj, L"DeviceId") << endl;
wcout << L"DriveType: " << WmiQueryValue(pclsObj, L"DriveType") << endl;
wcout << L"FreeSpace: " << WmiQueryValue(pclsObj, L"FreeSpace") << endl;
wcout << L"Size: " << WmiQueryValue(pclsObj, L"Size") << endl;
}
void WmiGetSpecialValues(PROCESSOR* el, IWbemClassObject* pclsObj)
{
wcout << L"Caption: " << WmiQueryValue(pclsObj, L"Caption") << endl;
wcout<<L"DeviceId: " << WmiQueryValue(pclsObj, L"DeviceId") << endl;
wcout<<L"Manufacturer: " << WmiQueryValue(pclsObj, L"Manufacturer") << endl;
wcout<<L"MaxClockSpeed: " << WmiQueryValue(pclsObj, L"MaxClockSpeed") << endl;
wcout<<L"Name: " << WmiQueryValue(pclsObj, L"Name") << endl;
wcout<<L"SochetDesignation: " << WmiQueryValue(pclsObj, L"SocketDesignation") << endl;
}
void WmiGetSpecialValues(BIOS* el, IWbemClassObject* pclsObj)
{
wcout<<L"SMBIOSBIOSVersion: " << WmiQueryValue(pclsObj, L"SMBIOSBIOSVersion") << endl;
wcout<<L"Manufacturer: " << WmiQueryValue(pclsObj, L"Manufacturer") << endl;
wcout<<L"Name: " << WmiQueryValue(pclsObj, L"Name") << endl;
wcout<<L"SerialNumber: " << WmiQueryValue(pclsObj, L"SerialNumber") << endl;
wcout<<L"Version: " << WmiQueryValue(pclsObj, L"Version") << endl;
}
void WmiGetSpecialValues(HARDDRIVE* el, IWbemClassObject* pclsObj)
{
wcout << L"Partitions: " << WmiQueryValue(pclsObj, L"Partitions") << endl;
wcout << L"DeviceId: " << WmiQueryValue(pclsObj, L"DeviceId") << endl;
wcout << L"Model: " << WmiQueryValue(pclsObj, L"Model") << endl;
wcout << L"Size: " << WmiQueryValue(pclsObj, L"Size") << endl;
wcout << L"Caption: " << WmiQueryValue(pclsObj, L"Caption") << endl;
}
void WmiGetSpecialValues(OS* el, IWbemClassObject* pclsObj)
{
wcout << L"SystemDirectory: " << WmiQueryValue(pclsObj, L"SystemDirectory") << endl;
wcout << L"BuildNumber: " << WmiQueryValue(pclsObj, L"BuildNumber") << endl;
wcout << L"RegisteredUser: " << WmiQueryValue(pclsObj, L"RegisteredUser") << endl;
wcout << L"SerialNumber: " << WmiQueryValue(pclsObj, L"SerialNumber") << endl;
wcout << L"Version: " << WmiQueryValue(pclsObj, L"Version") << endl;
}
void WmiGetSpecialValues(FIREWALL* el, IWbemClassObject* pclsObj)
{
wcout << L"InstanceGuid: " << WmiQueryValue(pclsObj, L"InstanceGuid") << endl;
wcout << L"PathToSignedProductExe: " << WmiQueryValue(pclsObj, L"PathToSignedProductExe") << endl;
wcout << L"TimeStamp: " << WmiQueryValue(pclsObj, L"TimeStamp") << endl;
}
void WmiGetSpecialValues(ANTIPRODUCT* el, IWbemClassObject* pclsObj)
{
wcout << L"DisplayName: " << WmiQueryValue(pclsObj, L"DisplayName") << endl;
wcout << L"InstanceGuid: " << WmiQueryValue(pclsObj, L"InstanceGuid") << endl;
wcout << L"PathToSignedProductExe: " << WmiQueryValue(pclsObj, L"PathToSignedProductExe") << endl;
wcout << L"TimeStamp: " << WmiQueryValue(pclsObj, L"TimeStamp") << endl;
}
template<typename T>
void WmiGetInfo(PWCHAR init, PCHAR value)
{
wchar_t s[CREDUI_MAX_USERNAME_LENGTH + 1];
wsprintf(s, L"\\\\%ws\\%ws", ipAddr, init);
HRESULT hres;
// Obtain the initial locator to WMI
hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc);
if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object." << " Err code = 0x" << hex << hres << endl;
CoUninitialize();
return;
}
// Connect to WMI through the IWbemLocator::ConnectServer method
hres = pLoc->ConnectServer(_bstr_t(s), _bstr_t(pszName), _bstr_t(pszPwd),
NULL, NULL, NULL, NULL, &pSvc);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
pLoc->Release();
CoUninitialize();
return;
}
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = wcslen(pszPwd);
authIdent.Password = (USHORT*)pszPwd;
LPWSTR slash = wcschr(pszName, L'\\');
if (slash == NULL)
{
cout << "Could not create Auth identity. No domain specified\n";
pSvc->Release();
pLoc->Release();
CoUninitialize();
return;
}
StringCchCopy(pszUserName, CREDUI_MAX_USERNAME_LENGTH + 1, slash + 1);
authIdent.User = (USHORT*)pszUserName;
authIdent.UserLength = wcslen(pszUserName);
StringCchCopyN(pszDomain, CREDUI_MAX_USERNAME_LENGTH + 1, pszName, slash - pszName);
authIdent.Domain = (USHORT*)pszDomain;
authIdent.DomainLength = slash - pszName;
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
// Set security levels on a WMI connection
hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT, COLE_DEFAULT_PRINCIPAL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, userAcct, EOAC_NONE);
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return;
}
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t(value), WBEM_FLAG_FORWARD_ONLY
| WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hres))
{
cout << "Query for name failed." << " Error code = 0x" << hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return;
}
hres = CoSetProxyBlanket(pEnumerator, RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT, COLE_DEFAULT_PRINCIPAL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, userAcct, EOAC_NONE);
if (FAILED(hres))
{
cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl;
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
return;
}
// Get the data from the query
IWbemClassObject* pclsObj;
ULONG uReturn = 0;
T el;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if (!uReturn)
{
break;
}
WmiGetSpecialValues(&el, pclsObj);
wcout << endl;
pclsObj->Release();
}
pEnumerator->Release();
unInitialize();
}
int __cdecl main(int argc, char **argv)
{
HRESULT hres;
// Initialize COM.
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x"
<< hex << hres << endl;
return 1;
}
// Set general COM security levels
hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_NONE, NULL);
if (FAILED(hres))
{
cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl;
CoUninitialize();
return 1;
}
// Get the user name and password for the remote computer
cout << "Target IP address: ";
wcin >> ipAddr;
cout << "Remote user name: ";
wcin >> pszName;
cout << "Remote user password: ";
wcin >> pszPwd;
/*wcscpy(ipAddr, L"192.168.79.129");
wcscpy(pszName, L"DESKTOP-J7GNUSB\\mrale");
wcscpy(pszPwd, L"<PASSWORD>");*/
//StringCchPrintf(pszAuthority, CREDUI_MAX_USERNAME_LENGTH + 1, L"kERBEROS:%s", pszNamePC);
int command, f = 1;
printf("1 - enum products\n2 - enum processes\n3 - enum services\n\
4 - enum logical disks\n5 - processor information\n\
6 - BIOS information\n7 - hard drive information\n8 - OS information\n\
9 - firewall information\n10 - antivirus information\n11 - spyware information\n\
0 - exit\n\n");
while (f)
{
printf(">> ");
scanf("%d", &command);
switch (command)
{
case 0: f = 0; break;
case 1: WmiGetInfo<PRODUCT>(L"root\\cimv2", "Select * from Win32_Product"); break;
case 2: WmiGetInfo<PROCESS>(L"root\\cimv2", "Select * from Win32_Process"); break;
case 3: WmiGetInfo<SERVICE>(L"root\\cimv2", "Select * from Win32_Service"); break;
case 4: WmiGetInfo<LOGICALDISK>(L"root\\cimv2", "Select * from Win32_LogicalDisk"); break;
case 5: WmiGetInfo<PROCESSOR>(L"root\\cimv2", "Select * from Win32_Processor"); break;
case 6: WmiGetInfo<BIOS>(L"root\\cimv2", "Select * from Win32_Bios"); break;
case 7: WmiGetInfo<HARDDRIVE>(L"root\\cimv2", "Select * from Win32_DiskDrive"); break;
case 8: WmiGetInfo<OS>(L"root\\cimv2", "Select * from Win32_OperatingSystem"); break;
case 9: WmiGetInfo<FIREWALL>(L"root\\SecurityCenter2", "Select * from FirewallProduct"); break;
case 10: WmiGetInfo<ANTIPRODUCT>(L"root\\SecurityCenter2", "Select * from AntiVirusProduct"); break;
case 11: WmiGetInfo<ANTIPRODUCT>(L"root\\SecurityCenter2", "Select * from AntiSpywareProduct"); break;
default: break;
}
}
SecureZeroMemory(pszName, sizeof(pszName));
SecureZeroMemory(pszPwd, sizeof(pszPwd));
SecureZeroMemory(pszUserName, sizeof(pszUserName));
SecureZeroMemory(pszDomain, sizeof(pszDomain));
CoUninitialize();
return 0;
} | 7b16cd06b26a5a1f7e9a62865aeb37b1ec01e629 | [
"C++"
] | 2 | C++ | fcccode/WMI | 811a5b9762d09ce0b813e616db91c453577482f1 | 34a5d7b9bb39d166d40bee499ea061401e303ba6 |
refs/heads/master | <file_sep>### Using platformIO on macOS with VS Code and the LPC1768 board by KEIL and the ULINK-ME JTAG adapter
A working platformIO blinky example for the LPC1768 board by KEIL.
This was constructed with the help of [maxgerhardt](https://github.com/maxgerhardt) in this forum post [platformIO community forum](https://community.platformio.org/t/how-to-properly-set-the-upload-port-on-macos-lpc1768-board-ulink-me/9560/16).<file_sep>Import("env", "projenv")
import sys
import struct
import intelhex
import time
# from https://github.com/basilfx/lpc_checksum/blob/master/lpc_checksum.py by <NAME>
BLOCK_START = 0
BLOCK_COUNT = 7
BLOCK_SIZE = 4
BLOCK_TOTAL = (BLOCK_COUNT * BLOCK_SIZE)
def checksum(filename, format="bin", read_only=False):
"""
Calculate the checksum of a given binary image. The checksum is written
back to the file and is returned. When read_only is set to True, the file
will not be changed.
filename -- firmware file to checksum
format -- input file format (bin or hex, default bin)
read_only -- whether to write checksum back to the file (default False)
"""
# Open the firmware file.
handle = intelhex.IntelHex()
handle.loadfile(filename, format=format)
# Read the data blocks used for checksum calculation.
block = bytearray(handle.gets(BLOCK_START, BLOCK_TOTAL))
if len(block) != BLOCK_TOTAL:
raise Exception("Could not read the required number of bytes.")
# Compute the checksum value.
result = 0
for i in range(BLOCK_COUNT):
value, = struct.unpack_from("I", block, i * BLOCK_SIZE)
result = (result + value) % 0xFFFFFFFF
result = ((~result) + 1) & 0xFFFFFFFF
# Write checksum back to the file.
if not read_only:
handle.puts(BLOCK_START + BLOCK_TOTAL, struct.pack("I", result))
handle.tofile(filename, format=format)
# Done
return result
def post_bin_file(source, target, env):
print("==== Post building BIN file ====")
target_firmware_bin = str(target[0])
#print(source, target, env)
print("Firmware path: %s" % target_firmware_bin)
ret_check = checksum(target_firmware_bin)
print("Wrote checksum 0x%x into binary." % ret_check)
# fix checksum
env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", post_bin_file)
# fix openocd target
platform = env.PioPlatform()
env.Prepend(
UPLOADERFLAGS=["-s", platform.get_package_dir("tool-openocd") or ""]
)
env.Append(
UPLOADERFLAGS=["-c", "program {$SOURCE} verify reset; shutdown"]
)
env.Replace(
UPLOADER="openocd",
UPLOADCMD="$UPLOADER $UPLOADERFLAGS"
)<file_sep>#include "mbed.h"
// disable these LEDs
DigitalOut led2(P1_29, 0);
DigitalOut led3(P1_31, 0);
DigitalOut led4(P2_2, 0);
DigitalOut led5(P2_3, 0);
DigitalOut led6(P2_4, 0);
DigitalOut led7(P2_5, 0);
DigitalOut led8(P2_6, 0);
// only blink this LED
DigitalOut myled(P1_28);
int main() {
while(1) {
myled = 1;
wait(1);
myled = 0;
wait(1);
}
}<file_sep>[env:lpc1768]
platform = nxplpc
board = lpc1768
framework = mbed
build_flags = -D MCB1700
extra_scripts = extra_script.py
upload_protocol = custom
upload_flags =
-f
scripts/interface/cmsis-dap.cfg
-f
scripts/board/mcb1700.cfg
debug_tool = custom
debug_server =
openocd
-f
../scripts/interface/cmsis-dap.cfg
-f
../scripts/board/mcb1700.cfg | ea1ff6305cf4d50c54b257b01c490ffeaf888717 | [
"Markdown",
"Python",
"C++",
"INI"
] | 4 | Markdown | Irgi07/lpc1768_blinky_example | ce413ceaad7fd1596da23e028082bdc631a309a8 | 1a5ac7d91a5dbf5a6c6060e3bbbc23eb21e6b329 |
refs/heads/master | <repo_name>HenChao/PiRacer<file_sep>/track_sensor.py
import time
import RPi.GPIO as GPIO
# 3 - Left Pre-stage - LPS
# 5 - Left Stage - LS
# 7 - Left Red Light - LRL
# 11 - Left 60ft Line - L60
# 12 - Left Finish Line - LFL
# 13 - Right Pre-stage - RPS
# 15 - Right Stage - RS
# 16 - Right Red Light - RRL
# 18 - Right 60ft Line - R60
# 22 - Right Finish Line - RFL
# 23 - Left Lights Pre-Stage - LLPS
# 24 - Left Lights Stage - LLS
# 26 - Left Lights Red - LLR
# 29 - Right Lights Pre-Stage - RLPS
# 31 - Right Lights Stage - RLS
# 32 - Right Lights Red - RLR
# 33 - Amber Lights 1 - AL1
# 35 - Amber Lights 2 - AL2
# 36 - Amber Lights 3 - AL3
# 37 - Green Light - GL
LPS = 3
LS = 5
LRL = 7
L60 = 11
LFL = 12
RPS = 13
RS = 15
RRL = 16
R60 = 18
RFL = 22
LLPS = 23
LLS = 24
LLR = 26
RLPS = 29
RLS = 31
RLR = 32
AL1 = 33
AL2 = 35
AL3 = 36
GL = 37
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LPS, GPIO.IN)
GPIO.setup(LS, GPIO.IN)
GPIO.setup(LRL, GPIO.IN)
GPIO.setup(L60, GPIO.IN)
GPIO.setup(LFL, GPIO.IN)
GPIO.setup(RPS, GPIO.IN)
GPIO.setup(RS, GPIO.IN)
GPIO.setup(RRL, GPIO.IN)
GPIO.setup(R60, GPIO.IN)
GPIO.setup(RFL, GPIO.IN)
GPIO.setup(LLPS, GPIO.OUT)
GPIO.setup(LLS, GPIO.OUT)
GPIO.setup(LLR, GPIO.OUT)
GPIO.setup(RLPS, GPIO.OUT)
GPIO.setup(RLS, GPIO.OUT)
GPIO.setup(RLR, GPIO.OUT)
GPIO.setup(AL1, GPIO.OUT)
GPIO.setup(AL2, GPIO.OUT)
GPIO.setup(AL3, GPIO.OUT)
GPIO.setup(GL, GPIO.OUT)
# Stage values
# 0 - initial
# 1 - at pre-stage
# 2 - at stage, ready to start
# 3 - racing
# 4 - completed
LSTATE = 0
RSTATE = 0
START_TIME = 0
L_60_TIME = 0
R_60_TIME = 0
L_FINISH_TIME = 0
R_FINISH_TIME = 0
def all_lights_on():
GPIO.output(LLPS, GPIO.HIGH)
GPIO.output(LLS, GPIO.HIGH)
GPIO.output(LLR, GPIO.HIGH)
GPIO.output(RLPS, GPIO.HIGH)
GPIO.output(RLS, GPIO.HIGH)
GPIO.output(RLR, GPIO.HIGH)
GPIO.output(AL1, GPIO.HIGH)
GPIO.output(AL2, GPIO.HIGH)
GPIO.output(AL3, GPIO.HIGH)
GPIO.output(GL, GPIO.HIGH)
def all_lights_off():
GPIO.output(LLPS, GPIO.LOW)
GPIO.output(LLS, GPIO.LOW)
GPIO.output(LLR, GPIO.LOW)
GPIO.output(RLPS, GPIO.LOW)
GPIO.output(RLS, GPIO.LOW)
GPIO.output(RLR, GPIO.LOW)
GPIO.output(AL1, GPIO.LOW)
GPIO.output(AL2, GPIO.LOW)
GPIO.output(AL3, GPIO.LOW)
GPIO.output(GL, GPIO.LOW)
def initialize():
for i in range(3):
all_lights_off()
time.sleep(1)
all_lights_on()
time.sleep(1)
reset()
def reset():
global LSTATE, RSTATE
LSTATE = 0
RSTATE = 0
all_lights_off()
def set_event(channel, edge, function):
# Set bouncetime value to prevent switch bounce (in ms)
GPIO.add_event_detect(channel, edge, callback=function, bouncetime=200)
def prestage(channel):
global LSTATE, RSTATE
if (channel == LPS) and (LSTATE == 0):
GPIO.output(LLPS, GPIO.HIGH)
LSTATE = 1
elif (channel == RPS) and (RSTATE == 0):
GPIO.output(RLPS, GPIO.HIGH)
RSTATE = 1
set_event(LPS, GPIO.FALLING, prestage)
set_event(RPS, GPIO.FALLING, prestage)
def staged(channel):
global LSTATE, RSTATE
if (channel == LS) and (GPIO.input(LS) == 0) and (GPIO.input(LRL) == 1) and (LSTATE == 1):
GPIO.output(LLS, GPIO.HIGH)
LSTATE = 2
elif (channel == RS) and (GPIO.input(RS) == 0) and (GPIO.input(RRL) == 1) and (RSTATE == 1):
GPIO.output(RLS, GPIO.HIGH)
RSTATE = 2
set_event(LS, GPIO.FALLING, staged)
set_event(RS, GPIO.FALLING, staged)
def cross_60(channel):
global L_60_TIME, R_60_TIME, START_TIME
if (channel == L60):
L_60_TIME = time.time() - START_TIME
elif (channel == R60):
R_60_TIME = time.time() - START_TIME
set_event(L60, GPIO.FALLING, cross_60)
set_event(R60, GPIO.FALLING, cross_60)
def cross_finish(channel):
global L_FINISH_TIME, R_FINISH_TIME, START_TIME, LSTATE, RSTATE
if (channel == LFL):
L_FINISH_TIME = time.time() - START_TIME
LSTATE = 4
elif (channel == RFL):
R_FINISH_TIME = time.time() - START_TIME
RSTATE = 4
def main_loop():
global START_TIME, LSTATE, RSTATE, L_FINISH_TIME, R_FINISH_TIME
if (LSTATE == 2) and (RSTATE == 2):
time.sleep(2)
GPIO.output(AL1, GPIO.HIGH)
time.sleep(1)
GPIO.output(AL2, GPIO.HIGH)
time.sleep(1)
GPIO.output(AL3, GPIO.HIGH)
time.sleep(1)
GPIO.output(GL, GPIO.HIGH)
START_TIME = time.time()
LSTATE = 3
RSTATE = 3
elif (LSTATE == 4):
print("Left finish time: %s (s)" % L_FINISH_TIME)
elif (RSTATE == 4):
print("Right finish time: %s (s)" % R_FINISH_TIME)
try:
initialize()
while 1:
main_loop()
finally:
GPIO.cleanup()
| a430069ffa7ff86287dbac8435209640c36ccc46 | [
"Python"
] | 1 | Python | HenChao/PiRacer | ee0f9bfeaf2f270a5d6b2e45611b92046f5e40e6 | b8a559c58ad18a09849aa4955f966be77d6cf6b6 |
refs/heads/master | <file_sep>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
namespace BattlePlanner.Models
{
public class User
{
[Key]
public int UserId { get; set; }
[Required(ErrorMessage="How will the bards sing songs of your glory without a name?")]
public string Name { get; set; }
[Required(ErrorMessage="Please, let us know what your fighting class is!")]
public string Class { get; set; }
[Required(ErrorMessage="We need to know your birthdate!")]
public DateTime Birthdate { get; set; }
[EmailAddress]
[Required(ErrorMessage="We need an email so you can log in!")]
public string Email { get; set; }
public List<Team> Events { get; set; }
public List<Taunt> Taunts { get; set; }
[DataType(DataType.Password)]
[Required]
[MinLength(8, ErrorMessage="Password must be longer than 8 characters!")]
public string Password { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
[NotMapped]
[Compare("Password")]
[DataType(DataType.Password)]
public string Confirm { get; set; }
}
public class Fight
{
[Key]
public int FightId { get; set; }
[Required(ErrorMessage="Where will the blood be spilt?")]
public string Location { get; set; }
[Required(ErrorMessage="We need to know when the brawl will take place!")]
public DateTime FightDate { get; set; }
public List<Team> Roster { get; set; }
public List<Taunt> Taunts { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
public int UserId { get; set; }
public User Creator { get; set; }
}
public class Team
{
[Key]
public int TeamId { get; set; }
public int UserId { get; set; }
public int FightId { get; set; }
public User Participant { get; set; }
public Fight Event { get; set; }
public string TeamColor { get; set; }
}
public class Taunt
{
[Key]
public int TauntID { get; set; }
[Required(ErrorMessage="You need to provide a message, you weak-livered hobgoblin!")]
public string Message { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
public int UserId { get; set; }
public User Creator { get; set; }
public int FightId { get; set; }
public Fight Fight { get; set; }
}
public class LoginUser
{
[Required(ErrorMessage="You must log in with an Email!")]
public string Email { get; set; }
[Required(ErrorMessage="Provide a passphrase so you may enter")]
public string Password { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using BattlePlanner.Models;
namespace BattlePlanner.Controllers
{
public class HomeController : Controller
{
private MyContext dbContext;
public HomeController(MyContext context)
{
dbContext = context;
}
//Homepage
[HttpGet("")]
public IActionResult Index()
{
HttpContext.Session.Clear();
return View();
}
//Login
[HttpPost("")]
public IActionResult LoginCheck(LoginUser fromForm)
{
if(ModelState.IsValid)
{
User selectedUser = dbContext.UserTable.FirstOrDefault(u => u.Email == fromForm.Email);
if (selectedUser == null)
{
ModelState.AddModelError("Email", "Invalid Email/Password!");
return View("Index");
}
else
{
var hasher = new PasswordHasher<LoginUser>();
var result = hasher.VerifyHashedPassword(fromForm, selectedUser.Password, fromForm.Password);
if(result == 0)
{
ModelState.AddModelError("Email", "Invalid Email/Password!");
return View("Index");
}
}
HttpContext.Session.SetInt32("userKey", selectedUser.UserId);
return RedirectToAction("Dashboard");
}
return View("Index");
}
//User Registration
[HttpGet("NewUser")]
public IActionResult Register()
{
HttpContext.Session.Clear();
return View();
}
[HttpPost("NewUser")]
public IActionResult AddNewUser(User fromForm)
{
DateTime now = DateTime.Now;
int years = (int)(now.Year - fromForm.Birthdate.Year);
if(now.Month < fromForm.Birthdate.Month || (now.Month == fromForm.Birthdate.Month && now.Day < fromForm.Birthdate.Day))
{
years = years - 1;
}
if(!ModelState.IsValid || years < 18)
{
ModelState.AddModelError("Birthdate", "You are too young! Try a fight club for babies.");
return View("Register");
}
if(dbContext.UserTable.Any(u => u.Email == fromForm.Email))
{
ModelState.AddModelError("Email", "Someone has claimed this email!");
return View("Register");
}
PasswordHasher<User> Hasher = new PasswordHasher<User>();
fromForm.Password = Hasher.HashPassword(fromForm, fromForm.Password);
dbContext.Add(fromForm);
dbContext.SaveChanges();
User selectedUser = dbContext.UserTable.FirstOrDefault(u => u.Email == fromForm.Email);
HttpContext.Session.SetInt32("userKey", selectedUser.UserId);
return RedirectToAction("Dashboard");
}
//Dashboard
[HttpGet("Dashboard")]
public IActionResult Dashboard()
{
int? SessionId = (HttpContext.Session.GetInt32("userKey"));
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
List<Fight> myFights = dbContext.FightTable.Where(f => f.Creator == LoggedUser).ToList();
List<Fight> AllFights = dbContext.FightTable.Include(f => f.Roster).ToList();
ViewBag.myFights = myFights;
ViewBag.AllFights = AllFights;
ViewBag.Creator = "YES";
return View(LoggedUser);
}
//Fights
[HttpGet("Fights")]
public IActionResult Fights()
{
List<Fight> AllFights = dbContext.FightTable.OrderBy(f => f.CreatedAt).ToList();
ViewBag.AllFights = AllFights;
return View("Fights", AllFights);
}
//FightViewer
[HttpGet("Fights/{ID}")]
public IActionResult FightViewer(int ID)
{
int? SessionId = HttpContext.Session.GetInt32("userKey");
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
Fight selectedFight = dbContext.FightTable.Include(f => f.Creator).FirstOrDefault(f => f.FightId == ID);
List<Team> AllTeams = dbContext.TeamTable.Include(t => t.Participant).Where(t => t.FightId == ID).ToList();
ViewBag.AllTeams = AllTeams;
List<Taunt> AllTaunts = dbContext.TauntTable.Where(t => t.FightId == ID).OrderBy(t => t.CreatedAt).ToList();
ViewBag.AllTaunts = AllTaunts;
return View(selectedFight);
}
//FightAdd
[HttpGet("Fights/Add")]
public IActionResult FightForm()
{
int? SessionId = (HttpContext.Session.GetInt32("userKey"));
ViewBag.SessionId = SessionId;
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
return View();
}
[HttpPost("Fights/Add")]
public IActionResult FightFormAction(Fight fromForm)
{
int? SessionId = (HttpContext.Session.GetInt32("userKey"));
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
DateTime now = DateTime.Now;
if(!ModelState.IsValid)
{
return View("FightForm");
}
if(fromForm.FightDate < now)
{
return View("FightForm");
}
var NewFight = new Fight()
{
Location = fromForm.Location,
FightDate = fromForm.FightDate,
UserId = LoggedUser.UserId
};
dbContext.Add(NewFight);
dbContext.SaveChanges();
return RedirectToAction("Dashboard");
}
//FightJoin
[HttpGet("Fights/{ID}/Red")]
public IActionResult JoinFightRed(int ID)
{
int? SessionId = HttpContext.Session.GetInt32("userKey");
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
Team TeamCheck = dbContext.TeamTable.FirstOrDefault((t => t.UserId == LoggedUser.UserId && t.FightId == ID));
if(TeamCheck != null && TeamCheck.TeamColor == "Red")
{
return RedirectToAction("FightViewer", new {ID = ID});
}
if(TeamCheck != null && TeamCheck.TeamColor == "Blue")
{
dbContext.TeamTable.Remove(TeamCheck);
}
Fight selectedFight = dbContext.FightTable.FirstOrDefault(f => f.FightId == ID);
var newTeam = new Team()
{
UserId = LoggedUser.UserId,
FightId = selectedFight.FightId,
TeamColor = "Red"
};
dbContext.Add(newTeam);
dbContext.SaveChanges();
return RedirectToAction("FightViewer", new {ID = ID});
}
[HttpGet("Fights/{ID}/Blue")]
public IActionResult JoinFightBlue(int ID)
{
int? SessionId = HttpContext.Session.GetInt32("userKey");
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
Team TeamCheck = dbContext.TeamTable.FirstOrDefault((t => t.UserId == LoggedUser.UserId && t.FightId == ID));
if(TeamCheck != null && TeamCheck.TeamColor == "Blue")
{
return RedirectToAction("FightViewer", new {ID = ID});
}
if(TeamCheck != null && TeamCheck.TeamColor == "Red")
{
dbContext.TeamTable.Remove(TeamCheck);
}
Fight selectedFight = dbContext.FightTable.FirstOrDefault(f => f.FightId == ID);
var newTeam = new Team()
{
UserId = LoggedUser.UserId,
FightId = selectedFight.FightId,
TeamColor = "Blue"
};
dbContext.Add(newTeam);
dbContext.SaveChanges();
return RedirectToAction("FightViewer", new {ID = ID});
}
[HttpGet("Fights/{ID}/Leave")]
public IActionResult LeaveFight(int ID)
{
int? SessionId = HttpContext.Session.GetInt32("userKey");
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
Team TeamCheck = dbContext.TeamTable.FirstOrDefault((t => t.UserId == LoggedUser.UserId && t.FightId == ID));
if(TeamCheck != null)
{
dbContext.TeamTable.Remove(TeamCheck);
dbContext.SaveChanges();
return RedirectToAction("FightViewer", new {ID = ID});
}
return RedirectToAction("FightViewer", new {ID = ID});
}
//AddTaunt
[HttpPost("Fights/{ID}")]
public IActionResult AddTaunt(int ID, Taunt fromForm)
{
int? SessionId = HttpContext.Session.GetInt32("userKey");
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
if(LoggedUser == null)
{
return RedirectToAction("Index");
}
var NewTaunt = new Taunt()
{
Message = fromForm.Message,
UserId = LoggedUser.UserId,
FightId = ID
};
dbContext.Add(NewTaunt);
dbContext.SaveChanges();
return RedirectToAction("FightViewer", new {ID = ID});
}
[HttpGet("Fights/{ID}/Edit")]
public IActionResult EditViewer(int ID)
{
var EditedFight = dbContext.FightTable.FirstOrDefault(f => f.FightId == ID);
return RedirectToAction ("FightForm");
}
[HttpPost("Fights/{ID}/Edit")]
public IActionResult EditAction(int ID, Fight fromForm)
{
int? SessionId = (HttpContext.Session.GetInt32("userKey"));
var LoggedUser = dbContext.UserTable.FirstOrDefault(u => u.UserId == SessionId);
var EditedFight = dbContext.FightTable.FirstOrDefault(f => f.FightId == ID);
DateTime now = DateTime.Now;
if(!ModelState.IsValid)
{
return View("FightForm");
}
if(fromForm.FightDate < now)
{
return View("FightForm");
}
EditedFight.Location = fromForm.Location;
EditedFight.FightDate = fromForm.FightDate;
dbContext.SaveChanges();
return RedirectToAction("FightViewer", new {ID = ID});
}
//----------------------------------------------------//
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace BattlePlanner.Models
{
public class MyContext : DbContext
{
// base() calls the parent class' constructor passing the "options" parameter along
public MyContext(DbContextOptions options) : base(options) { }
public DbSet<User> UserTable { get; set; }
public DbSet<Fight> FightTable { get; set; }
public DbSet<Taunt> TauntTable { get; set; }
public DbSet<Team> TeamTable { get; set; }
}
} | de7f763dc8011d0e07ff2048d0fe3443d6042892 | [
"C#"
] | 3 | C# | Dakota-G/FightCloob | 3aeedb1ff3ccbe04c834b1fa3758616c96ca4849 | c70446b47e99607b06ee3cf169a529158a88f368 |
refs/heads/master | <file_sep>const _ = require('lodash');
const fetch = require('node-fetch');
const { getCountryAlpha2Code } = require('./utils');
const BASE_URL = 'https://www.bloomberg.com/graphics';
function mapCountry(entry = {}) {
return {
code: getCountryAlpha2Code(entry.noc),
gold: entry.gold,
silver: entry.silver,
bronze: entry.bronze,
};
}
function setRank(entry, index, entries) {
const previousEntry = entries[index - 1];
if (_.isEqual(_.omit(previousEntry, ['code', 'rank']), _.omit(entry, ['code']))) {
entry.rank = previousEntry.rank;
} else {
entry.rank = index + 1;
}
}
async function getCountryMedals() {
const response = await fetch(`${BASE_URL}/beijing-2022-olympics-data/current.json`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
}
});
if (!response.ok) {
throw new Error('failed to fetch medals');
}
const parsedResponse = await response.json();
const countries = _.get(parsedResponse, 'data.medals');
const sortedCountries = _.orderBy(
countries,
['gold', 'silver', 'bronze', 'noc'],
['desc', 'desc', 'desc', 'asc']
);
const mappedCountries = _.map(sortedCountries, mapCountry);
const rankedCountries = _.each(mappedCountries, setRank);
return rankedCountries;
}
module.exports = { getCountryMedals };
<file_sep>const _ = require('lodash');
const fetch = require('node-fetch');
const { getCountryAlpha2Code } = require('./utils');
const BASE_URL = 'https://api-gracenote.nbcolympics.com/svc/games_v2.svc/json';
function mapCountry(entry = {}) {
return {
rank: entry.n_RankGold,
code: getCountryAlpha2Code(entry.c_NOCShort),
gold: entry.n_Gold,
silver: entry.n_Silver,
bronze: entry.n_Bronze,
};
}
async function getCountryMedals() {
const response = await fetch(`${BASE_URL}/GetMedalTable_Season?competitionSetId=2&season=20212022&languageCode=2`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
}
});
if (!response.ok) {
throw new Error('failed to fetch medals');
}
const parsedResponse = await response.json();
const countries = _.get(parsedResponse, 'MedalTableNOC');
const sortedCountries = _.orderBy(
countries,
['n_Gold', 'n_Silver', 'n_Bronze', 'c_NOCShort'],
['desc', 'desc', 'desc', 'asc']
);
const mappedCountries = _.map(sortedCountries, mapCountry);
return mappedCountries;
}
module.exports = { getCountryMedals };
<file_sep>/* MagicMirror²
* Module: MMM-OlympicGames
*
* By fewieden https://github.com/fewieden/MMM-OlympicGames
* MIT Licensed.
*/
/* eslint-env node */
const NodeHelper = require('node_helper');
const Log = require('logger');
const providers = require('./providers');
module.exports = NodeHelper.create({
requiresVersion: '2.15.0',
socketNotificationReceived(notification, payload) {
if (notification === 'CONFIG') {
this.config = payload;
this.getCountryMedals();
setInterval(() => {
this.getCountryMedals();
}, this.config.reloadInterval);
}
},
async getCountryMedals() {
try {
const provider = providers[this.config.provider];
if (!provider) {
throw new Error(`Unsupported provider: ${this.config.provider}`);
}
const countries = await provider.getCountryMedals();
this.sendSocketNotification('COUNTRIES', countries);
} catch (e) {
Log.error('Error getting olympic game medals', e);
}
}
});
<file_sep># MMM-OlympicGames Changelog
## [1.4.0]
### Added
* Data provider: `paralympic`
### Changed
* Default provider: `paralympic`
* Default title: `Paralympic Winter Games 2022`
## [1.3.0]
### Added
* Added option for user to input list of countries to display, see config option `countryList`.
* Added French language translations.
### Changed
* Uniform spelling for MagicMirror²
* Upgraded development dependencies
* Updated preview images
## [1.2.0]
### Added
* Added another data source, see new config option `provider`.
### Changed
* Countries with same medals share the same rank
## [1.1.0]
MagicMirror² version >= 2.15.0 required.
### Fixed
* Installation instructions
### Added
* Nunjuck template
* Dependency: `node-fetch`
* Dependency: `lodash`
* Github actions: `build` and `changelog`
* Github config files
### Changed
* Data source
* Preview image
* Config options
* Country names are now translated with the `Intl` object
* Translations
### Removed
* Dependency: `request`
* Travis-CI integration
## [1.0.0]
Initial version
<file_sep>const bloomberg = require('./bloomberg');
const nbc = require('./nbc');
const paralympic = require('./paralympic');
module.exports = { bloomberg, nbc, paralympic };
<file_sep># MMM-OlympicGames [](https://raw.githubusercontent.com/fewieden/MMM-OlympicGames/master/LICENSE)  [](https://codeclimate.com/github/fewieden/MMM-OlympicGames) [](https://snyk.io/test/github/fewieden/mmm-olympicgames)
Olympic Games Module for MagicMirror²
## Example
 
## Dependencies
* An installation of [MagicMirror²](https://github.com/MichMich/MagicMirror)
* npm
* [node-fetch](https://www.npmjs.com/package/node-fetch)
* [lodash](https://www.npmjs.com/package/lodash)
## Installation
1. Clone this repo into `~/MagicMirror/modules` directory.
1. Configure your `~/MagicMirror/config/config.js`:
```
{
module: 'MMM-OlympicGames',
position: 'top_right',
config: {
// all your config options, which are different than their default values
}
}
```
1. Run command `npm install --production` in `~/MagicMirror/modules/MMM-OlympicGames` directory.
## Global config
| **Option** | **Default** | **Description** |
| --- | --- | --- |
| `locale` | `undefined` | By default it is using your system settings. You can specify the locale in the global MagicMirror² config. Possible values are for e.g.: `'en-US'` or `'de-DE'`. |
To set a global config you have to set the value in your config.js file inside the MagicMirror² project.

## Config Options
| **Option** | **Default** | **Description** |
| --- | --- | --- |
| `highlight` | `false` | Which country (alpha-2 code) should be highlighted. E.g. `'DE'` for `Germany`. You can find all alpha-2 codes [here](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). |
| `maxRows` | `10` | How many countries should be displayed. Will be overwritten by config option `countryList`. |
| `title` | `'Paralympic Winter Games 2022'` | The title above the medal table. |
| `reloadInterval` | `1800000` (30 mins) | How often should the data be fetched. |
| `provider` | `'paralympic'` | Specify the data source. Possible options: `'paralympic'`, `'bloomberg'` and `'nbc'`. |
| `countryList` | `false` | Specify a list of country codes to display (alpha-2 code), e.g. `[ "NO", "AU", "US", "DE", "FR", "CA" ]`. Config option `maxRows` will be automatically overwritten accordingly. |
## Developer
* `npm run lint` - Lints JS and CSS files.
<file_sep>const countryCodeMapping = {
AFG: 'AF',
ALB: 'AL',
ALG: 'DZ',
AND: 'AD',
ANG: 'AO',
ANT: 'AG',
ARG: 'AR',
ARM: 'AM',
ARU: 'AW',
ASA: 'AS',
AUS: 'AU',
AUT: 'AT',
AZE: 'AZ',
BAH: 'BS',
BAN: 'BD',
BAR: 'BB',
BDI: 'BI',
BEL: 'BE',
BEN: 'BJ',
BER: 'BM',
BHU: 'BT',
BIH: 'BA',
BIZ: 'BZ',
BLR: 'BY',
BOL: 'BO',
BOT: 'BW',
BRA: 'BR',
BRN: 'BH',
BRU: 'BN',
BUL: 'BG',
BUR: 'BF',
CAF: 'CF',
CAM: 'KH',
CAN: 'CA',
CAY: 'KY',
CGO: 'CG',
CHA: 'TD',
CHI: 'CL',
CHN: 'CN',
CIV: 'CI',
CMR: 'CM',
COD: 'CD',
COL: 'CO',
COK: 'CK',
COM: 'KM',
CPV: 'CV',
CRC: 'CR',
CRO: 'HR',
CUB: 'CU',
CYP: 'CY',
CZE: 'CZ',
DEN: 'DK',
DJI: 'DJ',
DMA: 'DM',
DOM: 'DO',
ECU: 'EC',
EGY: 'EG',
ERI: 'ER',
ESA: 'SV',
ESP: 'ES',
EST: 'EE',
ETH: 'ET',
FIJ: 'FJ',
FIN: 'FI',
FRA: 'FR',
FSM: 'FM',
GAB: 'GA',
GAM: 'GM',
GBR: 'GB',
GBS: 'GW',
GEO: 'GE',
GEQ: 'GQ',
GER: 'DE',
GHA: 'GH',
GRE: 'GR',
GRN: 'GD',
GUA: 'GT',
GUI: 'GN',
GUM: 'GU',
GUY: 'GY',
HAI: 'HT',
HKG: 'HK',
HON: 'HN',
HUN: 'HU',
INA: 'ID',
IND: 'IN',
IRI: 'IR',
IRL: 'IE',
IRQ: 'IQ',
ISL: 'IS',
ISR: 'IL',
ISV: 'VI',
ITA: 'IT',
IVB: 'VG',
JAM: 'JM',
JOR: 'JO',
JPN: 'JP',
KAZ: 'KZ',
KEN: 'KE',
KGZ: 'KG',
KIR: 'KI',
KOR: 'KR',
KOS: 'XK',
KSA: 'SA',
KUW: 'KW',
LAO: 'LA',
LAT: 'LV',
LBA: 'LY',
LBN: 'LB',
LBR: 'LR',
LCA: 'LC',
LES: 'LS',
LIE: 'LI',
LTU: 'LT',
LUX: 'LU',
MAD: 'MG',
MAR: 'MA',
MAS: 'MY',
MAW: 'MW',
MDA: 'MD',
MDV: 'MV',
MEX: 'MX',
MGL: 'MN',
MHL: 'MH',
MKD: 'MK',
MLI: 'ML',
MLT: 'MT',
MNE: 'ME',
MON: 'MC',
MOZ: 'MZ',
MRI: 'MU',
MTN: 'MR',
MYA: 'MM',
NAM: 'NA',
NCA: 'NI',
NED: 'NL',
NEP: 'NP',
NGR: 'NG',
NIG: 'NE',
NOR: 'NO',
NRU: 'NR',
NZL: 'NZ',
OMA: 'OM',
PAK: 'PK',
PAN: 'PA',
PAR: 'PY',
PER: 'PE',
PHI: 'PH',
PLE: 'PS',
PLW: 'PW',
PNG: 'PG',
POL: 'PL',
POR: 'PT',
PUR: 'PR',
QAT: 'QA',
ROU: 'RO',
RSA: 'ZA',
RUS: 'RU',
RWA: 'RW',
SAM: 'WS',
SEN: 'SN',
SEY: 'SC',
SGP: 'SG',
SKN: 'KN',
SLE: 'SL',
SLO: 'SI',
SMR: 'SM',
SOL: 'SB',
SOM: 'SO',
SRB: 'RS',
SRI: 'LK',
SSD: 'SS',
STP: 'ST',
SUD: 'SD',
SUI: 'CH',
SUR: 'SR',
SVK: 'SK',
SWE: 'SE',
SWZ: 'SZ',
SYR: 'SY',
TAN: 'TZ',
TGA: 'TO',
THA: 'TH',
TJK: 'TJ',
TKM: 'TM',
TLS: 'TL',
TOG: 'TG',
TPE: 'TW',
TTO: 'TT',
TUN: 'TN',
TUR: 'TR',
TUV: 'TV',
UAE: 'AE',
UGA: 'UG',
UKR: 'UA',
URU: 'UY',
USA: 'US',
UZB: 'UZ',
VAN: 'VU',
VEN: 'VE',
VIE: 'VN',
VIN: 'VC',
YEM: 'YE',
ZAM: 'ZM',
ZIM: 'ZW'
};
function getCountryAlpha2Code(nocCode) {
return countryCodeMapping[nocCode] || nocCode;
}
module.exports = { getCountryAlpha2Code };
| 69f334dca41b9a7e4aab2fc3696c1c061bac8d07 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | fewieden/MMM-OlympicGames | c080be36cb4d3647150d4d9eace9290374392121 | 8a1d57913b0db0f4bd628868947ff403ea6c6e27 |
refs/heads/main | <repo_name>HaryAlfarizi/Lab9-10Web<file_sep>/README.md
## Nama : <NAME>
## Kelas : TI.19.B2
## NIM : 311910555
## Mata Kuliah : Pemrograman Web
# Praktikum 9 & 10
Header, Home pada modular

Form Input

CRUD pada tugas 10

Mengimplementasikan pada Tugas 8
<file_sep>/home.php
<?php require ('header.php'); ?>
<div class="content">
<h2>Ini Halaman Home</h2>
<p>Ini adalah bagian halaman content dati halaman.</p>
</div>
<?php require('footer.php'); ?> | 9f4d77e4cd5fb9ae1b5afd7f3db71098e5cf9ea3 | [
"Markdown",
"PHP"
] | 2 | Markdown | HaryAlfarizi/Lab9-10Web | 07f3eb9554edd34bb14aa5e20da9bdd66dd7c2cb | 118ad8ade334137d827fec35eb9277a3d72a0133 |
refs/heads/master | <file_sep>$(document).ready(function(){
//Add a listener for the form submission....
$('.sign-up-form').submit(function(){
event.preventDefault();
// console.log("Submitted!");
// 1. password must be 6 characters
var password= $('.password').val();
if(password.length < 6) {
$('.password').focus();
$('.pass-error').html('Your password must be atleast 6 characters')
}
console.log(password);
// 2. Field must be non-empty
});
$('.input').blur(function(){
if( !$(this).val() ) {
alert("Please complete");
}
});
});
// 3. agree to terms checkbox must be checked
// 4. valid email
// 5. make sure number is a number
// 6. make sure password is equal
| 9fa47eb9355ba5c9a409ec19b052d90d7958874d | [
"JavaScript"
] | 1 | JavaScript | drewwiley/Validating-Forms_files | 90fab6236e425c8a884942ef9f9955f794fd09ce | 37ab74d7436f425c2cc3247c23ce495a2a054c9e |
refs/heads/master | <repo_name>GabrielCarneiroDeveloper/flask-blueprint-factory-app<file_sep>/flask_auth/app/common/logger.py
import os
import logging
STREAM_HANDLER = logging.StreamHandler()
STREAM_HANDLER.setFormatter(
logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(pathname)s:%(lineno)s] %(message)s",
datefmt="%Y-%m-%d%T%H:%M:%S",
)
)
class Logger:
def __init__(self, module: str):
self.logger = logging.getLogger(module)
self.logger.setLevel(os.getenv("LOG_LEVEL", "INFO"))
self.logger.addHandler(STREAM_HANDLER)
def getLogger(self):
return self.logger
<file_sep>/flask_auth/tests/users/UserResourceTest.py
import unittest
import json
from flask import Flask, url_for
from flask_auth.app.blueprints.users.models import UserModel
from flask_auth.app.blueprints.users.resources import UserCreateListResource
from flask_auth.tests import client
from flask_auth.tests.users.UserModelMockFactory import UserModelMockFactory
from flask_auth.tests.users.UserModelMock import UserModelMock
"""
TODO: Necessary configure setUp() and tearDown() correctly due database connection.
TODO: Configure mocked data to test environment
"""
class UserResourceTest(unittest.TestCase):
def setUp(self):
self.users = UserModelMockFactory(number_of_users=2)
self.users.save_mocks_in_database()
def tearDown(self):
self.users.remove_all_registers_from_database()
def test_should_return_200_if_server_is_running(self):
response = client.get(path=url_for("index_route"))
self.assertEqual(response.status_code, 200)
def test_should_get_user_list(self):
response = client.get(path=url_for("users.usercreatelistresource"))
self.assertEqual(response.status_code, 200)
self.assertIsInstance(response.json, list)
def test_should_get_user_details(self):
first_user = UserModel().query.all()[0]
response = client.get(
path=url_for("users.userdetailupdateremoveresource", _id=first_user.id)
)
self.assertEqual(response.status_code, 200)
self.assertIsNotNone(response.json["login"])
self.assertIsNotNone(response.json["password"])
self.assertIsNotNone(response.json["id"])
def test_should_get_an_user_created_successfully(self):
response = client.post(
path=url_for("users.usercreatelistresource"),
data=json.dumps({"login": "gabu", "password": "<PASSWORD>"}),
follow_redirects=True,
mimetype="application/json",
)
self.assertEqual(200, response.status_code)
def test_should_get_an_user_removed_successfully(self):
first_user = UserModel().query.all()[0]
response = client.delete(
path=url_for("users.userdetailupdateremoveresource", _id=first_user.id),
follow_redirects=True,
mimetype="application/json",
)
self.assertEqual(response.status_code, 200)
def test_should_get_login_user_updated_with_new_login_successfully(self):
first_user = UserModel().query.all()[0]
new_login = "AN<PASSWORD>_NAME"
response = client.put(
path=url_for("users.userdetailupdateremoveresource", _id=first_user.id),
data=json.dumps({"login": new_login}),
follow_redirects=True,
mimetype="application/json",
)
updated_user = UserModel().query.all()[0]
self.assertEqual(new_login, updated_user.login)
<file_sep>/flask_auth/app/extensions/restful/rest_framework.py
from flask import Flask
from flask_restful import Api
def init_app(app: Flask):
return Api(app)
<file_sep>/flask_auth/app/extensions/migrate/migrate_framework.py
from flask import Flask
from flask_migrate import Migrate
from flask_auth.app.extensions.database.database_framework import db
def init_app(app: Flask):
migrate = Migrate(app, db)
return migrate
<file_sep>/flask_auth/tests/users/UserModelMock.py
from flask_auth.app.blueprints.users.models import UserModel
from faker import Faker
fake = Faker()
class UserModelMock(UserModel):
""" Extends UserModel and loads fake data to the seeder """
def __init__(self):
self.login = fake.email()
self.password = "<PASSWORD>"
super().__init__()
<file_sep>/pyproject.toml
[tool.poetry]
name = "flask_auth"
version = "0.1.0"
description = "Open Source project used to demonstrante Factory App + Blueprints project patterns usage"
authors = ["<NAME> <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.7"
Flask = "^1.1.1"
Flask-SQLAlchemy = "^2.4.1"
Flask-Marshmallow = "^0.11.0"
Flask-RESTful = "^0.3.8"
marshmallow-sqlalchemy = "^0.22.3"
Flask-Migrate = "^2.5.3"
python-dotenv = "^0.12.0"
black = "^19.10b0"
flake8 = "^3.7.9"
gunicorn = "^20.0.4"
flasgger = "^0.9.4"
[tool.poetry.dev-dependencies]
mypy = "^0.770"
ipython = "^7.13.0"
ipdb = "^0.13.2"
nose = "^1.3.7"
coverage = "^5.0.4"
black = {version = "^19.10b0", allow-prereleases = true}
faker = "^4.0.2"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
<file_sep>/Makefile
######################## Help ####################################
help:
@echo "Commands:"
@echo " check Check required principal dependencies"
@echo " init Initialize the project"
@echo " db-init Configure database to development and test environments"
@echo " db-init-test Configure database only to test environment"
@echo " test Run unit tests"
@echo " html-report Generate report as html"
@echo " lint Check code linting"
@echo " runserver Run the application in Development mode"
@echo " runserver-prod Run the application in Production mode"
@echo " runserver-prod-dev Run the application in Development but emulating the Production environment"
@echo " build Build the project Docker image"
@echo " deploy Build the projet Docker image and deploy it in Docker Swarm"
@echo " run-as-container Run the application as container"
@echo " run-as-temporary-container Run the application as temporary container, which will be automatically removed if stopped."
@echo " clean Remove not in use Docker objects"
@echo " logs Show service logs"
check:
python --version
pip --version
poetry --version
docker --version
docker-compose --version
######################## Environment configuration ####################################
init:
[ ! -f ./flask_auth/.env ] && echo "\n# Error: Required file ".env" not exists, create it based on ".env.example" and try it again!\n" && exit 2 || echo ""
pip install poetry
poetry install
@make db-init
db-init:
@echo "\n*** Removing data.db and migrations if they exists...."
[ -f ./flask_auth/data.db ] && rm data.db || echo ""
[ -d "./flask_auth/migrations" ] && rm -rf ./flask_auth/migrations || echo ""
@echo "\n*** Initializing database...."
cd flask_auth; poetry run flask db init
@echo "\n*** Migrating models...."
cd flask_auth; poetry run flask db migrate
@echo "\n*** Upgrading database based on current models...."
cd flask_auth; poetry run flask db upgrade
@make db-init-test
db-init-test:
@echo "\n*** Preparing test database environment...."
[ -f ./data_test.db ] && rm ./data_test.db || echo ""
APPLICATION_ENV=Test FLASK_APP=flask_auth.run:app poetry run flask db upgrade --directory flask_auth/migrations
@mv data_test.db ./flask_auth/
######################## Test scripts ####################################
test:
@make db-init-test
@make lint
@echo "\n*** unit tests...."
cd flask_auth; poetry run coverage run --source=flask_auth.app -m unittest --verbose flask_auth.test
html-report:
@echo "\n*** Generating report as htmlconv directory"
cd flask_auth; poetry run coverage html
lint:
@echo "\n*** Running linter to check code patterns"
poetry run flake8 --config=.flake8 flask_auth
######################## Environment Servers ####################################
runserver:
cd flask_auth; poetry run python run.py
runserver-prod-dev:
APPLICATION_ENV=Production poetry run gunicorn -c flask_auth/gunicorn.conf.py flask_auth.run:app
runserver-prod:
gunicorn -c flask_auth/gunicorn.conf.py flask_auth.run:app
######################## Deployment process ####################################
build:
@echo "\n*** Building the project...."
poetry export -f requirements.txt -o requirements.txt
docker-compose build
deploy:
@echo "\n*** Running deploy process"
@make test
@make build
docker stack rm flask_auth
sleep 20
docker stack deploy -c docker-compose-prod.yml flask_auth
run-as-container:
@echo "\n*** Run a container based on flask_auth_gabrielcarneirodeveloper:1 image"
docker run -p 8080:5010 --name flask_auth flask_auth_gabrielcarneirodeveloper:1
run-as-temporary-container:
@echo "\n*** Run a container based on flask_auth_gabrielcarneirodeveloper:1 image and activate its command line."
@echo "***Once its a temporary container, it will be automatically removed if stopped."
docker run --rm -it -p 8080:5010 flask_auth_gabrielcarneirodeveloper:1 /bin/sh
clean:
@echo "\n !!!!! CAUTION !!!!!!"
@echo "*** This command will remove all the images, volumes, containers, networks which are not in use currently"
docker system prune --volumes
logs:
@echo "\n*** Show flask_auth_web_service logs"
docker service logs flask_auth_web_service
<file_sep>/README.md
# Factory App + Blueprints [Study purpose]
There are many ways to develop a [Flask](https://flask.palletsprojects.com/en/1.1.x/) project and structure its directories. A very known and advised way to do it is using [Factory App](https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/) with [Blueprints](https://flask.palletsprojects.com/en/1.1.x/tutorial/views/). At use these two patterns, is possible to have an easier to debug, readable and well modularized Flask project. This project aims demonstrate how is possible use them.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development, testing and studying purposes. See deployment for notes on how to deploy the project on a live system using Docker.
### Prerequites
To use all project features, it should be in an Unix distro, preference Ubuntu (Sorry about this, but I will try solve it further ;D) and the dependecies bellow.
```
build-essential (to use **make** commands)
Python 3.x
Pip
Docker
docker-compose
```
### Clone the repository
``` shell
git clone https://github.com/GabrielCarneiroDeveloper/flask-blueprint-factory-app.git
```
### Install project dependencies
``` shell
make init
```
### Create .env inside flask_auth directory
Inside **flask-blueprint-factory-app/flask_auth/** directory:
* create **.env** file based on .env.example.
* .env should has two variables: **APPLICATION_ENV** and **FLASK_APP**.
* Configure **APPLICATION_ENV** with one of the possible values: <ins>Development</ins>, <ins>Production</ins> and <ins>Test</ins> (*Exactly as described before, with first letter in upper case*)
### Running server
Run with Flask default server
``` shell
make runserver
```
## Documentation
With the project running, access the documentation in http://localhost:5000/apidocs. The API documentation was created based on [Swagger](https://swagger.io/) using [Flasgger](https://github.com/flasgger/flasgger)

## Commands
To see available commands, run:
``` shell
make help
```
``` shell
Commands:
check Check required principal dependencies
init Initialize the project
db-init Configure database to development and test environments
db-init-test Configure database only to test environment
test Run unit tests
html-report Generate report as html
lint Check code linting
runserver Run the application in Development mode
runserver-prod Run the application in Production mode
runserver-prod-dev Run the application in Development but emulating the Production environment
build Build the project Docker image
deploy Build the projet Docker image and deploy it in Docker Swarm
run-as-container Run the application as container
run-as-temporary-container Run the application as temporary container, which will be automatically removed if stopped.
clean Remove not in use Docker objects
logs Show service logs
```
## Running Tests
### Unit test
The API unit tests were developed using **unittest** built-in Python module. Run unit tests with the command:
``` shell
make test
```
### Code style
To check code style, was used [Flake8](https://pypi.org/project/flake8/) and formatted using [Black](https://pypi.org/project/black/). Run style checker with the command:
``` shell
make lint
```
## Deployment
If you want run the application server in Docker orchestraded by Swarm:
1) Make your host as a Swarm master, if it isn't yet:
``` shell
docker swarm init
```
2) Run unit tests, linter, and deploy process:
``` shell
make deploy
```
3) Check if stack project's services are running:
``` shell
docker stack services flask_auth
```
``` shell
ID NAME MODE REPLICAS IMAGE PORTS
mitl3o76an26 flask_auth_web_service replicated 2/2 flask_auth_gabrielcarneirodeveloper:1 *:8080->5010/tcp
```
## Built with
* **[Flask](https://flask.palletsprojects.com/en/1.1.x/)** - Mainly framework used to develop the project
* **[Flake8](https://pypi.org/project/flake8/)** - Code Linter
* **[Black](https://pypi.org/project/black/)** - Code formatter
* **[Flasgger](https://github.com/flasgger/flasgger)** - Used to build API documentation. It is based on **[Swagger](https://swagger.io/)**
* **[Poetry](https://python-poetry.org/)** - Python package manager
To see all packages, please take a look in **pyproject.toml**
## Authors
* **<NAME>** - *Principal developer* - https://github.com/GabrielCarneiroDeveloper
## License
This project is licensed under the MIT License - see the [LICENSE](https://github.com/GabrielCarneiroDeveloper/flask-blueprint-factory-app/blob/master/LICENSE) file for details
## Contributing
Please read [CONTRIBUTING.md](https://github.com/GabrielCarneiroDeveloper/flask-blueprint-factory-app/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Contacts
If you have some question, improvement or issues at try to install/run the project, please contact me in my e-mail and i'll be glad to help you: **<EMAIL>**.
### If you like it, please give a star ;D
<file_sep>/flask_auth/app/extensions/documentation/documentation_framework.py
from flask import Flask
from flasgger import Swagger
swagger = Swagger()
def init_app(app: Flask):
app.config["SWAGGER"] = {
"title": "Flask Auth",
"version": "1.0.0",
"description": "Open Source project to demonstrate Factory App + Blueprints usage in Python projects",
"license": "MIT",
"termsOfService": "https://github.com/GabrielCarneiroDeveloper/flask-blueprint-factory-app",
}
swagger.init_app(app)
<file_sep>/flask_auth/app/blueprints/users/models.py
from flask_auth.app.extensions.database.database_framework import db
class UserModel(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(80), nullable=False)
password = db.Column(db.String(80), nullable=False)
def __repr__(self):
return f"<User login='{self.login}'>"
<file_sep>/flask_auth/app/app.py
from flask import jsonify
from flask import Flask
from flasgger import swag_from
from os import getenv
from flask_auth.app.common.logger import Logger
from flask_auth.app.common.loaders import get_swagger_file_path
import flask_auth.app.extensions.restful.rest_framework as rest_framework
import flask_auth.app.extensions.database.database_framework as database_framework
import flask_auth.app.extensions.migrate.migrate_framework as migrate_framework
import flask_auth.app.extensions.serializer.serializer_framework as serializer_framework
import flask_auth.app.extensions.documentation.documentation_framework as documentation_framework
import flask_auth.app.blueprints.users as user_module
logger = Logger(__file__).getLogger()
def minimal_app(**config):
app = Flask(__name__)
app.secret_key = "S0M3S3CR3TK3Y"
app.config.from_object(
"flask_auth.app.config." + getenv("APPLICATION_ENV", "Development")
)
return app
def main_app(**config):
# Extensions
app: Flask = minimal_app()
@app.route("/")
@swag_from(get_swagger_file_path(__name__, "index.yml"))
def index_route():
return jsonify(
message="Server is running...",
documentation=f"http://localhost:{app.config.get('PORT')}/apidocs",
github_repository="https://github.com/GabrielCarneiroDeveloper/flask-blueprint-factory-app",
)
# Extensions (Plugins)
database_framework.init_app(app)
logger.info("Finish to initialize extension: Database")
rest_framework.init_app(app)
logger.info("Finish to initialize extension: REST Api")
migrate_framework.init_app(app)
logger.info("Finish to initialize extension: Migrate")
serializer_framework.init_app(app)
logger.info("Finish to initialize extension: Serializer")
documentation_framework.init_app(app)
logger.info("Finish to initialize extension: Documentation")
# Blueprints (Modules)
user_module.init_app(app)
logger.info("Finish to initialize blueprint: Users")
return app
<file_sep>/Dockerfile
FROM python:3.8-slim
LABEL author="<NAME> <<EMAIL>>"
ENV FLASK_APP=run.py
ENV APPLICATION_ENV=Production
ENV FLASK_PORT=5010
RUN apt-get update
RUN python --version && pip --version
RUN pip install poetry
RUN mkdir /app
COPY ./flask_auth app/flask_auth
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
CMD gunicorn -c flask_auth/gunicorn.conf.py flask_auth.run:app
<file_sep>/flask_auth/tests/users/UserModelMockFactory.py
from .UserModelMock import UserModelMock
from typing import List
from flask_auth.app.extensions.database.database_framework import db
class UserModelMockFactory:
user_list: List
user_list_copy: List
number_of_users: int
def __init__(self, number_of_users: int):
""" __new__ is used instead of __init__ because have to be a list
assigned as UserModelMockFactory instance, not an object.
The value assigned to its instance will be the value
returned from __new__ """
self.user_list = []
self.number_of_users = number_of_users
for u in range(self.number_of_users):
self.user_list.append(UserModelMock())
# it keeps an user_list copy
self.user_list_copy = self.user_list.copy()
def save_mocks_in_database(self):
for user in self.user_list:
db.session.add(user)
db.session.commit()
db.session.close()
def remove_all_registers_from_database(self):
db.session.query(UserModelMock).delete()
db.session.commit()
<file_sep>/flask_auth/app/config.default.py
from abc import ABC
class Config(ABC):
DEBUG: bool
TESTING: bool
DATABASE_URI: str
ENV: str
HOST: str
SQLALCHEMY_TRACK_MODIFICATIONS: bool
SQLALCHEMY_DATABASE_URI: str
API_VERSION: str
PORT: str
SECRET_KEY: str
class Production(Config):
...
class Development(Config):
...
class Test(Config):
...
<file_sep>/flask_auth/app/blueprints/users/resources.py
from pprint import pprint
from flask import jsonify, request
from flask_marshmallow.sqla import ValidationError
from flask_restful import Resource, abort
from flask_auth.app.extensions.database.database_framework import db
from flask_auth.app.blueprints.users.models import UserModel
from flask_auth.app.blueprints.users.schemas import (
UserListSchema,
UserCreateSchema,
UserDetailsSchema,
UserUpdateSchema,
)
from flask_auth.app.common.loaders import get_swagger_file_path
from flasgger import swag_from
class UserCreateListResource(Resource):
__module__ = "users"
user_schema = UserListSchema()
users_schema = UserListSchema(many=True)
user_create_schema = UserCreateSchema()
user_model = UserModel()
@swag_from(get_swagger_file_path(__name__, "list.yml"))
def get(self):
user_list = self.users_schema.dump(self.user_model.query.all())
if not user_list:
return abort(401, message="There is no user registered")
return user_list
@swag_from(get_swagger_file_path(__name__, "create.yml"))
def post(self):
try:
user = self.user_create_schema.load(request.json)
db.session.add(user)
db.session.commit()
db.session.close()
return jsonify(message="User created successfully")
except ValidationError as error:
pprint(error.messages)
return abort(401)
class UserDetailUpdateRemoveResource(Resource):
user_details_schema = UserDetailsSchema()
user_update_schema = UserUpdateSchema()
user_model = UserModel()
@swag_from(get_swagger_file_path(__name__, "read.yml"))
def get(self, _id: int):
user = self.user_details_schema.dump(
self.user_model.query.filter_by(id=_id).first()
)
if not user:
return abort(401, message="User not found")
return user
# TODO: Improve this update approach
@swag_from(get_swagger_file_path(__name__, "update.yml"))
def put(self, _id: int):
try:
db_user = self.user_model.query.filter_by(id=_id).first()
if not db_user:
return abort(401, message="User not found")
new_user_values = self.user_update_schema.load(request.json)
db_user.login = new_user_values.login
db.session.commit()
db.session.close()
return jsonify(message="User updated successfully")
except ValidationError as error:
pprint(error.messages)
return abort(401)
@swag_from(get_swagger_file_path(__name__, "delete.yml"))
def delete(self, _id: int):
try:
user = self.user_model.query.filter_by(id=_id).first()
if user:
db.session.delete(user)
db.session.commit()
db.session.close()
return jsonify(message="User removed successfully")
return abort(401, message="User not found")
except ValidationError as error:
pprint(error.messages)
return abort(
401,
message="Some information is lacking or invalid. Please check them and try it again.",
)
<file_sep>/flask_auth/.env.example
FLASK_APP=run.py
APPLICATION_ENV=<file_sep>/flask_auth/app/config.py
import os
from abc import ABC
class Config(ABC):
DEBUG: bool
TESTING: bool
DATABASE_URI: str
ENV: str
HOST: str
SQLALCHEMY_TRACK_MODIFICATIONS: bool
SQLALCHEMY_DATABASE_URI: str
API_VERSION: str
PORT: str
SECRET_KEY: str
class Production(Config):
ENV = "Production"
HOST = "0.0.0.0"
PORT = "5010"
DATABASE_URI = "mysql://user@localhost/foo"
SECRET_KEY = "secret_key_prod"
DEBUG = False
TESTING = False
DATABASE_URI = "sqlite:///:memory:"
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.abspath(".")}/data.db'
API_VERSION = "v1"
class Development(Config):
ENV = "Development"
HOST = "0.0.0.0"
PORT = "5000"
DEBUG = True
SECRET_KEY = "secret_key_dev"
TESTING = False
DATABASE_URI = "sqlite:///:memory:"
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.abspath(".")}/data.db'
API_VERSION = "v1"
class Test(Config):
ENV = "Test"
HOST = "0.0.0.0"
PORT = "3214"
DEBUG = True
TESTING = True
SECRET_KEY = "secret_key_test"
SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.abspath(".")}/data_test.db'
DATABASE_URI = "sqlite:///:memory:"
SQLALCHEMY_TRACK_MODIFICATIONS = False
API_VERSION = "v1"
SECRET_KEY = "TestingSecretKey"
<file_sep>/flask_auth/app/blueprints/users/__init__.py
from flask import Blueprint, Flask
from flask_restful import Api
from flask_auth.app.blueprints.users.resources import (
UserCreateListResource,
UserDetailUpdateRemoveResource,
)
bp = Blueprint("users", __name__, url_prefix="/api/users")
api = Api(bp)
def init_app(app: Flask):
api.add_resource(UserCreateListResource, "/")
api.add_resource(UserDetailUpdateRemoveResource, "/<int:_id>")
app.register_blueprint(bp)
<file_sep>/flask_auth/run.py
from flask_auth.app.app import main_app
app = main_app()
if __name__ == "__main__":
app.run(host=app.config["HOST"] or "localhost", port=app.config["PORT"] or "5000")
<file_sep>/flask_auth/app/common/loaders.py
from os import sep
from os.path import dirname, abspath, join
def get_swagger_file_path(module: str, swagger_file_name: str) -> str:
try:
return join(
dirname(abspath(__file__)).rsplit(sep, 2)[0],
"docs",
module.rsplit(".")[-2],
swagger_file_name,
)
except IOError:
raise IOError("Not able to read swagger file")
except Exception:
raise Exception("Unexpected error occurred")
<file_sep>/flask_auth/app/extensions/serializer/serializer_framework.py
from flask import Flask
from flask_marshmallow import Marshmallow
ma = Marshmallow()
def init_app(app: Flask):
ma.init_app(app)
<file_sep>/flask_auth/test.py
import os
import unittest
from flask_auth.tests.users.UserResourceTest import UserResourceTest
os.environ["APPLICATION_ENV"] = "Test"
if __name__ == "__main__":
unittest.main()
<file_sep>/flask_auth/tests/__init__.py
from flask_auth.app.app import minimal_app, main_app
import tempfile
from flask import jsonify
import sqlite3
import os
from flask_auth.app.extensions.database.database_framework import db
"""
TODO: Configure test database name with app.config
TODO: Avoid have to use schema.sql in database_dev.db creation
"""
os.environ["APPLICATION_ENV"] = "Test"
app = main_app()
app.testing = True
app_context = app.test_request_context()
app_context.push()
client = app.test_client()
<file_sep>/flask_auth/app/blueprints/users/schemas.py
from flask_auth.app.blueprints.users.models import UserModel
from flask_auth.app.extensions.serializer.serializer_framework import ma
class UserListSchema(ma.ModelSchema):
class Meta:
model = UserModel
fields = ("id", "login")
class UserDetailsSchema(ma.ModelSchema):
class Meta:
model = UserModel
fields = ("id", "login", "password")
class UserCreateSchema(ma.ModelSchema):
class Meta:
model = UserModel
fields = ("login", "password")
class UserUpdateSchema(ma.ModelSchema):
class Meta:
model = UserModel
fields = ("login",)
| b2d9e2f96945b8045ebfc7f72424a4b4b8801387 | [
"TOML",
"Markdown",
"Makefile",
"Python",
"Dockerfile",
"Shell"
] | 24 | Python | GabrielCarneiroDeveloper/flask-blueprint-factory-app | b133ddc0de7d2780e6705ad115749522b69587cb | 1243b9c2ab6b642c7e6cd75420c7424e766b2345 |
refs/heads/master | <repo_name>yisus82/codelytv-go<file_sep>/cmd/beers-cli/main.go
package main
import (
"github.com/spf13/cobra"
"github.com/yisus82/codelytv-go/internal/cli"
"github.com/yisus82/codelytv-go/internal/storage/csv"
)
func main() {
csvRepo := csv.NewRepository()
rootCmd := &cobra.Command{Use: "beers-cli"}
rootCmd.AddCommand(cli.InitBeersCmd(csvRepo))
rootCmd.AddCommand(cli.InitStoresCmd())
rootCmd.Execute()
}
<file_sep>/go.mod
module github.com/yisus82/codelytv-go
go 1.14
require github.com/spf13/cobra v1.0.0
<file_sep>/README.md
# codelytv-go
Introducción a Go: Tu primera app - Codely.tv
| 7719f629a7bda91af3ac3795135c37f860446b9b | [
"Markdown",
"Go Module",
"Go"
] | 3 | Go | yisus82/codelytv-go | e605f5b698188220d714ec67dedc755bf5149cc5 | d16d6c418fe3d8dbcfec08d22761c8299901a8e8 |
refs/heads/master | <file_sep>/* eslint-disable no-underscore-dangle */
import { avoidWarnForRequire } from './utils';
const toggleNetworkInspect = enabled => {
if (!enabled && window.__NETWORK_INSPECT__) {
window.XMLHttpRequest = window.__NETWORK_INSPECT__.XMLHttpRequest;
window.FormData = window.__NETWORK_INSPECT__.FormData;
delete window.__NETWORK_INSPECT__;
return;
}
if (!enabled) return;
window.__NETWORK_INSPECT__ = {
XMLHttpRequest: window.XMLHttpRequest,
FormData: window.FormData,
};
window.XMLHttpRequest = window.originalXMLHttpRequest
? window.originalXMLHttpRequest
: window.XMLHttpRequest;
window.FormData = window.originalFormData ? window.originalFormData : window.FormData;
console.log(
'[RNDebugger]',
'Network Inspect is enabled,',
'you can open `Network` tab to inspect requests of `fetch` and `XMLHttpRequest`.'
);
};
const methodsGlobalName = '__AVAILABLE_METHODS_CAN_CALL_BY_RNDEBUGGER__';
export const checkAvailableDevMenuMethods = async (networkInspect = false) => {
const done = await avoidWarnForRequire('NativeModules', 'AsyncStorage');
const NativeModules = window.__DEV__ ? window.require('NativeModules') : {};
const AsyncStorage = window.__DEV__ ? window.require('AsyncStorage') : {};
done();
// RN 0.43 use DevSettings, DevMenu is deprecated
const DevSettings = NativeModules.DevSettings || NativeModules.DevMenu;
const methods = {
...DevSettings,
networkInspect: toggleNetworkInspect,
clearAsyncStorage: AsyncStorage.clear,
};
const result = Object.keys(methods).filter(key => !!methods[key]);
window[methodsGlobalName] = methods;
toggleNetworkInspect(networkInspect);
postMessage({ [methodsGlobalName]: result });
};
export const invokeDevMenuMethod = (name, args = []) => {
const method = window[methodsGlobalName][name];
if (method) method(...args);
};
| e8d9f90d2cf882e3a8498967e4f096b40e3fecd9 | [
"JavaScript"
] | 1 | JavaScript | linhhd1kt/react-native-debugger | db0ecf0318244746ab26f8989ff55a37d06d1756 | 453a7edf1dadb0f4d01cf97a8ed2a6c2a09e0171 |
refs/heads/master | <repo_name>TenghuiZhang/BusinessCardRing<file_sep>/README.md
# BusinessCardRing
Hello, everyone!
I am <NAME>, this is my product of a business card exchange system. The purpose of this project is that people can exchange their name card by shaking their hands and the Arduino will collect the signal and upload the business card information to the cloud by Python.
If you want to see how the product works, please go to the https://youtu.be/F6YNxm4p_R4 or visit my personal website: tenghuizhang.com
以下是实际调试时的一些操作注意事项:
首先,我们需要知道本地服务器的IP:1.Arduino控制端需要根据IP、无线网来初始化;2.APP需要IP来初始化。
接下来,Arduino部分:
首先,初始化,有wifi模块的初始化(波特率为115200),蓝牙模块不需要初始化(每次使用的时候将波特率设定为9600就OK了)。LED的初始化,戒指上按键的初始化,蓝牙模块和WiFi模块的选择端口初始化(CD4052的A口连接到Arduino的输出IO口,B口接到GND),RTC的初始化(不用管)。
当RTC时间出错后,用另一个程序来设定时间:
将时间改成当前时间的下两分钟,分别上传到两块带有RTC模块的ARDUINO板,等上传完成后,等待至当前时间与设定时间一致,同时复位两个ARDUINO板,完成RTC的配置。然后需要将之前的戒指的程序重新上传至ARDUINO板。
APP:
首先确定好配对的ARDUINO模块。打开之后,先设定自己的信息,然后点击更新(需要选取配对的蓝牙),(如果收到字符‘A’,说明更新成功)。等待新的名片进入。
服务器:
监听与ARDUINO连接的端口、接受数据、对比判断(是否更新数据库)
监听与APP连接的端口、接受请求,若有数据,则发送
<file_sep>/socket_server.py
#-*- coding:utf-8 -*-
from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH, ThreadingMixIn as TMI)
import traceback
import pymysql as mysql_module
TABLE = 'user_info'
earlyData = ''
class MyBaseRequestHandler(SRH):
"""
#从BaseRequestHandler继承,并重写handle方法
"""
def handle(self):
try:
global earlyData
#一次读取1024字节,并去除两端的空白字符(包括空格,TAB,\r,\n)
data = self.request.recv(1024).strip().decode('gbk')
#self.client_address是客户端的连接(host, port)的元组
print("receive from (%r):%s" % (self.client_address, data))
if earlyData == '':
earlyData = data
else:
# 解析新接收数据的时间,时间相差1s储存
if self.isValidInternal(data) :
# 将两条数据存入数据库为http请求做准备
self.saveToSql(data)
earlyData = ''
else :
earlyData = data
#转换成大写后写回(发生到)客户端
# self.request.sendall(data.upper())
except:
traceback.print_exc()
# break
#循环监听(读取)来自客户端的数据
#while True:
def isValidInternal(self, data):
return abs(float(data.split(' ')[0]) - float(earlyData.split(' ')[0])) <= 1.5
insertData = 'insert into ' + TABLE + ' (belong_to, timestamp, name, sex, company, phone_number, interest) ' \
'values(%s, %s, %s, %s, %s, %s, %s)'
def saveToSql(self, data):
global earlyData
# 连接数据库
conn = mysql_module.connect(user='root', passwd='<PASSWORD>',
host='localhost', port=3306, db='ring')
conn.set_charset('utf8')
cur = conn.cursor()
items1 = data.split(' ')
items1.insert(0, earlyData.split(' ')[4])
items2 = earlyData.split(' ')
items2.insert(0, data.split(' ')[4])
cur.executemany(self.insertData,
[tuple(items1),
tuple(items2)])
#sql="select * from " + TABLE
#print(execute(sql))
#print(cur.fetchone())
cur.close()
conn.commit()
print("存入数据库成功")
conn.close()
PORT = 9999 #端口
ADDR = ('', PORT)
class Server(TMI, TCP): #变动位置
pass
if __name__ == "__main__":
# 初始化TCPServer对象,
server = Server(ADDR, MyBaseRequestHandler)
# 启动服务监听
server.serve_forever()
<file_sep>/webserver.py
# encoding=utf-8
import io
import shutil
import urllib.request
import pymysql as mysql_module
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
TABLE = 'user_info'
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
path, args = urllib.request.splitquery(self.path) # ?分割
arg_item = args.split('=')
user_info = self.getUserInfo(arg_item[1])
self.output_txt(user_info)
def getUserInfo(self, args):
if len(args) != 11 :
return json.dumps({})
# 连接数据库
conn = mysql_module.connect(user='root', passwd='<PASSWORD>',
host='localhost', port=3306, db='ring')
conn.set_charset('utf8')
cur = conn.cursor()
select = "select name, sex, company, phone_number, interest, timestamp from " + TABLE + \
' where belong_to = "' + args + '" and inquire = 0'
cur.execute(select)
user_info = cur.fetchone()
if user_info == None :
cur.close()
conn.commit()
conn.close()
return json.dumps({})
else :
update = "update " + TABLE + " SET inquire = 1 where belong_to = " + args + " and timestamp=" + str(user_info[5])
cur.execute(update)
cur.close()
conn.commit()
conn.close()
result = {}
result['name'] = user_info[0]
result['sex'] = user_info[1]
result['company'] = user_info[2]
result ['phone'] = user_info[3]
result['interest'] = user_info[4]
return json.dumps(result)
def do_POST(self):
path, args = urllib.request.splitquery(self.path)
length = int(self.headers['content-length'])
data = self.rfile.read(length)
self.output_txt(path + args.decode() + data)
def output_txt(self, content):
# 指定返回编码
enc = "UTF-8"
content = content.encode(enc)
f = io.BytesIO()
f.write(content)
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "json; charset=%s" % enc)
self.send_header("Content-Length", str(len(content)))
self.end_headers()
shutil.copyfileobj(f, self.wfile)
PORT = 12138
server = HTTPServer(('', PORT), MyRequestHandler)
print('Started httpServer on port ', PORT)
server.serve_forever()
| 4688472546e1388c88334e0b8bf1c533f419c38e | [
"Markdown",
"Python"
] | 3 | Markdown | TenghuiZhang/BusinessCardRing | 6f4e23d64bf4c3a3be4b9dedd2da9925bbc022b6 | 6e7c4d3de09c55da0d08fbd7936a6b7caa64a00b |
refs/heads/master | <repo_name>dustanisci/14-10-2019-github-angular8-git-io<file_sep>/src/app/app.component.spec.ts
import { TestBed, async, ComponentFixture, inject } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { MatInputModule } from '@angular/material/input';
import { NgxSpinnerModule } from 'ngx-spinner';
import { ToastrModule } from 'ngx-toastr';
import { AppService } from './app.service';
import { SphereComponent } from './component/sphere/sphere.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
MatTableModule,
MatPaginatorModule,
MatSortModule,
MatInputModule,
NgxSpinnerModule,
ToastrModule.forRoot({
preventDuplicates: true
}),
],
declarations: [
AppComponent,
SphereComponent
],
providers: [
AppService,
HttpClientModule,
AppComponent
]
}).compileComponents();
}));
it('should create the app', () => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
expect(component).toBeTruthy();
});
});
| 72a05d13c7b3fd55a2113b95e9766d169a2797c2 | [
"TypeScript"
] | 1 | TypeScript | dustanisci/14-10-2019-github-angular8-git-io | 0cdfe09e23f7e3e25bd78f839e701bb5fcf2d6be | 0a9eba2870f92ff10f299a65a1ddfbce0de383e5 |
refs/heads/master | <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Planta_model extends CI_Model{
public function cadastrar($dados) {
if($dados!=NULL):
$this->db->insert('plantas',$dados);
return $this->db->insert_id();
endif;
}
public function addFoto($id, $ext){
$this->db->where("id", $id);
$this->db->update("plantas", array("foto" => $ext));
}
public function editar($id, $dados) {
$this->db->update('plantas', $dados, array('id' => $id));
}
public function excluir($id) {
if($id!=NULL):
$this->db->delete('plantas', array("id" => $id));
endif;
}
public function Listar($userId) {
$this->db->where('userid', $userId);
$this->db->order_by('nome', 'ASC');
return $this->db->get('plantas')->result();
}
public function getExt($id){
$this->db->select('foto');
$this->db->where('id', $id);
return $this->db->get('plantas')->row()->foto;
}
public function carregar($id) {
if ($id != NULL):
$this->db->where('id',$id);
return $this->db->get('plantas')->row();
endif;
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class CRUD_Usuario extends CI_Controller {
public function __CONSTRUCT() {
parent::__CONSTRUCT();
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('array');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('table');
$this->load->model('Usuario_model');
}
public function create() {
$this->form_validation->set_rules('nome','NOME','trim|required|max_length[80]');
$this->form_validation->set_message('is_unique','Este %s já está cadastrado no sistema');
$this->form_validation->set_rules('login','LOGIN','trim|required|max_length[70]|strtolower|is_unique[usuarios.login]');
$this->form_validation->set_rules('senha','SENHA','trim|required|strtolower');
$this->form_validation->set_message('matches','O campo %s está diferente do campo %s');
$this->form_validation->set_rules('senha2','REPITA A SENHA','trim|required|strtolower|matches[senha]');
if($this->form_validation->run()==TRUE):
$data = elements(array('nome','login','senha'), $this->input->post());
$data['senha']=md5($data['senha']);
$this->Usuario_model->do_insert($data, $permissoes);
endif;
$dados = array(
'titulo' => 'CRUD » Create',
'tela' => 'create',
);
$this->load->view('View_Usuario',$dados);
}
public function retrieve() {
$dados = array(
'titulo' => 'CRUD » Retrieve',
'tela' => 'retrieve',
'usuarios' => $this->Usuario_model->get_all()->result()
);
$this->load->view('View_Usuario',$dados);
}
public function login() {
$login = $this->input->post('login');
$senha = $this->input->post('senha');
$flag = $this->verifica_login($login, $senha);
if ($flag == true) {
$id = $this->busca_id($login, $senha);
$this->session->set_userdata('id', $id);
$this->session->set_userdata('login', $login);
$this->session->set_userdata('senha', $senha);
$this->session->set_userdata('logado', true);
redirect('/CRUD_Planta/index');
} else {
$this->session->set_flashdata('loginbad','O usuário ou a senha estão errados');
$this->session->set_userdata('logado', false);
$this->index();
}
}
public function logout() {
$this->session->sess_destroy();
$this->session->unset_userdata('id');
$this->session->unset_userdata('usuario');
$this->session->unset_userdata('senha');
$this->session->unset_userdata('logado');
$this->session->unset_userdata('admin');
$this->index();
}
public function index() {
$dados = array(
'titulo' => 'Index',
'tela' => 'login',
);
$this->load->view('View_Usuario',$dados);
}
public function verifica_login($login, $senha) {
$senha = md5($senha);
$usuarios = $this->Usuario_model->get_all()->result();
foreach ($usuarios as $u) {
if ($login == $u->login && $senha == $u->senha) {
return true;
}
}
return false;
}
public function busca_id($login, $senha) {
$senha = md5($senha);
$usuarios = $this->Usuario_model->get_all()->result();
foreach ($usuarios as $u) {
if ($login == $u->login && $senha == $u->senha) {
return $u->id;
}
}
return -1;
}
public function update() {
$this->form_validation->set_rules('nome','NOME','trim|required|max_length[80]');
$this->form_validation->set_message('Este %s já está cadastrado no sistema');
$this->form_validation->set_rules('login','USUARIO','trim|required|max_length[70]|strtolower');
$this->form_validation->set_rules('senha','SENHA','trim|required|strtolower');
$this->form_validation->set_message('matches','O campo %s está diferente do campo %s');
$this->form_validation->set_rules('senha2','REPITA A SENHA','trim|required|strtolower|matches[senha]');
if($this->form_validation->run()==TRUE):
$dados = elements(array('nome','senha','login'),$this->input->post());
$dados['senha']=md5($dados['senha']);
$this->Usuario_model->do_update($dados, $this->input->post('idusuario'), $permissoes);
endif;
$dados = array(
'titulo' => 'CRUD » Update',
'tela' => 'update',
);
$this->load->view('View_Usuario',$dados);
}
public function delete() {
if ($this->input->get('id')>0):
$this->Usuario_model->do_delete(array('id' => $this->input->get('id')));
endif;
$dados = array(
'titulo' => 'CRUD » Delete',
'tela' => 'retrieve',
'usuarios' => $this->Usuario_model->get_all()->result()
);
$this->load->view('View_Usuario',$dados);
}
}
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Usuario_model extends CI_Model{
public function do_insert($dados=NULL, $permissoes=NULL) {
if($dados!=NULL):
$this->db->insert('usuarios',$dados);
$this->session->set_flashdata('cadastrook','Cadastro realizado com sucesso!');
redirect('CRUD_Usuario/create');
endif;
}
public function do_update($dados=NULL,$id=NULL,$permissoes=NULL) {
if($dados!=NULL && $id!=NULL):
$this->db->update('usuarios', $dados, array('id' => $id));
$this->session->set_flashdata('edicaook','Atualização realizada com sucesso!');
redirect(current_url());
endif;
}
public function do_delete($id=NULL) {
if($id!=NULL):
$this->db->delete('usuarios',$id);
$this->session->set_flashdata('exclusaook','Registro excluído com sucesso!');
redirect('CRUD_Usuario/retrieve');
endif;
}
public function get_all() {
$this->db->order_by('id', 'ASC');
return $this->db->get('usuarios');
}
public function get_byid($id=NULL) {
if ($id != NULL):
$this->db->order_by('id', 'ASC');
$this->db->where('id',$id);
$this->db->limit(1);
return $this->db->get('usuarios');
else:
return FALSE;
endif;
}
}<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<nav id='menu' class='navbar navbar-expand-lg navbar-custom'>
<div class='collapse navbar-collapse' id='navbarSupportedContent'>
<img height='50px' width='50px' src='../../../uploads/imagens/logo.png'>
<ul class='navbar-nav mr-auto'>
<li class='nav-item'>" .
anchor('CRUD_Usuario/create','Cadastrar Usuário', array('class'=>'nav-link')) .
"</li>
<li class='nav-item'>" .
anchor('CRUD_Usuario/retrieve','Listar Usuários', array('class'=>'nav-link')) .
"</li>
<li class='nav-item'>" . anchor('CRUD_Planta/cadastrar','Cadastrar Planta', array('class'=>'nav-link')) . "</li>
<li class='nav-item'>" . anchor('CRUD_Planta/index','Listar Plantas', array('class'=>'nav-link')) . "</li>
<li class='nav-item'>" .
anchor('CRUD_Usuario/logout','Logout', array('class'=>'nav-link')) .
"</li>
</ul>
</div>
</nav>";
}<file_sep>#DATABASE: herbarium
CREATE TABLE usuarios (
id SERIAL NOT NULL PRIMARY KEY,
nome VARCHAR(40),
login VARCHAR(40),
senha VARCHAR(32)
);
CREATE TABLE plantas (
id SERIAL PRIMARY KEY,
nome VARCHAR(50) NOT NULL,
pais VARCHAR(20),
estado VARCHAR(20),
cidade VARCHAR(20) NOT NULL,
descricao VARCHAR(200),
data DATE,
foto VARCHAR(10),
userId INTEGER REFERENCES usuarios(id) NOT NULL
);<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-8'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Edição de Planta</h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
echo form_open_multipart('/CRUD_Planta/editar');
if ($this->session->flashdata('cadastrook')):
echo '<p>' . $this->session->flashdata('cadastrook') . '</p>';
endif;
echo "<div class='form-group'>";
echo form_label('Nome: ');
echo form_input(array('name'=>'nome'), set_value('nome', $planta->nome), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('País: ');
echo form_input(array('name'=>'pais'), set_value('pais', $planta->pais), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-row'>";
echo "<div class='form-group col-md-6'>";
echo form_label('Estado: ');
echo form_input(array('name'=>'estado'), set_value('estado', $planta->estado), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group col-md-6'>";
echo form_label('Cidade: ');
echo form_input(array('name'=>'cidade'), set_value('cidade', $planta->cidade), array('class' => 'form-control'));
echo "</div>";
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Descrição: ');
echo form_textarea(array('name'=>'descricao', 'rows'=>'5'), set_value('descricao', $planta->descricao), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-row'>";
echo "<div class='form-group col-md-6'>";
echo form_label('Data: ');
echo "<input type='date' name='data' id='data' value='$planta->data' class='form-control'>";
echo "</div>";
echo "<div class='form-group col-md-6'>";
echo form_label('Foto: ');
echo "<input type='file' name='foto' id='foto' accept='image/*' class='form-control'>";
echo "</div>";
echo "</div> <br />";
echo "<div class='text-center'>";
echo form_submit(array('name'=>'atualizar'), 'Alterar dados', array('class' => 'btn btn-secondary btn-block'));
echo "</div>";
echo form_hidden('id', $planta->id);
echo form_hidden('oldExt', $planta->foto);
echo form_close();
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class CRUD_Planta extends CI_Controller {
public function __CONSTRUCT() {
parent::__CONSTRUCT();
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('array');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('table');
$this->load->model('Planta_model');
}
public function index(){
$plantas = $this->Planta_model->listar($this->session->userdata('id'));
$dados = array(
'titulo' => 'Listar Plantas',
'tela' => 'index',
'plantas' => $plantas
);
$this->load->view('carregaPlantasTela',$dados);
}
public function cadastrar(){
$this->form_validation->set_rules('nome','Nome','trim|required|max_length[50]');
$this->form_validation->set_rules('pais','Pais','trim|max_length[20]');
$this->form_validation->set_rules('estado','Estado','trim|max_length[20]');
$this->form_validation->set_rules('cidade','Cidade','trim|max_length[20]|required');
$this->form_validation->set_rules('descricao','Descrição','trim|max_length[200]');
if($this->form_validation->run() == true){
$data = elements(array('nome','pais','estado', 'cidade', 'descricao', 'data'), $this->input->post());
$data['userid'] = $this->session->userdata('id');
$id = $this->Planta_model->cadastrar($data);
$this->realizaUpload($id);
redirect("/CRUD_Planta/index");
}
$dados = array(
'titulo' => 'Cadastrar Planta',
'tela' => 'cadastrar'
);
$this->load->view('carregaPlantasTela',$dados);
}
public function excluir(){
$id = $this->uri->segment(3);
$ext = $this->Planta_model->getExt($id);
$this->Planta_model->excluir($id);
unlink("./uploads/" . $id . $ext);
redirect('/CRUD_Planta/index');
}
public function editar(){
$this->form_validation->set_rules('nome','Nome','trim|required|max_length[50]');
$this->form_validation->set_rules('pais','Pais','trim|max_length[20]');
$this->form_validation->set_rules('estado','Estado','trim|max_length[20]');
$this->form_validation->set_rules('cidade','Cidade','trim|max_length[20]|required');
$this->form_validation->set_rules('descricao','Descrição','trim|max_length[200]');
if($this->form_validation->run() == true){
$data = elements(array('nome','pais','estado', 'cidade', 'descricao', 'data'), $this->input->post());
$id = $this->input->post('id');
$newFoto = $this->input->post('foto');
$data['userid'] = $this->session->userdata('id');
$this->Planta_model->editar($id, $data);
if($newFoto !== ''){
$oldFoto = $this->input->post('oldExt');
unlink('./uploads/' . $id. $oldFoto);
$this->realizaUpload($id);
}
redirect("/CRUD_Planta/index");
}
$id = $this->uri->segment(3);
$dados = $this->Planta_model->carregar($id);
$dados = array(
'titulo' => 'Cadastrar Planta',
'tela' => 'editar',
'planta' => $dados
);
$this->load->view('carregaPlantasTela',$dados);
}
public function Detalhes(){
$id = $this->uri->segment(3);
$dados = $this->Planta_model->carregar($id);
$dados = array(
'titulo' => 'Detalhes Planta',
'tela' => 'detalhes',
'planta' => $dados
);
$this->load->view('carregaPlantasTela',$dados);
}
private function realizaUpload($id){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['file_name'] = $id;
$this->load->library('upload', $config);
if($this->upload->do_upload('foto')){
$data = $this->upload->data();
$this->Planta_model->addFoto($id, $data['file_ext']);
}
}
}<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-10'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Plantas</h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
echo "<div class='row'>";
if ($this->session->flashdata('exclusaook')):
echo "<p class='success'>" . $this->session->flashdata('exclusaook') . "</p>";
endif;
foreach ($plantas as $linha):
echo "<div class='col-md-4'>";
echo "<div class='card'>";
echo "<img height='200px' width='100px' class='card-img-top' src='../uploads/" . $linha->id . $linha->foto . "/>";
echo "<h5 class='card-title text-center'> <a class='card-title text-center' href='/CRUD_Planta/Detalhes/$linha->id'> $linha->nome </a> </h5>";
echo "<div class='card-body'>";
echo "<div class='text-right'>";
echo anchor("/CRUD_Planta/editar/$linha->id", "<img height='25px' width='25px' src='../uploads/imagens/lapis.png'>");
echo anchor("/CRUD_Planta/excluir/$linha->id", "<img height='25px' width='25px' src='../uploads/imagens/lixeira.png'>");
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
endforeach;
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
}<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-8'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Cadastro de Usuários </h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
echo form_open('CRUD_Usuario/create');
if ($this->session->flashdata('cadastrook')):
echo "<p class='success'>" . $this->session->flashdata('cadastrook') . "</p>";
endif;
echo "<div class='form-group'>";
echo form_label('Nome completo: ');
echo form_input(array('name'=>'nome'), set_value('nome'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Login: ');
echo form_input(array('name'=>'login'), set_value('login'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Senha: ');
echo form_password(array('name'=>'senha'), set_value('<PASSWORD>'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Repita a senha: ');
echo form_password(array('name'=>'<PASSWORD>'), set_value('<PASSWORD>'), array('class' => 'form-control'));
echo "</div> <br />";
echo "<div class='text-center'>";
echo form_submit(array('name'=>'cadastrar'), 'Cadastrar', array('class' => 'btn btn-secondary btn-block'));
echo "</div>";
echo form_close();
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
}<file_sep><?php
if ($this->session->userdata('logado') == true) {
$iduser = $this->uri->segment(3);
if ($iduser == NULL) redirect ('CRUD_Usuario/retrieve');
$query = $this->Usuario_model->get_byid($iduser)->row();
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-8'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Edição de Usuário </h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
echo form_open("CRUD_Usuario/update/$iduser");
if ($this->session->flashdata('edicaook')):
echo "<p class='success'>" . $this->session->flashdata('edicaook') . "</p>";
endif;
echo "<div class='form-group'>";
echo form_label('Nome completo: ');
echo form_input(array('name'=>'nome'), set_value('nome', $query->nome), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Login: ');
echo form_input(array('name'=>'login'), set_value('login', $query->login), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Senha: ');
echo form_password(array('name'=>'senha'), set_value('<PASSWORD>'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Repita a senha: ');
echo form_password(array('name'=>'<PASSWORD>'), set_value('<PASSWORD>'), array('class' => 'form-control'));
echo "</div> <br />";
echo "<div class='text-center'>";
echo form_submit(array('name'=>'atualizar'), 'Alterar dados', array('class' => 'btn btn-secondary btn-block'));
echo "</div>";
echo form_hidden('idusuario',$query->id);
echo form_close();
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
}<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-8'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Cadastro de Plantas </h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
echo form_open_multipart('/CRUD_Planta/cadastrar');
if ($this->session->flashdata('cadastrook')):
echo '<p>' . $this->session->flashdata('cadastrook') . '</p>';
endif;
echo "<div class='form-group'>";
echo form_label('Nome: ');
echo form_input(array('name'=>'nome'), set_value('nome'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group'>";
echo form_label('País: ');
echo form_input(array('name'=>'pais'), set_value('pais'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-row'>";
echo "<div class='form-group col-md-6'>";
echo form_label('Estado: ');
echo form_input(array('name'=>'estado'), set_value('estado'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-group col-md-6'>";
echo form_label('Cidade: ');
echo form_input(array('name'=>'cidade'), set_value('cidade'), array('class' => 'form-control'));
echo "</div>";
echo "</div>";
echo "<div class='form-group'>";
echo form_label('Descrição: ');
echo form_textarea(array('name'=>'descricao', 'rows'=>'5'), set_value('descricao'), array('class' => 'form-control'));
echo "</div>";
echo "<div class='form-row'>";
echo "<div class='form-group col-md-6'>";
echo form_label('Data: ');
echo form_input(array('name'=>'data', 'type'=>'date', 'class'=>'form-control'), set_value('data'));
echo "</div>";
echo "<div class='form-group col-md-6'>";
echo form_label('Foto: ');
echo "<input type='file' name='foto' id='foto' accept='image/*' class='form-control'>";
echo "</div>";
echo "</div> <br />";
echo "<div class='text-center'>";
echo form_submit(array('name'=>'cadastrar'), 'Cadastrar', array('class' => 'btn btn-secondary btn-block'));
echo "</div>";
echo form_close();
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
}<file_sep><?php
$this->load->view('includes/header');
$this->load->view('includes/menu');
if ($tela != '')$this->load->view('plantasTelas/' . $tela);
$this->load->view('includes/footer');<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-10'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Planta</h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
echo "<div class='row'>";
if ($this->session->flashdata('exclusaook')):
echo '<p>'.$this->session->flashdata('exclusaook').'</p>';
endif;
echo "<div class='col-md-4'>";
echo "<div class='card'>";
echo "<img height='200px' width='100px' class='card-img-top' src='/uploads/" . $planta->id . $planta->foto . "'/>";
echo "<h5 class='card-title text-center'>" . $planta->nome . "</h5>";
echo "<div class='card-body'>";
echo "<p class='card-text text-justify' id='pais'> País: " . $planta->pais . "</p>";
echo "<p class='card-text text-justify' id='estado'> Estado: " . $planta->estado . "</p>";
echo "<p class='card-text text-justify' id='cidade'> Cidade: " . $planta->cidade . "</p>";
echo "<p class='card-text text-justify'> Descrição: " . $planta->descricao . "</p>";
echo "<p class='card-text text-justify'> Data: " . $planta->data . "</p>";
echo "<div class='text-right'>";
echo anchor("/CRUD_Planta/editar/$planta->id", "<img height='25px' width='25px' src='../../../uploads/imagens/lapis.png'>");
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "<input type='hidden' id='local' value='$planta->cidade'>";
echo "<input type='hidden' id='planta' value='$planta->nome'>";
echo "<div id='mapa' style='height: 500px; width: 670px; border: solid 1px'> </div>
<script>
function myMap() {
var mapCanvas = document.getElementById('mapa');
var addressInput = document.getElementById('local').value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: addressInput}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myResult = results[0].geometry.location;
var mapOptions = {
zoom: 10,
center: myResult
}
var map = new google.maps.Map(mapCanvas, mapOptions);
var planta = document.getElementById('planta').value;
var marker = new google.maps.Marker({
position: myResult,
title:planta
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
});
}
</script>
<script src='https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=myMap'></script>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
}<file_sep><?php
if ($this->session->userdata('logado') == true) {
echo "<br />";
echo "<div class='container-fluid'>";
echo "<div class='row align-items-center justify-content-center'>";
echo "<div class='col-lg-10'>";
echo "<div class='card'>";
echo "<div class='card-header card-title'>";
echo "<div class='text-center'>";
echo "<h5>Usuários</h5>";
echo "</div>";
echo "</div>";
echo "<div class='card-body'>";
if ($this->session->flashdata('exclusaook')):
echo "<p class='success'>" . $this->session->flashdata('exclusaook') . "</p>";
endif;
$template = array('table_open' => '<table class="table table-striped text-center">');
$this->table->set_template($template);
$this->table->set_heading('ID', 'Nome', 'Login', '', '');
foreach ($usuarios as $linha):
$this->table->add_row($linha->id, $linha->nome, $linha->login,
anchor("CRUD_Usuario/update/$linha->id", "<img height='25px' width='25px' src='../../uploads/imagens/lapis.png'>"),
anchor("CRUD_Usuario/delete/?id=$linha->id", "<img height='25px' width='25px' src='../../uploads/imagens/lixeira.png'>"));
endforeach;
echo $this->table->generate();
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
} else {
include "erro_permissao.php";
} | ce24ce4caf397dec85a7b0ce50fc7b571d36f8fe | [
"SQL",
"PHP"
] | 14 | PHP | lauraadalmolin/herbarium | 00498c61e0333e1f44f455e3a996a4bf483d02ab | 0c1d43b5278a3c5832e865f8c19e4c22b7e1675e |
refs/heads/master | <repo_name>beshkoon/test<file_sep>/blgen.py
import sys
import json
import socket
import time
from hashlib import sha256 as sha
#kirsche.emzy.de:50001
#electrum.jochen-hoenicke.de:50003
#electrum-server.ninja:50001
#electrum.emzy.de:50001
#e2.keff.org:50001
#fortress.qtornado.com:50001
#electrumx.erbium.eu:50001
#in servers.json find servers use t port.
f = open('tst', 'w')
f.write('.i 608\n.o 32\n')
MAX_BL = 2000
ID = 0
OFFSET = 0
MAX_ID = 300
s = socket.create_connection(('electrum.emzy.de', 50001))
s.setblocking(0)
def verify(t):
return int.from_bytes(sha(sha(bytes.fromhex(t)).digest()).digest(), 'little') <= ( int.from_bytes(bytes.fromhex(t[144:150]), 'little')*256**(int(t[150:152], 16)-3) )
for i in range(MAX_ID):
s.send(json.dumps({"id": ID, "method": 'blockchain.block.headers', "params": [(ID*MAX_BL) - OFFSET, MAX_BL]}).encode() + b'\n')
total_data = []
data = ''
begin = time.time()
while 1:
if total_data and time.time()-begin>1.5:
break
elif time.time()-begin>3:
break
try:
data = s.recv(16000)
if data:
total_data.append(data)
begin = time.time()
else:
time.sleep(0.1)
except:
pass
#try:
res_b = json.loads(b''.join(total_data).decode())
#except:
# continue
#if res is None:
# print("JSON-RPC: no response")
#sys.exit(1)
# break
#b = res.read()
#res_b = json.loads(b)
if res_b is None:
print('JSON-RPC: cannot JSON-decode body')
#sys.exit(2)
break
if 'error' in res_b and res_b['error'] != None:
print(res_b['error'])
#sys.exit(3)
break
if 'result' not in res_b:
print('JSON-RPC: no result in object')
#sys.exit(4)
break
ID = ID + 1
res = res_b['result']
count = res['count']
if count > 0:
t = res['hex']
h = int(len(t)/160)
OFFSET = OFFSET + (MAX_BL-h)
#print(str(len(t)))
#print(str(len(t)/160))
for j in range(h):
g = t[j*160:(j+1)*160]
if 1:
#print(g)
#print('\n')
#f.write('{0:0608b} {1:032b}\n'.format(int(g[0:152], 16), int(g[152:], 16)))
f.write(g)
f.write('\n')
else:
print('Q')
else:
if OFFSET > (10 * MAX_BL):
break
#print('pass')
if ID > 0:
f.write('.e')
else:
print("Nothing done!")
sys.exit(5)
print('bl generated :' + str(ID))
f.close()
sys.exit(0) | 98f2a9033d31e41dcec8ee74f87ea57dbb7f2ff6 | [
"Python"
] | 1 | Python | beshkoon/test | fcbb0af2ccee63744b74760a2c90be23bd2987c5 | 2370e21d30bf86d41d99c37c6096ab10bf827f40 |
refs/heads/master | <repo_name>MarkMondt/Discrete-Math-I-Extra-Credit<file_sep>/Mondt,MarkDiscreteExtraCredit.cpp
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
void RotateLeft(short int OldSquare[1024][1024], short int ArraySize)
{
int NewSquare[1024][1024];
for (int row = 0; row <= ArraySize - 1; row++)
for (int column = 0; column <= ArraySize - 1; column++)
NewSquare[row][column] = OldSquare[column][ArraySize - 1 - row];
for (int row = 0; row <= ArraySize - 1; row++)
for (int column = 0; column <= ArraySize - 1; column++)
{
OldSquare[row][column] = NewSquare[row][column];
if (OldSquare[row][column] == 1)
{
OldSquare[row][column] = 4;
continue;
}
if (OldSquare[row][column] == 2)
{
OldSquare[row][column] = 3;
continue;
}
if (OldSquare[row][column] == 3)
{
OldSquare[row][column] = 1;
continue;
}
if (OldSquare[row][column] == 4)
{
OldSquare[row][column] = 2;
continue;
}
}
}
void RotateRight(short int OldSquare[1024][1024], short int ArraySize)
{
int NewSquare[1024][1024];
for (int row = 0; row <= ArraySize - 1; row++)
for (int column = 0; column <= ArraySize - 1; column++)
NewSquare[row][column] = OldSquare[ArraySize - 1 - column][row];
for (int row = 0; row <= ArraySize - 1; row++)
for (int column = 0; column <= ArraySize - 1; column++)
{
OldSquare[row][column] = NewSquare[row][column];
if (OldSquare[row][column] == 1)
{
OldSquare[row][column] = 3;
continue;
}
if (OldSquare[row][column] == 2)
{
OldSquare[row][column] = 4;
continue;
}
if (OldSquare[row][column] == 3)
{
OldSquare[row][column] = 2;
continue;
}
if (OldSquare[row][column] == 4)
{
OldSquare[row][column] = 1;
continue;
}
}
}
void DisplayArray(short int Square[1024][1024], short int ArraySize)
{
for (int row = 0; row <= ArraySize - 1; row++)
{
for (int column = 0; column <= ArraySize - 1; column++)
cout << Square[row][column] << " ";
cout << endl;
}
cout << endl;
}
void GenerateTriomino(short int Smallest[2][2], short int EmptyX, short int EmptyY)
{
if (EmptyX == 0 && EmptyY == 0)
{
Smallest[0][0] = 0;
Smallest[0][1] = 3;
Smallest[1][0] = 3;
Smallest[1][1] = 3;
}
if(EmptyX == 0 && EmptyY == 1)
{
Smallest[0][0] = 2;
Smallest[0][1] = 0;
Smallest[1][0] = 2;
Smallest[1][1] = 2;
}
if (EmptyX == 1 && EmptyY == 0)
{
Smallest[0][0] = 1;
Smallest[0][1] = 1;
Smallest[1][0] = 0;
Smallest[1][1] = 1;
}
if (EmptyX == 1 && EmptyY == 1)
{
Smallest[0][0] = 4;
Smallest[0][1] = 4;
Smallest[1][0] = 4;
Smallest[1][1] = 0;
}
}
void ExpandPrimitave(short int Primitive[1024][1024], short int ArraySize)
{
short int Sub[512][512] = { 0 };
short int r = 0;
short int c = 0;
for (int row = 0; row <= (ArraySize/2)-1; row++)
for (int column = 0; column <= (ArraySize / 2) - 1; column++)
Sub[row][column] = Primitive[row][column];
r = 0;
for (int row = 0; row <= (ArraySize / 2) - 1; row++)
{
c = 0;
RotateRight(Primitive, ArraySize / 2);
for (int column = ArraySize/2; column <= ArraySize - 1; column++)
{
Sub[row][column] = Primitive[r][c];
c++;
}
RotateLeft(Primitive, ArraySize / 2);
r++;
}
r = 0;
for (int row = ArraySize / 2; row <= ArraySize - 1; row++)
{
c = 0;
for (int column = ArraySize / 2; column <= ArraySize - 1; column++)
{
Sub[row][column] = Primitive[r][c];
c++;
}
r++;
}
r = 0;
for (int row = ArraySize / 2; row <= ArraySize - 1; row++)
{
c = 0;
RotateLeft(Primitive, ArraySize / 2);
for (int column = 0; column <= (ArraySize / 2) - 1; column++)
{
Sub[row][column] = Primitive[r][c];
c++;
}
RotateRight(Primitive, ArraySize / 2);
r++;
}
Sub[ArraySize / 2 - 1][ArraySize / 2 - 1] = 4;
Sub[ArraySize / 2 - 1][ArraySize / 2] = 4;
Sub[ArraySize / 2][ArraySize / 2 - 1] = 4;
for (int row = 0; row <= ArraySize - 1; row++)
for (int column = 0; column <= ArraySize - 1; column++)
Primitive[row][column] = Sub[row][column];
}
int main()
{
short int Square[1024][1024] = { 0 };
short int SquarePrime[1024][1024] = { 0 };
short int Smallest[2][2];
short int Primitive[1024][1024] = { 0 };
short int EmptyPosition[2];
short int ArraySize;
short int Quadrant;
short int n;
short int r;
short int c;
int RandomSeed;
cout << "This program will make a checkerboard of size 2^n" << endl
<< "Enter a value between 1 and 10 for n: " << endl;
cin >> n;
cout << endl;
while (n < 1 || n > 10)
{
cout << "Invalid value for n (not between 1 and 10)" << endl
<< "Enter a value for n: " << endl;
cin >> n;
cout << endl;
}
ArraySize = pow(2, n);
RandomSeed = time(0);
srand(RandomSeed);
EmptyPosition[0] = rand() % ArraySize;
EmptyPosition[1] = rand() % ArraySize;
//cout << EmptyPosition[0] << endl;
//cout << EmptyPosition[1] << endl << endl;
GenerateTriomino(Smallest, EmptyPosition[0] % 2, EmptyPosition[1] % 2);
for (int row = 0; row <= 1; row++)
for (int column = 0; column <= 1; column++)
Square[row][column] = SquarePrime[row][column] = Smallest[row][column];
GenerateTriomino(Smallest, 1, 1);
for (int row = 0; row <= 1; row++)
for (int column = 0; column <= 1; column++)
Primitive[row][column] = Smallest[row][column];
//DisplayArray(SquarePrime, 2);
for (int Pow = 4; Pow <= ArraySize; Pow *= 2)
{
for (int row = 0; row <= Pow / 2 - 1; row++)
for (int column = 0; column <= Pow / 2 - 1; column++)
SquarePrime[row][column] = Square[row][column];
r = 0;
for (int row = EmptyPosition[0] % Pow - EmptyPosition[0] % (Pow / 2); row <= EmptyPosition[0] % Pow - EmptyPosition[0] % (Pow / 2) + (Pow / 2) - 1; row++)
{
c = 0;
for (int column = EmptyPosition[1] % Pow - EmptyPosition[1] % (Pow / 2); column <= EmptyPosition[1] % Pow - EmptyPosition[1] % (Pow / 2) + (Pow / 2) - 1; column++)
{
Square[row][column] = SquarePrime[r][c];
c++;
}
r++;
}
Quadrant = 0;
if ((EmptyPosition[0] % Pow) >= (Pow / 2) || (EmptyPosition[1] % Pow) >= (Pow / 2))
{
for (int row = 0; row <= Pow / 2 - 1; row++)
for (int column = 0; column <= Pow / 2 - 1; column++)
Square[row][column] = Primitive[row][column];
Quadrant += 1;
}
if ((EmptyPosition[0] % Pow) >= (Pow / 2) || (EmptyPosition[1] % Pow) < (Pow / 2))
{
RotateRight(Primitive, Pow / 2);
r = 0;
for (int row = 0; row <= Pow / 2 - 1; row++)
{
c = 0;
for (int column = Pow / 2; column <= Pow - 1; column++)
{
Square[row][column] = Primitive[r][c];
c++;
}
r++;
}
RotateLeft(Primitive, Pow / 2);
Quadrant += 2;
}
if ((EmptyPosition[0] % Pow) < (Pow / 2) || (EmptyPosition[1] % Pow) < (Pow / 2))
{
RotateRight(Primitive, Pow / 2);
RotateRight(Primitive, Pow / 2);
r = 0;
for (int row = Pow / 2; row <= Pow - 1; row++)
{
c = 0;
for (int column = Pow / 2; column <= Pow - 1; column++)
{
Square[row][column] = Primitive[r][c];
c++;
}
r++;
}
RotateLeft(Primitive, Pow / 2);
RotateLeft(Primitive, Pow / 2);
Quadrant += 3;
}
if ((EmptyPosition[0] % Pow) < (Pow / 2) || (EmptyPosition[1] % Pow) >= (Pow / 2))
{
RotateLeft(Primitive, Pow / 2);
r = 0;
for (int row = Pow / 2; row <= Pow - 1; row++)
{
c = 0;
for (int column = 0; column <= Pow / 2 - 1; column++)
{
Square[row][column] = Primitive[r][c];
c++;
}
r++;
}
RotateRight(Primitive, Pow / 2);
Quadrant += 4;
}
Quadrant = 10 - Quadrant;
if (Quadrant == 1)
{
Square[Pow / 2][Pow / 2] = 3;
Square[Pow / 2 - 1][Pow / 2] = 3;
Square[Pow / 2][Pow / 2 - 1] = 3;
}
else if (Quadrant == 2)
{
Square[Pow / 2][Pow / 2] = 2;
Square[Pow / 2 - 1][Pow / 2 - 1] = 2;
Square[Pow / 2][Pow / 2 - 1] = 2;
}
else if (Quadrant == 3)
{
Square[Pow / 2 - 1][Pow / 2] = 4;
Square[Pow / 2 - 1][Pow / 2 - 1] = 4;
Square[Pow / 2][Pow / 2 - 1] = 4;
}
else if (Quadrant == 4)
{
Square[Pow / 2 - 1][Pow / 2] = 1;
Square[Pow / 2 - 1][Pow / 2 - 1] = 1;
Square[Pow / 2][Pow / 2] = 1;
}
//DisplayArray(Square, Pow);
if (Pow == ArraySize)
break;
ExpandPrimitave(Primitive, Pow);
}
DisplayArray(Square, ArraySize);
system("pause");
return 0;
} | 5a189d6315ec5150062d5faec9c6565614e363ec | [
"C++"
] | 1 | C++ | MarkMondt/Discrete-Math-I-Extra-Credit | 4a994ad7593f5d2095d53d3d28d2df921535dfce | bb67f2a83bd51c301f821d1d7bddfb13e332f6d3 |
refs/heads/master | <repo_name>fattoc/jquerySlider<file_sep>/README.md
### jquery简单实现图片轮播
> 图片轮播效果在平时开发过程中使用的频率非常高,为了避免重复造轮子,也为了之后遇到可以节约时间,所以大致记录一下实现过程,方便复用。
图片轮播其实也有很多坑,因为有时候需要轮播的图片大小不一致,如果要照顾到美观、整齐等因素就可能导致某些图片被裁切或者挤压变形;如果重点是保障图片显示的完整性,并且尽量保证不变形不留白时,则可能导致图片显示区域来回变化挤占其它DOM位置的情况。关于这一部分有机会再研究,这里默认需要轮播的图片都是经过特殊处理,大小一致 风格统一的(手动滑稽)。
#### 轮播原理
图片轮播的原理就是把所有需要轮播的图片都横着排成一排(因为通常是横向轮播)就像一节节的火车一样,然后启动定时器,每秒向左移动一张图片宽度的距离,只有移动到显示区域的那一张图片会被看到,其它的图片隐藏。

比如上图逐次播放蓝、绿、黄三张图,接下来迅速将图片队列向右拉回到初始位置,之后再继续向左移动

#### HTML结构搭建
```html
<div id="slider-wrap">
<ul id="slider">
<li data-color="#1abc9c">
<div>
<h4>Slide #1</h4>
</div>
<i class="fa fa-image"></i>
</li>
<li data-color="#3498db">
<div>
<h4>Slide #2</h4>
</div>
<i class="fa fa-gears"></i>
</li>
<li data-color="#9b59b6">
<div>
<h4>Slide #3</h4>
</div>
<i class="fa fa-sliders"></i>
</li>
<li data-color="#34495e">
<div>
<h4>Slide #4</h4>
</div>
<i class="fa fa-code"></i>
</li>
<li data-color="#e74c3c">
<div>
<h4>Slide #5</h4>
</div>
<i class="fa fa-microphone-slash"></i>
</li>
</ul>
<!--controls-->
<div class="btns" id="next"><i class="fa fa-arrow-right"></i></div>
<div class="btns" id="pause"><i class="fa fa-pause" aria-hidden="true"></i></div>
<div class="btns" id="prev"><i class="fa fa-arrow-left"></i></div>
<div id="counter"></div>
<!--controls-->
</div>
```
#### 简单设置一下样式
```css
/*GLOBALS*/
*{margin:0; padding:0; list-style:none;}
a{text-decoration:none; color:#666;}
a:hover{color:#1bc1a3;}
body, hmtl{background: #ecf0f1; font-family: 'Anton', sans-serif;}
#wrapper{
width:600px;
margin:50px auto;
height:400px;
position:relative;
color:#fff;
text-shadow:rgba(0,0,0,0.1) 2px 2px 0px;
}
#slider-wrap{
width:600px;
height:400px;
position:relative;
overflow:hidden;
}
#slider-wrap ul#slider{
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
}
#slider-wrap ul#slider li{
float:left;
position:relative;
width:600px;
height:400px;
}
#slider-wrap ul#slider li > div{
position:absolute;
top:20px;
left:35px;
}
#slider-wrap ul#slider li > div h3{
font-size:36px;
text-transform:uppercase;
}
#slider-wrap ul#slider li > div span{
font-family: Neucha, Arial, sans serif;
font-size:21px;
}
#slider-wrap ul#slider li i{
text-align:center;
line-height:400px;
display:block;
width:100%;
font-size:90px;
}
/*btns*/
.btns{
position:absolute;
width:50px;
height:50px;
top:50%;
margin-top:-25px;
line-height:50px;
text-align:center;
cursor:pointer;
background:rgba(0,0,0,0.1);
z-index:100;
-webkit-user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-ms-user-select: none;
-webkit-transition: all 0.1s ease;
-moz-transition: all 0.1s ease;
-o-transition: all 0.1s ease;
-ms-transition: all 0.1s ease;
transition: all 0.1s ease;
}
.btns:hover{
background:rgba(0,0,0,0.3);
}
#next{right:-50px; border-radius:7px 0px 0px 7px;}
#prev{left:-50px; border-radius:0px 7px 7px 7px;}
#pause {
border-radius: 100%;
left: 50%;
top: 50%;
background: #000;
opacity: 0.8;
display:none;
}
#counter{
top: 30px;
right:35px;
width:auto;
position:absolute;
}
#slider-wrap.active #next{right:0px;}
#slider-wrap.active #prev{left:0px;}
/*Header*/
h1, h2{text-shadow:none; text-align:center;}
h1{ color: #666; text-transform:uppercase; font-size:36px;}
h2{ color: #7f8c8d; font-family: Neucha, Arial, sans serif; font-size:18px; margin-bottom:30px;}
/*ANIMATION*/
#slider-wrap ul{
-webkit-transition: all 0.3s cubic-bezier(1,.01,.32,1);
-moz-transition: all 0.3s cubic-bezier(1,.01,.32,1);
-o-transition: all 0.3s cubic-bezier(1,.01,.32,1);
-ms-transition: all 0.3s cubic-bezier(1,.01,.32,1);
transition: all 0.3s cubic-bezier(1,.01,.32,1);
}
```
#### 轮播实现
```javascript
var pos = 0;//当前位置
var totalSlides;//轮播总数
var sliderWidth;//单张图宽度
$(document).ready(function(){
//轮播图片总数
totalSlides = $('#slider li').length;
//外层div宽度
sliderWidth = $('#slider-wrap').width();
/*****************
创建轮播序列
*****************/
//把所有图片横排拼起来,取总宽度
$('#slider').width(sliderWidth*totalSlides);
//下一张
$('#next').click(function(){
slideRight();
});
//上一张
$('#prev').click(function(){
slideLeft();
});
//暂停 / 播放
var state=0;
$("#pause").click(function() {
if(state==0){
//停止播放,并将按钮改为播放按钮
clearInterval(autoSlider);
$(this).find('i').removeClass('fa-pause').addClass('fa-play');
state=1;
}else {
////重新播放,并将按钮改为暂停按钮
$(this).find('i').removeClass('fa-play').addClass('fa-pause');
autoSlider = setInterval(slideRight, 5000);
state=0;
}
});
/*************************
//*> 操作设置
************************/
//5秒自动播放
var autoSlider = setInterval(slideRight, 5000);
//遍历每一张图片
$.each($('#slider-wrap ul li'), function() {
//设置背景色
var bgc = $(this).attr("data-color");
$(this).css("background",bgc);
});
//统计当前是第几张
countSlides();
//鼠标滑过时暂停播放,鼠标移开,重新播放
$('#slider-wrap').hover(
function(){
$(this).addClass('active');
$("#pause").show();
},
function(){
$(this).removeClass('active');
$("#pause").hide();
}
);
});
/***********
左滑
************/
function slideLeft(){
pos--;
if(pos==-1){ pos = totalSlides-1; }
$('#slider').css('left', -(sliderWidth*pos));
//*>
countSlides();
}
/************
右滑
*************/
function slideRight(){
pos++;
if(pos==totalSlides){ pos = 0; }
$('#slider').css('left', -(sliderWidth*pos));
//*>
countSlides();
}
/************************
//*> 轮播计数
************************/
function countSlides(){
$('#counter').html(pos+1 + ' / ' + totalSlides);
}
```
#### 最终效果

源码地址【[github](https://github.com/fattoc/jquerySlider)】
<file_sep>/js/slide.js
var pos = 0;//当前位置
var totalSlides;//轮播总数
var sliderWidth;//单张图宽度
$(document).ready(function(){
//轮播图片总数
totalSlides = $('#slider li').length;
//外层div宽度
sliderWidth = $('#slider-wrap').width();
/*****************
创建轮播序列
*****************/
//把所有图片横排拼起来,取总宽度
$('#slider').width(sliderWidth*totalSlides);
//下一张
$('#next').click(function(){
slideRight();
});
//上一张
$('#prev').click(function(){
slideLeft();
});
//暂停 / 播放
var state=0;
$("#pause").click(function() {
if(state==0){
//停止播放,并将按钮改为播放按钮
clearInterval(autoSlider);
$(this).find('i').removeClass('fa-pause').addClass('fa-play');
state=1;
}else {
////重新播放,并将按钮改为暂停按钮
$(this).find('i').removeClass('fa-play').addClass('fa-pause');
autoSlider = setInterval(slideRight, 2000);
state=0;
}
});
/*************************
//*> 操作设置
************************/
//5秒自动播放
var autoSlider = setInterval(slideRight, 2000);
//遍历每一张图片
$.each($('#slider-wrap ul li'), function() {
//设置背景色
var bgc = $(this).attr("data-color");
$(this).css("background",bgc);
});
//统计当前是第几张
countSlides();
//鼠标滑过时暂停播放,鼠标移开,重新播放
$('#slider-wrap').hover(
function(){
$(this).addClass('active');
$("#pause").show();
},
function(){
$(this).removeClass('active');
$("#pause").hide();
}
);
});
/***********
左滑
************/
function slideLeft(){
pos--;
if(pos==-1){ pos = totalSlides-1; }
$('#slider').css('left', -(sliderWidth*pos));
//*>
countSlides();
}
/************
右滑
*************/
function slideRight(){
pos++;
if(pos==totalSlides){ pos = 0; }
$('#slider').css('left', -(sliderWidth*pos));
//*>
countSlides();
}
/************************
//*> 轮播计数
************************/
function countSlides(){
$('#counter').html(pos+1 + ' / ' + totalSlides);
}
| 1b887d66f5a5fb00186893eaeb7f841b6d4dbca5 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | fattoc/jquerySlider | e28fb56538d4b83d36e7cce90aa2255422efb75a | 4ed0e2c028c40288fe0db4afab29c869bc4154ff |
refs/heads/master | <repo_name>fitraditya/Obrel<file_sep>/app/models/channel.js
var Mongoose = require('../../database').Mongoose
var ObjectId = Mongoose.Schema.Types.ObjectId;
var channelSchema = new Mongoose.Schema({
name: { type : String, required: true },
hash: { type : String, required: true },
type: { type : String, required: true },
description: { type : String },
createdBy: { type : ObjectId, required: true },
createdDate: { type : Date, default: Date.now }
});
exports.Channel = Mongoose.model('Channel', channelSchema);
<file_sep>/doc/stories/user.md
# User Stories
## Authentication
- [x] As USER, I should be able to sign up into Obrel
- [x] As USER, I should be able to sign in into Obrel
- [x] As USER, I should be able to sign out from Obrel
- [ ] As USER, I should be able to change my password
- [ ] As USER, I should be able to reset my password
## Channel
- [x] As USER, I should be able to create a new channel
- [x] As USER, I should be able to load my subscribed channels
- [ ] As USER, I should be able to edit a channel created by me
- [x] As USER, I should be able to join a public channel using given hash
- [x] As USER, I should be able to invite someone to a public channel
- [x] As USER, I should be able to invite someone to a private channel created by me
- [x] As USER, I should be able to invited to a channel
- [x] As USER, I should be able to leave a channel
- [x] As USER, I should not be able to leave a channel created by me
## Message
- [ ] As USER, I should be able to load previous message in selected channel
- [ ] As USER, I should be able to send text message
- [ ] As USER, I should be able to send media message
- [ ] As USER, I should be able to send attachment message
- [ ] As USER, I should be able to view sent messages from other users in channel
- [ ] As USER, I should be able to get respective timestamp on each message
- [ ] As USER, I should be able to view all sent media messages
- [ ] As USER, I should be able to view all sent attachment messages
- [ ] As USER, I should be able to view all my sent media messages
- [ ] As USER, I should be able to view all my sent attachment messages
<file_sep>/index.js
var Hapi = require('hapi')
var SocketIO = require('socket.io')
var server = new Hapi.Server()
server.connection({ port: 9876, labels: ['api'] })
var io = SocketIO.listen(server.listener)
require('./app/controllers/socket.js')(io)
server.start(function () {
console.log('Server running at:', server.info.uri)
})
<file_sep>/README.md
# Obrel
Open source messaging system
## Features
* BYOS (bring your own server)
* Persistent messages
* Multiple channels
* Public and private channels
* Websocket API
* MIT licensed
## Installation
```
$ git clone https://github.com/fitraditya/Obrel.git
$ cd Obrel
$ npm install
$ npm install obrel-web
$ npm start
```
## License
Released under [MIT license]
[MIT license]: https://github.com/fitraditya/Obrel/blob/master/LICENSE
<file_sep>/app/models/user.js
var Bcrypt = require('bcryptjs')
var Mongoose = require('../../database').Mongoose
var ObjectId = Mongoose.Schema.Types.ObjectId;
var userSchema = new Mongoose.Schema({
username: {
type : String,
required: true,
unique: true,
trim: true,
lowercase: true,
match: /^[\w][\w\-\.]*[\w]$/i
},
password: {
type : String,
required: true,
trim: true
},
email: {
type : String,
required: true,
unique: true,
trim: true
},
token: {
type : String,
required: false,
trim: true
},
registeredDate: {
type : Date,
default: Date.now
},
channels: [{
type: ObjectId,
ref: 'Channel'
}]
})
userSchema.pre('save', function (next) {
var user = this
if (this.isModified('password') || this.isNew) {
Bcrypt.genSalt(10, function (error, salt) {
if (error) {
return next(error)
}
Bcrypt.hash(user.password, salt, function (error, hash) {
if (error) {
return next(error)
}
user.password = hash
next()
})
})
}
else {
return next()
}
})
userSchema.methods.comparePassword = function (pwd, callback) {
Bcrypt.compare(pwd, this.password, function (error, isMatch) {
if (error) {
return callback(error)
}
callback(null, isMatch)
})
}
exports.User = Mongoose.model('User', userSchema)
<file_sep>/app/models/session.js
var Mongoose = require('../../database').Mongoose
var ObjectId = Mongoose.Schema.Types.ObjectId;
var sessionSchema = new Mongoose.Schema({
session: {
type : String,
required: true
},
user: {
type : ObjectId,
ref: 'User'
},
addedDate: {
type : Date,
default: Date.now
}
})
exports.Session = Mongoose.model('Session', sessionSchema)
| bf25bd65b6e0ab9adbd57a046ce1d597436131d8 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | fitraditya/Obrel | bdb89ac2f0ac2bd4c4c843ea5efcd1d3edbe1af1 | 8724da3cbd67c194d69f389a83011ff69911d01b |
refs/heads/master | <repo_name>gameschoolofficial/Data-Structures---Gun-UI<file_sep>/Assets/Scripts/Lists/GunBag.cs
using UnityEngine;
using System.Collections;
//Add the correct Collections library
using System.Collections.Generic;
using UnityEngine.UI;
public class GunBag : MonoBehaviour {
public Image handgun;
public Image SMG;
public Image AK47;
public Image RPG;
public int currentImage;
// create 2 text objects to show the number of guns
public Text numGuns;
public Text nameGun;
//Create a new list of images
// Use this for initialization
void Start () {
//create a new List of Images
}
// Update is called once per frame
void Update () {
}
//Add a function for each button of buying a gun
//Remove the first gun you purchased
}
<file_sep>/Assets/Scripts/Dictionary/GunPurchase.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class GunPurchase : MonoBehaviour {
public Image handgun;
public Button buyHandgun;
public Image SMG;
public Button buySMG;
public Image AK47;
public Button buyAK47;
public Image RPG;
public Button buyRPG;
public Dictionary<Button, Image> imageTie = new Dictionary<Button, Image>();
// Use this for initialization
void Start () {
imageTie[buyHandgun] = handgun;
}
// Update is called once per frame
void Update () {
}
public void turnImageGreen(Button b)
{
imageTie[b].color = Color.green;
}
}
<file_sep>/Assets/Scripts/Arrays/GunHighlighter.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GunHighlighter : MonoBehaviour {
public Image handgun;
public Image SMG;
public Image AK47;
public Image RPG;
public int currentImage;
public Image[] gunArray;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void nextImage()
{
//turn off color for last image
gunArray[currentImage].color = Color.white;
//increase currentImage number unless it's at the end
currentImage++;
if(currentImage >= gunArray.Length)
{
currentImage = 0;
}
//turn new image to red
gunArray[currentImage].color = Color.red;
}
}
| 6986d4cca8dfb0232753bb2fb9712a598689d0f7 | [
"C#"
] | 3 | C# | gameschoolofficial/Data-Structures---Gun-UI | 0b828f6334e856fac9eabb15f74ab154ad637619 | 6da96451635e9d49e0a8e9f7c1acaa003d25f5fb |
refs/heads/master | <repo_name>pgroot/laravel-aliyun-dysms<file_sep>/src/Mindertech/Dysms/QuerySendDetailsRequest.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:35
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest as AliyunQuerySendDetailsRequest;
use Mindertech\Dysms\Traits\RuntimeConfig;
/**
* Class QuerySendDetailsRequest
* @package Mindertech\Dysms
*/
class QuerySendDetailsRequest {
use RuntimeConfig;
/**
* @var
*/
public $app;
/**
* QuerySendDetailsRequest constructor.
* @param $app
*/
public function __construct($app)
{
$this->app = $app;
}
/**
* @param $phoneNumber
* @param $sendDate
* @param int $page
* @param int $pageSize
* @param null $bizId
* @param null $protocol
* @return array
*/
public function search($phoneNumber, $sendDate, $page = 1, $pageSize = 10, $bizId = null, $protocol = null)
{
$client = new AcsClient($this->getRuntimeConfig());
$config = $client->getConfig();
$request = new AliyunQuerySendDetailsRequest();
$request->setPhoneNumber($phoneNumber);
$request->setSendDate($sendDate);
$request->setPageSize($pageSize);
$request->setCurrentPage($page);
if(!is_null($bizId)) {
$request->setBizId($bizId);
}
if(!is_null($protocol)) {
$request->setProtocol($protocol);
}
$acsResponse = $client->getAcsClient()->getAcsResponse($request);
if(config('dysms.log')) {
\Log::info(print_r($acsResponse, true));
}
$status = isset($acsResponse->Code) ? $acsResponse->Code : 'ERROR';
$default = [
'page' => $page,
'pageSize' => $pageSize,
'sendDate' => $sendDate,
'result' => []
];
if(strtolower($status) !== 'ok') {
return $default;
}
return array_merge($default, [
'total' => $acsResponse->TotalCount,
'result' => $acsResponse->SmsSendDetailDTOs->SmsSendDetailDTO
]);
}
}<file_sep>/src/Mindertech/Dysms/SmsQueueRequest.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:35
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms;
use AliyunMNS\Lib\TokenGetterForAlicom;
use AliyunMNS\Lib\TokenForAlicom;
use Aliyun\Core\Config;
use AliyunMNS\Exception\MnsException;
use AliyunMNS\Requests\BatchReceiveMessageRequest;
use Mindertech\Dysms\Traits\RuntimeConfig;
/**
* Class SmsQueueRequest
* @package Mindertech\Dysms
*/
class SmsQueueRequest
{
/**
*
*/
use RuntimeConfig;
/**
* @var null
*/
private $tokenGetter = null;
/**
* @var array
*/
private $config = [];
/**
* @var
*/
public $app;
/**
* SmsQueueRequest constructor.
* @param $app
*/
public function __construct($app)
{
$this->app = $app;
$this->mergeConfig();
}
/**
*
*/
private function mergeConfig()
{
$this->config = array_merge(config('dysms'), $this->getRuntimeConfig());
}
/**
* @return TokenGetterForAlicom|null
*/
private function getTokenGetter()
{
$this->tokenGetter = new TokenGetterForAlicom($this->config);
return $this->tokenGetter;
}
/**
* @param callable $callback
* @param mixed $batch
*/
public function up(callable $callback, $batch = false)
{
$this->mergeConfig();
$this->receiveMessage('SmsUp', $this->config['sms-up-queue'], $callback, $batch);
}
/**
* @param callable $callback
* @param mixed $batch
*/
public function report(callable $callback, $batch = false)
{
$this->mergeConfig();
$this->receiveMessage('SmsReport', $this->config['sms-report-queue'], $callback, $batch);
}
/**
* @param $messageType
* @param $queueName
* @param callable $callback
* @param mixed $batch
* @throws
*/
private function receiveMessage($messageType, $queueName, callable $callback, $batch = false)
{
$i = 0;
// 取回执消息失败3次则停止循环拉取
while ($i < 3) {
try {
// 取临时token
$tokenForAlicom = $this->getTokenGetter()->getTokenByMessageType($messageType, $queueName);
// 使用MNSClient得到Queue
$queue = $tokenForAlicom->getClient()->getQueueRef($queueName);
$messages = [];
if($batch && is_integer($batch)) {
$res = $queue->batchReceiveMessage(new BatchReceiveMessageRequest($batch, config('dysms.mns.wait_seconds', 3)));
/* @var \AliyunMNS\Model\Message[] $messages */
$messages = $res->getMessages();
} else {
$message = $queue->receiveMessage(config('dysms.mns.wait_seconds', 3));
$messages = [$message];
}
foreach($messages as $message) {
// 计算消息体的摘要用作校验
$bodyMD5 = strtoupper(md5(base64_encode($message->getMessageBody())));
// 比对摘要,防止消息被截断或发生错误
if ($bodyMD5 == $message->getMessageBodyMD5())
{
// 执行回调
if(call_user_func($callback, json_decode($message->getMessageBody())))
{
// 当回调返回真值时,删除已接收的信息
$receiptHandle = $message->getReceiptHandle();
$queue->deleteMessage($receiptHandle);
}
}
}
return; // 整个取回执消息流程完成后退出
} catch (MnsException $e) {
$i++;
if ($this->config['log']) {
\Log::info("ex:{$e->getMnsErrorCode()}");
\Log::info("ReceiveMessage Failed: {$e}");
}
}
}
}
}<file_sep>/src/Mindertech/Dysms/MindertechDysmsServiceProvider.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:25
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms;
use Illuminate\Support\ServiceProvider;
use Mindertech\Dysms\SendSmsRequest;
use Mindertech\Dysms\QuerySendDetailsRequest;
use Mindertech\Dysms\SmsQueueRequest;
use Mindertech\Dysms\SendBatchSmsRequest;
class MindertechDysmsServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot() {
$this->publishes([
__DIR__.'/../../config/dysms.php' => config_path('dysms.php')
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../../config/dysms.php', 'dysms'
);
$this->registerDysms();
}
private function registerDysms() {
//https://help.aliyun.com/document_detail/55451.html
$this->app->bind('send-sms', function ($app) {
return new SendSmsRequest($app);
});
$this->app->alias('send-sms', 'Mindertech\Dysms\SendSmsRequest');
//https://help.aliyun.com/document_detail/55452.html
$this->app->bind('query-sms', function($app) {
return new QuerySendDetailsRequest($app);
});
$this->app->alias('query-sms', 'Mindertech\Dysms\QuerySendDetailsRequest');
//https://help.aliyun.com/document_detail/66262.html
$this->app->bind('send-sms-batch', function($app) {
return new SendBatchSmsRequest($app);
});
$this->app->alias('send-sms-batch', 'Mindertech\Dysms\SendBatchSmsRequest');
//https://help.aliyun.com/document_detail/55500.html
$this->app->bind('sms-queue', function($app) {
return new SmsQueueRequest($app);
});
$this->app->alias('sms-queue', 'Mindertech\Dysms\SmsQueueRequest');
}
}<file_sep>/src/Mindertech/Dysms/Traits/RuntimeConfig.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-17 10:04
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms\Traits;
/**
* Trait SetConfig
* @package Mindertech\Dysms\Traits
*/
trait RuntimeConfig
{
/**
* @var
*/
private $runtimeConfig = [];
/**
* @param array $config
* @return $this
*/
public function setRuntimeConfig(array $config = [])
{
$this->runtimeConfig = $config;
return $this;
}
/**
* @return mixed
*/
public function getRuntimeConfig()
{
return $this->runtimeConfig;
}
}<file_sep>/src/Mindertech/Dysms/AcsClient.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:55
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
/**
* Class AcsClient
* @package Mindertech\Dysms
*/
class AcsClient
{
/**
* @var array
*/
private $config = [];
/**
* AcsClient constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$defaultConfig = config('dysms');
$this->config = array_merge($defaultConfig, $config);
}
/**
* @return DefaultAcsClient
*/
public function getAcsClient()
{
Config::load();
$profile = DefaultProfile::getProfile(
$this->config['region'],
$this->config['access_key_id'],
$this->config['access_key_secret']
);
DefaultProfile::addEndpoint(
$this->config['end_point_name'],
$this->config['region'],
$this->config['product'],
$this->config['domain']
);
return new DefaultAcsClient($profile);
}
/**
* @return array
*/
public function getConfig()
{
return $this->config;
}
}<file_sep>/src/Mindertech/Dysms/SendSmsRequest.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:34
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest as AliSendSmsRequest;
use Mindertech\Dysms\AcsClient;
use Mindertech\Dysms\Traits\RuntimeConfig;
/**
* Class SendSmsRequest
* @package Mindertech\Dysms
*/
class SendSmsRequest {
use RuntimeConfig;
/**
* @var
*/
public $app;
/**
* SendSmsRequest constructor.
* @param $app
*/
public function __construct($app)
{
$this->app = $app;
}
/**
* @param $templateId
* @param $sendTo
* @param array $params
* @param null $outId
* @param null $extendCode
* @param null $protocol
* @return bool|\SimpleXMLElement|string
* @throws \Exception
*/
public function to($templateId, $sendTo, array $params = [], $outId = null, $extendCode = null, $protocol = null) {
$client = new AcsClient($this->getRuntimeConfig());
$request = new AliSendSmsRequest();
$config = $client->getConfig();
if(!is_null($protocol) && in_array($protocol, ['http', 'https'])) {
$request->setProtocol($protocol);
}
$request->setPhoneNumbers($sendTo);
$request->setSignName($config['sign']);
$request->setTemplateCode($templateId);
$request->setTemplateParam(json_encode($params, JSON_UNESCAPED_UNICODE));
if(!is_null($outId)) {
$request->setOutId($outId);
}
if(!is_null($extendCode)) {
$request->setSmsUpExtendCode($extendCode);
}
$acsResponse = $client->getAcsClient()->getAcsResponse($request);
/**
* {"Message": "OK", "RequestId":"AC7CC92E-B0A0-4AB1-83DC-A42FBF757607", "BizId":"999612626451607776^0","Code": "OK"}
*/
if(config('dysms.log')) {
\Log::info(print_r($acsResponse, true));
}
$status = isset($acsResponse->Code) ? $acsResponse->Code : 'ERROR';
$bizId = isset($acsResponse->BizId) ? $acsResponse->BizId : '';
if(strtolower($status) !== 'ok') {
throw new \Exception($acsResponse->Code);
}
return $bizId;
}
}<file_sep>/src/Mindertech/Dysms/SendBatchSmsRequest.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:35
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms;
use Aliyun\Api\Sms\Request\V20170525\SendBatchSmsRequest as AliyunSendBatchSmsRequest;
use Mindertech\Dysms\Traits\RuntimeConfig;
/**
* Class SendBatchSmsRequest
* @package Mindertech\Dysms
*/
class SendBatchSmsRequest {
use RuntimeConfig;
/**
* @var
*/
public $app;
/**
* SendBatchSmsRequest constructor.
* @param $app
*/
public function __construct($app)
{
$this->app = $app;
}
/**
* @param $templateId
* @param array $phoneNumbers
* @param array $sign
* @param array $params
* @param array|null $extendCodes
* @param null $protocol
* @return \SimpleXMLElement|string
* @throws \Exception
*/
public function to($templateId, array $phoneNumbers, array $sign, array $params = [], array $extendCodes = null, $protocol = null)
{
$client = new AcsClient($this->getRuntimeConfig());
$request = new AliyunSendBatchSmsRequest();
$request->setPhoneNumberJson(json_encode($phoneNumbers, JSON_UNESCAPED_UNICODE));
$request->setSignNameJson(json_encode($sign, JSON_UNESCAPED_UNICODE));
$request->setTemplateCode($templateId);
$request->setTemplateParamJson(json_encode($params, JSON_UNESCAPED_UNICODE));
if(!is_null($protocol)) {
$request->setProtocol($protocol);
}
if(!is_null($extendCodes)) {
$request->setSmsUpExtendCodeJson(json_encode($extendCodes, JSON_UNESCAPED_UNICODE));
}
$acsResponse = $client->getAcsClient()->getAcsResponse($request);
if(config('dysms.log')) {
\Log::info(print_r($acsResponse, true));
}
$status = isset($acsResponse->Code) ? $acsResponse->Code : 'ERROR';
$bizId = isset($acsResponse->BizId) ? $acsResponse->BizId : '';
if(strtolower($status) !== 'ok') {
throw new \Exception($acsResponse->Code);
}
return $bizId;
}
}<file_sep>/src/config/dysms.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:24
* @author: GROOT (<EMAIL>)
*/
return [
'access_key_id' => '',
'access_key_secret' => '',
'sign' => '',
'log' => false,
'sms-report-queue' => '',
'sms-up-queue' => '',
//以下配置暂时无需替换
'product' => 'Dysmsapi',
'domain' => 'dysmsapi.aliyuncs.com',
'region' => 'cn-hangzhou',
'end_point_name' => 'cn-hangzhou',
'mns' => [
'account_id' => '1943695596114318',
'product' => 'Dybaseapi',
'domain' => 'dybaseapi.aliyuncs.com',
'wait_seconds' => 3
],
];<file_sep>/readme.md
## Installation
1. add the following to your composer.json. Then run `composer update`:
```json
"pgroot/laravel-aliyun-dysms": "dev-master"
```
or
```bash
composer require pgroot/laravel-aliyun-dysms
```
2. Run the command below to publish the package config file `config/dysms.php`:
```shell
php artisan vendor:publish --provider=Mindertech\Dysms\MindertechDysmsServiceProvider
```
## Configuration
Set the property values in the `config/dysms.php`.
default
```php
return [
'access_key_id' => '',
'access_key_secret' => '',
'sign' => '',
'log' => false,
'sms-report-queue' => '',
'sms-up-queue' => '',
//以下配置暂时无需替换
'product' => 'Dysmsapi',
'domain' => 'dysmsapi.aliyuncs.com',
'region' => 'cn-hangzhou',
'end_point_name' => 'cn-hangzhou',
'mns' => [
'account_id' => '1943695596114318',
'product' => 'Dybaseapi',
'domain' => 'dybaseapi.aliyuncs.com',
'wait_seconds' => 3
],
];
```
## Usage
1. send sms
```php
try {
$bizId = SendSms::to('SMS_123456', '18688886666', [
'code' => mt_rand(1000, 9999)
]);
} catch(\Exception $e) {
echo $e->getMessage();
}
```
2. query sms
```php
$page = 1;
$pageSize = 1;
$bizId = null;
$result = QuerySms::search('18688886666', '20180516', $page, $pageSize, $bizId);
```
response
```json
{
"page": 1,
"pageSize": 1,
"sendDate": "20180516",
"result": [{
"SendDate": "2018-05-16 16:04:53",
"SendStatus": 3,
"ReceiveDate": "2018-05-16 16:04:57",
"ErrCode": "0",
"TemplateCode": "SMS_123456",
"Content": "",
"PhoneNum": "18688886666"
}],
"total": 7
}
```
3. send batch sms
```php
try {
$bizId = SendSmsBatch::to(
'SMS_123456',
[
'18688886666',
'18666666666'
],
[
'sign-1', 'sign-2'
],
[
[
'code' => mt_rand(1000, 9999)
],
[
'code' => mt_rand(1000, 9999)
]
]
);
} catch (\Exception $e) {
echo $e->getMessage();
}
```
4. MNS
see: https://help.aliyun.com/document_detail/55500.html
```php
/**
* 回调
* @param stdClass $message 消息数据
* @return bool 返回true,则工具类自动删除已拉取的消息。返回false,消息不删除可以下次获取
*/
SmsQueue::up(function($message) {
/*
{
"dest_code": "2199787"
"send_time": "2018-05-16 18:05:13"
"sign_name": "signname"
"sp_id": null
"sequence_id": 531571249
"phone_number": "18688886666"
"content": "回复测试"
}
*/
print_r($message);
return true;
});
```
```php
/**
* 回调
* @param stdClass $message 消息数据
* @return bool 返回true,则工具类自动删除已拉取的消息。返回false,消息不删除可以下次获取
*/
SmsQueue::report(function($message) {
/*
{
"send_time": "2018-05-16 14:18:57"
"report_time": "2018-05-16 14:19:02"
"success": true
"err_msg": "用户接收成功"
"err_code": "DELIVERED"
"phone_number": "18688886666"
"sms_size": "1"
"biz_id": "48490846451537371^0"
"out_id": null
}
*/
print_r($message);
return true;
});
```
5. set config at runtime
```php
try {
$bizId = SendSms::setRuntimeConfig([
'access_key_id' => 'id',
'access_key_secret' => 'key'
])->to('SMS_123456', '18688886666', [
'code' => mt_rand(1000, 9999)
]);
} catch(\Exception $e) {
echo $e->getMessage();
}
```
## Todo
<file_sep>/src/Mindertech/Dysms/Facades/SmsQueueFacade.php
<?php
/**
* laravel-aliyun-dysms
* Date: 2018-05-16 10:51
* @author: GROOT (<EMAIL>)
*/
namespace Mindertech\Dysms\Facades;
use Illuminate\Support\Facades\Facade;
class SmsQueueFacade extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'sms-queue';
}
} | 2394e891fcdfb2e0137223fec93c7eeb18b1c899 | [
"Markdown",
"PHP"
] | 10 | PHP | pgroot/laravel-aliyun-dysms | e3566684bd186f53c866bafd4d99c97e508ecfa8 | e0f052a8eba7061223f99f46e474622f64e46855 |
refs/heads/master | <file_sep><?php
namespace Bebella\Events\Mobile;
use Bebella\Recipe;
use Bebella\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class RecipeWasViewed extends Event
{
use SerializesModels;
public $recipe;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Recipe $recipe)
{
$this->recipe = $recipe;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
<file_sep>var Bebella = angular.module('Bebella', ['ui.router', 'datatables', 'angular-flot', 'ngStorage']);
var APP_URL = $("#APP_URL").val();
var API_TOKEN = $("#API_TOKEN").val();
function view(path) {
return APP_URL + '/channel/' + path;
}
function api_v1(path, token) {
return APP_URL + '/api/v1/' + path + '?api_token=' + API_TOKEN;
}
function attr(dest, src) {
for (var e in src) {
if (e == "created_at" || e == "updated_at") {
dest[e] = new Date(src[e]);
} else if (e.startsWith("has_") || e.startsWith("is_") || e.startsWith("used_for_") || e == "active") {
dest[e] = (src[e] == 1);
} else {
dest[e] = src[e];
}
}
}
Bebella.run([
function () {
}
]);
Bebella.factory('Product', [
function () {
var Product = new Function();
return Product;
}
]);
Bebella.factory('Recipe', [
function () {
var Recipe = function () {
this.tags = new Array();
this.steps = new Array();
this.products = new Array();
this.comments = new Array();
this.related = new Array();
};
return Recipe;
}
]);
Bebella.service('CurrentRecipe', ['$q', '$localStorage', 'Recipe',
function ($q, $localStorage, Recipe) {
var service = this;
service.get = function () {
if (! $localStorage.current_recipe) {
$localStorage.current_recipe = new Recipe();
}
return $localStorage.current_recipe;
};
service.clear = function () {
$localStorage.current_recipe = new Recipe();
};
}
]);
Bebella.service('ProductRepository', ['$http', '$q', 'Product',
function ($http, $q, Product) {
var repository = this;
repository.find = function (id) {
var deferred = $q.defer();
$http.get(api_v1('product/find/' + id)).then(
function (res) {
var product = new Product();
attr(product, res.data);
deferred.resolve(product);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.groupByCategory = function () {
var deferred = $q.defer();
$http.get(api_v1("product/groupByCategory")).then(
function (res) {
var categories = _.map(res.data, function (json) {
var products = _.map(json, function (e) {
var product = new Product();
attr(product, e);
return product;
});
return products;
});
deferred.resolve(categories);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.all = function () {
var deferred = $q.defer();
$http.get(api_v1("product/all")).then(
function (res) {
var products = _.map(res.data, function (json) {
var product = new Product();
attr(product, json);
return product;
});
deferred.resolve(products);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.edit = function (product) {
var deferred = $q.defer();
var data = JSON.stringify(product);
$http.post(api_v1("product/edit"), data).then(
function (res) {
deferred.resolve(product);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.save = function (product) {
var deferred = $q.defer();
var data = JSON.stringify(product);
$http.post(api_v1("product/save"), data).then(
function (res) {
product.id = res.data.id;
deferred.resolve(product);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
}
]);
Bebella.service('RecipeRepository', ['$http', '$q', 'Recipe',
function ($http, $q, Recipe) {
var repository = this;
repository.find = function (id) {
var deferred = $q.defer();
$http.get(api_v1('recipe/find/' + id)).then(
function (res) {
var recipe = new Recipe();
attr(recipe, res.data);
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.all = function () {
var deferred = $q.defer();
$http.get(api_v1("recipe/all")).then(
function (res) {
var recipes = _.map(res.data, function (json) {
var recipe = new Recipe();
attr(recipe, json);
return recipe;
});
deferred.resolve(recipes);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.edit = function (recipe) {
var deferred = $q.defer();
var data = JSON.stringify(recipe);
$http.post(api_v1("recipe/edit"), data).then(
function (res) {
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.save = function (recipe) {
var deferred = $q.defer();
var data = JSON.stringify(recipe);
$http.post(api_v1("recipe/save"), data).then(
function (res) {
recipe.id = res.data.id;
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.sendForApproval = function (recipe) {
var deferred = $q.defer();
var data = JSON.stringify(recipe);
$http.post(api_v1("recipe/sendForApproval"), data).then(
function (res) {
recipe.id = res.data.id;
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
}
]);
Bebella.controller('ProfileIndexCtrl', ['$scope',
function ($scope) {
}
]);
Bebella.controller('StatsIndexCtrl', ['$scope',
function ($scope) {
}
]);
Bebella.controller('HomeIndexCtrl', ['$scope',
function ($scope) {
}
]);
Bebella.controller('RecipeListCtrl', ['$scope',
function ($scope) {
}
]);
Bebella.controller('RecipeNewCtrl', ['$scope', 'Recipe', 'ProductRepository', 'RecipeRepository', 'CurrentRecipe',
function ($scope, Recipe, ProductRepository, RecipeRepository, CurrentRecipe) {
$scope.recipe = CurrentRecipe.get();
function formatedUrl() {
if ( ! $scope.videoUrl) return undefined;
var regex = new RegExp("[?&]v(=([^&#]*)|&|#|$)"),
results = regex.exec($scope.videoUrl);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
function getTags() {
return $scope.tags.trim().split(",");
};
$scope.addProduct = function() {
if ( ! $scope.selectedProduct) {
alert("Selecione um produto.");
}
if ($scope.selectedProduct != '-1') {
ProductRepository.find($scope.selectedProduct).then(
function onSuccess (product) {
$scope.recipe.products.push(product);
},
function onError (res) {
alert("Houve um erro na obtenção do produto selecionado");
}
);
} else {
$scope.recipe.products.push({
name: $scope.newProductName,
short_desc: $scope.newProductDesc
});
$scope.newProductName = '';
$scope.selectedProduct = '';
$scope.newProductDesc = '';
}
};
$scope.insertImageStep = function () {
var step = {
type: "image"
};
$scope.recipe.steps.push(step);
};
$scope.insertMomentStep = function () {
var step = {
type: "moment"
};
$scope.recipe.steps.push(step);
};
$scope.moveStep = function (from, to) {
var aux = $scope.recipe.steps[to];
$scope.recipe.steps[to] = $scope.recipe.steps[from];
$scope.recipe.steps[from] = aux;
};
$scope.removeStep = function (index) {
$scope.recipe.steps.splice(index, 1);
};
$scope.create = function () {
if ($scope.recipe.has_video) {
var url = formatedUrl();
if ( ! url || url === "") {
return alert("Url não informada ou incorreta.");
}
$scope.recipe.video_id = url;
}
$scope.recipe.tags = getTags();
if ($scope.recipe.tags.length > 10) {
return alert("Número de tags acima do limite definido.");
}
RecipeRepository.sendForApproval($scope.recipe).then(
function onSuccess (msg) {
alert(msg);
},
function onError (res) {
alert("Houve um erro no envio da receita.");
}
);
};
ProductRepository.groupByCategory().then(
function onSuccess (list) {
$scope.categories = list;
},
function onError (res) {
alert("Erro ao obter a lista de produtos agrupados por categoria");
}
);
}
]);
Bebella.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
};
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
};
}]);
Bebella.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/dashboard/profile');
$stateProvider
.state('recipes', {
url: '/recipe/list',
views: {
Content: {
controller: 'RecipeListCtrl',
templateUrl: view('recipe/list')
}
}
})
.state('new_recipe', {
url: '/recipe/new',
views: {
Content: {
controller: 'RecipeNewCtrl',
templateUrl: view('recipe/new')
}
}
})
.state('dashboard', {
url: '/dashboard',
views: {
Content: {
controller: 'HomeIndexCtrl',
templateUrl: view('dashboard')
}
}
})
.state('dashboard.profile', {
url: '/profile',
views: {
SubContent: {
controller: 'ProfileIndexCtrl',
templateUrl: view('profile')
}
}
})
.state('dashboard.stats', {
url: '/stats',
views: {
SubContent: {
controller: 'StatsIndexCtrl',
templateUrl: view('stats')
}
}
})
}
]);<file_sep><?php
use Illuminate\Database\Seeder;
use Bebella\User;
class DummyUsersSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$admUser = new User;
$admUser->type = "admin";
$admUser->name = "<NAME>";
$admUser->email = "<EMAIL>";
$admUser->password = bcrypt("<PASSWORD>");
$admUser->save();
$admUser = new User;
$admUser->type = "admin";
$admUser->name = "<NAME>";
$admUser->email = "<EMAIL>";
$admUser->password = bcrypt("<PASSWORD>");
$admUser->save();
}
}
<file_sep>/*! bebella 2016-07-16 */
<file_sep>var Bebella = angular.module('Bebella', ['ui.router', 'datatables', 'angular-flot']);
var APP_URL = $("#APP_URL").val();
var API_TOKEN = $("#API_TOKEN").val();
function view(path) {
return APP_URL + '/admin/' + path;
}
function api_v1(path, token) {
return APP_URL + '/api/v1/' + path + '?api_token=' + API_TOKEN;
}
function attr(dest, src) {
for (var e in src) {
if (e == "created_at" || e == "updated_at") {
dest[e] = new Date(src[e]);
} else if (e.startsWith("has_") || e.startsWith("is_") || e.startsWith("used_for_") || e == "active") {
dest[e] = (src[e] == 1);
} else {
dest[e] = src[e];
}
}
}
Bebella.run([
function () {
}
]);<file_sep>Bebella.controller('RecipeUnderApprovalListCtrl', ['$scope', 'RecipeRepository',
function ($scope, RecipeRepository) {
RecipeRepository.underApprovalList().then(
function onSuccess(list) {
$scope.recipes = list;
},
function onError(res) {
alert("Houve um erro na obtenção da lista de receitas sob aprovação.");
}
);
}
]);<file_sep><?php
namespace Bebella\Http\Controllers\Admin\Dashboard;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getIndex()
{
return view('admin.dashboard.index');
}
}
<file_sep>/*! bebella 2016-07-08 */
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class WishlistController extends Controller
{
//
}
<file_sep>Bebella.service('ProductRepository', ['$http', '$q', 'Product',
function ($http, $q, Product) {
var repository = this;
repository.find = function (id) {
var deferred = $q.defer();
$http.get(api_v1('product/find/' + id)).then(
function (res) {
var product = new Product();
attr(product, res.data);
deferred.resolve(product);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.groupByCategory = function () {
var deferred = $q.defer();
$http.get(api_v1("product/groupByCategory")).then(
function (res) {
var categories = _.map(res.data, function (json) {
var products = _.map(json, function (e) {
var product = new Product();
attr(product, e);
return product;
});
return products;
});
deferred.resolve(categories);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.all = function () {
var deferred = $q.defer();
$http.get(api_v1("product/all")).then(
function (res) {
var products = _.map(res.data, function (json) {
var product = new Product();
attr(product, json);
return product;
});
deferred.resolve(products);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.edit = function (product) {
var deferred = $q.defer();
var data = JSON.stringify(product);
$http.post(api_v1("product/edit"), data).then(
function (res) {
deferred.resolve(product);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.save = function (product) {
var deferred = $q.defer();
var data = JSON.stringify(product);
$http.post(api_v1("product/save"), data).then(
function (res) {
product.id = res.data.id;
deferred.resolve(product);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
}
]);<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Event;
use Bebella\User;
use Bebella\Events\Admin\UserWasCreated;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class UserController extends Controller
{
public function all()
{
return User::get();
}
public function save(Request $request)
{
$user = User::create([
"name" => $request->name,
"email" => $request->email,
"type" => $request->type,
"password" => <PASSWORD>($request->password),
"api_token" => str_random(120)
]);
Event::fire(new UserWasCreated($user, $request));
return $user;
}
}
<file_sep>Bebella.service('CurrentRecipe', ['Recipe',
function (Recipe) {
var service = this;
var _recipe = new Recipe();
service.get = function () {
return _recipe;
};
service.clear = function () {
_recipe = new Recipe();
};
}
]);
<file_sep>Bebella.factory('Category', [
function () {
var Category = new Function();
return Category;
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Auth;
use Illuminate\Http\Request;
use Bebella\Favorite;
use Bebella\Recipe;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class FavoriteController extends Controller
{
public function byUser($id)
{
return Recipe::where('recipes.active', true)
->where('favorites.user_id', $id)
->where('favorites.active', true)
->join('favorites', function ($join) {
$join->on('recipes.id', '=', 'favorites.recipe_id');
})
->join('channels', function ($join) {
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name')
->get();
}
public function add($id)
{
$recipe = Recipe::find($id);
$fav = new Favorite;
$fav->user_id = Auth::guard('api')->user()->id;
$fav->recipe_id = $id;
$fav->save();
$recipe->like_count += 1;
$recipe->save();
return 1;
}
public function remove($id)
{
$recipe = Recipe::find($id);
Favorite::where('recipe_id', $id)
->where('user_id', Auth::guard('api')->user()->id)
->update(['active' => false]);
$recipe->like_count -= 1;
$recipe->save();
return 1;
}
}
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ProductOptionColumns extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('product_options', function (Blueprint $table) {
$table->string('name')->nullable(true);
$table->string('image_path')->nullable(true);
$table->text('desc')->nullable(true);
$table->double('price')->nullable(false);
$table->string('store_url')->nullable(false);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('product_options', function (Blueprint $table) {
$table->dropColumn('name');
$table->dropColumn('image_path');
$table->dropColumn('desc');
$table->dropColumn('price');
$table->dropColumn('store_url');
});
}
}
<file_sep>Bebella.controller('ProductOptionListCtrl', ['$scope', 'ProductOptionRepository',
function ($scope, ProductOptionRepository) {
ProductOptionRepository.all().then(
function onSuccess (list) {
$scope.product_options = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de opções de produto.");
}
);
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Illuminate\Http\Request;
use Event;
use Bebella\Category;
use Bebella\Events\Admin\CategoryWasCreated;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class CategoryController extends Controller
{
public function find ($id)
{
return Category::find($id);
}
public function all()
{
return Category::where('active', true)
->get();
}
public function save(Request $request)
{
$category = Category::create($request->all());
Event::fire(new CategoryWasCreated($category, $request));
return $category;
}
public function edit(Request $request)
{
return Category::where('id', $request->id)
->update(
array_except(
$request->all(),
"api_token"
)
);
}
}
<file_sep>Bebella.controller('UserListCtrl', ['$scope', 'UserRepository', 'Breadcumb',
function ($scope, UserRepository, Breadcumb) {
Breadcumb.title = 'Usuários';
Breadcumb.items = [
{url: 'home', text: 'Dashboard'},
{text: 'Lista'}
];
UserRepository.all().then(
function onSuccess (list) {
$scope.users = list;
},
function onError (res) {
alert("Erro ao obter lista de usuários");
}
);
}
]);
<file_sep>Bebella.controller('CategoryEditCtrl', ['$scope', 'Breadcumb', '$stateParams', 'CategoryRepository',
function ($scope, Breadcumb, $stateParams, CategoryRepository) {
Breadcumb.items = [
{url: 'home', text: 'Dashboard'},
{url: 'category_detail({categoryId: ' + $stateParams.categoryId + '})', text: 'Categoria'},
{text: 'Formulário de Cadastro'}
];
$scope.edit = function () {
CategoryRepository.edit($scope.category).then(
function onSuccess (category) {
alert("Categoria editada com sucesso.");
},
function onError (res) {
alert("Erro ao criar esta categoria.");
}
);
};
CategoryRepository.find($stateParams.categoryId).then(
function onSuccess (category) {
$scope.category = category;
Breadcumb.title = category.name;
},
function onError (res) {
alert("Houve um erro na obtenção dos dados desta categoria");
}
);
}
]);
<file_sep>Bebella.controller('ChannelNewCtrl', ['$scope', 'CurrentChannel', 'ChannelRepository',
function ($scope, CurrentChannel, ChannelRepository) {
$scope.channel = CurrentChannel.get();
$scope.create = function () {
ChannelRepository.save($scope.channel).then(
function onSuccess (channel) {
alert(channel.id);
alert("Canal cadastrado com sucesso.");
},
function onError (res) {
alert("Houve um erro no cadasto deste canal.");
}
);
};
$scope.clear = function () {
CurrentChannel.clear();
$scope.channel = CurrentChannel.get();
};
}
]);
<file_sep><?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');
Route::get('/fix', function () {
foreach (Bebella\User::get() as $user)
{
$user->api_token = str_random(120);
$user->save();
}
return 1;
});
Route::get('/ping', function () {
return "Pong!";
});
Route::group([
'namespace' => 'Auth',
'prefix' => 'auth',
'middleware' => 'web'
], function () {
Route::get('/login', 'AuthController@getLogin');
Route::post('/login', 'AuthController@postlogin');
Route::post('/api_login', 'AuthController@postApiLogin');
Route::post('/api_register', 'AuthController@postApiRegister');
});
Route::group([
'namespace' => 'Auth',
'prefix' => 'auth',
'middleware' => 'auth'
], function () {
Route::get('/logout', 'AuthController@getLogout');
Route::get('/user', 'AuthController@getUser');
});
Route::get('/', function () {
return redirect()->to('/web');
});
Route::group([
'namespace' => 'Api',
'prefix' => 'api',
'middleware' => 'auth:api'
], function () {
Route::group([
'namespace' => 'v1',
'prefix' => 'v1'
], function () {
Route::group([
'prefix' => 'user'
], function () {
Route::post('/save', 'UserController@save');
Route::get('/all', 'UserController@all');
});
Route::group([
'prefix' => 'store'
], function () {
Route::get('/all', 'StoreController@all');
Route::get('/find/{id}', 'StoreController@find');
Route::post('/save', 'StoreController@save');
Route::post('/edit', 'StoreController@edit');
});
Route::group([
'prefix' => 'search'
], function () {
Route::post('/recipe', 'SearchController@searchRecipe');
});
Route::group([
'prefix' => 'channel'
], function () {
Route::get('/all', 'ChannelController@all');
Route::get('/find/{id}', 'ChannelController@find');
Route::post('/save', 'ChannelController@save');
Route::post('/edit', 'ChannelController@edit');
});
Route::group([
'prefix' => 'category'
], function () {
Route::get('/all', 'CategoryController@all');
Route::get('/find/{id}', 'CategoryController@find');
Route::post('/save', 'CategoryController@save');
Route::post('/edit', 'CategoryController@edit');
});
Route::group([
'prefix' => 'product'
], function () {
Route::get('/all', 'ProductController@all');
Route::get('/find/{id}', 'ProductController@find');
Route::post('/save', 'ProductController@save');
Route::post('/edit', 'ProductController@edit');
Route::get('/groupByCategory', 'ProductController@groupByCategory');
});
Route::group([
'prefix' => 'product_option'
], function () {
Route::get('/all', 'ProductOptionController@all');
Route::get('/find/{id}', 'ProductOptionController@find');
Route::get('/byProduct/{id}', 'ProductOptionController@byProduct');
Route::get('/getStoreUrl/{id}', 'ProductOptionController@getStoreUrl');
Route::post('/save', 'ProductOptionController@save');
});
Route::group([
'prefix' => 'recipe'
], function () {
Route::get('/all', 'RecipeController@all');
Route::get('/trending', 'RecipeController@trending');
Route::get('/find/{id}', 'RecipeController@find');
Route::post('/save', 'RecipeController@save');
Route::post('/edit', 'RecipeController@edit');
Route::post('/comment/{id}', 'RecipeController@comment');
Route::post('/paginateWithFilters/{page}', 'RecipeController@paginateWithFilters');
Route::post('/trendingWithFilters/{page}', 'RecipeController@trendingWithFilters');
Route::get('/underApprovalList', 'RecipeController@underApprovalList');
Route::post('/sendForApproval', 'RecipeController@sendForApproval');
});
Route::group([
'prefix' => 'report'
], function () {
Route::get('/redirectsByProductOption/{id}', 'ReportController@redirectsByProductOption');
Route::get('/clicksByProductOption/{id}', 'ReportController@clicksByProductOption');
Route::get('/viewsByProductOption/{id}', 'ReportController@viewsByProductOption');
});
Route::group([
'prefix' => 'favorite'
], function () {
Route::get('/byUser/{id}', 'FavoriteController@byUser');
Route::get('/add/{id}', 'FavoriteController@add');
Route::get('/remove/{id}', 'FavoriteController@remove');
});
Route::group([
'prefix' => 'wishlist'
], function () {
Route::get('/byUser/{id}', 'WishlistController@byUser');
Route::get('/add/{id}', 'WishlistController@add');
});
});
});
Route::group([
'namespace' => 'Web',
'prefix' => 'web'
], function () {
Route::get('/', 'IndexController@getIndex');
});
Route::group([
'namespace' => 'User',
'prefix' => 'user'
], function () {
Route::get('/', 'IndexController@getIndex');
});
Route::group([
'namespace' => 'Admin',
'prefix' => 'admin',
'middleware' => ['auth', 'admin']
], function () {
Route::get('/', 'IndexController@getIndex');
Route::group([
'namespace' => 'Dashboard',
'prefix' => 'dashboard'
], function () {
Route::get('/', 'ViewController@getIndex');
});
Route::group([
'namespace' => 'Category',
'prefix' => 'category'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
Route::get('/edit', 'ViewController@getEdit');
});
Route::group([
'namespace' => 'Channel',
'prefix' => 'channel'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
});
Route::group([
'namespace' => 'Store',
'prefix' => 'store'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
});
Route::group([
'namespace' => 'Product',
'prefix' => 'product'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
Route::get('/edit', 'ViewController@getEdit');
});
Route::group([
'namespace' => 'ProductOption',
'prefix' => 'product_option'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
Route::get('/detail', 'ViewController@getDetail');
});
Route::group([
'namespace' => 'Recipe',
'prefix' => 'recipe'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
Route::get('/edit', 'ViewController@getEdit');
Route::get('/under_approval', 'ViewController@getUnderApproval');
});
Route::group([
'namespace' => 'User',
'prefix' => 'user'
], function () {
Route::get('/new', 'ViewController@getNew');
Route::get('/list', 'ViewController@getList');
});
});
Route::group([
'namespace' => 'Channel',
'prefix' => 'channel'
], function () {
Route::get('/', 'IndexController@getIndex');
Route::group([
'namespace' => 'Dashboard',
'prefix' => 'dashboard'
], function () {
Route::get('/', 'ViewController@getIndex');
});
Route::group([
'namespace' => 'Profile',
'prefix' => 'profile'
], function () {
Route::get('/', 'ViewController@getIndex');
});
Route::group([
'namespace' => 'Recipe',
'prefix' => 'recipe'
], function () {
Route::get('/list', 'ViewController@getList');
Route::get('/new', 'ViewController@getNew');
});
});
Route::group([
'namespace' => 'Store',
'prefix' => 'store'
], function () {
Route::get('/', 'IndexController@getIndex');
});
<file_sep><?php
namespace Bebella\Http\Controllers\Admin\ProductOption;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getNew()
{
return view('admin.product_option.new');
}
public function getList()
{
return view('admin.product_option.list');
}
public function getDetail()
{
return view('admin.product_option.detail');
}
}
<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class Search extends Model
{
//
}
<file_sep>Bebella.controller('RecipeNewCtrl', ['$scope', 'ChannelRepository', 'RecipeRepository', 'ProductRepository', 'CurrentRecipe',
function ($scope, ChannelRepository, RecipeRepository, ProductRepository, CurrentRecipe) {
$scope.recipe = CurrentRecipe.get();
ChannelRepository.all().then(
function onSuccess (list) {
$scope.channels = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de canais");
}
);
ProductRepository.all().then(
function onSuccess (list) {
$scope.products = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de produtos");
}
);
$scope.create = function () {
RecipeRepository.save($scope.recipe).then(
function (recipe) {
alert(recipe.id);
alert("Nova receita criada com sucesso.");
},
function (res) {
alert("Houve um erro na criação desta receita.");
}
);
};
$scope.clear = function () {
CurrentRecipe.clear();
$scope.recipe = CurrentRecipe.get();
};
$scope.newTag = function () {
$scope.recipe.tags.push({});
};
$scope.removeTag = function () {
$scope.recipe.tags.pop();
};
$scope.newStep = function () {
$scope.recipe.steps.push({});
};
$scope.removeStep = function () {
$scope.recipe.steps.pop();
};
$scope.newProduct = function () {
$scope.recipe.products.push({});
};
$scope.removeProduct = function () {
$scope.recipe.products.pop();
};
}
]);
<file_sep>Bebella.controller('ProductNewCtrl', ['$scope', 'CurrentProduct', 'CategoryRepository', 'ProductRepository',
function ($scope, CurrentProduct, CategoryRepository, ProductRepository) {
$scope.product = CurrentProduct.get();
$scope.create = function () {
ProductRepository.save($scope.product).then(
function onSuccess (product) {
alert(product.id);
alert("Produto criado com sucesso.");
},
function onError () {
alert("Houve um erro na criação do produto.");
}
);
};
$scope.clear = function () {
CurrentProduct.clear();
$scope.product = CurrentProduct.get();
};
CategoryRepository.all().then(
function onSuccess (list) {
$scope.categories = list;
},
function onError (res) {
alert("Houve um erro na obtenção das lista de categorias");
}
);
}
]);
<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RecipeNewColumns extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('recipes', function (Blueprint $table) {
$table->boolean('has_video')->default(false);
$table->boolean('is_under_approval')->default(false);
$table->string('video_id')->nullable(true);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('recipes', function (Blueprint $table) {
$table->dropColumn('has_video');
$table->dropColumn('is_under_approval');
$table->dropColumn('video_id');
});
}
}
<file_sep><?php
namespace Bebella\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'Bebella\Events\Admin\CategoryWasCreated' => [
'Bebella\Listeners\Admin\CategoryImageSaving',
],
'Bebella\Events\Admin\ProductWasCreated' => [
'Bebella\Listeners\Admin\ProductImageSaving',
],
'Bebella\Events\Admin\ProductOptionWasCreated' => [
'Bebella\Listeners\Admin\ProductOptionImageSaving',
],
'Bebella\Events\Admin\UserWasCreated' => [
'Bebella\Listeners\Admin\UserImageSaving',
],
'Bebella\Events\Admin\ChannelWasCreated' => [
'Bebella\Listeners\Admin\ChannelImageSaving',
],
'Bebella\Events\Admin\RecipeWasCreated' => [
'Bebella\Listeners\Admin\RecipeImageSaving',
],
'Bebella\Events\Admin\StoreWasCreated' => [
'Bebella\Listeners\Admin\StoreImageSaving',
],
'Bebella\Events\Admin\RecipeStepWasCreated' => [
'Bebella\Listeners\Admin\RecipeStepImageSaving',
],
'Bebella\Events\Mobile\RecipeWasViewed' => [
'Bebella\Listeners\Mobile\RecipeViewCountUpdating',
],
'Bebella\Events\Mobile\RedirectionToProductOptionUrl' => [
'Bebella\Listeners\Mobile\UserProductOptionRedirectionRegistration',
],
'Bebella\Events\Mobile\ProductOptionWasViewed' => [
'Bebella\Listeners\Mobile\ProductOptionVisualizationCounting',
],
'Bebella\Events\Mobile\ProductOptionWasClicked' => [
'Bebella\Listeners\Mobile\ProductOptionClickCounting',
],
'Bebella\Events\Mobile\RecipeWasSearched' => [
'Bebella\Listeners\Mobile\RecipeSearchRegistering',
],
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
<file_sep><?php
namespace Bebella\Listeners\Mobile;
use Bebella\Events\Mobile\RecipeWasViewed;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class RecipeViewCountUpdating
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param RecipeWasViewed $event
* @return void
*/
public function handle(RecipeWasViewed $event)
{
$event->recipe->view_count += 1;
$event->recipe->save();
}
}
<file_sep>Bebella.controller('RecipeEditCtrl', ['$scope', '$stateParams', '$timeout', 'RecipeRepository', 'ChannelRepository', 'ProductRepository',
function ($scope, $stateParams, $timeout, RecipeRepository, ChannelRepository, ProductRepository) {
ChannelRepository.all().then(
function onSuccess (list) {
$scope.channels = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de canais");
}
);
ProductRepository.all().then(
function onSuccess (list) {
$scope.products = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de produtos");
}
);
RecipeRepository.find($stateParams.recipeId).then(
function onSuccess (recipe) {
$scope.recipe = recipe;
console.log(recipe);
},
function onError (res) {
alert("Houve um erro na obtenção da receita.");
}
);
$scope.edit = function () {
RecipeRepository.edit($scope.recipe).then(
function onSuccess (recipe) {
alert("Receita editada com sucesso.");
},
function onError (res) {
alert("Erro ao editar receita");
}
);
};
$scope.newTag = function () {
$scope.recipe.tags.push({});
};
$scope.removeTag = function () {
$scope.recipe.tags.pop();
};
$scope.newStep = function () {
$scope.recipe.steps.push({});
};
$scope.removeStep = function () {
$scope.recipe.steps.pop();
};
$scope.newProduct = function () {
$scope.recipe.products.push({});
};
$scope.removeProduct = function () {
$scope.recipe.products.pop();
};
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use DB;
use Auth;
use Event;
use Bebella\Recipe;
use Bebella\Events\Mobile\RecipeWasSearched;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class SearchController extends Controller
{
public function searchRecipe(Request $request)
{
$user = Auth::guard('api')->user();
$data = array();
$results = Recipe::where('recipes.active', true)
->where(DB::raw(
"recipes.name like '%$request->term%' or recipes.desc like '%$request->term%'"
))
->join('channels', function ($join) {
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name', 'channels.image_path as channel_image')
->orderBy('recipes.created_at', 'desc')
->take($request->page * 5)
->skip(($request->page - 1) * 5)
->get();
Event::fire(new RecipeWasSearched($user, $request));
$data["result"] = $results;
$data["term"] = $request->term;
$data["page"] = $request->page;
return $data;
}
}
<file_sep>Bebella.controller('ChannelListCtrl', ['$scope', 'ChannelRepository',
function ($scope, ChannelRepository) {
ChannelRepository.all().then(
function onSuccess (list) {
$scope.channels = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de canais");
}
);
}
]);
<file_sep>Bebella.service('Breadcumb', [
function () {
var service = this;
service.title = "Teste";
service.items = [];
}
]);
<file_sep><?php
namespace Bebella\Listeners\Mobile;
use Bebella\Search;
use Bebella\Events\Mobile\RecipeWasSearched;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class RecipeSearchRegistering
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param RecipeWasSearched $event
* @return void
*/
public function handle(RecipeWasSearched $event)
{
$search = new Search;
$search->type = 'recipe';
$search->user_id = $event->user->id;
$search->term = $event->request->term;
$search->save();
}
}
<file_sep><?php
namespace Bebella\Http\Controllers\Admin\Category;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getNew()
{
return view('admin.category.new');
}
public function getList()
{
return view('admin.category.list');
}
public function getEdit()
{
return view('admin.category.edit');
}
}
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Auth;
use Event;
use Illuminate\Http\Request;
use Bebella\Product;
use Bebella\Favorite;
use Bebella\Recipe;
use Bebella\RecipeTag;
use Bebella\RecipeStep;
use Bebella\RecipeProduct;
use Bebella\RecipeComment;
use Bebella\Events\Admin\RecipeWasCreated;
use Bebella\Events\Admin\RecipeWasEdited;
use Bebella\Events\Admin\RecipeStepWasCreated;
use Bebella\Events\Mobile\RecipeWasViewed;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class RecipeController extends Controller
{
public function find($id)
{
$user = Auth::guard('api')->user();
$recipe = Recipe::where('recipes.id', $id)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select(
'recipes.*', 'channels.name as channel_name', 'channels.image_path as channel_image'
)
->first();
Event::fire(new RecipeWasViewed($recipe));
$fav = Favorite::where('user_id', $user->id)
->where('recipe_id', $recipe->id)
->where('active', true)
->first();
$recipe["is_liked"] = (!is_null($fav));
$recipe["tags"] = RecipeTag::where('recipe_id', $id)
->where('active', true)
->get();
$recipe["steps"] = RecipeStep::where('recipe_id', $id)
->where('active', true)
->get();
$recipe["products"] = RecipeProduct::where('recipe_products.recipe_id', $id)
->where('recipe_products.active', true)
->join('products', function ($join)
{
$join->on('recipe_products.product_id', '=', 'products.id');
})
->select(
'recipe_products.*', 'products.name as product_name', 'products.short_desc as product_desc', 'products.image_path as product_image'
)
->get();
$recipe["comments"] = RecipeComment::where('recipe_comments.active', true)
->where('recipe_comments.recipe_id', $recipe->id)
->join('users', function ($join)
{
$join->on('users.id', '=', 'recipe_comments.user_id');
})
->select(
'recipe_comments.*', 'users.name as user_name', 'users.image_path as user_image'
)
->orderBy('recipe_comments.created_at', 'desc')
->take(10)
->get();
$array = array();
$last = Recipe::where('recipes.channel_id', $recipe->channel_id)
->where('recipes.active', true)
->where('recipes.type', $recipe->type)
->where('recipes.id', '!=', $recipe->id)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select(
'recipes.*', 'channels.name as channel_name'
)
->orderBy('recipes.created_at', 'desc')
->first();
array_push($array, $last);
$bests = Recipe::where('recipes.channel_id', $recipe->channel_id)
->where('recipes.active', true)
->where('recipes.type', $recipe->type)
->where('recipes.id', '!=', $recipe->id)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select(
'recipes.*', 'channels.name as channel_name'
)
->orderBy('recipes.like_count', 'desc')
->take(3)
->get();
foreach ($bests as $item)
{
if ($item->id != $last->id)
{
array_push($array, $item);
}
}
if (count($array) <= 4)
{
$others = Recipe::where('recipes.active', true)
->where('recipes.type', $recipe->type)
->where('recipes.id', '!=', $recipe->id)
->whereNotIn('recipes.id', collect($array)->map(function ($e)
{
return $e["id"];
}))
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select(
'recipes.*', 'channels.name as channel_name'
)
->orderBy('recipes.like_count', 'desc')
->take(4 - count($array))
->get();
foreach ($others as $other)
{
array_push($array, $other);
}
}
if (count($array) <= 4)
{
$others = Recipe::where('recipes.active', true)
->where('recipes.id', '!=', $recipe->id)
->whereNotIn('recipes.id', collect($array)->map(function ($e)
{
return $e["id"];
}))
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select(
'recipes.*', 'channels.name as channel_name'
)
->orderBy('recipes.like_count', 'desc')
->take(4 - count($array))
->get();
foreach ($others as $other)
{
array_push($array, $other);
}
}
$recipe["related"] = $array;
return $recipe;
}
public function comment($id, Request $request)
{
$user = Auth::guard('api')->user();
$comment = RecipeComment::create([
"user_id" => $user->id,
"recipe_id" => $id,
"comment" => $request->text
]);
$comment["user_name"] = $user->name;
$comment["user_image"] = $user->image_path;
return $comment;
}
public function paginateWithFilters($page, Request $request)
{
$filters = array();
$response = array();
foreach ($request->all() as $key => $value)
{
if ($value)
array_push($filters, $key);
}
$data = Recipe::where('recipes.active', true)
->whereIn('recipes.type', $filters)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name', 'channels.image_path as channel_image')
->orderBy('recipes.created_at', 'desc')
->take($page * 5)
->skip(($page - 1) * 5)
->get();
$response["data"] = $data;
$response["page"] = $page;
return $response;
}
public function trendingWithFilters($page, Request $request)
{
$filters = array();
$response = array();
foreach ($request->all() as $key => $value)
{
if ($value)
array_push($filters, $key);
}
$data = Recipe::where('recipes.active', true)
->whereIn('recipes.type', $filters)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name', 'channels.image_path as channel_image')
->orderBy('recipes.view_count', 'desc')
->take($page * 5)
->skip(($page - 1) * 5)
->get();
$response["data"] = $data;
$response["page"] = $page;
return $response;
}
public function all()
{
return Recipe::where('recipes.active', true)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name', 'channels.image_path as channel_image')
->orderBy('recipes.created_at', 'desc')
->get();
}
public function underApprovalList()
{
return Recipe::where('recipes.is_under_approval', true)
->join('channels', function ($join) {
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name')
->get();
}
public function trending()
{
return Recipe::where('recipes.active', true)
->join('channels', function ($join)
{
$join->on('recipes.channel_id', '=', 'channels.id');
})
->select('recipes.*', 'channels.name as channel_name', 'channels.image_path as channel_image')
->orderBy('recipes.view_count', 'desc')
->get();
}
public function sendForApproval(Request $request)
{
$user = Auth::guard('api')->user();
$recipe = new Recipe;
$recipe->type = $request->type;
$recipe->channel_id = $user->channel()->id;
$recipe->name = $request->name;
$recipe->desc = $request->desc;
$recipe->active = false;
$recipe->is_under_approval = true;
$recipe->has_video = $request->has_video;
if ($recipe->has_video)
{
$recipe->video_id = $request->video_id;
}
$recipe->save();
Event::fire(new RecipeWasCreated($recipe, $request));
foreach ($request->tags as $value)
{
$tag = new RecipeTag;
$tag->recipe_id = $recipe->id;
$tag->name = $value;
$tag->save();
}
foreach ($request->steps as $key => $value)
{
$step = new RecipeStep;
$step->recipe_id = $recipe->id;
$step->desc = $value["desc"];
$step->type = $value["type"];
$step->order = $key + 1;
$step->save();
if ($step->type == "image")
{
Event::fire(new RecipeStepWasCreated($step, $request));
}
else
{
$step->moment = $value["moment"];
$step->save();
}
}
foreach ($request->products as $key => $value)
{
if (array_key_exists("id", $value) && !is_null($value["id"]))
{
$product = new RecipeProduct;
$product->recipe_id = $recipe->id;
$product->product_id = $value["id"];
$product->save();
}
else
{
$product = new Product;
$product->name = $value["name"];
$product->short_desc = $value["short_desc"];
$product->active = false;
$product->save();
$rel = new RecipeProduct;
$rel->recipe_id = $recipe->id;
$rel->product_id = $product->id;
$rel->save();
}
}
return "Receita enviada para aprovação com sucesso.";
}
public function save(Request $request)
{
$recipe = Recipe::create($request->all());
Event::fire(new RecipeWasCreated($recipe, $request));
foreach ($request->tags as $key => $value)
{
$tag = new RecipeTag;
$tag->recipe_id = $recipe->id;
$tag->name = $value["name"];
$tag->save();
}
foreach ($request->steps as $key => $value)
{
$step = new RecipeStep;
$step->recipe_id = $recipe->id;
$step->desc = $value["desc"];
$step->order = $key + 1;
$step->save();
Event::fire(new RecipeStepWasCreated($step, $value));
}
foreach ($request->products as $key => $value)
{
$product = new RecipeProduct;
$product->recipe_id = $recipe->id;
$product->product_id = $value["product_id"];
$product->save();
}
return $recipe;
}
public function edit(Request $request)
{
Recipe::where('id', $request->id)
->update([
"name" => $request->name,
"desc" => $request->desc,
"channel_id" => $request->id,
"type" => $request->type
]);
if ($request->main_image)
{
Event::fire(new RecipeWasEdited($recipe, $request));
}
RecipeTag::where('recipe_id', $request->id)
->update([
'active' => false
]);
foreach ($request->tags as $key => $value)
{
$tag = new RecipeTag;
$tag->recipe_id = $request->id;
$tag->name = $value["name"];
$tag->save();
}
RecipeProduct::where('recipe_id', $request->id)
->update([
'active' => false
]);
foreach ($request->products as $key => $value)
{
$product = new RecipeProduct;
$product->recipe_id = $request->id;
$product->product_id = $value["product_id"];
$product->save();
}
RecipeStep::where('recipe_id', $request->id)
->update([
'active' => false
]);
foreach ($request->steps as $key => $value)
{
$step = new RecipeStep;
$step->recipe_id = $request->id;
$step->desc = $value["desc"];
$step->order = $key + 1;
$step->save();
if (array_has($value, "image"))
{
Event::fire(new RecipeStepWasCreated($step, $value));
} else
{
$step->image_path = $value["image_path"];
$step->save();
}
}
return 1;
}
}
<file_sep>Bebella.controller('ProductEditCtrl', ['$scope', '$stateParams', 'ProductRepository', 'CategoryRepository',
function ($scope, $stateParams, ProductRepository, CategoryRepository) {
$scope.edit = function () {
ProductRepository.edit($scope.product).then(
function onSuccess (product) {
alert("Produto editado com sucesso.");
},
function onError (res) {
alert("Erro ao criar este produto.");
}
);
};
ProductRepository.find($stateParams.productId).then(
function onSuccess (product) {
$scope.product = product;
},
function onError (res) {
alert("Houve um erro na obtenção dos dados deste produto");
}
);
CategoryRepository.all().then(
function onSuccess (list) {
$scope.categories = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de categorias");
}
);
}
]);
<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class Click extends Model
{
//
}
<file_sep>Bebella.factory('Store', [
function () {
var Store = new Function();
return Store;
}
]);
<file_sep><?php
namespace Bebella\Listeners\Mobile;
use Bebella\Click;
use Bebella\Events\ProductOptionWasClicked;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProductOptionClickCounting
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ProductOptionWasClicked $event
* @return void
*/
public function handle(ProductOptionWasClicked $event)
{
$click = new Click;
$click->user_id = $event->user->id;
$click->recipe_id = $event->recipe->id;
$click->product_option_id = $event->productOption->id;
$click->save();
}
}
<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class ProductOption extends Model
{
protected $fillable = [
"store_id",
"product_id",
"name",
"desc",
"price",
"store_url",
"image_path"
];
}
<file_sep>Bebella.controller('StoreNewCtrl', ['$scope', 'CurrentStore', 'StoreRepository',
function ($scope, CurrentStore, StoreRepository) {
$scope.store = CurrentStore.get();
$scope.create = function () {
StoreRepository.save($scope.store).then(
function onSuccess (store) {
alert(store.id);
alert("Loja cadastrada com sucesso");
},
function onError (res) {
alert("Houve um erro ao cadastrar a loja.");
}
);
};
$scope.clear = function () {
CurrentStore.clear();
$scope.store = CurrentStore.get();
};
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Event;
use Auth;
use Bebella\Recipe;
use Bebella\ProductOption;
use Bebella\Events\Admin\ProductOptionWasCreated;
use Bebella\Events\Mobile\RedirectionToProductOptionUrl;
use Bebella\Events\Mobile\ProductOptionWasViewed;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ProductOptionController extends Controller
{
public function find($id)
{
return ProductOption::where('product_options.id', $id)
->where('product_options.active', true)
->join('products', function ($join) {
$join->on('product_options.product_id' , '=', 'products.id');
})
->join('stores', function ($join) {
$join->on('product_options.store_id' , '=', 'stores.id');
})
->select(
"product_options.*",
"products.name as product_name",
"stores.name as store_name",
"stores.image_path as store_image_path"
)->first();
}
public function getStoreUrl($id, Request $request)
{
$user = Auth::guard('api')->user();
$productOption = ProductOption::find($id);
$recipe = Recipe::find($request->recipe_id);
Event::fire(new RedirectionToProductOptionUrl($user, $recipe, $productOption));
return $productOption->store_url;
}
public function save(Request $request)
{
$productOption = ProductOption::create($request->all());
Event::fire(new ProductOptionWasCreated($productOption, $request));
return $productOption;
}
public function all()
{
return ProductOption::where('product_options.active', true)
->join('products', function ($join) {
$join->on('product_options.product_id' , '=', 'products.id');
})
->join('stores', function ($join) {
$join->on('product_options.store_id' , '=', 'stores.id');
})
->select(
"product_options.*",
"products.name as product_name",
"stores.name as store_name"
)->get();
}
public function byProduct($id, Request $request)
{
$user = Auth::guard('api')->user();
$recipe = Recipe::find($request->recipe_id);
$options = ProductOption::where('product_options.active', true)
->where('product_options.product_id', $id)
->join('products', function ($join) {
$join->on('product_options.product_id' , '=', 'products.id');
})
->join('stores', function ($join) {
$join->on('product_options.store_id' , '=', 'stores.id');
})
->select(
"product_options.*",
"products.name as product_name",
"stores.name as store_name",
"stores.image_path as store_image"
)->get();
foreach ($options as $option)
{
Event::fire(new ProductOptionWasViewed($user, $recipe, $option));
}
return $options;
}
}
<file_sep><?php
namespace Bebella\Listeners\Mobile;
use Bebella\Visualization;
use Bebella\Events\Mobile\ProductOptionWasViewed;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProductOptionVisualizationCounting
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ProductOptionWasViewed $event
* @return void
*/
public function handle(ProductOptionWasViewed $event)
{
$visualization = new Visualization;
$visualization->user_id = $event->user->id;
$visualization->recipe_id = $event->recipe->id;
$visualization->product_option_id = $event->productOption->id;
$visualization->save();
}
}
<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class RecipeComment extends Model
{
protected $fillable = [
"user_id",
"recipe_id",
"comment"
];
}
<file_sep>Bebella.controller('CategoryNewCtrl', ['$scope', 'CurrentCategory', 'CategoryRepository', 'Breadcumb',
function ($scope, CurrentCategory, CategoryRepository, Breadcumb) {
Breadcumb.title = 'Nova Categoria';
Breadcumb.items = [
{url: 'home', text: 'Dashboard'},
{text: 'Formulário de Cadastro'}
];
$scope.category = CurrentCategory.get();
$scope.create = function () {
CategoryRepository.save($scope.category).then(
function onSuccess (category) {
alert("Categoria cadastrada com sucesso.");
CurrentCategory.clear();
},
function onError (res) {
alert("Erro ao criar esta categoria.");
}
);
};
$scope.clear = function () {
CurrentCategory.clear();
$scope.category = CurrentCategory.get();
};
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Event;
use Bebella\User;
use Bebella\Store;
use Bebella\Events\Admin\UserWasCreated;
use Bebella\Events\Admin\StoreWasCreated;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class StoreController extends Controller
{
public function all()
{
return Store::where('stores.active', true)
->join('users', function ($join) {
$join->on('stores.user_id', '=', 'users.id');
})
->select('stores.*', 'users.name as user_name')
->get();
}
public function save(Request $request)
{
$user = User::create([
"type" => "store",
"name" => $request->user_name,
"email" => $request->user_email,
"password" => <PASSWORD>($request->user_password)
]);
Event::fire(new UserWasCreated($user, $request));
$store = Store::create(
array_merge(
[ "user_id" => $user->id ],
$request->all()
)
);
Event::fire(new StoreWasCreated($store, $request));
return $store;
}
}
<file_sep>Bebella.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('user_new', {
url: '/user/new',
views: {
MainContent: {
templateUrl: view('user/new')
}
}
})
.state('user_list', {
url: '/user/list',
views: {
MainContent: {
templateUrl: view('user/list')
}
}
})
.state('recipe_new', {
url: '/recipe/new',
views: {
MainContent: {
templateUrl: view('recipe/new')
}
}
})
.state('recipe_edit', {
url: '/recipe/{recipeId}/edit',
views: {
MainContent: {
templateUrl: view('recipe/edit')
}
}
})
.state('recipe_list', {
url: '/recipe/list',
views: {
MainContent: {
templateUrl: view('recipe/list')
}
}
})
.state('recipe_under_approval', {
url: '/recipe/under_approval',
views: {
MainContent: {
templateUrl: view('recipe/under_approval')
}
}
})
.state('category_new', {
url: '/category/new',
views: {
MainContent: {
templateUrl: view('category/new')
}
}
})
.state('category_list', {
url: '/category/list',
views: {
MainContent: {
templateUrl: view('category/list')
}
}
})
.state('category_edit', {
url: '/category/edit/{categoryId}',
views: {
MainContent: {
templateUrl: view('category/edit')
}
}
})
.state('store_new', {
url: '/store/new',
views: {
MainContent: {
templateUrl: view('store/new')
}
}
})
.state('store_list', {
url: '/store/list',
views: {
MainContent: {
templateUrl: view('store/list')
}
}
})
.state('channel_new', {
url: '/channel/new',
views: {
MainContent: {
templateUrl: view('channel/new')
}
}
})
.state('channel_list', {
url: '/channel/list',
views: {
MainContent: {
templateUrl: view('channel/list')
}
}
})
.state('product_new', {
url: '/product/new',
views: {
MainContent: {
templateUrl: view('product/new')
}
}
})
.state('product_list', {
url: '/product/list',
views: {
MainContent: {
templateUrl: view('product/list')
}
}
})
.state('product_edit', {
url: '/product/edit/{productId}',
views: {
MainContent: {
templateUrl: view('product/edit')
}
}
})
.state('product_option_new', {
url: '/product_option/new',
views: {
MainContent: {
templateUrl: view('product_option/new')
}
}
})
.state('product_option_list', {
url: '/product_option/list',
views: {
MainContent: {
templateUrl: view('product_option/list')
}
}
})
.state('product_option_detail', {
url: '/product_option/{productOptionId}/detail',
views: {
MainContent: {
templateUrl: view('product_option/detail')
}
}
})
.state('home', {
url: '/',
views: {
MainContent: {
templateUrl: view('dashboard')
}
}
});
}
]);<file_sep><?php
namespace Bebella\Http\Controllers\Channel\Profile;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getIndex()
{
return view('channel.profile.index');
}
}
<file_sep>Bebella.service('CurrentProductOption', ['ProductOption',
function (ProductOption) {
var service = this;
var _product_option = new ProductOption();
service.get = function () {
return _product_option;
};
service.clear = function () {
_product_option = new ProductOption();
};
}
]);
<file_sep>Bebella.service('CurrentStore', ['Store',
function (Store) {
var service = this;
var _store = new Store();
service.get = function () {
return _store;
};
service.clear = function () {
_store = new Store();
};
}
]);
<file_sep><?php
namespace Bebella\Http\ViewComposers\User;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\View;
class GeneralViewComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$view->with('STATIC_URL', env('APP_URL') . '/static/user');
}
}<file_sep><?php
namespace Bebella\Events;
abstract class Event
{
//
}
<file_sep>Bebella.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/dashboard/profile');
$stateProvider
.state('recipes', {
url: '/recipe/list',
views: {
Content: {
controller: 'RecipeListCtrl',
templateUrl: view('recipe/list')
}
}
})
.state('new_recipe', {
url: '/recipe/new',
views: {
Content: {
controller: 'RecipeNewCtrl',
templateUrl: view('recipe/new')
}
}
})
.state('dashboard', {
url: '/dashboard',
views: {
Content: {
controller: 'HomeIndexCtrl',
templateUrl: view('dashboard')
}
}
})
.state('dashboard.profile', {
url: '/profile',
views: {
SubContent: {
controller: 'ProfileIndexCtrl',
templateUrl: view('profile')
}
}
})
.state('dashboard.stats', {
url: '/stats',
views: {
SubContent: {
controller: 'StatsIndexCtrl',
templateUrl: view('stats')
}
}
})
}
]);<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use Event;
use Illuminate\Http\Request;
use Bebella\Product;
use Bebella\Events\Admin\ProductWasCreated;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ProductController extends Controller
{
public function find($id)
{
return Product::find($id);
}
public function save(Request $request)
{
$product = Product::create($request->all());
Event::fire(new ProductWasCreated($product, $request));
return $product;
}
public function all()
{
return Product::where('products.active', true)
->join('categories', function ($join) {
$join->on('products.category_id', '=', 'categories.id');
})
->select('products.*', 'categories.name as category_name')
->get();
}
public function edit(Request $request)
{
return Product::where('id', $request->id)
->update(
array_except(
$request->all(),
"api_token"
)
);
}
public function groupByCategory()
{
return collect($this->all())->groupBy('category_name');
}
}
<file_sep><?php
namespace Bebella\Http\Controllers\Channel\Dashboard;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getIndex()
{
return view('channel.dashboard.index');
}
}
<file_sep>module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
web: {
options: {
separator: '\n\n'
},
src: [
'public/static/web/app/main.js',
'public/static/web/app/factory/**/*.js',
'public/static/web/app/service/**/*.js',
'public/static/web/app/repository/**/*.js',
'public/static/web/app/controller/**/*.js',
'public/static/web/app/directive/**/*.js',
'public/static/web/app/config.js'
],
dest: 'public/static/web/dist/<%= pkg.version %>/<%= pkg.name %>.js'
},
admin: {
options: {
separator: '\n\n'
},
src: [
'public/static/admin/app/main.js',
'public/static/admin/app/factory/**/*.js',
'public/static/admin/app/service/**/*.js',
'public/static/admin/app/repository/**/*.js',
'public/static/admin/app/controller/**/*.js',
'public/static/admin/app/directive/**/*.js',
'public/static/admin/app/config.js'
],
dest: 'public/static/admin/dist/<%= pkg.version %>/<%= pkg.name %>.js'
},
user: {
options: {
separator: '\n\n'
},
src: [
'public/static/user/app/main.js',
'public/static/user/app/factory/**/*.js',
'public/static/user/app/service/**/*.js',
'public/static/user/app/repository/**/*.js',
'public/static/user/app/controller/**/*.js',
'public/static/user/app/directive/**/*.js',
'public/static/user/app/config.js'
],
dest: 'public/static/user/dist/<%= pkg.version %>/<%= pkg.name %>.js'
},
store: {
options: {
separator: '\n\n'
},
src: [
'public/static/store/app/main.js',
'public/static/store/app/factory/**/*.js',
'public/static/store/app/service/**/*.js',
'public/static/store/app/repository/**/*.js',
'public/static/store/app/controller/**/*.js',
'public/static/store/app/directive/**/*.js',
'public/static/store/app/config.js'
],
dest: 'public/static/store/dist/<%= pkg.version %>/<%= pkg.name %>.js'
},
channel: {
options: {
separator: '\n\n'
},
src: [
'public/static/channel/app/main.js',
'public/static/channel/app/factory/**/*.js',
'public/static/channel/app/service/**/*.js',
'public/static/channel/app/repository/**/*.js',
'public/static/channel/app/controller/**/*.js',
'public/static/channel/app/directive/**/*.js',
'public/static/channel/app/config.js'
],
dest: 'public/static/channel/dist/<%= pkg.version %>/<%= pkg.name %>.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
// Default task(s).
grunt.registerTask('default', ['concat']);
};<file_sep><?php
namespace Bebella\Http\ViewComposers\Admin;
use Auth;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\View;
class GeneralViewComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$view->with('STATIC_URL', env('APP_URL') . '/static/admin');
$view->with('API_TOKEN', Auth::user()->api_token);
}
}<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
protected $fillable = [
"user_id",
"name",
"short_desc",
"desc",
"image_path",
"website",
"facebook_page"
];
}
<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class Channel extends Model
{
protected $fillable = [
"user_id",
"name",
"short_desc",
"desc",
"image_path",
"youtube_user",
"facebook_page",
"website"
];
}
<file_sep>Bebella.controller('ProductListCtrl', ['$scope', 'ProductRepository',
function ($scope, ProductRepository) {
ProductRepository.all().then(
function onSuccess (list) {
$scope.products = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de produtos.");
}
);
}
]);
<file_sep><?php
namespace Bebella\Events\Admin;
use Illuminate\Http\Request;
use Bebella\Product;
use Bebella\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ProductWasCreated extends Event
{
use SerializesModels;
public $product;
public $request;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Product $product, Request $request)
{
$this->product = $product;
$this->request = $request;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
<file_sep><?php
namespace Bebella;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
"category_id",
"name",
"short_desc",
"desc"
];
}
<file_sep><?php
namespace Bebella\Listeners\Admin;
use Storage;
use Bebella\Events\Admin\RecipeWasCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class RecipeImageSaving
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param RecipeWasCreated $event
* @return void
*/
public function handle(RecipeWasCreated $event)
{
if ($event->request->main_image)
{
$base64_str = substr($event->request->main_image, strpos($event->request->main_image, ",")+1);
$image = base64_decode($base64_str);
$f = finfo_open();
$mime_type = finfo_buffer($f, $image, FILEINFO_MIME_TYPE);
$parts = explode('/', $mime_type);
$ext = $parts[1];
$filename = "images/recipe/" . time() . "-" . $event->recipe->id . "." . $ext;
Storage::put($filename, $image);
$event->recipe->image_path = "storage/" . $filename;
$event->recipe->save();
}
}
}
<file_sep>Bebella.controller('CategoryListCtrl', ['$scope', 'CategoryRepository', 'Breadcumb',
function ($scope, CategoryRepository, Breadcumb) {
Breadcumb.title = 'Categorias';
Breadcumb.items = [
{url: 'home', text: 'Dashboard'},
{text: 'Lista'}
];
CategoryRepository.all().then(
function onSuccess (list) {
$scope.categories = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de categorias");
}
);
}
]);
<file_sep><?php
namespace Bebella\Http\ViewComposers;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\View;
class GeneralViewComposer
{
public function __construct()
{
}
public function compose(View $view)
{
Blade::setEscapedContentTags('<%', '%>');
Blade::setContentTags('<%%', '%%>');
$view->with('APP_URL', env('APP_URL'));
}
}<file_sep><?php
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class NewRecipeTypes extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement("ALTER TABLE recipes CHANGE type type ENUM('beauty', 'decoration', 'clothing', 'health', 'food')");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('recipes', function (Blueprint $table) {
//
});
}
}
<file_sep>Bebella.service('RecipeRepository', ['$http', '$q', 'Recipe',
function ($http, $q, Recipe) {
var repository = this;
repository.find = function (id) {
var deferred = $q.defer();
$http.get(api_v1('recipe/find/' + id)).then(
function (res) {
var recipe = new Recipe();
attr(recipe, res.data);
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.all = function () {
var deferred = $q.defer();
$http.get(api_v1("recipe/all")).then(
function (res) {
var recipes = _.map(res.data, function (json) {
var recipe = new Recipe();
attr(recipe, json);
return recipe;
});
deferred.resolve(recipes);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.underApprovalList = function () {
var deferred = $q.defer();
$http.get(api_v1("recipe/underApprovalList")).then(
function (res) {
var recipes = _.map(res.data, function (json) {
var recipe = new Recipe();
attr(recipe, json);
return recipe;
});
deferred.resolve(recipes);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.edit = function (recipe) {
var deferred = $q.defer();
var data = JSON.stringify(recipe);
$http.post(api_v1("recipe/edit"), data).then(
function (res) {
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.save = function (recipe) {
var deferred = $q.defer();
var data = JSON.stringify(recipe);
$http.post(api_v1("recipe/save"), data).then(
function (res) {
recipe.id = res.data.id;
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.sendForApproval = function (recipe) {
var deferred = $q.defer();
var data = JSON.stringify(recipe);
$http.post(api_v1("recipe/sendForApproval"), data).then(
function (res) {
recipe.id = res.data.id;
deferred.resolve(recipe);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Admin\Channel;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getNew()
{
return view('admin.channel.new');
}
public function getList()
{
return view('admin.channel.list');
}
}
<file_sep><?php
namespace Bebella\Http\ViewComposers\Channel;
use Auth;
use Bebella\Channel;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\View;
class GeneralViewComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$view->with('STATIC_URL', env('APP_URL') . '/static/channel');
$view->with('CHANNEL', Channel::where('user_id', Auth::user()->id)
->first());
$view->with('API_TOKEN', Auth::user()->api_token);
}
}<file_sep><?php
namespace Bebella\Http\Controllers\Api\v1;
use DB;
use Illuminate\Http\Request;
use Bebella\Redirection;
use Bebella\Click;
use Bebella\Visualization;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ReportController extends Controller
{
public function redirectsByProductOption ($id)
{
return Redirection::where('product_option_id', $id)
->where('active', true)
->select(
DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d 00:00:00') as `date`"),
DB::raw("COUNT(id) as `count`")
)
->groupBy('date')
->get();
}
public function clicksByProductOption ($id)
{
return Click::where('product_option_id', $id)
->where('active', true)
->get();
}
public function viewsByProductOption ($id)
{
return Visualization::where('product_option_id', $id)
->where('active', true)
->select(
DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d 00:00:00') as `date`"),
DB::raw("COUNT(id) as `count`")
)
->groupBy('date')
->get();
}
}
<file_sep><?php
namespace Bebella\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
view()->composer(
['admin.*', 'auth.*', 'channel.*', 'store.*', 'user.*', 'web.*'],
'Bebella\Http\ViewComposers\GeneralViewComposer'
);
view()->composer(
['admin.*'],
'Bebella\Http\ViewComposers\Admin\GeneralViewComposer'
);
view()->composer(
['auth.*'],
'Bebella\Http\ViewComposers\Auth\GeneralViewComposer'
);
view()->composer(
['channel.*'],
'Bebella\Http\ViewComposers\Channel\GeneralViewComposer'
);
view()->composer(
['store.*'],
'Bebella\Http\ViewComposers\Store\GeneralViewComposer'
);
view()->composer(
['user.*'],
'Bebella\Http\ViewComposers\User\GeneralViewComposer'
);
view()->composer(
['web.*'],
'Bebella\Http\ViewComposers\Web\GeneralViewComposer'
);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep><?php
namespace Bebella\Http\Controllers\Web;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class IndexController extends Controller
{
public function getIndex()
{
return view('web.index');
}
}
<file_sep><?php
namespace Bebella\Http\Controllers\Admin\Product;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getNew()
{
return view('admin.product.new');
}
public function getList()
{
return view('admin.product.list');
}
public function getEdit()
{
return view('admin.product.edit');
}
}
<file_sep>Bebella.service('ReportRepository', ['$http', '$q',
function ($http, $q) {
var repository = this;
repository.redirectsByProductOption = function (id) {
var deferred = $q.defer();
$http.get(api_v1("report/redirectsByProductOption/" + id)).then(
function (res) {
deferred.resolve(res.data);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.clicksByProductOption = function (id) {
var deferred = $q.defer();
$http.get(api_v1("report/clicksByProductOption/" + id)).then(
function (res) {
deferred.resolve(res.data);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
repository.viewsByProductOption = function (id) {
var deferred = $q.defer();
$http.get(api_v1("report/viewsByProductOption/" + id)).then(
function (res) {
deferred.resolve(res.data);
},
function (res) {
deferred.reject(res);
}
);
return deferred.promise;
};
}
]);
<file_sep><?php
namespace Bebella\Http\Controllers\Admin\Recipe;
use Illuminate\Http\Request;
use Bebella\Http\Requests;
use Bebella\Http\Controllers\Controller;
class ViewController extends Controller
{
public function getNew()
{
return view('admin.recipe.new');
}
public function getList()
{
return view('admin.recipe.list');
}
public function getEdit()
{
return view('admin.recipe.edit');
}
public function getUnderApproval()
{
return view('admin.recipe.under_approval');
}
}
<file_sep><?php
namespace Bebella\Listeners\Mobile;
use Bebella\Redirection;
use Bebella\Events\Mobile\RedirectionToProductOptionUrl;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class UserProductOptionRedirectionRegistration
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param RedirectionToProductOptionUrl $event
* @return void
*/
public function handle(RedirectionToProductOptionUrl $event)
{
$redirection = new Redirection;
$redirection->user_id = $event->user->id;
$redirection->product_option_id = $event->productOption->id;
$redirection->recipe_id = $event->recipe->id;
$redirection->url = $event->productOption->store_url;
$redirection->save();
}
}
<file_sep><?php
namespace Bebella\Events\Mobile;
use Bebella\User;
use Bebella\Recipe;
use Bebella\ProductOption;
use Bebella\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ProductOptionWasViewed extends Event
{
use SerializesModels;
public $user;
public $recipe;
public $productOption;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(User $user, Recipe $recipe, ProductOption $productOption)
{
$this->user = $user;
$this->recipe = $recipe;
$this->productOption = $productOption;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
<file_sep>Bebella.controller('StoreListCtrl', ['$scope', 'StoreRepository',
function ($scope, StoreRepository) {
StoreRepository.all().then(
function onSuccess (list) {
$scope.stores = list;
},
function onError (res) {
alert("Erro ao obter a lista de lojas.");
}
);
}
]);
<file_sep>Bebella.controller('ProductOptionNewCtrl', ['$scope', 'StoreRepository', 'ProductRepository', 'ProductOptionRepository', 'CurrentProductOption',
function ($scope, StoreRepository, ProductRepository, ProductOptionRepository, CurrentProductOption) {
$scope.product_option = CurrentProductOption.get();
StoreRepository.all().then(
function onSuccess (list) {
$scope.stores = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de lojas");
}
);
ProductRepository.all().then(
function onSuccess (list) {
$scope.products = list;
},
function onError (res) {
alert("Houve um erro na obtenção da lista de lojas");
}
);
$scope.create = function () {
ProductOptionRepository.save($scope.product_option).then(
function onSuccess (product_option) {
alert(product_option.id);
alert("Opção de produto cadastrada com sucesso");
},
function onError (res) {
alert("Erro ao cadastrar opção de produto.");
}
);
};
$scope.clear = function () {
CurrentProductOption.clear();
$scope.product_option = CurrentProductOption.get();
};
}
]);
| 0acc0e525d948a95ea7e7b2a584faa9d21a831a7 | [
"JavaScript",
"PHP"
] | 79 | PHP | diegomrodz/BebellaBackend | 8f55ce29c9974634d535bd0546e976b9e3a8ee09 | 8ba3b8cb1e711aa9f6ce507a0d29e4bbc5300906 |
refs/heads/master | <repo_name>rakesh2277/flawless-rider-joblist-react-native-<file_sep>/src/screens/orderSingle/index.js
import React, { Component } from "react";
import { View, Text, ImageBackground, TouchableHighlight, TouchableOpacity, ScrollView, ActivityIndicator, Modal } from "react-native";
import { Body, Button, Card, CardItem, Container, Icon, Header, Title, Left } from 'native-base';
import styles from "./style";
import axios from 'axios';
import CONFIG from '../../config';
import { Col } from "react-native-easy-grid";
import { connect } from 'react-redux';
import { updateText } from "../../actions/index";
class OrderSingleScreen extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
variantTitle: '',
hideCUstomerNote: false,
MessageTemplate: '',
modalVisible: false,
agentId: '',
agentName: '',
userType: '',
order_line_item_detail: ''
}
}
componentDidMount() {
console.log('GETEGETE');
let idnrole = this.props.updateText_1.updateText.split('|__|');
this.setState({ userType: idnrole[0], agentId: idnrole[1], agentName: idnrole[2] })
let { navigation } = this.props;
let itemId = navigation.getParam('id');
let orderId = navigation.getParam('orderId');
let that = this;
axios({
method: 'post',
url: `${CONFIG.url}/responseClient.php?id=${orderId}&agentid=${idnrole[1]}`,
})
.then(function (responsedata) {
console.log(responsedata);
console.log('Client Response Recorded');
});
console.log(`${CONFIG.url}/orders_single.php?id=${itemId}&orderId=${orderId}`);
axios({
method: 'get',
url: `${CONFIG.url}/orders_single.php?id=${itemId}&orderId=${orderId}`,
responseType: 'json'
})
.then(function (response) {
console.log(response)
response.data != null && response.data != 'null' && response.data != '' ?
that.setState({ data: response.data.records, variantTitle: JSON.parse(response.data.records['0']['order_line_item_detail'])['variant_title'] })
:
that.setState({ data: [] })
});
}
_startClick = (data) => {
this.setState({ hideCUstomerNote: true });
axios.get(`${CONFIG.url}/sendemail.php?status=start&emailid=` + data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
_stopClick = (data) => {
this.setState({ hideCUstomerNote: false });
axios.get(`${CONFIG.url}/sendemail.php?status=stop&emailid=` + data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
_ststusClick = (key, id, orderid) => {
if(key == 'Available'){
this.setState({ hideCUstomerNote: false });
}else{
this.setState({ hideCUstomerNote: true });
}
let index = this.props.navigation.getParam('index');
axios({
method: 'post',
url: `${CONFIG.url}/updateStatus.php?usertype=${this.state.userType}&emailId=${this.state.data[0].email}&agentId=${this.state.agentId}&agentName=${this.state.agentName}&lineitem_id=${this.state.data[0].lineitem_id}&status=${key}&id=${id}&orderId=${orderid}&customer_name=${this.state.data[0].customer_name}&order_name=${this.state.data[0].order_name.replace('#', '')}&order_line_item_detail=${this.state.data[0].order_line_item_detail}`
}).then((response) => {
// console.log(response.data);
if (response.data.trim() == 'Already Reserved') {
alert('Already Reserved Order');
} else {
if (key == 'Available') {
console.log(`usertype=${this.state.userType}&agentId=${this.state.agentId}&agentName=${this.state.agentName}&status=${key}&id=${id}&orderId=${orderid}`);
this.props.navigation.state.params._updateStatus(key, index, '', '');
} else {
console.log(`usertype=${this.state.userType}&agentId=${this.state.agentId}&agentName=${this.state.agentName}&status=${key}&id=${id}&orderId=${orderid}`);
this.props.navigation.state.params._updateStatus(key, index, this.state.agentId, this.state.agentName);
}
}
// console.log(key);
})
}
_ststusSupportClick = (key, id, orderid) => {
this.setState({ modalVisible: true });
}
sendMailSupport = (supportdata) => {
this.setState({ modalVisible: false });
console.log(`${CONFIG.url}/sendemail.php?supportdata=${supportdata}&agentId=${this.state.agentId}&agentName=${this.state.agentName}&email=${this.state.data[0].email}&order_id=${this.state.data[0].order_id}&status=${this.state.data[0].status}&id=${this.state.data[0].id}&customer_name=${this.state.data[0].customer_name}&order_name=${this.state.data[0].order_name.replace('#', '')}&order_line_item_detail=${this.state.data[0].order_line_item_detail}`);
axios({
method: 'post',
url: `${CONFIG.url}/sendemail.php?supportdata=${supportdata}&agentId=${this.state.agentId}&agentName=${this.state.agentName}&email=${this.state.data[0].email}&order_id=${this.state.data[0].order_id}&status=${this.state.data[0].status}&id=${this.state.data[0].id}&customer_name=${this.state.data[0].customer_name}&order_name=${this.state.data[0].order_name.replace('#', '')}&order_line_item_detail=${this.state.data[0].order_line_item_detail}`
}).then((response) => {
alert('Email Sent');
console.log(response.data);
})
}
_colorCodeStatus = (key) => {
switch (key) {
case 'start':
return 'yellow'
break;
case 'active':
return 'yellow'
break;
case 'completed':
return '#6FDA44'
break;
case 'stuck':
return '#FE0000'
break;
case 'priority':
return '#f26522'
break;
case 'support':
return 'purple'
break;
default:
return '#2D7E08'
break;
}
}
render() {
const { goBack } = this.props.navigation;
return (
<Container style={{}}>
<Header androidStatusBarColor='#000' style={styles.blackBackground}>
<Left>
<Button transparent onPress={() => goBack()} >
<Icon name='arrow-back' />
</Button>
</Left>
<Body>
<Title style={styles.bodyTitle}>ORDER DETAILS</Title>
</Body>
</Header>
{this.state.data.length > 0 ?
<ImageBackground source={require('../../assets/bg.png')} style={styles.imageBackground}>
<ScrollView>
<Card style={styles.firstCard}>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
{/* <Text style={styles.firstCardBodyText}>ORDER Name</Text> */}
<Text style={styles.firstCardBodyText_sec}>{this.state.data['0']['line_item_title']}</Text>
<Text style={styles.firstCardBodyText_sec}>Order-Id:{this.state.data['0']['order_name']}</Text>
</Body>
</CardItem>
</Card>
<View style={styles.secondView}>
<Text style={styles.secondViewText}>{'\u00A9'} An Email has been sent to {this.state.data['0']['email']}</Text>
</View>
<CardItem style={{ backgroundColor: '#111111' }}>
<Body style={styles.statusAllWrapperFirstInner}>
<TouchableOpacity onPress={() => this._ststusClick('active', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.startStatusWrp}>
<Text style={styles.startStopStatus}>START</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this._ststusClick('Available', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.stopStatusWrp}>
<Text style={styles.startStopStatus} >STOP</Text>
</TouchableOpacity>
</Body>
</CardItem>
{this.state.data['0']['customer_email_na'] != '' && this.state.hideCUstomerNote &&
(<Card style={styles.customerInfoWrp}>
<CardItem style={styles.blackBackground}>
<Body style={styles.customernotewrapcust}>
<Text style={styles.firstCardBodyText_sec}>Email: {this.state.data['0']['customer_email_na']}</Text>
<Text style={styles.firstCardBodyText_sec}>Password: {this.state.data['0']['customer_password_na']}</Text>
<Text style={styles.firstCardBodyText_sec}>Gamertag: {this.state.data['0']['customer_gamertag_na']}</Text>
<Text style={styles.firstCardBodyText_sec}>Browser Ip: {this.state.data['0']['browser_ip']}</Text>
</Body>
</CardItem>
</Card>
)
}
{this.state.data['0']['note'] != '' &&
<Card style={styles.customerInfoWrp}>
<CardItem style={styles.blackBackground}>
<Body style={styles.customernotewrap}>
<Text style={styles.firstCardBodyText}>CUSTOMER NOTE</Text>
<Text style={styles.firstCardBodyText_sec}>{this.state.data['0']['note']}</Text>
</Body>
</CardItem>
</Card>
}
<Card style={styles.additionalDetails}>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
{/* <Text style={styles.firstCardBodyText}>ADDITIONAL DETAILS</Text> */}
<Text style={styles.firstCardBodyText_sec}>{this.state.data['0']['order_attribute']}</Text>
</Body>
</CardItem>
</Card>
{this.state.variantTitle != '' ?
<Card style={styles.additionalDetails}>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
{/* <Text style={styles.firstCardBodyText}>VARIANTS</Text> */}
<Text style={styles.firstCardBodyText_sec}>{this.state.variantTitle}</Text>
</Body>
</CardItem>
</Card>
: <Text></Text>}
{this.state.data['0']['agentHistory'] != '' ?
<Card style={styles.agentHistory}>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
<Text style={styles.firstCardBodyText}>ORDER HISTORY</Text>
<Text style={styles.firstCardBodyText_sec}>Started by: #{this.state.agentId} {this.state.agentName}</Text>
<Text style={styles.firstCardBodyText_sec}>Current Status: <Text style={{ backgroundColor: this._colorCodeStatus(this.state.data['0']['status']), color: '#000' }}>{this.state.data['0']['status']}</Text></Text>
{
this.state.data['0']['agentHistory']['status'] == undefined && JSON.parse(this.state.data['0']['agentHistory']).length != undefined ? (
<View>
{
JSON.parse(this.state.data['0']['agentHistory']).map((item, index, array) => {
return (
<Text key={index} style={{ color: '#ffffff', borderLeftWidth:1, borderLeftColor:'#ffffff', paddingBottom:5, paddingLeft:5 }}>{`-- `} {item.status} at {item.time}</Text>
)
})
}
</View>
) :
<Text style={{ color: '#ffffff' }}>{JSON.parse(this.state.data['0']['agentHistory'])['status']} at {JSON.parse(this.state.data['0']['agentHistory'])['time']}</Text>
}
</Body>
</CardItem>
</Card>
:
<Text></Text>
}
<Card style={styles.allTransparent}>
<CardItem style={styles.statusAllWrapper}>
<Body style={styles.statusAllWrapperFirstInner}>
{/* <Col style={styles.statusAllWrapperInner}> */}
<TouchableOpacity onPress={() => this._ststusClick('active', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.activeStatus}>
<Text style={styles.statusTextActive}>ACTIVE</Text>
</TouchableOpacity>
{/* </Col>
<Col style={styles.statusAllWrapperInner}> */}
<TouchableOpacity onPress={() => this._ststusClick('completed', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.completedStatus}>
<Text style={styles.statusofOrder} >COMPLETED</Text>
</TouchableOpacity>
{/* </Col> */}
{/* <Col style={styles.statusAllWrapperInner}> */}
<TouchableOpacity onPress={() => this._ststusClick('stuck', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.stuckStatus}>
<Text style={styles.statusofOrder} >STUCK</Text>
</TouchableOpacity>
{/* </Col> */}
{/* <Col style={styles.statusAllWrapperInner}> */}
<TouchableOpacity onPress={() => this._ststusClick('priority', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.priorityStatus}>
<Text style={styles.statusofOrder} >PRIORITY</Text>
</TouchableOpacity>
{/* </Col> */}
</Body>
</CardItem>
</Card>
<Card style={styles.statusNeedSupport}>
<CardItem style={styles.backgroundTranparent}>
<Body style={styles.wrapperNeedSupportText}>
<TouchableOpacity onPress={() => this._ststusSupportClick('support', this.state.data['0']['id'], this.state.data['0']['order_id'])} style={styles.backgroundNeedSupport}>
<Text style={styles.backgroundNeedSupportText} >Need Support</Text>
</TouchableOpacity>
</Body>
</CardItem>
</Card>
</ScrollView>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View>
<ImageBackground source={require('../../assets/bg.png')} style={styles.imageBackground}>
<Card style={styles.firstCard}>
<CardItem style={styles.backgroundColor}>
<TouchableHighlight
onPress={() => {
// this.setModalVisible(!this.state.modalVisible);
this.setState({ modalVisible: false });
}}>
<Text style={styles.firstCardBodyText}>CLOSE</Text>
</TouchableHighlight>
</CardItem>
</Card>
<ScrollView>
<Card style={styles.firstCard}>
<CardItem style={styles.backgroundColor} >
<Body style={styles.firstCardBody}>
<Text onPress={() => this.sendMailSupport('password')} style={styles.firstCardBodyText}>Wrong Password or email</Text>
</Body>
</CardItem>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
<Text onPress={() => this.sendMailSupport('character')} style={styles.firstCardBodyText}>Which Character?</Text>
</Body>
</CardItem>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
<Text onPress={() => this.sendMailSupport('vcode')} style={styles.firstCardBodyText}>Need Verification code</Text>
</Body>
</CardItem>
<CardItem style={styles.backgroundColor}>
<Body style={styles.firstCardBody}>
<Text onPress={() => this.sendMailSupport('other')} style={styles.firstCardBodyText}>Other..</Text>
</Body>
</CardItem>
</Card>
</ScrollView>
</ImageBackground>
</View>
</Modal>
</ImageBackground>
:
<View style={styles.dataEmpty}>
<ActivityIndicator size="large" color="#3f3f3f" />
</View>
}
</Container>
)
}
}
function mapStateToProps(state) {
return {
updateText_1: state.userRole
}
}
function mapDispatchToProps(dispatch) {
return {
updateText: (text) => dispatch(updateText(text)),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(OrderSingleScreen)<file_sep>/src/screens/BlogPost/index.js
import React, { Component } from "react";
import { Text, ImageBackground, View, TouchableOpacity, ScrollView, KeyboardAvoidingView } from "react-native";
import { Body, Button, Container, Icon, Header, Title, Left, Input } from 'native-base';
import styles from "./style";
import axios from 'axios';
import CONFIG from '../../config';
export default class BlogPost extends Component {
constructor(props) {
super(props);
this.state = {
blogTitle: '',
blogBody: '',
downloadLink: ''
}
}
downloadFormData = () => {
// Add form download link ( Admin functionality )
axios({
method: 'post',
url: `${CONFIG.url}/taxFileDownload.php?link=${this.state.downloadLink}`,
})
.then(function (response) {
if (response.data == 'success') {
alert('Link Submitted Successfully');
} else {
alert('Technical Error');
}
});
}
submitBlog = () => {
// Add Blog Post ( Admin functionality )
axios({
method: 'post',
url: `${CONFIG.url}/postBlogs.php?blogTitle=${this.state.blogTitle}&blogBody=${this.state.blogBody}`,
})
.then(function (response) {
if (response.data == 'success') {
alert('Blog Submitted Successfully');
} else if (response.data == 'exist') {
alert('This Blog Title is already available');
} else {
alert('Technical Error');
}
});
}
render() {
const { goBack } = this.props.navigation;
return (
<Container style={{}}>
<Header androidStatusBarColor='#000' style={{ backgroundColor: '#000' }}>
<Left>
<Button transparent onPress={() => goBack()} >
<Icon name='arrow-back' style={{ color: '#ffffff' }} />
</Button>
</Left>
<Body>
<Title style={styles.bodyTitle}>News Post</Title>
</Body>
</Header>
<ImageBackground source={require('../../assets/bg.png')} style={styles.imageBackground}>
<KeyboardAvoidingView behavior="padding" enabled>
<ScrollView style={styles.mainWrap}>
<View style={styles.textAreaContainerfirst}>
<Input
secureTextEntry={false}
placeholder="Blog Title"
placeholderTextColor="#FFFFFF"
onChangeText={(blogTitle) => { this.setState({ blogTitle }); }}
value={this.state.blogTitle}
style={styles.formInput}
/>
{this.state.error == 1 ? <Icon style={styles.error} name='close-circle' /> : null}
</View>
<View style={styles.textAreaContainer} >
<Input
style={styles.formInput}
placeholderTextColor="#FFFFFF"
placeholder="News Content"
numberOfLines={15}
multiline={true}
value={this.state.blogBody}
onChangeText={(blogBody) => { console.log(blogBody); this.setState({ blogBody }); }}
/>
</View>
<View style={{ height: 50 }}>
<TouchableOpacity style={styles.postSubmitButton} onPress={() => this.submitBlog()}>
<Text style={styles.postSubmitButtonText}>Submit</Text>
</TouchableOpacity>
</View>
<Text style={{ borderWidth: 4, margin: 10 }}></Text>
<View style={styles.textAreaContainerfirst} >
<Input
style={styles.formInput}
placeholderTextColor="#FFFFFF"
placeholder="Add File Download Link"
numberOfLines={15}
multiline={true}
value={this.state.downloadLink}
onChangeText={(downloadLink) => { console.log(downloadLink); this.setState({ downloadLink }); }}
/>
</View>
<View style={{ height: 50 }}>
<TouchableOpacity style={styles.postSubmitButton} onPress={() => this.downloadFormData()}>
<Text style={styles.postSubmitButtonText}>Add Link</Text>
</TouchableOpacity>
</View>
</ScrollView>
</KeyboardAvoidingView>
</ImageBackground>
</Container>
);
}
}
<file_sep>/src/screens/team/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
firstCol: {
backgroundColor: '#3f3f3f', height: 150, borderRadius: 12, marginLeft: 10, marginTop: 50, justifyContent: 'center', alignItems: 'center'
},
colImageDimensions: {
width: 51, height: 51
},
colButtonWrap: {
justifyContent: 'center', alignItems: 'center'
},
colSecondWrp: {
backgroundColor: '#3f3f3f', height: 150, borderRadius: 12, marginRight: 10, marginLeft: 10, marginTop: 50, paddingTop: 10, justifyContent: 'center', alignItems: 'center'
},
colSecondText: {
color: '#FFFFFF', fontFamily: 'Enter-The-Grid', fontSize: 21, textAlign: 'center', lineHeight: 25, paddingTop: 15
},
colThird: {
backgroundColor: '#3f3f3f', height: 150, borderRadius: 12, marginRight: 10, marginTop: 50, justifyContent: 'center', alignItems: 'center'
},
colThirdText: {
color: '#FFFFFF', fontFamily: 'Enter-The-Grid', fontSize: 21, lineHeight: 25, paddingTop: 15
},
colFirstText: {
color: '#FFFFFF', fontFamily: 'Enter-The-Grid', fontSize: 21, lineHeight: 25, paddingTop: 15
},
imgBackground: {
width: '100%', height: '100%'
},
headerTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1, color:'#ffffff'
},
backgroundColor: {
backgroundColor: '#000'
},
animatedView: {
width: deviceWidth - 20,
backgroundColor: "#424040",
elevation: 2,
position: "absolute",
bottom: 0,
padding: 10,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
left: 0,
right: 0,
textAlign: 'center',
marginLeft: 10
},
exitTitleText: {
textAlign: "center",
color: "#ffffff",
marginRight: 10,
},
exitText: {
color: "#e5933a",
paddingHorizontal: 10,
paddingVertical: 3
}
}<file_sep>/src/screens/support/index.js
import React, { Component } from "react";
import { View, Text, ImageBackground, TouchableOpacity, ActivityIndicator, FlatList } from "react-native";
import { Body, Button, Card, CardItem, Container, Icon, Left, Header, Title ,Right} from 'native-base';
import styles from "./style";
import axios from 'axios';
import CONFIG from '../../config';
import { connect } from 'react-redux';
import { updateText } from "../../actions/index";
class SupportScreen extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
agentType: '',
agent_data: [],
agentId: '',
agentPhoneNumber: '',
agentName: '',
agentEmail: '',
dataAgent: [],
loader: 0
}
}
componentDidMount = () => {
let idnrole = this.props.updateText_1.updateText.split('|__|');
this.setState({ agentType: idnrole[0], agentId: idnrole[1], agentName: idnrole[2], agentPhoneNumber: idnrole[4], agentEmail: idnrole[5] })
if (idnrole[0] == 'admin') {
axios({
method: 'get',
url: `${CONFIG.url}/reademail.php?userType=admin`,
// responseType: 'json'
})
.then((response) => {
console.log(response);
response.data.records != undefined && response.data.records != '' && response.data.records != 'undefined' && response.data.records != 'error' ?
this.setState({ data: response.data.records, loader: 1 })
:
this.setState({ data: [], loader: 1 })
});
}
if (idnrole[0] == 'agent') {
axios({
method: 'get',
url: `${CONFIG.url}/reademail.php?userType=agent&agentId=${idnrole[1]}`,
// responseType: 'json'
})
.then((response) => {
console.log(response);
response.data.records != undefined && response.data.records != '' && response.data.records != 'undefined' && response.data.records != 'error' ?
this.setState({ dataAgent: response.data.records, loader: 1 })
:
this.setState({ dataAgent: [], loader: 1 })
});
}
}
render() {
const { goBack } = this.props.navigation;
return (
<Container style={{}}>
<Header androidStatusBarColor='#000' style={styles.blackBackground}>
<Left style={{flex:1}}>
<Button transparent onPress={() => goBack()} >
<Icon name='arrow-back' style={{ color: '#ffffff' }} />
</Button>
</Left>
<Body style={{alignItems:'center',justifyContent:'center', flex:1}}>
<Title style={styles.bodyTitleText}>SUPPORT</Title>
</Body>
<Right style={{flex:1}}>
<Button transparent >
<Icon />
</Button>
</Right>
</Header>
<ImageBackground source={require('../../assets/bg.png')} style={styles.imgBackground}>
<View style={styles.imgBackgroundInnerView}>
<TouchableOpacity style={{ padding: 20 }}>
<Text style={styles.buttonTopBar}>LIVE CHAT</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.inboxButton}>
<Text style={styles.buttonTopBar} >INBOX</Text>
</TouchableOpacity>
</View>
{
this.state.data.length > 0 && this.state.agentType == 'admin' ?
<FlatList
data={this.state.data}
extraData={this.state}
renderItem={({ item, key, index }) =>
(
<Card style={styles.cardWrapper}>
<CardItem style={styles.backgroundColor}>
<Body style={styles.backgroundColor}>
<Text style={styles.cardFirstText}>Email ID: {item.id}</Text>
<Text style={styles.textItem_time}>SUBJECT: {item.subject}</Text>
<Text style={styles.textItem_time}>MESSAGE:</Text>
<Text style={styles.cardFourthText}>{item.message} </Text>
<View style={styles.cardFifthTextWrapper}>
<Text style={styles.topBarAgentName}>CUSTOMER: </Text>
<Text style={styles.topBarAgentNameM}>{item.from}</Text>
</View>
<Text style={styles.textItem_time}>Time: {item.date}</Text>
</Body>
</CardItem>
</Card>
)}
keyExtractor={item => item.id.toString()}
/>
:
<View style={styles.cardFirstText}>
{
this.state.loader == 0 ?
<ActivityIndicator size="large" color="#ffffff" />
:
<Text style={styles.cardFirstTextNop}></Text>
}
</View>
}
{
this.state.dataAgent.length > 0 && this.state.agentType == 'agent' ?
<FlatList
data={this.state.dataAgent}
extraData={this.state}
renderItem={({ item, key, index }) =>
(
<Card style={styles.cardWrapper}>
<CardItem style={styles.backgroundColor}>
<Body style={styles.backgroundColor}>
<Text style={styles.cardFirstText}>Email ID: {item.id}</Text>
<Text style={styles.textItem_time}>SUBJECT: {item.subject.replace("Re:", '')}</Text>
<Text style={styles.textItem_time}>MESSAGE:</Text>
<Text style={styles.cardFourthText}>{item.message} </Text>
<View style={styles.cardFifthTextWrapper}>
<Text style={styles.topBarAgentName}>CUSTOMER: </Text>
<Text style={styles.topBarAgentNameM}>{item.from}</Text>
</View>
<Text style={styles.textItem_time}>Time: {item.date}</Text>
</Body>
</CardItem>
</Card>
)}
keyExtractor={item => item.id.toString()}
/>
:
<View style={styles.cardFirstText}>
{
this.state.loader == 0 ?
// <ActivityIndicator size="large" color="#ffffff" />
<Text></Text>
:
<Text style={styles.cardFirstTextNop}></Text>
}
</View>
}
<View style={{ padding: 30 }} />
</ImageBackground>
</Container>
);
}
}
function mapStateToProps(state) {
return {
updateText_1: state.userRole
}
}
function mapDispatchToProps(dispatch) {
return {
updateText: (text) => dispatch(updateText(text)),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(SupportScreen)<file_sep>/src/reducers/userRole.js
let initialState = {
updateText: null
}
export default function userRole (state = initialState, action) {
switch (action.type) {
case 'updateText':
return {
...state,
updateText: action.text
}
break;
default:
return state
}
}<file_sep>/src/screens/screenBasedOnUser/index.js
import React, { Component } from "react";
import { AsyncStorage } from 'react-native';
import Myorder from '../myorder';
import MyOrdersAgent from '../MyOrdersAgent';
import { View } from 'react-native';
export default class ScreenBasedOnUser extends Component {
constructor(props) {
super(props);
this.state = {
userType: ''
}
}
componentDidMount() {
AsyncStorage.getItem('userflaw', (err, result) => {
console.log(result);
this.setState({ userType: result})
})
}
render() {
return (
<View>
{
this.state.userType == 'admin' ?
<Myorder navigation={this.props.navigation}/>
:
<View></View>
}
{
this.state.userType == 'agent' ?
<MyOrdersAgent navigation={this.props.navigation} />
:
<View></View>
}
</View>
);
}
}
<file_sep>/src/screens/registration/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
import color from "color";
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
container: {
alignItems: "center",
backgroundColor: "transparent",
color: "#fff",
justifyContent: "center",
flex: 1,
},
formButtonSub: {
margin: 10,
},
formButtonSubText: {
color: "#fff",
fontSize: 18,
fontWeight: "600",
},
formContainer: {
marginTop: 5,
justifyContent: 'center',
alignItems: 'center',
width: deviceWidth - 20,
backgroundColor: '#000',
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
borderBottomRightRadius: 20,
borderBottomRightRadius: 20,
marginLeft: 10,
marginRight: 10,
paddingTop: 20,
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
},
formInput: {
backgroundColor: "transparent",
borderWidth: 0,
borderRadius: 0,
elevation: 0,
shadowOpacity: 0,
shadowRadius: 0,
color: '#fff',
fontFamily: 'Chosence Light',
fontSize: 18,
paddingLeft: 12,
letterSpacing: 5,
marginTop: 10,
},
formInputDropDown: {
backgroundColor: "transparent",
borderWidth: 200,
borderRadius: 0,
elevation: 0,
shadowOpacity: 0,
shadowRadius: 0,
color: '#000',
fontFamily: 'Chosence Light',
fontSize: 18,
marginTop: 10,
position:'relative'
},
helpButtonRight: {
alignItems: "flex-end",
justifyContent: "flex-end",
},
helpTextLeft: {
textAlign: "left",
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpTextRight: {
textAlign: "right",
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpRowCenter: {
alignItems: "center",
justifyContent: "center",
marginTop: 2,
},
helpTextCenter: {
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpRowCenterForgetPass: {
alignItems: "center",
justifyContent: "center",
marginTop: 2,
},
helptextCenterForgetPass: {
color: "#b08d58",
fontWeight: "600",
fontSize: 14,
},
listItemCheckBox: {
borderBottomWidth: 0,
},
listItemCheckBoxText: {
paddingLeft: 15,
},
logoutText: {
color: '#fff',
fontSize: 20,
},
success: {
color: "green",
paddingLeft: 5,
},
error: {
color: "red",
paddingLeft: 5,
},
botom: {
width: deviceWidth,
marginLeft: 10
},
buttonStyle: {
padding: 10,
margin: 40,
alignItems: 'flex-end',
justifyContent: 'flex-end'
},
imageDimensions: {
width: 26, height: 20
},
viewWrapper: {
justifyContent: 'center', alignItems: 'center', paddingTop: 10, paddingBottom: 4
},
bodyTitleText: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1
},
imgBackgroundW: {
width: '100%',
height: '100%'
},
imgDimensions: {
width: 250, height: 80
},
imageDimensionsMultilsect: {
width: 26,
height: 20,
// position: 'fixed',
// top: 0,
// left: 0,
// right: 0,
// bottom: 0,
},
passwordFieldImgDimensions: {
width: 17, height: 23
},
formSubmit: {
width: '100%', padding: 15, justifyContent: 'flex-end', alignItems: 'flex-end', alignContent: 'flex-end'
},
formSubmitImgBtn: {
width: 65, height: 65
},
blckBackground: {
backgroundColor: '#000'
}
};<file_sep>/src/screens/login/index.js
import React, { Component } from "react";
import { View, Text, ImageBackground, Image, TouchableOpacity, AsyncStorage, BackHandler, Animated, Dimensions } from "react-native";
import { Container, Form, Icon, Input, Item, Header, Title } from 'native-base';
import styles from "./style";
import axios from 'axios';
let { height } = Dimensions.get('window');
import { connect } from 'react-redux';
import { updateText } from "../../actions/index";
import CONFIG from '../../config';
import RNFetchBlob from 'rn-fetch-blob'
class LoginScreen extends Component {
constructor(props) {
super(props);
this.springValue = new Animated.Value(100);
this.state = {
uname: null,
password: <PASSWORD>,
error: 0,
navigate: this.props.navigation.navigate,
signInBox: 0,
success: 0,
backClickCount: 0
}
}
redirectToOrder = () => {
axios({
method: 'get',
url: `${CONFIG.url}/Login_user_role.php?username=${this.state.uname}&password=${<PASSWORD>}`,
})
.then((response) => {
console.log(response.data);
if (response.data == 'nulldata') {
alert('Invalid UserName and Password')
} else {
this.props.updateText(response.data.records['0']['role'] + "|__|" + response.data.records['0']['id'] + "|__|" + response.data.records['0']['agentname'] + "|__|" + response.data.records['0']['numberofrecords'] + "|__|" + response.data.records['0']['phonenumber'] + "|__|" + response.data.records['0']['email']+"#"+response.data.records['0']['teamname'])
AsyncStorage.setItem('userflaw', response.data.records['0']['role']);
AsyncStorage.setItem('userflawLogin', 'login');
this.setState({ uname: '', password: '' })
this.props.navigation.navigate('Home')
}
});
}
componentDidMount = () => {
// Add Hardware back button Event
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
// Remove Hardware back button Event
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillReceiveProps = () => {
// Add Hardware back button Event
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
_spring() {
// Exit App, Animated popup
this.setState({ backClickCount: 1 }, () => {
Animated.sequence([
Animated.spring(
this.springValue,
{
toValue: -.02 * height,
friction: 5,
duration: 300,
useNativeDriver: true,
}
),
Animated.timing(
this.springValue,
{
toValue: 100,
duration: 300,
useNativeDriver: true,
}
),
]).start(() => {
this.setState({ backClickCount: 0 });
});
});
}
handleBackButton = () => {
// Back Button Handler
this.state.backClickCount == 1 ? BackHandler.exitApp() : this._spring();
return true;
};
render() {
return (
<Container>
<Header androidStatusBarColor='#000' style={styles.headerBackground}>
<Title style={styles.headerTitle}>LOG IN</Title>
</Header>
<Animated.View style={[styles.animatedView, { transform: [{ translateY: this.springValue }] }]}>
<Text style={styles.exitTitleText}>Double press to exit the app</Text>
<TouchableOpacity
activeOpacity={0.9}
onPress={() => BackHandler.exitApp()}
>
<Text style={styles.exitText}>Exit</Text>
</TouchableOpacity>
</Animated.View>
<ImageBackground source={require('../../assets/bg.png')} style={styles.ImageBackground}>
<View style={styles.logoWrapper}>
<Image source={require('../../assets/logoapp.png')} style={styles.logoInner} />
</View>
<Form style={styles.formContainer}>
<Item style={styles.formItem}>
<Image source={require('../../assets/id-card.png')} style={styles.username} />
<Input
placeholder="UserName"
placeholderTextColor="#FFFFFF"
onChangeText={(uname) => { this.setState({ uname }); }}
value={this.state.uname}
style={styles.formInput}
/>
{this.state.error == 1 ? <Icon style={styles.error} name='close-circle' /> : null}
</Item>
<Item style={styles.formItem}>
<Image source={require('../../assets/lock.png')} style={styles.password} />
<Input
secureTextEntry={true}
placeholder="Password"
placeholderTextColor="#FFFFFF"
onChangeText={(password) => { this.setState({ password }); }}
value={this.state.password}
style={styles.formInput}
/>
{this.state.error == 1 ? <Icon style={styles.error} name='close-circle' /> : null}
</Item>
<View style={styles.loginButton}>
<TouchableOpacity onPress={() => this.redirectToOrder()}>
<Image source={require('../../assets/login.png')} style={styles.loginButtonImage} />
</TouchableOpacity>
</View>
</Form>
</ImageBackground>
</Container>
);
}
}
function mapStateToProps(state) {
return {
updateText_1: state.userRole
}
}
function mapDispatchToProps(dispatch) {
return {
updateText: (text) => dispatch(updateText(text)),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginScreen)<file_sep>/src/screens/customMessage/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
import color from "color";
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
container: {
alignItems: "center",
backgroundColor: "transparent",
color: "#fff",
justifyContent: "center",
flex: 1,
},
formButtonSub: {
margin: 10,
},
formButtonSubText: {
color: "#fff",
fontSize: 18,
fontWeight: "600",
},
formContainer: {
marginTop: 5,
justifyContent: 'center',
alignItems: 'center',
width: deviceWidth - 20,
backgroundColor: '#000',
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
borderBottomRightRadius: 20,
borderBottomRightRadius: 20,
marginLeft: 10,
marginRight: 10,
paddingTop: 40,
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
},
formInput: {
backgroundColor: "transparent",
borderWidth: 0,
borderRadius: 0,
elevation: 0,
shadowOpacity: 0,
shadowRadius: 0,
color: '#fff',
fontFamily: 'Chosence Light',
fontSize: 18,
paddingLeft: 12,
letterSpacing: 5,
marginTop: 10,
},
headerBackground: {
backgroundColor: '#000'
},
headerTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1
},
ImageBackground: {
width: '100%', height: '100%'
},
helpButtonRight: {
alignItems: "flex-end",
justifyContent: "flex-end",
},
helpTextLeft: {
textAlign: "left",
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpTextRight: {
textAlign: "right",
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpRowCenter: {
alignItems: "center",
justifyContent: "center",
marginTop: 2,
},
helpTextCenter: {
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpRowCenterForgetPass: {
alignItems: "center",
justifyContent: "center",
marginTop: 2,
},
helptextCenterForgetPass: {
color: "#b08d58",
fontWeight: "600",
fontSize: 14,
},
listItemCheckBox: {
borderBottomWidth: 0,
},
listItemCheckBoxText: {
paddingLeft: 15,
},
logoWrapper: {
justifyContent: 'center', alignItems: 'center', paddingTop: 25, paddingBottom: 25
},
logoInner: {
width: 250, height: 100
},
logoutText: {
color: '#fff',
fontSize: 20,
},
loginButton: {
backgroundColor:'#ffffff', justifyContent: 'flex-end', alignItems: 'flex-end', alignContent: 'flex-end', marginBottom: 10, marginTop: 10
},
loginButtonImage: {
width: 65, height: 65
},
success: {
color: "green",
paddingLeft: 5,
},
error: {
color: "red",
paddingLeft: 5,
},
botom: {
width: deviceWidth,
marginLeft: 10
},
buttonStyle: {
padding: 10,
margin: 40,
alignItems: 'flex-end',
justifyContent: 'flex-end'
},
username: {
width: 26, height: 20
},
password: {
width: 17, height: 23
},
signupButton: {
color: '#000000', fontFamily: 'Enter-The-Grid', fontSize: 20, letterSpacing: 2, padding:15
},
signupButtonWrapper: {
paddingBottom: 30, justifyContent:'flex-end', alignItems:'flex-end'
}
};<file_sep>/src/screens/BlogPost/style.js
const React = require("react-native");
const { Dimensions } = React;
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
backgroundColor: {
backgroundColor: '#3f3f3f'
},
bodyTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1
},
rowFirstColumn: {
backgroundColor: '#3f3f3f', borderRightColor: '#000', borderRightWidth: 2, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: 10
},
rowFirstColumnText: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 20
},
rowSecColumn: {
backgroundColor: '#3f3f3f', justifyContent: 'center', alignItems: 'center', borderTopRightRadius: 10, borderBottomRightRadius: 10, padding: 10, marginRight: 10
},
rowSecColumnText: {
color: '#fff', fontFamily: 'RobotoCondensed-Light', fontSize: 20, lineHeight: 22
},
formInput: {
backgroundColor: "transparent",
borderWidth: 0,
borderRadius: 0,
elevation: 0,
shadowOpacity: 0,
shadowRadius: 0,
color: '#fff',
fontFamily: 'Chosence Light',
fontSize: 18,
paddingLeft: 12,
letterSpacing: 5,
marginTop: 10,
},
imageBackground: {
width: '100%', height: '100%'
},
textAreaContainer: {
borderColor: 'grey',
borderWidth: 1,
padding: 5,
height: 250,
marginTop: 15
},
textAreaContainerfirst: {
borderColor: 'grey',
borderWidth: 1,
padding: 5,
height: 80,
marginTop: 15
},
textArea: {
height: 100,
justifyContent: "center"
},
postSubmitButton: {
justifyContent: 'center',
alignItems: 'flex-start',
marginTop: 15,
padding: 5
},
postSubmitButtonText: {
color: '#000000',
fontFamily: 'Chosence Light',
backgroundColor: "#ffffff",
padding: 5,
justifyContent: 'center',
alignItems: 'center',
fontSize: 20
},
mainWrap: {
width: deviceWidth - 20,
marginLeft: 10,
marginRight: 10
}
}<file_sep>/src/screens/news/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
backgroundColor: {
backgroundColor: '#3f3f3f'
},
bodyTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1,color:'#ffffff'
},
rowFirstColumn: {
backgroundColor: '#3f3f3f', borderRightColor: '#000', borderRightWidth: 2, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 5, marginLeft: 10
},
rowFirstColumnDownload:{
backgroundColor: '#3f3f3f', justifyContent: 'center', alignItems: 'center', padding: 5, marginLeft: 10
},
rowFirstColumnText: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 20
},
rowSecColumn: {
backgroundColor: '#3f3f3f', justifyContent: 'center', alignItems: 'center', borderTopRightRadius: 10, borderBottomRightRadius: 10, padding: 10, marginRight: 10
},
rowSecColumnText: {
color: '#fff', fontFamily: 'RobotoCondensed-Light', fontSize: 20, lineHeight: 22
},
formInput: {
backgroundColor: "transparent",
borderWidth: 0,
borderRadius: 0,
elevation: 0,
shadowOpacity: 0,
shadowRadius: 0,
color: '#fff',
fontFamily: 'Chosence Light',
fontSize: 18,
paddingLeft: 12,
letterSpacing: 5,
marginTop: 10,
},
imageBackground: {
width: '100%', height: '100%'
},
textAreaContainer: {
borderColor: 'grey',
borderWidth: 1,
padding: 5,
height: 250,
marginTop: 15
},
textAreaContainerfirst: {
borderColor: 'grey',
borderWidth: 1,
padding: 5,
height: 80,
marginTop: 15
},
textArea: {
height: 100,
justifyContent: "center"
},
postSubmitButton: {
justifyContent: 'center',
alignItems: 'flex-start',
marginTop: 15,
padding: 5
},
postSubmitButtonText: {
color: '#000000',
fontFamily: 'Chosence Light',
backgroundColor: "#ffffff",
padding: 5,
justifyContent: 'center',
alignItems: 'center',
fontSize: 20
},
mainWrap: {
width: deviceWidth - 20,
marginLeft: 10,
marginRight: 10
},
actionSheetTextStyle: {
fontSize: 16, fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', color: '#ffffff', justifyContent: 'center', alignItems: 'center'
},
actionSheetTextStyle_c: {
fontSize: 16, fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', color: '#000000', justifyContent: 'center', alignItems: 'center'
},
startAction: {
width: '100%', backgroundColor: 'grey', justifyContent: 'center', alignItems: 'center', flex: 1
},
activeAction: {
width: '100%', backgroundColor: 'yellow', justifyContent: 'center', alignItems: 'center', flex: 1
},
priorityAction: {
width: '100%', backgroundColor: 'orange', justifyContent: 'center', alignItems: 'center', flex: 1
},
stuckAction: {
width: '100%', backgroundColor: 'red', justifyContent: 'center', alignItems: 'center', flex: 1
},
needSupportAction: {
width: '100%', backgroundColor: 'purple', justifyContent: 'center', alignItems: 'center', flex: 1
},
completedAction: {
width: '100%', backgroundColor: '#6FDA44', justifyContent: 'center', alignItems: 'center', flex: 1
},
cancleAction: {
width: '100%', backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center', flex: 1
},
filterText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 18
},
wrapperMyOrder: {
width: '18%', backgroundColor: '#3f3f3f', height: 78, borderRightColor: '#000', borderRightWidth: 1, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: '2%'
},
itemStatus: {
minWidth: 90, justifyContent: 'center', alignItems: 'center', flexDirection: 'row'
},
itemStatusText: {
color: '#000', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 15, flexDirection: 'row'
},
itemTitle: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 17, paddingLeft: 5, paddingRight: 5
},
createdDate: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 14, paddingLeft: 5, paddingRight: 5, marginTop: 5
},
itemTitleWrapper: {
width: '40%', backgroundColor: '#3f3f3f', height: 78, justifyContent: 'center', alignItems: 'center'
},
reservedAgent: {
color: '#000', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 12
},
itemPrice: {
width: '18%', backgroundColor: '#000000', height: 78, justifyContent: 'center', alignItems: 'center', padding: 10, marginRight: '2%'
},
itemPriceInputField: {
borderColor: '#ffffff', borderWidth: 1, color: '#fff', fontSize: 12
},
backGroundColorMyOrder: {
backgroundColor: '#3f3f3f'
},
backGroundColorBody: {
backgroundColor: '#3f3f3f', justifyContent: 'center', alignItems: 'center'
},
cardItem: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 21, paddingBottom: 5, letterSpacing: 2
},
cardMain: {
backgroundColor: '#3f3f3f', marginLeft: 10, marginRight: 10, paddingTop: 5, paddingBottom: 5, borderColor: 'transparent'
},
emptyData: {
flex: 1, justifyContent: 'center', alignItems: 'center'
},
emptyDataText: {
borderRightWidth: 1, justifyContent: 'center', alignItems: 'center'
},
emptyDataInnerText: {
color: '#fff', justifyContent: 'center', alignItems: 'center', fontFamily: 'Enter-The-Grid', fontSize: 18
},
actionSheetElements: {
backgroundColor: '#000000', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', color: '#ffffff'
},
headerBodyText: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1
},
filterWrapper: {
flex: 1, justifyContent: 'center', alignItems: 'center', margin: 15, flexDirection: 'row'
},
searchbarStyle: {
backgroundColor: '#000000', color: '#ffffff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 15
},
ImageBackgroundMyOrder: {
width: '100%', height: '100%'
}
}<file_sep>/src/actions/index.js
const UPDATE_TEXT = 'updateText'
export function updateText(data){
return {
type: UPDATE_TEXT,
text: data,
}
}<file_sep>/src/index.js
import React, { Component } from 'react';
import { createTabNavigator, createStackNavigator } from 'react-navigation';
import { Image } from 'react-native';
import HomeScreen from './screens/home';
import TeamScreen from './screens/team';
import OrderScreen from './screens/order';
import ProfileScreen from './screens/profile';
import LoginScreen from './screens/login';
import RegistrationScreen from './screens/registration';
import NewsScreen from './screens/news';
import SupportScreen from './screens/support';
import OrderSingleScreen from './screens/orderSingle';
import MyOrderScreen from './screens/myorder';
import MyOrdersAgent from './screens/MyOrdersAgent';
import AssignOrders from './screens/assignOrders';
import RankingUser from './screens/RankingUser';
import CustomMessage from './screens/customMessage';
import BlogPost from './screens/BlogPost';
import ScreenBasedOnUser from './screens/screenBasedOnUser';
import DeletAgent from './screens/DeleteAgent';
const Tabs = createTabNavigator(
{
Home: HomeScreen,
Team: TeamScreen,
MyOrders: ScreenBasedOnUser,
Profile: ProfileScreen,
},
{
navigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, tintColor }) => {
const { routeName } = navigation.state;
let iconName;
if (routeName === 'Home') {
let iconHome = focused ? require('./assets/home-h.png') : require('./assets/home.png');
return <Image source={iconHome} style={{ width: 30, height: 30 }} />;
}
if (routeName === 'Team') {
let iconTeam = focused ? require('./assets/team-h.png') : require('./assets/team.png');
return <Image source={iconTeam} style={{ width: 30, height: 30 }} />;
}
if (routeName === 'MyOrders') {
let iconOrder = focused ? require('./assets/orders-h.png') : require('./assets/orders.png');
return <Image source={iconOrder} style={{ width: 30, height: 30 }} />;
}
if (routeName === 'Profile') {
let iconProfile = focused ? require('./assets/profiles-h.png') : require('./assets/profiles.png');
return <Image source={iconProfile} style={{ width: 24, paddingTop: 8, paddingBottom:8 }} />;
}
}
}),
tabBarOptions: {
activeTintColor: '#014197',
inactiveTintColor: '#ccc',
showIcon: true,
style: {
backgroundColor: '#000000',
},
tabStyle: {
backgroundColor: '#000000',
},
},
tabBarPosition: 'bottom',
animationEnabled: true,
lazy: false,
swipeEnabled: true,
}
);
const RootStack = createStackNavigator({
Login: LoginScreen,
News: NewsScreen,
Support: SupportScreen,
Registration: RegistrationScreen,
OrderSingleScreen: OrderSingleScreen,
Order: OrderScreen,
MyOrdersAgent: MyOrdersAgent,
ScreenBasedOnUser: ScreenBasedOnUser,
MyOrders: MyOrderScreen,
AssignOrders: AssignOrders,
RankingUser: RankingUser,
CustomMessage: CustomMessage,
BlogPost: BlogPost,
DeletAgent:DeletAgent,
Tabs: Tabs,
},
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
});
export default class Maintabs extends Component {
render() {
return (
<RootStack />
);
}
}
<file_sep>/README.md
# joblist
<file_sep>/src/screens/RankingUser/index.js
import React, { Component } from "react";
// import { Text, ImageBackground, Image, TouchableOpacity, BackHandler, View } from "react-native";
import { Container, Header, Title, Left, Button, Icon, Body } from 'native-base';
import { Col, Row, Grid } from "react-native-easy-grid";
// import styles from "./style";
import { StyleSheet, PixelRatio, TextInput, Alert, Text, ImageBackground, Image, TouchableOpacity, Dimensions, BackHandler, View } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import RNFetchBlob from 'rn-fetch-blob';
import axios from 'axios';
const w = Dimensions.get('window');
// https://reactnativecode.com/upload-image-to-server-using-php-mysql/
export default class RankingUser extends Component {
constructor(props) {
super(props);
this.state = {
ImageSource: null,
data: null,
ageid: '1403',
ageprourl: ''
}
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Home');
return true;
});
}
selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = { uri: response.uri };
this.setState({
ImageSource: source,
data: response.data,
ageprourl: response.uri
});
}
});
}
uploadImageToServer = () => {
// RNFetchBlob.fetch('POST', 'https://shopify.wpfruits.com/client/jobList/updateagent.php', {
// Authorization: "Bearer access-token",
// otherHeader: "foo",
// 'Content-Type': 'multipart/form-data',
// },
// // console.log(RNFetchBlob)
// [
// { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.ageprourl },
// { name: '1403', data: this.state.ageid }
// ]).then((resp) => {
// console,log('responce',resp)
// // ageid
// // ageprourl
// var tempMSG = resp.data;
// tempMSG = tempMSG.replace(/^"|"$/g, '');
// Alert.alert(tempMSG);
// }).catch((err) => {
// // ...
// })
// axios({
// method: 'post',
// url: `https://shopify.wpfruits.com/client/jobList/updateagent.php?ageid=${this.state.ageid}&ageprourl=${this.state.ageprourl}`,
// responseType: 'json'
// })
// .then(function (response) {
// console.log(response)
// that.setState({});
// });
}
render() {
console.log('imageSource', this.state.ImageSource)
console.log('asdfasdf', this.state.ageprourl)
console.log('data', this.state.data)
const { goBack } = this.props.navigation;
return (
<Container style={{}}>
<Header androidStatusBarColor='#000' style={{ backgroundColor: '#000' }}>
<Left>
<Button transparent onPress={() => goBack()} >
<Icon name='arrow-back' style={{ color: '#ffffff' }} />
</Button>
</Left>
<Body>
<Title style={{ color: '#ffffff' }}>Ranking User</Title>
</Body>
</Header>
<View style={styles.container}>
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View style={styles.ImageContainer}>
{this.state.ImageSource === null ? <Text>Select a Photo</Text> :
<Image style={styles.ImageContainer} source={this.state.ImageSource} />
}
</View>
</TouchableOpacity>
{/* <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View style={styles.ImageContainer}>
<Image
source={{ uri: `https://images.pexels.com/photos/671557/pexels-photo-671557.jpeg?w=${w.width * 2}&buster=${Math.random()}` }}
style={{ width: w.width, height: w.width }}
resizeMode="cover"
/>
</View>
</TouchableOpacity> */}
{/* <TextInput
placeholder="Enter Image Name "
onChangeText={data => this.setState({ Image_TAG: data })}
underlineColorAndroid='transparent'
style={styles.TextInputStyle}
/> */}
<TouchableOpacity onPress={this.uploadImageToServer} activeOpacity={0.6} style={styles.button} >
<Text style={styles.TextStyle}> UPLOAD IMAGE TO SERVER </Text>
</TouchableOpacity>
<Text>This is only for testing purpose</Text>
</View>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: '#FFF8E1',
paddingTop: 20
},
ImageContainer: {
borderRadius: 10,
width: 200,
height: 200,
borderColor: '#9B9B9B',
borderWidth: 1 / PixelRatio.get(),
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#CDDC39',
},
TextInputStyle: {
textAlign: 'center',
height: 40,
width: '80%',
borderRadius: 10,
borderWidth: 1,
borderColor: '#028b53',
marginTop: 20
},
button: {
width: '80%',
backgroundColor: '#00BCD4',
borderRadius: 7,
marginTop: 20
},
TextStyle: {
color: '#fff',
textAlign: 'center',
padding: 10
}
});<file_sep>/src/screens/profile/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
blackBackground: {
backgroundColor: '#000'
},
headerTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1, color:'#ffffff'
},
logoutTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 15, letterSpacing: 1, marginLeft:15, color:'#ffffff'
},
imgBackground: {
width: '100%', height: '100%'
},
firstView: {
justifyContent: 'center', alignItems: 'center', alignContent: 'center', marginTop: 15, marginBottom: 15, flexDirection:'row'
},
firstViewText: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 22, letterSpacing: 2
},
secViewText: {
alignItems: 'center', marginTop: 15
},
alignItemCenter: {
alignItems: 'center'
},
iconColor: {
fontSize: 35, color: '#fff'
},
firstRowFirstCol: {
backgroundColor: '#3f3f3f', height: 40, borderRightColor: '#000', borderRightWidth: 1, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: '2%'
},
insideGridRowCol: {
backgroundColor: '#3f3f3f', height: 40, justifyContent: 'center', alignItems: 'center', borderRightColor: '#000', borderRightWidth: 1
},
insideGridRowColText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 20, paddingLeft: 5, paddingRight: 5,
},
secondRowCol: {
backgroundColor: '#060D75', height: 40, borderRightColor: '#000', borderRightWidth: 1, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: '2%'
},
rowLastColumn: {
backgroundColor: '#3f3f3f', height: 40, justifyContent: 'center', alignItems: 'center', padding: 10, marginRight: '2%', borderTopRightRadius: 10, borderBottomRightRadius: 10
},
rowLastColumnText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 20
},
rowSecondColumnText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 20, letterSpacing: 2, paddingLeft: 5, paddingRight: 5
},
rowThirdColumnText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 20, letterSpacing: 2
},
rowThirdWrp: {
backgroundColor: '#01A705', height: 40, borderRightColor: '#000', borderRightWidth: 1, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: '2%'
},
rowFourthColWrp: {
backgroundColor: '#0F6BD8', height: 40, borderRightColor: '#000', borderRightWidth: 1, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: '2%'
},
imgHeightWid: {
width: 180, height: 180, borderRadius: 150 / 2
},
rowHeight: {
height: 50
},
signupButton: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 18, letterSpacing: 2
},
signupButtonWrapper: {
paddingBottom: 30, justifyContent:'center', alignItems:'center'
},
csvdownload:{
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 16, letterSpacing: 2
},
itemTitle: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 17, paddingLeft: 5, paddingRight: 5
},
itemTitleWrapper_1: {
width: '33%', backgroundColor: '#3f3f3f', height: 74, justifyContent: 'center', alignItems: 'center'
},
backGroundColorMyOrder: {
backgroundColor: '#3f3f3f'
},
cardMain: {
backgroundColor: '#3f3f3f', marginLeft: 10, marginRight: 10, paddingTop: 5, paddingBottom: 5, borderColor: 'transparent'
},
animatedView: {
width: deviceWidth - 20,
backgroundColor: "#424040",
elevation: 2,
position: "absolute",
bottom: 0,
padding: 10,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
left: 0,
right: 0,
textAlign: 'center',
marginLeft: 10
},
exitTitleText: {
textAlign: "center",
color: "#ffffff",
marginRight: 10,
},
exitText: {
color: "#e5933a",
paddingHorizontal: 10,
paddingVertical: 3
}
}<file_sep>/src/screens/home/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
backgroundColor: {
backgroundColor: '#3f3f3f'
},
container: {
alignItems: "center",
backgroundColor: "#fff",
justifyContent: "center",
},
formButtonSub: {
backgroundColor: "#323232",
borderRadius: 5,
margin: 10,
width: deviceWidth - 70,
alignItems: "center",
justifyContent: "center",
},
formButtonSubText: {
color: "#fff",
fontSize: 18,
fontWeight: "600",
},
formContainer: {
marginTop: 5,
width: deviceWidth - 50,
},
formInput: {
backgroundColor: "#f5f5f5",
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
elevation: 5,
shadowColor: '#ccc',
shadowOpacity: 10,
shadowRadius: 5,
},
formItem: {
borderBottomWidth: 0,
margin: 10,
backgroundColor: "#f5f5f5",
elevation: 1,
borderWidth: 1,
borderTopWidth: 2,
borderBottomWidth: 0,
borderBottomColor: 'transparent',
},
helpButtonRight: {
alignItems: "flex-end",
justifyContent: "flex-end",
},
headerBackground: {
backgroundColor: '#000'
},
headerTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1,color:'#ffffff'
},
helpTextLeft: {
textAlign: "left",
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpTextRight: {
textAlign: "right",
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpRowCenter: {
alignItems: "center",
justifyContent: "center",
marginTop: 2,
},
helpTextCenter: {
color: "#b08d58",
fontWeight: "600",
fontSize: 18,
},
helpRowCenterForgetPass: {
alignItems: "center",
justifyContent: "center",
marginTop: 2,
},
helptextCenterForgetPass: {
color: "#b08d58",
fontWeight: "600",
fontSize: 14,
},
ImageBackground: {
width: '100%', height: '100%'
},
listItemCheckBox: {
borderBottomWidth: 0,
},
listItemCheckBoxText: {
paddingLeft: 15,
},
logoutText: {
color: '#fff',
fontSize: 20,
},
profileInfo: {
backgroundColor: '#3f3f3f', marginBottom: 20, marginLeft: 10, marginRight: 10, paddingTop: 10, paddingBottom: 10, borderRadius: 5
},
success: {
color: "green",
paddingLeft: 5,
},
error: {
color: "red",
paddingLeft: 5,
},
textUsername: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 22, letterSpacing: 2
},
_textUsername: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 16, letterSpacing: 2, paddingTop: 10
},
textUsingPosition: {
flexDirection: "row", marginTop: 20, position: 'relative'
},
innerTextUsingPosition: {
color: '#000', fontFamily: 'RobotoCondensed-Light', fontSize: 11, position: 'absolute', left: 15, top: -6, width: 15, height: 16, backgroundColor: '#ccc', borderRadius: 25, paddingLeft: 4, paddingBottom: 4
},
homeScreenMessage: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 18, letterSpacing: 2, marginLeft: 10
},
textUsingPositionSec: {
color: '#000', fontFamily: 'RobotoCondensed-Light', fontSize: 11, position: 'absolute', left: 15, top: -6, width: 15, height: 16, backgroundColor: '#ccc', borderRadius: 25, paddingLeft: 4, paddingBottom: 4
},
homePageMain: {
paddingLeft: 10, paddingRight: 10, position: 'relative', width: '100%'
},
firstHomeText: {
position: 'absolute', top: '14%', left: '8.3%', justifyContent: 'center', alignItems: 'center', alignContent: 'center'
},
secondHomeText: {
position: 'absolute', top: 122, left: '40%', justifyContent: 'center', alignItems: 'center', alignContent: 'center'
},
thirdHomeText: {
position: 'absolute', top: '14%', left: '74%', justifyContent: 'center', alignItems: 'center', alignContent: 'center'
},
fourthHomeText: {
position: 'absolute', top: 250, left: '45%', justifyContent: 'center', alignItems: 'center', alignContent: 'center'
},
homeImageText: {
color: '#FFFFFF', fontFamily: 'Enter-The-Grid', fontSize: 16, lineHeight: 23
},
homeImageText_line: {
color: '#FFFFFF', fontFamily: 'Enter-The-Grid', fontSize: 16, lineHeight: 22
},
homeImageTextColor: {
color: '#000', fontFamily: 'Enter-The-Grid', fontSize: 16, lineHeight: 23
},
imgHome: {
width: 26, height: 18
},
firstHomeTextImg: {
width: 35, height: 35
},
secondHomeTextImg: {
width: 30, height: 30
},
thirdHomeTextImg:
{
width: 40, height: 40
},
fourthHomeTextImg: {
width: 44, height: 44
},
animatedView: {
width: deviceWidth - 20,
backgroundColor: "#424040",
elevation: 2,
position: "absolute",
bottom: 0,
padding: 10,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
left: 0,
right: 0,
textAlign: 'center',
marginLeft: 10
},
exitTitleText: {
textAlign: "center",
color: "#ffffff",
marginRight: 10,
},
exitText: {
color: "#e5933a",
paddingHorizontal: 10,
paddingVertical: 3
}
};<file_sep>/src/screens/MyOrdersAgent/index.js
import React, { Component } from "react";
import { View, Platform, Text, FlatList, ActivityIndicator, ImageBackground, Image, ScrollView, TouchableOpacity, Alert, Modal, TouchableHighlight, BackHandler } from "react-native";
import { Header, Title, Left, Button, Icon, Body, Card, CardItem, Right } from 'native-base';
import axios from 'axios';
import { Col, Row, Grid } from "react-native-easy-grid";
import { SearchBar } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet'
import styles from "./style";
import CONFIG from '../../config';
import { connect } from 'react-redux';
import { updateText } from "../../actions/index";
import { MyOrderScreen } from '../myorder';
import RNFetchBlob from 'rn-fetch-blob';
let totalPrice = 0;
class MyOrdersAgent extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
arrayholder: [],
blankdata: [],
loader: 0,
colorCodeStatusFilterButtonT: '#3f3f3f',
colorCodeStatusFilterButtonM: '#3f3f3f',
colorCodeStatusFilterButtonW: '#3f3f3f',
colorCodeStatusFilterButtonA: '#014198',
keyId: '',
_orderId: '',
dataIndex: 0,
_orderName: '',
_order_line_item_detail: '',
tempState: 0,
modalVisible: false,
agentId: '',
userType: '',
customer_name: '',
email: '',
filterType: 'alldata',
lineitem_id: ''
}
}
setModalVisible(visible) {
this.setState({ modalVisible: visible });
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonMyAgent);
let idnrole = this.props.updateText_1.updateText.split('|__|');
idnrole[0] == 'agent' && (this.setState({ userType: idnrole[0], agentId: idnrole[1], agentName: idnrole[2] }))
let that = this;
// Intially fetch agent orders
axios({
method: 'get',
url: `${CONFIG.url}/orders_by_agentid.php?agentid=${idnrole[1]}`,
responseType: 'json'
})
.then(function (response) {
response.data.records != undefined && response.data.records != '' && response.data.records != 'undefined' && response.data.records != 'No products found' ?
that.setState({ data: response.data.records, arrayholder: response.data.records, loader: 1 })
:
that.setState({ data: [], arrayholder: [], loader: 1 })
});
}
searchFilterFunction = text => {
// Search data
const newData = this.state.arrayholder.filter(item => {
const itemData = `${item.line_item_title.toUpperCase()}${item.line_item_title.toUpperCase()}${item.line_item_title.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
})
this.setState({ data: newData });
};
_colorCodeStatus = (key) => {
// Based on item status show button colors
switch (key) {
case 'start':
return 'grey'
break;
case 'active':
return 'yellow'
break;
case 'completed':
return '#6FDA44'
break;
case 'stuck':
return '#FE0000'
break;
case 'priority':
return '#f26522'
break;
case 'support':
return 'purple'
break;
default:
return '#2D7E08'
break;
}
}
_imgStatus = (key) => {
// Based on item status show order icon
switch (key) {
case 'PC':
return require('../../assets/orderStatusImg/driver.png')
break;
case 'PS4':
return require('../../assets/orderStatusImg/ps4.png')
break;
case 'XB1':
return require('../../assets/orderStatusImg/xbox.png')
break;
default:
return require('../../assets/orderStatusImg/driver.png')
break;
}
}
_orderSingle = (index, id, orderId) => {
// Navigate to order single page
this.props.navigation.navigate('OrderSingleScreen', { index: index, id: id, orderId: orderId, _updateStatus: this._statusUpdate })
}
_statusUpdate = (key, index) => {
// Send function as a prop to order single page
alert('Status Updated');
this.state.data[index]['status'] = key
this.state.arrayholder[index]['status'] = key
this.setState({ tempState: 1 });
}
showActionSheet = (key, id, orderId, email, customer_name, ordername, lineitem, lineitem_id) => {
//onClick item status Show actionSheet
this.setState({ keyId: id, _orderId: orderId, dataIndex: key, email: email, customer_name: customer_name, _orderName: ordername, _order_line_item_detail: lineitem, lineitem_id: lineitem_id });
this.ActionSheet.show()
}
handlePress = (buttonIndex) => {
// onClick options available in Actionsheet
if (buttonIndex == '0') {
this.state.data[this.state.dataIndex]['status'] = 'start'
this.state.arrayholder[this.state.dataIndex]['status'] = 'start'
this.setState({ tempState: 1 });
axios({
method: 'post',
url: `${CONFIG.url}/updateStatus.php?usertype=agent&customer_name=${this.state.customer_name}&order_name=${this.state._orderName.replace('#', '')}&order_line_item_detail=${this.state._order_line_item_detail}&agentId=${this.state.agentId}&status=active&id=${this.state.keyId}&orderId=${this.state._orderId}`,
}).then(function (response) {
})
}
if (buttonIndex == '1') {
this.state.data[this.state.dataIndex]['status'] = 'active'
this.state.arrayholder[this.state.dataIndex]['status'] = 'active'
this.setState({ tempState: 1 });
axios({
method: 'post',
url: `${CONFIG.url}/updateStatus.php?usertype=agent&customer_name=${this.state.customer_name}&order_name=${this.state._orderName.replace('#', '')}&order_line_item_detail=${this.state._order_line_item_detail}&agentId=${this.state.agentId}&status=active&id=${this.state.keyId}&orderId=${this.state._orderId}`,
}).then(function (response) {
})
}
if (buttonIndex == '2') {
this.state.data[this.state.dataIndex]['status'] = 'priority'
this.state.arrayholder[this.state.dataIndex]['status'] = 'priority'
this.setState({ tempState: 4 });
axios({
method: 'post',
url: `${CONFIG.url}/updateStatus.php?usertype=agent&customer_name=${this.state.customer_name}&order_name=${this.state._orderName.replace('#', '')}&order_line_item_detail=${this.state._order_line_item_detail}&agentId=${this.state.agentId}&status=priority&id=${this.state.keyId}&orderId=${this.state._orderId}`,
}).then(function (response) {
})
}
if (buttonIndex == '3') {
this.state.data[this.state.dataIndex]['status'] = 'stuck'
this.state.arrayholder[this.state.dataIndex]['status'] = 'stuck'
this.setState({ tempState: 3 });
axios({
method: 'post',
url: `${CONFIG.url}/updateStatus.php?usertype=agent&customer_name=${this.state.customer_name}&order_name=${this.state._orderName.replace('#', '')}&order_line_item_detail=${this.state._order_line_item_detail}&agentId=${this.state.agentId}&status=stuck&id=${this.state.keyId}&orderId=${this.state._orderId}`,
}).then(function (response) {
})
}
if (buttonIndex == '4') {
this.setModalVisible(true);
}
if (buttonIndex == '5') {
this.state.data[this.state.dataIndex]['status'] = 'completed'
this.state.arrayholder[this.state.dataIndex]['status'] = 'completed'
this.setState({ tempState: 2 });
axios({
method: 'post',
url: `${CONFIG.url}/updateStatus.php?usertype=agent&customer_name=${this.state.customer_name}&order_name=${this.state._orderName.replace('#', '')}&order_line_item_detail=${this.state._order_line_item_detail}&agentId=${this.state.agentId}&lineitem_id=${this.state.lineitem_id}&status=completed&id=${this.state.keyId}&orderId=${this.state._orderId}`,
}).then(function (response) {
})
}
}
sendMailSupport = (supportdata) => {
axios({
method: 'post',
url: `${CONFIG.url}/sendemail.php?supportdata=${supportdata}&agentId=${this.state.agentId}&agentName=${this.state.agentName}&id=${this.state.keyId}&order_id=${this.state._orderId}&emailId=${this.state.email}&customer_name=${this.state.customer_name}&order_name=${this.state._orderName.replace('#', '')}&order_line_item_detail=${this.state._order_line_item_detail}`
}).then((response) => {
alert('Email Sent');
})
}
orderExport = (id, name) => {
// Order Export
axios({
method: 'get',
url: `${CONFIG.url}/ordercsv/create.php?hitfile=createcsv&agentid=${id}&agentname=${name}&filtertype=${this.state.filterType}`,
}).then((response) => {
if (response.data.trim() == 'done') {
let dirs = RNFetchBlob.fs.dirs;
RNFetchBlob
.config({
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
mime: 'text/csv',
description: 'File downloaded by download manager.'
},
IOSDownloadTask: true,
path: Platform.OS === 'ios' ? `${dirs.DocumentDir}/joblist_${name.replace(/ /g, "_")}_${id}_order.csv` : ''
})
.fetch('GET', `${CONFIG.url}/ordercsv/joblist_${name.replace(/ /g, "_")}_${id}_order.csv`)
.then((resp) => {
resp.path();
})
this.setState({ modalVisible: false })
} else {
alert(`No data Available for ${name} Agent`);
}
})
}
componentWillUnmount() {
// Remove Action Listener
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonMyAgent);
}
componentWillReceiveProps = () => {
// Add Action Listener
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonMyAgent);
}
handleBackButtonMyAgent = () => {
// Hardware Back Button Handler
this.props.navigation.navigate('Home')
return true;
};
__onPressButton_filter = (data) => {
// Week-Month Filter
let that = this;
let idnrole = this.props.updateText_1.updateText.split('|__|');
that.setState({ data: [], arrayholder: [], loader: 0 })
if (data == 'month') {
that.setState({ colorCodeStatusFilterButtonM: '#014198' })
that.setState({ colorCodeStatusFilterButtonA: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonW: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonT: '#3f3f3f' })
}
if (data == 'week') {
that.setState({ colorCodeStatusFilterButtonW: '#014198' })
that.setState({ colorCodeStatusFilterButtonA: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonT: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonM: '#3f3f3f' })
}
if (data == 'alldata') {
that.setState({ colorCodeStatusFilterButtonA: '#014198' })
that.setState({ colorCodeStatusFilterButtonT: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonW: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonM: '#3f3f3f' })
}
if (data == 'today') {
that.setState({ colorCodeStatusFilterButtonT: '#014198' })
that.setState({ colorCodeStatusFilterButtonA: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonW: '#3f3f3f' })
that.setState({ colorCodeStatusFilterButtonM: '#3f3f3f' })
}
axios({
method: 'get',
url: `${CONFIG.url}/orders_by_agentid.php?data_filter=${data}&agentid=${idnrole[1]}`
})
.then(function (response) {
response.data != null && response.data != 'null' && response.data != '' && response.data.records != 'No products found' ?
that.setState({ filterType: data, data: response.data.records, arrayholder: response.data.records, totalPrice: response.data.records['0'].totalPrice })
:
that.setState({ data: [], arrayholder: [], loader: 1 })
});
}
render() {
totalPrice = 0
const { goBack } = this.props.navigation;
// ActionSheet options for Android
const options = [
<View style={styles.startAction}>
<Text style={styles.actionSheetTextStyle}>Start</Text>
</View>,
<View style={styles.activeAction}>
<Text style={styles.actionSheetTextStyle_c}>Active</Text>
</View>,
<View style={styles.priorityAction}>
<Text style={styles.actionSheetTextStyle}>Priority</Text>
</View>,
<View style={styles.stuckAction}>
<Text style={styles.actionSheetTextStyle}>Stuck</Text>
</View>,
<View style={styles.needSupportAction}>
<Text style={styles.actionSheetTextStyle}>Need Support</Text>
</View>,
<View style={styles.completedAction}>
<Text style={styles.actionSheetTextStyle}>Completed</Text>
</View>,
<View style={styles.cancleAction}>
<Text style={styles.actionSheetTextStyle_c}>Cancle</Text>
</View>
]
// ActionSheet options for IOS
const optionsIos = [
'Start',
'Active',
'Priority',
'Stuck',
'Need Support',
'Completed',
'Cancle'
]
return (
<View style={{}}>
<Header androidStatusBarColor='#000' style={styles.blackBackgroundColor}>
<Left>
<Button transparent onPress={() => goBack()} >
<Icon name='arrow-back' style={{ color: '#ffffff' }} />
</Button>
</Left>
<Body>
<Title style={styles.headerBodyText}>MY ORDERS</Title>
</Body>
<Right>
<Button transparent onPress={() => this.orderExport(this.state.agentId, this.state.agentName)} >
<Icon name='download' style={{ color: '#ffffff' }} />
</Button>
</Right>
</Header>
{this.state.userType == 'agent' ?
(
<ImageBackground source={require('../../assets/bg.png')} style={styles.ImageBackgroundMyOrder}>
<View style={{ height: 100 }}>
<SearchBar
placeholder="Type Here..."
containerStyle={styles.backGroundColorMyOrder}
placeholderTextColor='#ffffff'
inputStyle={styles.searchbarStyle}
onChangeText={text => this.searchFilterFunction(text)}
autoCorrect={false}
/>
<View style={styles.filterWrapper}>
<Col onPress={() => this.__onPressButton_filter('week')} style={{ backgroundColor: this.state.colorCodeStatusFilterButtonW, height: 45, borderRightColor: '#000', margin: 10, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.filterText}>Week</Text>
</Col>
<Col onPress={() => this.__onPressButton_filter('month')} style={{ backgroundColor: this.state.colorCodeStatusFilterButtonM, height: 45, borderRightColor: '#000', margin: 10, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.filterText} >Month</Text>
</Col>
<Col onPress={() => this.__onPressButton_filter('alldata')} style={{ backgroundColor: this.state.colorCodeStatusFilterButtonA, height: 45, borderRightColor: '#000', margin: 10, justifyContent: 'center', alignItems: 'center' }}>
<Text style={styles.filterText}>All</Text>
</Col>
</View>
</View>
<View style={{ height: 60 }}>
{this.state.data.length > 0 &&
(<View style={styles.filterWrapper}>
<Col style={{ backgroundColor: this.state.colorCodeStatusFilterButtonT, height: 50, borderRightColor: '#000', margin: 10, justifyContent: 'flex-end', alignItems: 'center', flexDirection: 'row' }}>
<Text style={styles.totalPrice}>Total Earning: </Text>
<Text style={styles.totalPrice}>${this.state.data[0].totalPrice}</Text>
</Col>
</View>
)
}
</View>
<Grid>
{
this.state.data.length > 0 ?
<View style={{ marginBottom: 180 }}>
<FlatList
data={this.state.data}
extraData={this.state}
renderItem={({ item, key, index }) =>
(
<Row style={{ height: 90 }} key onPress={() => this._orderSingle(index, item.id, item.order_id)}>
<Col style={styles.wrapperMyOrder}>
<Image source={this._imgStatus(item.order_attribute)} style={{ maxWidth: 50, resizeMode: 'contain' }} />
</Col>
<Col style={styles.itemTitleWrapper}>
<Text style={styles.itemTitle}>
{
item.line_item_title.length < 25 ? item.line_item_title : item.line_item_title.substring(1, 20) + '. . .'
}
</Text>
<Text style={styles.createdDate}>{item.created_date.split('T')['0']}</Text>
<Text style={styles.createdDate}>{item.created_date.split('T')['1']}</Text>
</Col>
<Col style={{ backgroundColor: this._colorCodeStatus(item.status), width: '20%', zIndex: 99, height: 78, justifyContent: 'center', alignItems: 'center', flexDirection: 'column' }}>
<TouchableOpacity onPress={() => this.showActionSheet(index, item.id, item.order_id, item.email, item.customer_name, item.order_name, item.order_line_item_detail, item.line_item_id)} style={styles.itemStatus}>
<Text style={styles.itemStatusText}>{item.status}</Text>
</TouchableOpacity>
</Col>
<Col style={styles.itemPrice}>
<Text style={styles.itemPriceText}>${item.price}</Text>
</Col>
</Row>
)}
keyExtractor={item => item.id}
/>
<ActionSheet
ref={o => this.ActionSheet = o}
title={'Which one do you like ?'}
options={Platform.OS === 'ios' ? optionsIos : options}
onPress={this.handlePress}
styles={{ titleText: styles.actionSheetElements }}
tintColor={Platform.OS === 'ios' ? '#000000' : '#ffffff'}
/>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View>
<ImageBackground source={require('../../assets/bg.png')} style={styles.ImageBackgroundMyOrder}>
<Card style={styles.cardMain}>
<CardItem style={styles.backGroundColorMyOrder}>
<TouchableHighlight
onPress={() => {
this.setState({ modalVisible: false });
}}>
<Text style={styles.cardItem}>CLOSE</Text>
</TouchableHighlight>
</CardItem>
</Card>
<ScrollView>
<Card style={styles.cardMain}>
<CardItem style={styles.backGroundColorMyOrder} >
<Body style={styles.backGroundColorBody}>
<Text onPress={() => this.sendMailSupport('password')} style={styles.cardItem}>Wrong Password or email</Text>
</Body>
</CardItem>
<CardItem style={styles.backGroundColorMyOrder}>
<Body style={styles.backGroundColorBody}>
<Text onPress={() => this.sendMailSupport('character')} style={styles.cardItem}>Which Character?</Text>
</Body>
</CardItem>
<CardItem style={styles.backGroundColorMyOrder}>
<Body style={styles.backGroundColorBody}>
<Text onPress={() => this.sendMailSupport('vcode')} style={styles.cardItem}>Need Verification code</Text>
</Body>
</CardItem>
<CardItem style={styles.backGroundColorMyOrder}>
<Body style={styles.backGroundColorBody}>
<Text onPress={() => this.sendMailSupport('other')} style={styles.cardItem}>Other..</Text>
</Body>
</CardItem>
</Card>
</ScrollView>
</ImageBackground>
</View>
</Modal>
</View>
:
<View style={styles.emptyData}>
{this.state.loader == 0 ?
<Col style={styles.emptyData}>
<ActivityIndicator size="large" color="#ffffff" />
</Col>
:
<Col style={styles.emptyDataText}>
<Text style={styles.emptyDataInnerText}>Orders are Not Available</Text>
</Col>
}
</View>
}
</Grid>
</ImageBackground >
)
:
<ImageBackground source={require('../../assets/bg.png')} style={styles.ImageBackgroundMyOrder}></ImageBackground>
}
</View>
);
}
}
function mapStateToProps(state) {
return {
updateText_1: state.userRole
}
}
function mapDispatchToProps(dispatch) {
return {
updateText: (text) => dispatch(updateText(text)),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(MyOrdersAgent)<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux'
import userRole from './userRole'
const rootReducer = combineReducers({
userRole
})
export default rootReducer<file_sep>/src/screens/order/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
import color from "color";
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
actionSheetTextStyle: {
fontSize: 16, fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', color: '#ffffff', justifyContent: 'center', alignItems: 'center'
},
actionSheetTextStyle_c: {
fontSize: 16, fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', color: '#000000', justifyContent: 'center', alignItems: 'center'
},
startAction: {
width: '100%', backgroundColor: 'grey', justifyContent: 'center', alignItems: 'center', flex: 1
},
activeAction: {
width: '100%', backgroundColor: 'yellow', justifyContent: 'center', alignItems: 'center', flex: 1
},
priorityAction: {
width: '100%', backgroundColor: 'orange', justifyContent: 'center', alignItems: 'center', flex: 1
},
stuckAction: {
width: '100%', backgroundColor: 'red', justifyContent: 'center', alignItems: 'center', flex: 1
},
needSupportAction: {
width: '100%', backgroundColor: 'purple', justifyContent: 'center', alignItems: 'center', flex: 1
},
completedAction: {
width: '100%', backgroundColor: '#6FDA44', justifyContent: 'center', alignItems: 'center', flex: 1
},
cancleAction: {
width: '100%', backgroundColor: '#fff', justifyContent: 'center', alignItems: 'center', flex: 1
},
filterText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 18
},
wrapperMyOrder: {
width: '18%', backgroundColor: '#3f3f3f', height: 78, borderRightColor: '#000', borderRightWidth: 1, justifyContent: 'center', alignItems: 'center', borderTopLeftRadius: 10, borderBottomLeftRadius: 10, padding: 10, marginLeft: '2%'
},
itemStatus: {
minWidth: 90, justifyContent: 'center', alignItems: 'center', flexDirection: 'row'
},
itemStatusText: {
color: '#000', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 15, flexDirection: 'row'
},
itemTitle: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 17, paddingLeft: 5, paddingRight: 5
},
createdDate: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 14, paddingLeft: 5, paddingRight: 5, marginTop: 5
},
itemTitleWrapper: {
width: '40%', backgroundColor: '#3f3f3f', height: 78, justifyContent: 'center', alignItems: 'flex-start', marginLeft: 10
},
reservedAgent: {
color: '#000', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 12
},
itemPrice: {
width: '18%', backgroundColor: '#000000', height: 78, justifyContent: 'center', alignItems: 'center', padding: 10, marginRight: '2%'
},
itemPriceInputField: {
borderColor: '#ffffff', borderWidth: 1, color: '#fff', fontSize: 12
},
backGroundColorMyOrder: {
backgroundColor: '#3f3f3f'
},
backGroundColorBody: {
backgroundColor: '#3f3f3f', justifyContent: 'center', alignItems: 'center'
},
cardItem: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 21, paddingBottom: 5, letterSpacing: 2
},
cardMain: {
borderColor: 'transparent', backgroundColor: '#3f3f3f', marginLeft: 10, marginRight: 10, paddingTop: 5, paddingBottom: 5, borderColor: 'transparent'
},
orderidstyle:{
color: '#fff', fontSize: 12, paddingLeft: 5, paddingRight: 5,
},
emptyData: {
flex: 1, justifyContent: 'center', alignItems: 'center'
},
emptyDataText: {
borderRightWidth: 1, justifyContent: 'center', alignItems: 'center'
},
emptyDataInnerText: {
color: '#fff', justifyContent: 'center', alignItems: 'center', fontFamily: 'Enter-The-Grid', fontSize: 18
},
actionSheetElements: {
backgroundColor: '#000000', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', color: '#ffffff'
},
headerBodyText: {
fontFamily: 'Enter-The-Grid', fontSize: 22, letterSpacing: 1, color:'#ffffff'
},
filterWrapper: {
flex: 1, justifyContent: 'center', alignItems: 'center', margin: 15, flexDirection: 'row'
},
searchbarStyle: {
backgroundColor: '#000000', color: '#ffffff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 15
},
ImageBackgroundMyOrder: {
width: '100%', height: '100%'
},
itemPriceText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 15
}
}<file_sep>/src/screens/orderSingle/style.js
const React = require("react-native");
const { Dimensions, Platform } = React;
const deviceWidth = Dimensions.get("window").width;
const deviceHeight = Dimensions.get("window").height;
export default {
backgroundColor: {
backgroundColor: '#3f3f3f'
},
bodyTitle: {
fontFamily: 'Enter-The-Grid', fontSize: 23, letterSpacing: 1
},
imageBackground: {
width: '100%', height: '100%'
},
firstCard: {
borderColor: 'transparent', backgroundColor: '#3f3f3f', marginLeft: 10, marginRight: 10, paddingTop: 5, paddingBottom: 5, borderColor: 'transparent'
},
firstCardBody: {
backgroundColor: '#3f3f3f', justifyContent: 'center', alignItems: 'center'
},
firstCardBodyText: {
color: '#fff', fontFamily: Platform.OS === 'ios' ? 'Chosence' : 'Chosence Regular', fontSize: 21, paddingBottom: 5, letterSpacing: 2
},
firstCardBodyText_sec: {
color: '#fff', fontSize: 15, paddingBottom: 5, letterSpacing: 2
},
secondView: {
alignItems: 'center', justifyContent: 'center'
},
secondViewText: {
color: '#fff', fontSize: 12, paddingBottom: 5, letterSpacing: 1, marginTop: 20
},
additionalDetails: {
borderColor: 'transparent', backgroundColor: '#3f3f3f', marginBottom: 20, marginLeft: 10, marginRight: 10, paddingTop: 5, paddingBottom: 5
},
statusofOrder: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 12
},
activeStatus: {
backgroundColor: 'yellow', padding: 10, margin: 5, borderRadius: 8
},
completedStatus: {
backgroundColor: '#6FDA44', padding: 10, margin: 5, borderRadius: 8
},
stuckStatus: {
backgroundColor: '#ff0000', padding: 10, margin: 5, borderRadius: 8
},
priorityStatus: {
backgroundColor: '#f26522', padding: 10, margin: 5, borderRadius: 8
},
startStopStatus: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 15, letterSpacing: 2
},
startStatusWrp: {
backgroundColor: 'grey', padding: 10, borderRadius: 8
},
stopStatusWrp: {
backgroundColor: '#DA8A8B', padding: 10, borderRadius: 8
},
customerInfoWrp: {
borderColor: 'transparent', backgroundColor: '#000000', marginBottom: 20, marginTop: 20, marginLeft: 10, marginRight: 10, paddingTop: 5, paddingBottom: 5
},
customernotewrap: {
backgroundColor: '#000000', justifyContent: 'center', alignItems: 'center'
},
customernotewrapcust: {
backgroundColor: '#000000', justifyContent: 'center', alignItems: 'flex-start'
},
agentHistory: {
borderColor: 'transparent', backgroundColor: '#3f3f3f', marginBottom: 20, marginLeft: 10, marginRight: 10, paddingTop: 5
},
statusAllWrapper: {
backgroundColor: 'transparent', borderColor: 'transparent', backgroundColor: 'transparent'
},
statusAllWrapperInner: {
justifyContent: 'center', alignItems: 'center'
},
statusAllWrapperFirstInner: {
justifyContent: 'space-around', flexDirection: "row"
},
statusTextActive: {
color: '#000', fontFamily: 'Enter-The-Grid', fontSize: 12, letterSpacing: 1
},
statusNeedSupport: {
marginBottom: 90, borderColor: 'transparent', backgroundColor: 'transparent', marginLeft: 10, marginRight: 10
},
backgroundTranparent: {
backgroundColor: 'transparent'
},
backgroundNeedSupport: {
backgroundColor: 'purple', padding: 10, margin: 5, borderRadius: 8
},
backgroundNeedSupportText: {
color: '#fff', fontFamily: 'Enter-The-Grid', fontSize: 13, letterSpacing: 1
},
wrapperNeedSupportText: {
backgroundColor: 'transparent', justifyContent: 'center', alignItems: 'center'
},
dataEmpty: {
flex: 1, justifyContent: 'center', alignItems: 'center'
},
allTransparent: {
backgroundColor: 'transparent', borderColor: 'transparent'
},
blackBackground: {
backgroundColor: '#000000'
}
} | d57d952d570511a08bd9740ef3cc9af5df88ff61 | [
"JavaScript",
"Markdown"
] | 21 | JavaScript | rakesh2277/flawless-rider-joblist-react-native- | a23ec6c328e1e2f6cd9fb885e935abd92d456d1f | 93bd6da5fbee1f3fc90815625613e157306a32ff |
refs/heads/master | <file_sep>package com.smk.promotion;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.smk.client.NetworkEngine;
import com.smk.model.Shop;
import com.smk.model.User;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.StoreUtil;
import com.thuongnh.zprogresshud.ZProgressHUD;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class VerifyActivity extends BaseAppCompatActivity {
MaterialEditText edt_verify_code;
FloatingActionButton btn_success;
Button btn_verify;
Button btn_resend;
private ZProgressHUD dialog;
private Shop shop;
private String activationCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_variants);
EventBus.getDefault().register(this);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
shop = new Gson().fromJson(bundle.getString("shop"), Shop.class);
}
edt_verify_code = (MaterialEditText) findViewById(R.id.edt_verify_code);
btn_success = (FloatingActionButton) findViewById(R.id.btn_success);
btn_verify = (Button) findViewById(R.id.btn_verify);
btn_resend = (Button) findViewById(R.id.btn_resend);
btn_verify.setOnClickListener(clickListener);
btn_resend.setOnClickListener(clickListener);
btn_success.setImageDrawable(new IconicsDrawable(this)
.icon(GoogleMaterial.Icon.gmd_check)
.color(Color.WHITE)
.sizeDp(24));
addDrawable(edt_verify_code, GoogleMaterial.Icon.gmd_verified_user.toString());
}
@Subscribe
public void onEvent(String activationCode) {
edt_verify_code.setText(activationCode.replace(" ",""));
activate();
};
private void activate(){
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().activateShop(shop.getId(), edt_verify_code.getText().toString(), new Callback<Shop>() {
@Override
public void success(Shop shop, Response response) {
dialog.dismissWithSuccess();
User user = StoreUtil.getInstance().selectFrom("users");
if(user != null){
user.getShops().add(shop);
StoreUtil.getInstance().saveTo("users", user);
}
startActivity(new Intent(getApplicationContext(), CreateFoodActivity.class).putExtra("shop", new Gson().toJson(shop)));
finish();
}
@Override
public void failure(RetrofitError error) {
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(VerifyActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
dialog.dismissWithFailure();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v == btn_verify){
if(edt_verify_code.getText().length() > 0){
activate();
}else {
edt_verify_code.setError(getResources().getString(R.string.str_enter_verify_code));
}
}
if(v == btn_resend){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(VerifyActivity.this);
View contentView = View.inflate(VerifyActivity.this, R.layout.dialog_resend_code, null);
final EditText phoneNo = (EditText) contentView.findViewById(R.id.edt_phone);
final TextView messsage = (TextView) contentView.findViewById(R.id.txt_msg);
messsage.setText(String.format(getResources().getString(R.string.str_confirm_phone), shop.getPhone()));
phoneNo.setText(shop.getPhone());
alertBuilder.setView(contentView);
alertBuilder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(phoneNo.getText().length() > 0) {
resendCode(phoneNo.getText().toString());
}
else {
phoneNo.setError(getResources().getString(R.string.str_enter_phone));
}
}
});
alertBuilder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertBuilder.show();
}
}
};
private void resendCode(String phone){
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().resendActivateCode(shop.getId(), phone, new Callback<Shop>() {
@Override
public void success(Shop shop, Response response) {
dialog.dismissWithSuccess();
}
@Override
public void failure(RetrofitError error) {
dialog.dismissWithFailure();
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(VerifyActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
}
<file_sep>package com.smk.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import org.greenrobot.eventbus.EventBus;
public class IncomingSmsReceiver extends BroadcastReceiver {
private String TAG = IncomingSmsReceiver.class.getSimpleName();
public IncomingSmsReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// Get the data (SMS data) bound to intent
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String phone = "";
if (bundle != null) {
// Retrieve the SMS Messages received
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
// For every SMS message received
for (int i=0; i < msgs.length; i++) {
// Convert Object array
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Sender's phone number
phone = msgs[i].getOriginatingAddress();
// Fetch the text message
str = msgs[i].getMessageBody().toString();
}
Log.i("528Go","Hello SMS"+ str);
String[] sms = str.split(":");
if(sms != null && sms.length == 2){
Log.i("528Go","Hello sms [0] :"+ sms[0]);
if(sms[0].contains("528Food Activation Code")){
EventBus.getDefault().post(sms[1]);
}
}
}
}
}
<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
public class ThankYouActivity extends BaseAppCompatActivity {
Toolbar toolbar;
Button btn_again;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thank_you);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_thank_you));
setSupportActionBar(toolbar);
btn_again = (Button) findViewById(R.id.btn_again);
btn_again.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ThankYouActivity.this, FoodActivity.class));
closeAllActivities();
}
});
}
@Override
public void onBackPressed() {
return;
}
}<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Button;
public class AboutActivity extends BaseAppCompatActivity {
Toolbar toolbar;
Button btn_back;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_about));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
@Nullable
@Override
public Intent getSupportParentActivityIntent() {
finish();
return super.getSupportParentActivityIntent();
}
}<file_sep>package com.smk.adapter;
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.view.IconicsImageView;
import com.ms.square.android.expandabletextview.ExpandableTextView;
import com.smk.model.Food;
import com.smk.model.FoodReview;
import com.smk.model.User;
import com.smk.promotion.R;
import com.smk.utils.CircleTransform;
import com.smk.utils.ClickListener;
import com.smk.utils.StoreUtil;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ShopFoodRVAdapter extends RecyclerView.Adapter<ShopFoodRVAdapter.ViewHolder> {
private final Boolean isShopOwner;
Context ctx = null;
List<Food> shopFoodList;
ClickListener clicklistener = null;
Food foods;
List<FoodReview> food_review;
User user;
private Callbacks mCallback;
public ShopFoodRVAdapter(Context ctx, List<Food> shopFoodList, Boolean owner) {
this.ctx = ctx;
this.shopFoodList = shopFoodList;
this.isShopOwner = owner;
}
@Override
public ShopFoodRVAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_shop_food_list, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ShopFoodRVAdapter.ViewHolder holder, final int position) {
foods = shopFoodList.get(position);
user = StoreUtil.getInstance().selectFrom("users");
try {
if (foods.getFoodCategory().getName() != null && foods.getFoodCategory().getName().length() > 0) {
holder.txt_food_category_name.setText(foods.getFoodCategory().getName());
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if (foods.getFoodSizes() != null && foods.getFoodSizes().size() > 0) {
holder.txt_food_price.setText(foods.getFoodSizes().get(0).getPrice().toString() + " MMK");
}
if (foods.getFoodPhotos() != null && foods.getFoodPhotos().size() > 0) {
Picasso.with(ctx).load("http://foods.528go.com/foodPhotos/x400/" + foods.getFoodPhotos().get(0).getImage()).into(holder.img_food);
}else{
Picasso.with(ctx).load("http://foods.528go.com/foodPhotos/x400/...").into(holder.img_food);
}
if (foods.getName() != null && foods.getName().length() > 0) {
holder.txt_food_name.setText(foods.getName());
}
if (foods.getDescription() != null && foods.getDescription().length() > 0) {
holder.expand_text_view.setText(foods.getDescription());
}
try {
if (foods.getShop().getOpenHr() != null && foods.getShop().getOpenHr().length() > 0) {
holder.txt_shop_time.setText(foods.getShop().getOpenHr());
}
if (foods.getTotalRatings().toString() != null && foods.getTotalRatings().toString().length() > 0) {
DecimalFormat form = new DecimalFormat("0.0");
holder.txt_food_rating.setText(form.format(foods.getTotalRatings()));
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if (food_review != null && food_review.size() > 0) {
if (food_review.get(0).getUser().getImage() != null && food_review.get(0).getUser().getImage().length() > 0) {
Picasso.with(ctx).load("http://foods.528go.com/users/x200/" + food_review.get(0).getUser().getImage()).placeholder(getIconicDrawable(GoogleMaterial.Icon.gmd_account_circle.toString(), R.color.colorOrage, 48)).transform(new CircleTransform()).into(holder.img_account);
}else{
Picasso.with(ctx).load("http://foods.528go.com/users/x200/...").placeholder(getIconicDrawable(GoogleMaterial.Icon.gmd_account_circle.toString(), R.color.colorOrage, 48)).transform(new CircleTransform()).into(holder.img_account);
}
holder.txt_food_review_user_name.setText(food_review.get(0).getUser().getName());
holder.txt_food_review_comment.setText(food_review.get(0).getReviews());
} else {
if (user != null) {
holder.txt_food_review_user_name.setText("Hello " + user.getName());
holder.txt_food_review_comment.setText("Please Write your review");
} else {
holder.txt_food_review_user_name.setText("Hello Customer");
holder.txt_food_review_comment.setText("Please Write your review");
}
}
if(foods.getFoodDiscounts() != null && foods.getFoodDiscounts().size() > 0 && foods.getFoodSizes() != null && foods.getFoodSizes().size() > 0){
holder.txt_discount.setVisibility(View.VISIBLE);
int percentage = ((foods.getFoodSizes().get(0).getPrice() - foods.getFoodDiscounts().get(0).getDiscount()) * 100) / foods.getFoodSizes().get(0).getPrice();
holder.txt_discount.setText(Math.round(100 - percentage)+"% OFF");
holder.txt_food_price.setText((foods.getFoodSizes().get(0).getPrice() - foods.getFoodDiscounts().get(0).getDiscount()) + " MMK");
}else{
holder.txt_discount.setVisibility(View.GONE);
}
if(foods.getShop().getOpenHr() != null && foods.getShop().getOpenHr().contains("to")){
String[] openHr = foods.getShop().getOpenHr().split(" to ");
if(openHr.length == 2){
if(checkOpen(openHr[0], openHr[1])){
holder.ico_open.setIcon(GoogleMaterial.Icon.gmd_timelapse);
holder.ico_open.setColor(ctx.getResources().getColor(R.color.colorPrimary));
}else{
holder.ico_open.setIcon(CommunityMaterial.Icon.cmd_sleep);
holder.ico_open.setColor(ctx.getResources().getColor(R.color.md_grey_500));
}
}
}
if(!foods.getShop().getOpenHr().contains("to")){
holder.txt_shop_time.setText("24 Hours Open");
holder.ico_open.setIcon(GoogleMaterial.Icon.gmd_timelapse);
holder.ico_open.setColor(ctx.getResources().getColor(R.color.colorPrimary));
}
try {
if (foods.getTotalLikes().toString() != null && foods.getTotalLikes().toString().length() > 0) {
holder.txt_food_like.setText(String.valueOf(foods.getTotalLikes()));
}
} catch (NullPointerException e) {
e.printStackTrace();
}
if(isShopOwner != null && isShopOwner.equals(false)){
holder.btn_action_menu.setVisibility(View.GONE);
}else{
holder.btn_action_menu.setVisibility(View.VISIBLE);
}
holder.btn_action_menu.setTag(position);
holder.btn_action_menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = (int) v.getTag();
showPopupMenu(v, pos);
}
});
}
private boolean checkOpen(String startTime, String endTime){
try {
Date time1 = new SimpleDateFormat("h:mm a").parse(startTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
Date time2 = new SimpleDateFormat("h:mm a").parse(endTime);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("h:mm a");
String currentTime = date.format(currentLocalTime);
Date d = new SimpleDateFormat("h:mm a").parse(currentTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
@Override
public int getItemCount() {
return shopFoodList.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView txt_discount;
private final IconicsImageView btn_action_menu;
private final View overlay;
private final IconicsImageView ico_open;
TextView txt_food_category_name, txt_food_price, txt_food_name, txt_shop_time, txt_food_rating, txt_food_review_user_name, txt_food_review_comment, txt_food_like;
ImageView img_food;
IconicsImageView img_account;
ExpandableTextView expand_text_view;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txt_food_category_name = (TextView) itemView.findViewById(R.id.txt_food_category_name);
txt_food_price = (TextView) itemView.findViewById(R.id.txt_food_price);
txt_discount = (TextView) itemView.findViewById(R.id.txt_discount);
img_food = (ImageView) itemView.findViewById(R.id.img_food);
ico_open = (IconicsImageView) itemView.findViewById(R.id.ico_open_time);
img_food = (ImageView) itemView.findViewById(R.id.img_food);
overlay = (View) itemView.findViewById(R.id.fade_view);
btn_action_menu = (IconicsImageView) itemView.findViewById(R.id.btn_action_menu);
txt_food_name = (TextView) itemView.findViewById(R.id.txt_food_name);
expand_text_view = (ExpandableTextView) itemView.findViewById(R.id.expand_text_view);
txt_shop_time = (TextView) itemView.findViewById(R.id.txt_shop_time);
txt_food_rating = (TextView) itemView.findViewById(R.id.txt_food_rating);
img_account = (IconicsImageView) itemView.findViewById(R.id.img_account);
txt_food_review_user_name = (TextView) itemView.findViewById(R.id.txt_food_review_user_name);
txt_food_review_comment = (TextView) itemView.findViewById(R.id.txt_food_review_comment);
txt_food_like = (TextView) itemView.findViewById(R.id.txt_food_like);
}
@Override
public void onClick(View v) {
if (clicklistener != null) {
clicklistener.itemClicked(v, getAdapterPosition());
}
}
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view, int position) {
// inflate menu
PopupMenu popup = new PopupMenu(ctx, view);
popup.setGravity(Gravity.RIGHT);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_items, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener(position));
popup.show();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
private final int position;
public MyMenuItemClickListener(int position) {
this.position = position;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete:
if(mCallback != null){
mCallback.onItemClickDelete(position);
}
return true;
case R.id.action_edit_discount:
if(mCallback != null){
mCallback.onItemClickEditDiscount(position);
}
return true;
case R.id.action_edit_photo:
if(mCallback != null){
mCallback.onItemClickEditPhoto(position);
}
return true;
case R.id.action_edit_ingredients:
if(mCallback != null){
mCallback.onItemClickEditIngredient(position);
}
return true;
case R.id.action_edit_size:
if(mCallback != null){
mCallback.onItemClickEditSize(position);
}
return true;
case R.id.action_edit_food:
if(mCallback != null){
mCallback.onItemClickEditFood(position);
}
return true;
default:
}
return false;
}
}
public void setOnCallbacksListener(Callbacks callbacks){
this.mCallback = callbacks;
}
public interface Callbacks{
void onItemClickDelete(int position);
void onItemClickEditDiscount(int position);
void onItemClickEditPhoto(int position);
void onItemClickEditFood(int position);
void onItemClickEditIngredient(int position);
void onItemClickEditSize(int position);
}
public void setClickListener(ClickListener clicklistener) {
this.clicklistener = clicklistener;
}
public IconicsDrawable getIconicDrawable(String icon, int color, int size) {
return new IconicsDrawable(ctx)
.icon(icon)
.color(ctx.getResources().getColor(color))
.sizeDp(size);
}
}<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.smk.adapter.FoodCategorySpinnerAdapter;
import com.smk.adapter.FoodTypeSpinnerAdapter;
import com.smk.client.NetworkEngine;
import com.smk.model.Food;
import com.smk.model.FoodCategory;
import com.smk.model.FoodType;
import com.smk.model.Shop;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.StoreUtil;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.util.List;
import fr.ganfra.materialspinner.MaterialSpinner;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class CreateFoodActivity extends BaseAppCompatActivity implements View.OnClickListener {
Toolbar toolbar;
MaterialEditText edt_food_name, edt_food_description;
MaterialSpinner spn_food_category;
Button btn_next;
List<FoodType> food_type;
FoodTypeSpinnerAdapter adapter;
Integer foodType;
ZProgressHUD dialog;
private Shop shop;
private SwitchButton chk_order_now;
private MaterialSpinner spn_food_type;
private FoodTypeSpinnerAdapter adapterFoodType;
private List<FoodCategory> food_category;
private FoodCategorySpinnerAdapter adapterFoodCategory;
private Food food;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_food);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_create_food));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Bundle bundle = getIntent().getExtras();
if(bundle != null){
shop = new Gson().fromJson(bundle.getString("shop"), Shop.class);
food = new Gson().fromJson(bundle.getString("food"), Food.class);
}
edt_food_name = (MaterialEditText) findViewById(R.id.edt_food_name);
spn_food_type = (MaterialSpinner) findViewById(R.id.spn_food_type);
spn_food_category = (MaterialSpinner) findViewById(R.id.spn_food_category);
edt_food_description = (MaterialEditText) findViewById(R.id.edt_food_description);
chk_order_now = (SwitchButton) findViewById(R.id.chk_order_now);
btn_next = (Button) findViewById(R.id.btn_next);
if (btn_next != null) {
btn_next.setOnClickListener(this);
}
if(food != null){
edt_food_name.setText(food.getName());
edt_food_description.setText(food.getDescription());
if(food.getOrderNow()){
chk_order_now.setChecked(true);
}else{
chk_order_now.setChecked(false);
}
btn_next.setText(getResources().getString(R.string.str_update));
}
food_type = StoreUtil.getInstance().selectFrom("FoodTypes");
if (food_type != null) {
getFoodType();
adapterFoodType = new FoodTypeSpinnerAdapter(CreateFoodActivity.this, food_type);
spn_food_type.setAdapter(adapterFoodType);
if(food != null){
int i = 0;
for(FoodType foodType: food_type){
if(foodType.getId().equals(food.getFoodCategory().getTypeId())){
spn_food_type.setSelection(i,true);
}
i++;
}
}
spn_food_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
food_category = food_type.get(position).getCategories();
adapterFoodCategory = new FoodCategorySpinnerAdapter(CreateFoodActivity.this, food_category);
spn_food_category.setAdapter(adapterFoodCategory);
if(food != null){
int i = 0;
for(FoodCategory foodCategory: food_category){
if(foodCategory.getId().equals(food.getFoodCategory().getId())){
spn_food_category.setSelection(i,true);
}
i++;
}
}
spn_food_category.setOnItemSelectedListener(foodCategoryOnItemSelectedListener);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
getFoodType();
}
}
private AdapterView.OnItemSelectedListener foodCategoryOnItemSelectedListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
FoodCategory foodCategory = (FoodCategory) parent.getAdapter().getItem(position);
foodType = foodCategory.getId();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
private void getFoodType() {
NetworkEngine.getInstance().getFoodTypes(new Callback<List<FoodType>>() {
@Override
public void success(List<FoodType> foodTypes, Response response) {
StoreUtil.getInstance().saveTo("FoodTypes", foodTypes);
if (food_type == null) {
food_type = foodTypes;
adapterFoodType = new FoodTypeSpinnerAdapter(CreateFoodActivity.this, food_type);
spn_food_type.setAdapter(adapterFoodType);
spn_food_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
food_category = food_type.get(position).getCategories();
adapterFoodCategory = new FoodCategorySpinnerAdapter(CreateFoodActivity.this, food_category);
spn_food_category.setAdapter(adapterFoodCategory);
spn_food_category.setOnItemSelectedListener(foodCategoryOnItemSelectedListener);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
@Override
public void failure(RetrofitError error) {
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_next:
if (checkField()) {
if(food != null){
updateFood();
}else {
postFoodInformation();
}
}
break;
default:
break;
}
}
private void postFoodInformation() {
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().postFoodInformation(edt_food_name.getText().toString(), foodType, edt_food_description.getText().toString(), shop.getId(), chk_order_now.isChecked() ? 1 : 0, new Callback<Food>(){
public void success(Food food, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
Intent intent = new Intent(CreateFoodActivity.this, CreateFoodSizePriceActivity.class);
Bundle extras = new Bundle();
extras.putInt("food_id", food.getId());
extras.putString("shop", new Gson().toJson(shop));
intent.putExtras(extras);
startActivity(intent);
finish();
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(CreateFoodActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private void updateFood(){
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().updateFoodInformation(food.getId(),edt_food_name.getText().toString(), foodType, edt_food_description.getText().toString(), shop.getId(), chk_order_now.isChecked() ? 1 : 0, new Callback<Food>() {
@Override
public void success(Food food, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", new Gson().toJson(shop));
startActivity(intent);
finish();
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(CreateFoodActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private boolean checkField() {
if (edt_food_name.getText().length() == 0) {
edt_food_name.setError(getResources().getString(R.string.invalid_food_name));
edt_food_name.requestFocus();
return false;
}
if (edt_food_description.getText().length() == 0) {
edt_food_description.setError(getResources().getString(R.string.invalid_food_description));
edt_food_description.requestFocus();
return false;
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.smk.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.view.IconicsImageView;
import com.smk.model.Order;
import com.smk.model.User;
import com.smk.promotion.R;
import com.smk.utils.CircleTransform;
import com.squareup.picasso.Picasso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* Created by SMK on 12/15/2015.
*/
public class ShopCustomersAdapter extends RecyclerView.Adapter<ShopCustomersAdapter.MyViewHolder> {
private final Context content;
List<User> list;
private Callbacks mCallback;
public ShopCustomersAdapter(Context ctx, List<User> list){
this.list = list;
this.content = ctx;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_friend, parent, false);
return new MyViewHolder(itemView);
}
private User getItem(int positon){
return this.list.get(positon);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int arg0) {
Picasso.with(content).load("http://foods.528go.com/users/x200/"+getItem(arg0).getImage()).placeholder(getIconicDrawable(GoogleMaterial.Icon.gmd_account_circle.toString(),R.color.md_grey_300,50)).transform(new CircleTransform()).into(holder.img_friend);
holder.name.setText(getItem(arg0).getName());
holder.date.setText(changeDateFormat(getItem(arg0).getUpdatedAt()));
String strMessage = "Offline ";
if(getItem(arg0).getOnSession()){
strMessage = "Online ";
}
strMessage += getItem(arg0).getMessage() != null ? ":"+getItem(arg0).getMessage() : "";
holder.message.setText(strMessage);
if(getItem(arg0).getNotSeenCount() != null && getItem(arg0).getNotSeenCount() > 0){
holder.not_seen_msg_count.setVisibility(View.VISIBLE);
holder.not_seen_msg_count.setText(getItem(arg0).getNotSeenCount()+"");
}else{
holder.not_seen_msg_count.setVisibility(View.GONE);
}
}
public IconicsDrawable getIconicDrawable(String icon, int color, int size){
return new IconicsDrawable(content)
.icon(icon)
.color(content.getResources().getColor(color))
.sizeDp(size);
}
public void setOnCallbackListener(Callbacks callbacks){
this.mCallback = callbacks;
}
public interface Callbacks{
void reply(Order order);
void replyMessage(Order order);
void acceptOrder(Order order);
void deleteOrder(Order order);
}
private String changeDateFormat(String date){
SimpleDateFormat fromUser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yy");
String reformattedStr = null;
try {
reformattedStr = myFormat.format(fromUser.parse(date));
} catch (ParseException e) {
e.printStackTrace();
} catch (NullPointerException e){
}
return reformattedStr;
}
@Override
public int getItemCount() {
return this.list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView date;
TextView message;
TextView not_seen_msg_count;
IconicsImageView img_friend;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.txt_name);
date = (TextView) itemView.findViewById(R.id.txt_date);
message = (TextView) itemView.findViewById(R.id.txt_message);
not_seen_msg_count = (TextView) itemView.findViewById(R.id.txt_not_seen_count);
img_friend = (IconicsImageView) itemView.findViewById(R.id.img_friend);
}
}
}
<file_sep>package com.smk.promotion;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.widget.Button;
import com.mikepenz.iconics.IconicsDrawable;
import com.nullwire.trace.ExceptionHandler;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.smk.client.NetworkEngine;
import com.smk.utils.StoreUtil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class BaseAppCompatActivity extends AppCompatActivity {
public static final String FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION = "com.smk.promotion.FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION";
public static final int OPEN_GPS = 120;
private BaseActivityReceiver baseActivityReceiver = new BaseActivityReceiver();
public static final IntentFilter INTENT_FILTER = createIntentFilter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, "http://shopyface.com/api/v1/errorReports");
checkNewVersion();
String languages = StoreUtil.getInstance().selectFrom("languages");
if (languages != null) {
Locale locale = new Locale(languages);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, null);
} else {
StoreUtil.getInstance().saveTo("languages", "en");
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, null);
}
}
private void checkNewVersion(){
NetworkEngine.getInstance().getNewVersion(new Callback<Integer>() {
@Override
public void success(final Integer newVersionCode, Response arg1) {
// TODO Auto-generated method stub
try {
final int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
if(versionCode < newVersionCode){
final AlertDialog.Builder builder = new AlertDialog.Builder(BaseAppCompatActivity.this);
builder.setTitle("New Version");
builder.setMessage("We has already updated new version "+ versionName+". You can download via Play Store or Direct Download.");
builder.setPositiveButton("Play Store", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
builder.setNegativeButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String url = "http://truetaximyanmar.com/apk/app-release-v"+newVersionCode+".apk";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
dialog.dismiss();
}
});
builder.show();
}
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
}
}
@Override
public void failure(RetrofitError arg0) {
// TODO Auto-generated method stub
}
});
}
public void addDrawable(MaterialEditText editText, String icon) {
editText.setCompoundDrawablePadding(16);
editText.setCompoundDrawables(new IconicsDrawable(this)
.icon(icon)
.color(getResources().getColor(R.color.colorGray))
.sizeDp(22), null, null, null);
}
public void addDrawableRight(Button button, String icon, int size) {
button.setCompoundDrawablePadding(16);
button.setCompoundDrawables(null, null, new IconicsDrawable(this)
.icon(icon)
.color(getResources().getColor(R.color.colorWhite))
.sizeDp(size), null);
}
public IconicsDrawable getIconicDrawable(String icon) {
return new IconicsDrawable(this)
.icon(icon)
.color(getResources().getColor(R.color.colorWhite))
.sizeDp(24);
}
public IconicsDrawable getIconicDrawable(String icon, int size) {
return new IconicsDrawable(this)
.icon(icon)
.color(getResources().getColor(R.color.colorAccent))
.sizeDp(size);
}
public IconicsDrawable getIconicDrawable(String icon, int color, int size){
return new IconicsDrawable(this)
.icon(icon)
.color(getResources().getColor(color))
.sizeDp(size);
}
private static IntentFilter createIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION);
return filter;
}
protected void registerBaseActivityReceiver() {
registerReceiver(baseActivityReceiver, INTENT_FILTER);
}
protected void unRegisterBaseActivityReceiver() {
unregisterReceiver(baseActivityReceiver);
}
public class BaseActivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION)) {
finish();
}
}
}
protected void closeAllActivities() {
sendBroadcast(new Intent(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION));
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showGPSSettingsAlert(){
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Required GPS");
dialog.setMessage("Turn on location services to allow \"528 Food\" to determine your location.");
dialog.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, OPEN_GPS);
dialog.dismiss();
}
});
dialog.show();
}
/**
* Converting dp to pixel
*/
public int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
public boolean checkOpen(String startTime, String endTime){
try {
Date time1 = new SimpleDateFormat("hh:mm aa").parse(startTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
Date time2 = new SimpleDateFormat("hh:mm aa").parse(endTime);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("hh:mm aa");
String currentTime = date.format(currentLocalTime);
Date d = new SimpleDateFormat("hh:mm aa").parse(currentTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
}
<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.gson.Gson;
import com.smk.adapter.BookingPendingCompleteListRVAdapter;
import com.smk.client.NetworkEngine;
import com.smk.model.Booking;
import com.smk.model.User;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.ClickListener;
import com.smk.utils.StoreUtil;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class BookingCompleteListActivity extends BaseAppCompatActivity implements ClickListener {
Toolbar toolbar;
TextView txt_no_food;
RecyclerView recyclerView;
List<Booking> bookingList;
ZProgressHUD dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_booking_pending_complete_list);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_booking_complete_list));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
txt_no_food = (TextView) findViewById(R.id.txt_no_food);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
User user = StoreUtil.getInstance().selectFrom("users");
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().getBooking(user.getId(), true, new Callback<List<Booking>>() {
@Override
public void success(List<Booking> bookings, Response response) {
if (bookings != null && bookings.size() > 0) {
txt_no_food.setVisibility(View.GONE);
bookingList = bookings;
BookingPendingCompleteListRVAdapter adapter = new BookingPendingCompleteListRVAdapter(BookingCompleteListActivity.this, bookings);
recyclerView.setAdapter(adapter);
adapter.setClickListener(BookingCompleteListActivity.this);
adapter.notifyDataSetChanged();
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
} else {
txt_no_food.setVisibility(View.VISIBLE);
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
}
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(BookingCompleteListActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
@Override
public void itemClicked(View view, int position) {
Intent intent = new Intent(BookingCompleteListActivity.this, BookingPendingDetailActivity.class);
intent.putExtra("Booking", new Gson().toJson(bookingList.get(position)));
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
}<file_sep>package com.smk.promotion;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.smk.model.Booking;
import com.smk.model.User;
import com.smk.utils.StoreUtil;
public class BookingPendingDetailActivity extends BaseAppCompatActivity {
Toolbar toolbar;
TextView txt_name, txt_email, txt_phone_number, txt_shop_name, txt_total_amount, txt_booking_person, txt_booking_date_time;
Booking booking;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking_pending_detail);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_booking_pending_list));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
txt_name = (TextView) findViewById(R.id.txt_name);
txt_email = (TextView) findViewById(R.id.txt_email);
txt_phone_number = (TextView) findViewById(R.id.txt_phone_number);
txt_shop_name = (TextView) findViewById(R.id.txt_shop_name);
txt_booking_person = (TextView) findViewById(R.id.txt_booking_person);
txt_booking_date_time = (TextView) findViewById(R.id.txt_booking_date_time);
lv = (ListView) findViewById(R.id.list);
User user = StoreUtil.getInstance().selectFrom("users");
txt_name.setText(getResources().getString(R.string.name) + " " + user.getName());
txt_email.setText(getResources().getString(R.string.email) + " " + user.getEmail());
txt_phone_number.setText(getResources().getString(R.string.phone_number) + " " + user.getPhone());
Bundle bundle = getIntent().getExtras();
booking = new Gson().fromJson(bundle.getString("Booking"), Booking.class);
try {
txt_shop_name.setText(getResources().getString(R.string.shop_name) + " " + booking.getShop().getName());
txt_booking_person.setText(getResources().getString(R.string.number_of_person) + " " + booking.getBookingPerson().toString());
txt_booking_date_time.setText(getResources().getString(R.string.booking_date) + " " + booking.getBookingDatetime());
} catch (NullPointerException e) {
e.printStackTrace();
}
/*List<Booking> bookingList = new ArrayList<Booking>();
bookingList.add(booking);
BookingDetailAdapter adapter = new BookingDetailAdapter(BookingPendingDetailActivity.this, bookingList.get(0).getOrderDetail());
lv.setAdapter(adapter);*/
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
}
<file_sep>package com.smk.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.mikepenz.iconics.IconicsDrawable;
import com.smk.model.SpecialDiscount;
import com.smk.promotion.R;
import com.smk.utils.CircleTransform;
import com.squareup.picasso.Picasso;
import java.util.List;
public class PromotionListAdapter extends BaseAdapter {
private final String title;
private Context mContext;
private LayoutInflater mInflater;
private List<SpecialDiscount> listItem;
private boolean firstSelfVisible = true;
private boolean firstNotSelfVisible = true;
private Callbacks mCallback;
public PromotionListAdapter(Context ctx, List<SpecialDiscount> list, String title){
mContext = ctx;
listItem = list;
this.title = title;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
@Override
public SpecialDiscount getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if (convertView == null) {
// You can move this line into your constructor, the inflater service won't change.
mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item_promotion, null);
holder = new ViewHolder();
holder.txt_shop_name = (TextView) convertView.findViewById(R.id.txt_shop_name);
holder.txt_shop_distance = (TextView) convertView.findViewById(R.id.txt_shop_distance);
holder.img_shop = (ImageView) convertView.findViewById(R.id.img_shop);
holder.txt_food_price = (TextView) convertView.findViewById(R.id.txt_food_price);
holder.txt_discount = (TextView) convertView.findViewById(R.id.txt_discount);
holder.img_food = (ImageView) convertView.findViewById(R.id.img_food);
holder.txt_food_name = (TextView) convertView.findViewById(R.id.txt_food_name);
holder.txt_no_need = (TextView) convertView.findViewById(R.id.txt_no_need);
holder.txt_more = (TextView) convertView.findViewById(R.id.txt_more);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
SpecialDiscount specialDiscount = getItem(position);
holder.txt_shop_name.setText(specialDiscount.getShopName());
holder.txt_shop_distance.setText(String.format( "%.2f", specialDiscount.getShopDistance() )+" Km "+ mContext.getResources().getString(R.string.str_distance));
Picasso.with(mContext).load("http://foods.528go.com/shops/x200/" + specialDiscount.getShopImage()).placeholder(R.drawable.logo).transform(new CircleTransform()).into(holder.img_shop);
holder.txt_food_name.setText(specialDiscount.getName());
holder.txt_food_price.setText(specialDiscount.getPrice() + " MMK");
Picasso.with(mContext).load("http://foods.528go.com/foodPhotos/x400/" + specialDiscount.getImage()).into(holder.img_food);
int percentage = ((specialDiscount.getPrice() - specialDiscount.getDiscount()) * 100) / specialDiscount.getPrice();
holder.txt_discount.setText(Math.round(100 - percentage)+"% OFF");
holder.txt_food_price.setText((specialDiscount.getPrice() - specialDiscount.getDiscount()) + " MMK");
holder.txt_no_need.setTag(position);
holder.txt_no_need.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = (int) v.getTag();
if(mCallback != null){
mCallback.onClickNoNeed(pos);
}
}
});
holder.txt_more.setTag(position);
holder.txt_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = (int) v.getTag();
if(mCallback != null){
mCallback.onClickMore(pos);
}
}
});
return convertView;
}
public void setOnCallbackLinstener(Callbacks callbacks){
this.mCallback = callbacks;
}
public interface Callbacks{
void onClickNoNeed(int position);
void onClickMore(int position);
}
public IconicsDrawable getIconicDrawable(String icon, int color, int size){
return new IconicsDrawable(mContext)
.icon(icon)
.color(mContext.getResources().getColor(color))
.sizeDp(size);
}
public static class ViewHolder {
TextView txt_shop_name;
TextView txt_shop_distance;
ImageView img_shop;
TextView txt_food_price;
TextView txt_discount;
TextView txt_food_name;
ImageView img_food;
TextView txt_no_need;
TextView txt_more;
}
}
<file_sep>package com.smk.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import com.mikepenz.iconics.view.IconicsImageView;
import com.smk.model.Shop;
import com.smk.promotion.R;
import com.smk.utils.CircleTransform;
import com.smk.utils.ClickListener;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ShopListRVAdapter extends RecyclerView.Adapter<ShopListRVAdapter.ViewHolder> {
Context ctx;
List<Shop> list;
ClickListener clicklistener = null;
public ShopListRVAdapter(Context ctx, List<Shop> list) {
this.ctx = ctx;
this.list = list;
}
@Override
public ShopListRVAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_shop, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ShopListRVAdapter.ViewHolder holder, int position) {
Shop shop = list.get(position);
try {
holder.txt_shop_name.setText(shop.getName());
if (shop.getTotalReviews() <= 1) {
holder.txt_shop_review.setText(shop.getTotalReviews().toString() + " REVIEW");
} else {
holder.txt_shop_review.setText(shop.getTotalReviews().toString() + " REVIEWS");
}
holder.txt_shop_address.setText(ctx.getResources().getString(R.string.address) + " " + shop.getAddress());
holder.txt_shop_phone_number.setText(ctx.getResources().getString(R.string.phone_number) + " " +shop.getPhone());
holder.rbShop.setRating(Float.valueOf(shop.getTotalRatings().toString()));
if (shop.getImage() != null) {
Picasso.with(ctx).load("http://foods.528go.com/shops/x400/" + shop.getImage()).transform(new CircleTransform()).into(holder.img_shop);
}else{
Picasso.with(ctx).load("http://foods.528go.com/shops/x400/...").into(holder.img_shop);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return list.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final IconicsImageView img_shop;
TextView txt_shop_name, txt_shop_review, txt_shop_phone_number, txt_shop_address;
RatingBar rbShop;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rbShop = (RatingBar) itemView.findViewById(R.id.rbShop);
txt_shop_name = (TextView) itemView.findViewById(R.id.txt_shop_name);
txt_shop_review = (TextView) itemView.findViewById(R.id.txt_shop_review);
txt_shop_phone_number = (TextView) itemView.findViewById(R.id.txt_shop_phone_number);
txt_shop_address = (TextView) itemView.findViewById(R.id.txt_shop_address);
img_shop = (IconicsImageView) itemView.findViewById(R.id.img_shop);
}
@Override
public void onClick(View v) {
if (clicklistener != null) {
clicklistener.itemClicked(v, getAdapterPosition());
}
}
}
public void setClickListener(ClickListener clicklistener) {
this.clicklistener = clicklistener;
}
}<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Location implements Serializable{
private Integer passengerId;
private String phone;
@SerializedName("lat")
@Expose
private Double lat;
@SerializedName("lng")
@Expose
private Double lng;
public Location(Integer passengerId, String phone, Double lat, Double lng) {
super();
this.passengerId = passengerId;
this.phone = phone;
this.lat = lat;
this.lng = lng;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getPassengerId() {
return passengerId;
}
public void setPassengerId(Integer passengerId) {
this.passengerId = passengerId;
}
/**
*
* @return
* The lat
*/
public Double getLat() {
return lat;
}
/**
*
* @param lat
* The lat
*/
public void setLat(Double lat) {
this.lat = lat;
}
/**
*
* @return
* The lng
*/
public Double getLng() {
return lng;
}
/**
*
* @param lng
* The lng
*/
public void setLng(Double lng) {
this.lng = lng;
}
@Override
public String toString() {
return "Location [passengerId=" + passengerId + ", phone=" + phone
+ ", lat=" + lat + ", lng=" + lng + "]";
}
}<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ViewHolder;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.smk.adapter.IngredientListAdapter;
import com.smk.client.NetworkEngine;
import com.smk.model.Food;
import com.smk.model.Ingredient;
import com.smk.skalertmessage.SKToastMessage;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.util.ArrayList;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class CreateFoodIngredientActivity extends BaseAppCompatActivity implements View.OnClickListener {
Toolbar toolbar;
MaterialEditText edt_food_material, edt_food_amount, edt_food_unit;
Button btn_add, btn_skip, btn_next;
ListView lvList;
ArrayList<Ingredient> ingredient_list = new ArrayList<Ingredient>();
IngredientListAdapter listAdapter;
Integer food_id;
ZProgressHUD dialog;
private FloatingActionButton btn_add_ingredient;
private Bundle extras;
private Food food;
private boolean doubleBackToExitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_food_ingredient);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_create_food_ingredient));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
lvList = (ListView) findViewById(R.id.lvList);
btn_add_ingredient = (FloatingActionButton) findViewById(R.id.btn_add_ingredient);
btn_skip = (Button) findViewById(R.id.btn_skip);
btn_next = (Button) findViewById(R.id.btn_next);
if (btn_next != null) {
btn_next.setOnClickListener(this);
}
btn_skip.setOnClickListener(this);
btn_add_ingredient.setOnClickListener(this);
extras = getIntent().getExtras();
food_id = extras.getInt("food_id");
food = new Gson().fromJson(extras.getString("food"), Food.class);
if(food != null){
ingredient_list.addAll(food.getIngredients());
btn_next.setText(getResources().getString(R.string.str_update));
btn_skip.setText(getResources().getString(R.string.str_cancel));
}
listAdapter = new IngredientListAdapter(CreateFoodIngredientActivity.this, ingredient_list);
lvList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
listAdapter.setOnCallbackListener(new IngredientListAdapter.Callbacks() {
@Override
public void onClickDelete(int position) {
if(food != null && ingredient_list.get(position).getId() != null){
deleteIngredient(ingredient_list.get(position).getId(), position);
}else {
ingredient_list.remove(position);
listAdapter.notifyDataSetChanged();
}
}
});
}
private void addIngredient() {
View contentView = View.inflate(this, R.layout.dialog_ingredient, null);
edt_food_material = (MaterialEditText) contentView.findViewById(R.id.edt_food_material);
edt_food_amount = (MaterialEditText) contentView.findViewById(R.id.edt_food_amount);
edt_food_unit = (MaterialEditText) contentView.findViewById(R.id.edt_food_unit);
btn_add = (Button) contentView.findViewById(R.id.btn_add);
final DialogPlus dialog = DialogPlus.newDialog(this)
.setContentHolder(new ViewHolder(contentView))
.setExpanded(false) // This will enable the expand feature, (similar to android L share dialog)
.create();
dialog.show();
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkField()) {
String foodMaterial = edt_food_material.getText().toString();
String foodAmount = edt_food_amount.getText().toString();
String foodUnit = edt_food_unit.getText().toString();
Ingredient mIngredient = new Ingredient();
mIngredient.setFoodId(food_id);
mIngredient.setName(foodMaterial);
mIngredient.setIngredientAmt(Integer.valueOf(foodAmount));
mIngredient.setIngredientUnit(foodUnit);
ingredient_list.add(mIngredient);
listAdapter.notifyDataSetChanged();
dialog.dismiss();
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add_ingredient:
addIngredient();
break;
case R.id.btn_skip:
if(food != null){
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", extras.getString("shop"));
startActivity(intent);
}else{
Intent intent = new Intent(CreateFoodIngredientActivity.this, CreateFoodPhotoActivity.class);
intent.putExtras(extras);
startActivity(intent);
}
finish();
break;
case R.id.btn_next:
if (ingredient_list != null && ingredient_list.size() > 0)
postIngredient();
else
SKToastMessage.showMessage(CreateFoodIngredientActivity.this, getResources().getString(R.string.str_please_add_ingredient), SKToastMessage.ERROR);
break;
default:
break;
}
}
private void deleteIngredient(Integer id, final int position){
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().deleteIngredient(id, new Callback<String>() {
@Override
public void success(String arg0, Response response) {
dialog.dismissWithSuccess();
ingredient_list.remove(position);
listAdapter.notifyDataSetChanged();
}
@Override
public void failure(RetrofitError error) {
dialog.dismissWithFailure();
}
});
}
private void postIngredient() {
dialog = new ZProgressHUD(this);
dialog.show();
ArrayList<Ingredient> uploadIngredients = new ArrayList<>();
for(Ingredient ingredient: ingredient_list){
if(ingredient.getId() == null){
uploadIngredients.add(ingredient);
}
}
if(uploadIngredients.size() == 0){
SKToastMessage.showMessage(this, getResources().getString(R.string.str_alert_create_ingredient), SKToastMessage.ERROR);
dialog.dismiss();
return;
}
NetworkEngine.getInstance().postIngredient(new Gson().toJson(uploadIngredients), new Callback<JsonObject>() {
@Override
public void success(JsonObject arg0, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
if(food != null){
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", extras.getString("shop"));
startActivity(intent);
}else{
Intent intent = new Intent(CreateFoodIngredientActivity.this, CreateFoodPhotoActivity.class);
intent.putExtras(extras);
startActivity(intent);
}
finish();
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(CreateFoodIngredientActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private boolean checkField() {
if (edt_food_material.getText().length() == 0) {
edt_food_material.setError(getResources().getString(R.string.invalid_food_material));
edt_food_material.requestFocus();
return false;
}
if (edt_food_amount.getText().length() == 0) {
edt_food_amount.setError(getResources().getString(R.string.invalid_food_amount));
edt_food_amount.requestFocus();
return false;
}
if (edt_food_unit.getText().length() == 0) {
edt_food_unit.setError(getResources().getString(R.string.invalid_food_unit));
edt_food_unit.requestFocus();
return false;
}
return true;
}
@Nullable
@Override
public Intent getSupportParentActivityIntent() {
onBackPressed();
return super.getSupportParentActivityIntent();
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
SKToastMessage.showMessage(this, getResources().getString(R.string.press_again_cancel), SKToastMessage.INFO);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
<file_sep>package com.smk.fragment;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.smk.model.QuickStart;
import com.smk.promotion.R;
public class QuickStartFragment extends Fragment {
private View convertView;
private ImageView image;
private TextView title;
private TextView desc;
private int mPosition;
private QuickStart quickStart;
// TODO: Rename parameter arguments, choose names that match
public QuickStartFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static QuickStartFragment newInstance(int position, QuickStart quickStart) {
QuickStartFragment frag = new QuickStartFragment();
Bundle bundle = new Bundle();
bundle.putInt("_position", position);
bundle.putString("_object", new Gson().toJson(quickStart));
frag.setArguments(bundle);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPosition = getArguments() != null ? getArguments().getInt("_position") : 1;
quickStart = getArguments() != null ? new Gson().fromJson(getArguments().getString("_object"), QuickStart.class) : null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
convertView = inflater.inflate(R.layout.fragment_quick_start, container, false);
return convertView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
image = (ImageView) convertView.findViewById(R.id.img_quick);
title = (TextView) convertView.findViewById(R.id.txt_title);
desc = (TextView) convertView.findViewById(R.id.txt_desc);
desc.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/zawgyione.ttf"));
image.setImageResource(quickStart.getImage());
image.setBackgroundColor(Color.parseColor(quickStart.getBackground()));
title.setText(quickStart.getTitle());
desc.setText(quickStart.getDesc());
}
}
<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class FoodCategory implements Serializable {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("type_id")
@Expose
private Integer typeId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("description")
@Expose
private String description;
@SerializedName("icon")
@Expose
private String icon;
@SerializedName("background")
@Expose
private String background;
@SerializedName("color")
@Expose
private String color;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("deleted_at")
@Expose
private Object deletedAt;
/**
* @return The id
*/
public Integer getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Integer id) {
this.id = id;
}
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
/**
* @return The name
*/
public String getName() {
return name;
}
/**
* @param name The name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return The description
*/
public String getDescription() {
return description;
}
/**
* @param description The description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return The icon
*/
public String getIcon() {
return icon;
}
/**
* @param icon The icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* @return The background
*/
public String getBackground() {
return background;
}
/**
* @param background The background
*/
public void setBackground(String background) {
this.background = background;
}
/**
* @return The color
*/
public String getColor() {
return color;
}
/**
* @param color The color
*/
public void setColor(String color) {
this.color = color;
}
/**
* @return The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
* @param createdAt The created_at
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
* @return The updatedAt
*/
public String getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt The updated_at
*/
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return The deletedAt
*/
public Object getDeletedAt() {
return deletedAt;
}
/**
* @param deletedAt The deleted_at
*/
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
@Override
public String toString() {
return name;
}
}<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.File;
import java.io.Serializable;
public class UploadFoodPhoto implements Serializable{
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("image")
@Expose
private String image;
private File photo;
public UploadFoodPhoto(Integer id, String image, File photo) {
this.id = id;
this.image = image;
this.photo = photo;
}
public UploadFoodPhoto(File photo) {
this.photo = photo;
}
/**
* @return The id
*/
public Integer getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return The image
*/
public String getImage() {
return image;
}
/**
* @param image The image
*/
public void setImage(String image) {
this.image = image;
}
public File getPhoto() {
return photo;
}
public void setPhoto(File photo) {
this.photo = photo;
}
}<file_sep>package com.smk.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.view.IconicsImageView;
import com.ms.square.android.expandabletextview.ExpandableTextView;
import com.smk.model.Food;
import com.smk.promotion.R;
import com.smk.utils.CircleTransform;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class SearchResultRVAdapter extends RecyclerView.Adapter<SearchResultRVAdapter.ItemViewHolder> {
List<Food> foodList;
Context ctx;
public SearchResultRVAdapter(Context ctx, List<Food> foodList) {
this.ctx = ctx;
this.foodList = foodList;
}
@Override
public int getItemCount() {
return foodList.size();
}
@Override
public SearchResultRVAdapter.ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_item, parent, false);
return new SearchResultRVAdapter.ItemViewHolder(view) {
};
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
try {
Picasso.with(ctx).load("http://foods.528go.com/shops/x200/" + foodList.get(position).getShop().getImage()).placeholder(getIconicDrawable(GoogleMaterial.Icon.gmd_account_circle.toString(), R.color.colorGreen, 48)).transform(new CircleTransform()).into(holder.img_shop);
holder.txt_shop_name.setText(foodList.get(position).getShop().getName());
holder.rbShop.setRating(Float.valueOf(foodList.get(position).getShop().getTotalRatings().toString()));
if (foodList.get(position).getShop().getTotalReviews() <= 1) {
holder.txt_shop_review.setText(foodList.get(position).getShop().getTotalReviews().toString() + " REVIEW");
} else {
holder.txt_shop_review.setText(foodList.get(position).getShop().getTotalReviews().toString() + " REVIEWS");
}
Picasso.with(ctx).load("http://foods.528go.com/foodPhotos/x400/" + foodList.get(position).getFoodPhotos().get(0).getImage()).into(holder.img_food);
holder.txt_food_price.setText(foodList.get(position).getFoodSizes().get(0).getPrice().toString() + " MMK");
holder.txt_food_name.setText(foodList.get(position).getName());
holder.txt_shop_time.setText(foodList.get(position).getShop().getOpenHr());
DecimalFormat form = new DecimalFormat("0.0");
holder.txt_food_rating.setText(form.format(foodList.get(position).getTotalRatings()));
holder.txt_food_like.setText(foodList.get(position).getTotalLikes().toString());
holder.txt_food_review.setText(foodList.get(position).getTotalReviews().toString());
if(foodList.get(position).getShop().getOpenHr() != null && foodList.get(position).getShop().getOpenHr().contains("to")){
String[] openHr = foodList.get(position).getShop().getOpenHr().split(" to ");
if(openHr.length == 2){
if(checkOpen(openHr[0], openHr[1])){
holder.ico_open.setIcon(GoogleMaterial.Icon.gmd_timelapse);
holder.ico_open.setColor(ctx.getResources().getColor(R.color.colorPrimary));
}else{
holder.ico_open.setIcon(CommunityMaterial.Icon.cmd_sleep);
holder.ico_open.setColor(ctx.getResources().getColor(R.color.md_grey_500));
}
}
}
if(!foodList.get(position).getShop().getOpenHr().contains("to")){
holder.txt_shop_time.setText("24 Hours Open");
}
if(foodList.get(position).getFoodDiscounts() != null && foodList.get(position).getFoodDiscounts().size() > 0 && foodList.get(position).getFoodSizes() != null && foodList.get(position).getFoodSizes().size() > 0){
holder.txt_discount.setVisibility(View.VISIBLE);
int percentage = ((foodList.get(position).getFoodSizes().get(0).getPrice() - foodList.get(position).getFoodDiscounts().get(0).getDiscount()) * 100) / foodList.get(position).getFoodSizes().get(0).getPrice();
holder.txt_discount.setText(Math.round(100 - percentage)+"% OFF");
holder.txt_food_price.setText((foodList.get(position).getFoodSizes().get(0).getPrice() - foodList.get(position).getFoodDiscounts().get(0).getDiscount()) + " MMK");
}else{
holder.txt_discount.setVisibility(View.GONE);
}
} catch (NullPointerException | IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
private boolean checkOpen(String startTime, String endTime){
try {
Date time1 = new SimpleDateFormat("h:mm a").parse(startTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
Date time2 = new SimpleDateFormat("h:mm a").parse(endTime);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("h:mm a");
String currentTime = date.format(currentLocalTime);
Date d = new SimpleDateFormat("h:mm a").parse(currentTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private final IconicsImageView ico_open;
private final TextView txt_discount;
public TextView txt_header_name, txt_header_desc, txt_shop_name, txt_shop_review, txt_food_price, txt_food_name, txt_shop_time, txt_food_rating, txt_food_like, txt_food_review;
public IconicsImageView img_shop;
public RatingBar rbShop;
public ImageView img_header_food, img_food;
public ExpandableTextView expand_text_view;
public ItemViewHolder(View itemView) {
super(itemView);
// TYPE_CELL
img_shop = (IconicsImageView) itemView.findViewById(R.id.img_shop);
ico_open = (IconicsImageView) itemView.findViewById(R.id.ico_open_time);
txt_shop_name = (TextView) itemView.findViewById(R.id.txt_shop_name);
rbShop = (RatingBar) itemView.findViewById(R.id.rb_shop);
txt_shop_review = (TextView) itemView.findViewById(R.id.txt_shop_review);
img_food = (ImageView) itemView.findViewById(R.id.img_food);
txt_food_price = (TextView) itemView.findViewById(R.id.txt_food_price);
txt_discount = (TextView) itemView.findViewById(R.id.txt_discount);
txt_food_name = (TextView) itemView.findViewById(R.id.txt_food_name);
expand_text_view = (ExpandableTextView) itemView.findViewById(R.id.expand_text_view);
txt_shop_time = (TextView) itemView.findViewById(R.id.txt_shop_time);
txt_food_rating = (TextView) itemView.findViewById(R.id.txt_food_rating);
txt_food_like = (TextView) itemView.findViewById(R.id.txt_food_like);
txt_food_review = (TextView) itemView.findViewById(R.id.txt_food_review);
}
}
public IconicsDrawable getIconicDrawable(String icon, int color, int size) {
return new IconicsDrawable(ctx)
.icon(icon)
.color(ctx.getResources().getColor(color))
.sizeDp(size);
}
}<file_sep>package com.smk.client;
import com.google.gson.JsonObject;
import com.smk.model.Booking;
import com.smk.model.Business;
import com.smk.model.Food;
import com.smk.model.FoodCategory;
import com.smk.model.FoodDiscount;
import com.smk.model.FoodReview;
import com.smk.model.FoodType;
import com.smk.model.GeoLocation;
import com.smk.model.Ingredient;
import com.smk.model.Order;
import com.smk.model.Shop;
import com.smk.model.ShopNotiCount;
import com.smk.model.ShopReview;
import com.smk.model.ShopUser;
import com.smk.model.Shoptype;
import com.smk.model.User;
import com.smk.model.UserLike;
import com.smk.model.UserNotiCount;
import java.util.List;
import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.DELETE;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
import retrofit.mime.MultipartTypedOutput;
public interface INetworkEngine {
@FormUrlEncoded
@POST("/api/v1/login")
void postLogin(
@Field("email") String email,
@Field("password") String password,
Callback<User> callback);
@FormUrlEncoded
@POST("/api/v1/users")
void postRegister(
@Field("name") String name,
@Field("password") String password,
@Field("phone") String phone,
@Field("image") String image,
Callback<User> callback);
@GET("/api/v1/users")
void getUsers(
@Query("shop_id") Integer shop_id,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
Callback<List<User>> callback);
@PUT("/api/v1/users/{id}")
void updateUser(
@Path("id") Integer id,
@Query("name") String name,
@Query("password") String password,
@Query("phone") String phone,
@Query("image") String image,
Callback<User> callback);
@GET("/api/v1/users/{id}")
void getUser(@Path("id") Integer id, Callback<User> callback);
@POST("/api/v1/userUploadImage")
void uploadUserPhoto(
@Body MultipartTypedOutput attachments,
Callback<String> callback);
@FormUrlEncoded
@POST("/api/v1/foodOrders")
void postOrderConfirm(
@Field("user_id") Integer user_id,
@Field("order_menus") String order_menus,
@Field("status") Integer status,
Callback<JsonObject> callback);
@FormUrlEncoded
@POST("/api/v1/foodOrders")
void postBookingConfirm(
@Field("user_id") Integer user_id,
@Field("shop_id") Integer shop_id,
@Field("booking_person") Integer booking_person,
@Field("booking_datetime") String booking_datetime,
@Field("phone") String phone,
@Field("note") String note,
@Field("order_menus") String order_menus,
@Field("status") Integer status,
Callback<JsonObject> callback);
@DELETE("/api/v1/foodOrders/{id}")
void getDeleteOrder(
@Path("id") Integer id,
Callback<String> callback);
@PUT("/api/v1/foodOrders/{id}")
void acceptOrder(
@Path("id") Integer id,
@Query("approved") boolean approved,
Callback<Order> callback);
@GET("/api/v1/userOrder/{id}")
void getOrder(
@Path("id") Integer id,
@Query("approved") Boolean approved,
Callback<List<Order>> callback);
@GET("/api/v1/userBooking/{id}")
void getBooking(
@Path("id") Integer id,
@Query("approved") Boolean approved,
Callback<List<Booking>> callback);
@GET("/api/v1/shopNotiCount/{id}")
void getShopNotiCount(
@Path("id") Integer id,
Callback<ShopNotiCount> callback);
@GET("/api/v1/userNotiCount/{id}")
void getUserNotiCount(
@Path("id") Integer id,
Callback<UserNotiCount> callback);
@FormUrlEncoded
@POST("/api/v1/shops")
void postShop(
@Field("name") String name,
@Field("address") String address,
@Field("lat") double lat,
@Field("lng") double lng,
@Field("phone") String phone,
@Field("image") String image,
@Field("shop_type_id") Integer shop_type_id,
@Field("open_hr") String open_hr,
@Field("user_id") Integer user_id,
Callback<Shop> callback);
@FormUrlEncoded
@POST("/api/v1/shopActivate/{id}")
void activateShop(
@Path("id") Integer id,
@Field("activation_code") String activation_code,
Callback<Shop> callback);
@FormUrlEncoded
@POST("/api/v1/resendActivate/{id}")
void resendActivateCode(
@Path("id") Integer id,
@Field("phone") String phone,
Callback<Shop> callback);
@POST("/api/v1/shopUploadImage")
void uploadShopPhoto(
@Body MultipartTypedOutput attachments,
Callback<String> callback);
@GET("/api/v1/foodTypes")
void getFoodTypes(
Callback<List<FoodType>> callback);
@GET("/api/v1/foodCategories")
void getFoodCategory(
Callback<List<FoodCategory>> callback);
@GET("/api/v1/foods")
void getFood(
@Query("type_id") Integer type_id,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
Callback<List<Food>> callback);
@GET("/api/v1/food/{id}")
void getShopFoodList(
@Path("id") Integer id,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
Callback<List<Food>> callback);
@GET("/api/v1/shops")
void getShop(
@Query("shop_id") Integer shop_id,
Callback<List<Shop>> callback);
@FormUrlEncoded
@POST("/api/v1/foodReviews")
void postFoodRatingAndReview(
@Field("reviews") String reviews,
@Field("ratings") Double ratings,
@Field("food_id") Integer food_id,
@Field("user_id") Integer user_id,
Callback<FoodReview> callback);
@FormUrlEncoded
@POST("/api/v1/shopReviews")
void postShopRatingAndReview(
@Field("reviews") String reviews,
@Field("ratings") Double ratings,
@Field("shop_id") Integer shop_id,
@Field("user_id") Integer user_id,
Callback<ShopReview> callback);
@POST("/api/v1/foodPhotos")
void uploadFoodPhoto(
@Body MultipartTypedOutput attachments,
Callback<JsonObject> callback);
@DELETE("/api/v1/foodPhotos/{id}")
void deletePhoto(@Path("id") Integer id, Callback<String> callback);
@FormUrlEncoded
@POST("/api/v1/userLikes")
void postUserLike(
@Field("food_id") Integer food_id,
@Field("user_id") Integer user_id,
Callback<UserLike> callback);
@GET("/api-v1/business")
void getBusiness(
Callback<List<Business>> callback);
@GET("/api/v1/shoptypes")
void getShopType(
Callback<List<Shoptype>> callback);
@GET("/api/v1/foodReviews")
void getFoodReview(
@Query("food_id") Integer food_id,
Callback<List<FoodReview>> callback);
@GET("/api/v1/shopReviews")
void getShopReview(
@Query("shop_id") Integer food_id,
Callback<List<ShopReview>> callback);
@GET("/api/v1/ingredients")
void getIngredient(
@Query("food_id") Integer food_id,
Callback<List<Ingredient>> callback);
@FormUrlEncoded
@POST("/api/v1/foods")
void postFoodInformation(
@Field("name") String name,
@Field("category_id") Integer category_id,
@Field("description") String description,
@Field("shop_id") Integer shop_id,
@Field("order_now") Integer order_now,
Callback<Food> callback);
@PUT("/api/v1/foods/{id}")
void updateFoodInformation(
@Path("id") Integer id,
@Query("name") String name,
@Query("category_id") Integer category_id,
@Query("description") String description,
@Query("shop_id") Integer shop_id,
@Query("order_now") Integer order_now,
Callback<Food> callback);
@DELETE("/api/v1/foods/{id}")
void deleteFoodInformation(
@Path("id") Integer id,
Callback<String> callback);
@FormUrlEncoded
@POST("/api/v1/foodSizes")
void postSizeAndPrice(
@Field("json") String json,
Callback<JsonObject> callback);
@DELETE("/api/v1/foodSizes/{id}")
void deleteSizePrice(
@Path("id") Integer id,
Callback<String> callback);
@GET("/api/v1/foodSizes")
void getFoodSize(
@Query("food_id") Integer food_id,
@Query("size") String size,
Callback<List<Food>> callback);
@FormUrlEncoded
@POST("/api/v1/ingredients")
void postIngredient(
@Field("json") String json,
Callback<JsonObject> callback);
@DELETE("/api/v1/ingredients/{id}")
void deleteIngredient(
@Path("id") Integer id,
Callback<String> callback);
@FormUrlEncoded
@POST("/api/v1/foodDiscounts")
void postDiscount(
@Field("food_id") Integer food_id,
@Field("discount") Integer discount,
@Field("start_date") String start_date,
@Field("end_date") String end_date,
Callback<FoodDiscount> callback);
@PUT("/api/v1/foodDiscounts/{id}")
void editDiscount(
@Path("id") Integer id,
@Query("food_id") Integer food_id,
@Query("discount") Integer discount,
@Query("start_date") String start_date,
@Query("end_date") String end_date,
Callback<FoodDiscount> callback);
@GET("/maps/api/geocode/json")
void getGoogleAddress(
@Query("latlng") String latlng,
@Query("sensor") Boolean sensor,
Callback<GeoLocation> callback);
@GET("/api/v1/food/search")
void searchFood(
@Query("keywords") String keywords,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
Callback<List<Food>> callback);
@GET("/api/v1/checkUserLike/{food_id}/{user_id}")
void checkUserLike(
@Path("food_id") Integer food_id,
@Path("user_id") Integer user_id,
Callback<Boolean> callback);
@FormUrlEncoded
@POST("/api/v1/deleteUserLike")
void deleteUserLike(
@Field("food_id") Integer food_id,
@Field("user_id") Integer user_id,
Callback<Integer> callback);
@GET("/api/v1/userLikes")
void getUserLike(
@Query("food_id") Integer food_id,
Callback<Integer> callback);
@GET("/api/v1/shopUsers")
void getShopUser(
@Query("shop_id") Integer shop_id,
Callback<List<ShopUser>> callback);
@GET("/api/v1/foodOrders")
void getShopOrder(
@Query("shop_id") Integer shop_id,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
Callback<List<Order>> callback);
@GET("/api/v1/version")
void getNewVersion(Callback<Integer> callback);
@FormUrlEncoded
@POST("/api/v1/gcmDevices")
void postGcmDevice(
@Field("device_id") String device_id,
@Field("register_id") String register_id,
Callback<JsonObject> callback);
@FormUrlEncoded
@POST("/api/v1/gcmDevices")
void updateGcmDevice(
@Field("device_id") String device_id,
@Field("register_id") String register_id,
@Field("user_id") Integer user_id,
Callback<JsonObject> callback);
@GET("/api/v1/nearbyPromotion")
void getNearbyPromotion(
@Query("lat") double lat,
@Query("lng") double lng,
@Query("distance") double distance,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
Callback<List<Food>> callback);
@GET("/api/v1/nearbyNotification/{device_id}")
void getNearbyNotification(
@Path("device_id") String device_id,
@Query("lat") double lat,
@Query("lng") double lng,
Callback<Integer> callback);
}
<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Ingredient implements Serializable{
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("food_id")
@Expose
private Integer foodId;
@SerializedName("ingredient_amt")
@Expose
private Integer ingredientAmt;
@SerializedName("ingredient_unit")
@Expose
private String ingredientUnit;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("deleted_at")
@Expose
private Object deletedAt;
@SerializedName("food")
@Expose
private Food food;
/**
* @return The id
*/
public Integer getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return The name
*/
public String getName() {
return name;
}
/**
* @param name The name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return The foodId
*/
public Integer getFoodId() {
return foodId;
}
/**
* @param foodId The food_id
*/
public void setFoodId(Integer foodId) {
this.foodId = foodId;
}
/**
* @return The ingredientAmt
*/
public Integer getIngredientAmt() {
return ingredientAmt;
}
/**
* @param ingredientAmt The ingredient_amt
*/
public void setIngredientAmt(Integer ingredientAmt) {
this.ingredientAmt = ingredientAmt;
}
/**
* @return The ingredientUnit
*/
public String getIngredientUnit() {
return ingredientUnit;
}
/**
* @param ingredientUnit The ingredient_unit
*/
public void setIngredientUnit(String ingredientUnit) {
this.ingredientUnit = ingredientUnit;
}
/**
* @return The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
* @param createdAt The created_at
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
* @return The updatedAt
*/
public String getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt The updated_at
*/
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return The deletedAt
*/
public Object getDeletedAt() {
return deletedAt;
}
/**
* @param deletedAt The deleted_at
*/
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
/**
* @return The food
*/
public Food getFood() {
return food;
}
/**
* @param food The food
*/
public void setFood(Food food) {
this.food = food;
}
}<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.smk.promotion"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
debuggable true
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dexOptions {
jumboMode true
}
}
repositories {
mavenCentral()
jcenter()
maven { url "https://jitpack.io" }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile ('com.github.florent37:materialviewpager:1.2.0@aar'){
transitive = true
}
compile('com.mikepenz:materialdrawer:4.5.6@aar') {
transitive = true
}
compile project(':MapNavigator')
compile project(':Websockets')
compile project(':SKAlertMessage')
compile project(':noCropper')
compile project(':ZProgressHUD')
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.code.gson:gson:2.5'
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:cardview-v7:23.3.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:design:23.3.0'
compile 'com.rengwuxian.materialedittext:library:2.1.4'
compile 'com.github.ganfra:material-spinner:1.1.1'
compile 'com.wdullaer:materialdatetimepicker:2.1.0'
compile 'com.mikepenz:iconics-core:2.5.1@aar'
compile 'com.mikepenz:google-material-typeface:2.1.0.1.original@aar'
compile 'com.mikepenz:material-design-iconic-typeface:2.2.0.2@aar'
compile 'com.mikepenz:fontawesome-typeface:4.5.0.1@aar'
compile 'com.mikepenz:octicons-typeface:3.2.0.1@aar'
compile 'com.mikepenz:meteocons-typeface:1.1.0.1@aar'
compile 'com.mikepenz:community-material-typeface:1.3.41.1@aar'
compile 'com.mikepenz:typeicons-typeface:2.0.7.1@aar'
compile 'com.mikepenz:entypo-typeface:1.0.0.1@aar'
compile 'com.mikepenz:devicon-typeface:2.0.0.1@aar'
compile 'com.mikepenz:ionicons-typeface:2.0.1.1@aar'
compile 'com.kyleduo.switchbutton:library:1.3.1'
compile 'com.ms-square:expandableTextView:0.1.4'
compile 'com.github.jkwiecien:EasyImage:1.1.0'
compile 'me.relex:circleindicator:1.1.6@aar'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.github.kanytu:android-parallax-recyclerview:v1.4'
compile 'com.android.support:support-v4:23.3.0'
compile 'com.alexbbb:uploadservice:1.6'
compile 'info.hoang8f:android-segmented:1.0.6'
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
compile 'com.orhanobut:dialogplus:1.11@aar'
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.github.curioustechizen.android-ago:library:1.3.2'
compile 'com.miguelcatalan:materialsearchview:1.4.0'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'
compile 'com.google.maps.android:android-maps-utils:0.4.3'
compile 'com.facebook.android:facebook-android-sdk:4.+'
compile 'com.rockerhieu.emojicon:library:1.3.3'
compile 'org.apache.commons:commons-lang3:3.4'
compile 'org.lucasr.twowayview:twowayview:0.1.4'
compile 'com.google.maps.android:android-maps-utils:0.4+'
compile "com.android.support:support-v4:+"
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
}
<file_sep>apply plugin: 'com.android.library'
version = "0.1.3"
group = "com.fenchtose.nocropper"
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
resourcePrefix "nocropper__"
defaultConfig {
minSdkVersion 11
targetSdkVersion 23
versionCode 1
versionName version
}
buildTypes {
}
}
dependencies {
}
<file_sep>package com.smk.promotion;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.google.gson.Gson;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.view.IconicsImageView;
import com.smk.adapter.FoodReviewRVAdapter;
import com.smk.client.NetworkEngine;
import com.smk.model.Food;
import com.smk.model.FoodReview;
import com.smk.model.User;
import com.smk.model.UserLike;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.CircleTransform;
import com.smk.utils.StoreUtil;
import com.squareup.picasso.Picasso;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class FoodReviewActivity extends BaseAppCompatActivity {
Toolbar toolbar;
ImageView img_food;
TextView txt_food_like;
TextView btn_share;
Button btn_review;
RecyclerView recyclerView;
FoodReviewRVAdapter mAdapter;
List<FoodReview> food_review;
Food food;
private ZProgressHUD loadingDialog;
User user;
private CallbackManager callbackManager;
private ShareDialog shareDialog;
private LinearLayout btn_like;
private IconicsImageView ico_like;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_reviews);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_food_review));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
}
});
img_food = (ImageView) findViewById(R.id.img_food);
btn_like = (LinearLayout) findViewById(R.id.btn_like);
txt_food_like = (TextView) findViewById(R.id.txt_food_like);
btn_share = (TextView) findViewById(R.id.btn_share);
ico_like = (IconicsImageView) findViewById(R.id.ico_like);
btn_review = (Button) findViewById(R.id.btn_review);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
/*RelativeTimeTextView v = (RelativeTimeTextView)findViewById(R.id.timestamp); //Or just use Butterknife!
v.setReferenceTime(new Date().getTime());*/
btn_review.setOnClickListener(clickListener);
Bundle bundle = getIntent().getExtras();
food = new Gson().fromJson(bundle.getString("Foods"), Food.class);
user = StoreUtil.getInstance().selectFrom("users");
getUserLike();
checkUserLike();
getFoodReview();
try {
if (food.getFoodPhotos() != null && food.getFoodPhotos().size() > 0) {
Picasso.with(this).load("http://foods.528go.com/foodPhotos/x400/" + food.getFoodPhotos().get(0).getImage()).into(img_food);
}
if (food.getTotalLikes().toString() != null && food.getTotalLikes().toString().length() > 0) {
txt_food_like.setText(String.valueOf(food.getTotalLikes()));
}
} catch (NullPointerException e) {
e.printStackTrace();
}
food_review = new ArrayList<>();
mAdapter = new FoodReviewRVAdapter(FoodReviewActivity.this, food_review);
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
btn_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle(food.getName())
.setContentDescription(food.getDescription())
.setImageUrl(Uri.parse("http://foods.528go.com/foodPhotos/"+food.getFoodPhotos().get(0).getImage().replace(" ","%20")))
.setContentUrl(Uri.parse("http://food.528go.com/detail/"+food.getId()))
.build();
shareDialog.show(linkContent);
}
}
});
}
private void deleteUserLike(){
loadingDialog = new ZProgressHUD(this);
loadingDialog.show();
NetworkEngine.getInstance().deleteUserLike(food.getId(), user.getId(), new Callback<Integer>() {
@Override
public void success(Integer likeCount, Response response) {
txt_food_like.setText(""+likeCount);
ico_like.setColor(getResources().getColor(R.color.md_grey_500));
btn_like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postLike();
}
});
loadingDialog.dismissWithSuccess();
}
@Override
public void failure(RetrofitError error) {
loadingDialog.dismissWithFailure();
}
});
}
private void postLike(){
loadingDialog = new ZProgressHUD(FoodReviewActivity.this);
loadingDialog.show();
NetworkEngine.getInstance().postUserLike(food.getId(), user.getId(), new Callback<UserLike>() {
@Override
public void success(UserLike userLike, Response response) {
loadingDialog.dismissWithSuccess();
txt_food_like.setText(userLike.getFood().getTotalLikes().toString());
ico_like.setColor(getResources().getColor(R.color.colorAccent));
btn_like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteUserLike();
}
});
}
@Override
public void failure(RetrofitError error) {
loadingDialog.dismissWithSuccess();
}
});
}
private void checkUserLike(){
NetworkEngine.getInstance().checkUserLike(food.getId(), user.getId(), new Callback<Boolean>() {
@Override
public void success(Boolean like, Response response) {
if(like){
ico_like.setColor(getResources().getColor(R.color.colorAccent));
btn_like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteUserLike();
}
});
}else{
ico_like.setColor(getResources().getColor(R.color.md_grey_500));
btn_like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postLike();
}
});
}
}
@Override
public void failure(RetrofitError error) {
}
});
}
private void getUserLike(){
NetworkEngine.getInstance().getUserLike(food.getId(), new Callback<Integer>() {
@Override
public void success(Integer likeCount, Response response) {
txt_food_like.setText(""+likeCount);
}
@Override
public void failure(RetrofitError error) {
}
});
}
private void getFoodReview() {
loadingDialog = new ZProgressHUD(this);
loadingDialog.show();
NetworkEngine.getInstance().getFoodReview(food.getId(), new Callback<List<FoodReview>>() {
@Override
public void success(List<FoodReview> foodReviews, Response response) {
food_review.addAll(foodReviews);
mAdapter.notifyDataSetChanged();
loadingDialog.dismissWithSuccess();
}
@Override
public void failure(RetrofitError error) {
loadingDialog.dismissWithFailure();
}
});
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (user != null) {
if (v == btn_review) {
setUpDialog();
}
} else {
SKToastMessage.showMessage(FoodReviewActivity.this, getResources().getString(R.string.require_login), SKToastMessage.INFO);
startActivity(new Intent(FoodReviewActivity.this, LoginActivity.class));
}
}
};
private void setUpDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View convertView = View.inflate(this, R.layout.dialog_review, null);
dialog.setContentView(convertView);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button btn_cancel = (Button) convertView.findViewById(R.id.btn_cancel);
Button btn_submit = (Button) convertView.findViewById(R.id.btn_submit);
final TextView txt_food_review = (TextView) convertView.findViewById(R.id.txt_food_review);
final RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.rb_food);
IconicsImageView img_user = (IconicsImageView) convertView.findViewById(R.id.img_user);
final TextView txt_user_name = (TextView) convertView.findViewById(R.id.txt_user_name);
txt_user_name.setText(user.getName());
Picasso.with(this).load("http://foods.528go.com/users/x200/" + user.getImage()).placeholder(getIconicDrawable(GoogleMaterial.Icon.gmd_account_circle.toString(), R.color.colorAccent, 48)).transform(new CircleTransform()).into(img_user);
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadingDialog = new ZProgressHUD(FoodReviewActivity.this);
loadingDialog.show();
double ratingResult = (double) ratingBar.getRating();
// DecimalFormat form = new DecimalFormat("0.0");
// String res = form.format(ratingResult);
NetworkEngine.getInstance().postFoodRatingAndReview(txt_food_review.getText().toString(), ratingResult, food.getId(), user.getId(), new Callback<FoodReview>() {
@Override
public void success(FoodReview foodReview, Response response) {
food_review.add(foodReview);
loadingDialog.dismissWithSuccess();
mAdapter.notifyDataSetChanged();
SKToastMessage.showMessage(FoodReviewActivity.this, foodReview.getMessage(), SKToastMessage.INFO);
dialog.cancel();
}
@Override
public void failure(RetrofitError error) {
loadingDialog.dismissWithFailure();
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(FoodReviewActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
dialog.cancel();
}
});
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
public IconicsDrawable getIconicDrawable(String icon, int color, int size) {
return new IconicsDrawable(this)
.icon(icon)
.color(this.getResources().getColor(color))
.sizeDp(size);
}
}
<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ShopNotiCount {
@SerializedName("item_count")
@Expose
private Integer itemCount;
@SerializedName("user_count")
@Expose
private Integer userCount;
@SerializedName("order_count")
@Expose
private Integer orderCount;
/**
* @return The itemCount
*/
public Integer getItemCount() {
return itemCount;
}
/**
* @param itemCount The item_count
*/
public void setItemCount(Integer itemCount) {
this.itemCount = itemCount;
}
/**
* @return The userCount
*/
public Integer getUserCount() {
return userCount;
}
/**
* @param userCount The user_count
*/
public void setUserCount(Integer userCount) {
this.userCount = userCount;
}
/**
* @return The orderCount
*/
public Integer getOrderCount() {
return orderCount;
}
/**
* @param orderCount The order_count
*/
public void setOrderCount(Integer orderCount) {
this.orderCount = orderCount;
}
}<file_sep>package com.smk.promotion;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.github.florent37.materialviewpager.MaterialViewPager;
import com.github.florent37.materialviewpager.header.HeaderDesign;
import com.google.gson.JsonObject;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.view.IconicsImageView;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.holder.BadgeStyle;
import com.mikepenz.materialdrawer.holder.StringHolder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.smk.adapter.FoodCategoriesAdapter;
import com.smk.client.NetworkEngine;
import com.smk.fragment.FoodRVFragment;
import com.smk.gcm.GcmCommon;
import com.smk.model.Food;
import com.smk.model.FoodCategory;
import com.smk.model.FoodType;
import com.smk.model.User;
import com.smk.model.UserNotiCount;
import com.smk.service.ChatService;
import com.smk.service.LocationAPIService;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.CircleTransform;
import com.smk.utils.DeviceUtil;
import com.smk.utils.StoreUtil;
import com.squareup.picasso.Picasso;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class FoodActivity extends BaseAppCompatActivity implements View.OnClickListener {
MaterialViewPager viewPager;
FloatingActionButton btn_create_shop;
IconicsImageView icon_header;
User user;
boolean doubleBackToExitPressedOnce = false;
public static Drawer result;
public static PrimaryDrawerItem mCartOrderDrawerItem, mOrderReceiveDrawerItem, mOrderDrawerItem, mCartBookingDrawerItem, mBookingReceiveDrawerItem, mBookingDrawerItem;
int notificationCount;
ZProgressHUD dialog;
private MaterialSearchView searchView;
private List<FoodType> foodTypes;
private ListView lst_suggestion;
private List<FoodCategory> foodCategories;
private LocationManager locationManager;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
startService(new Intent(getApplicationContext(), ChatService.class));
viewPager = (MaterialViewPager) findViewById(R.id.materialViewPager);
btn_create_shop = (FloatingActionButton) findViewById(R.id.btn_create_shop);
icon_header = (IconicsImageView) findViewById(R.id.icon_header);
lst_suggestion = (ListView) findViewById(R.id.lst_suggestion);
Toolbar toolbar = viewPager.getToolbar();
if (toolbar != null) {
toolbar.setLogo(R.drawable.title_logo);
toolbar.setTitle("");
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
foodTypes = StoreUtil.getInstance().selectFrom("FoodTypes");
if (foodTypes != null && foodTypes.size() > 0) {
init(foodTypes);
getFoodType();
} else {
getFoodType();
}
}
user = StoreUtil.getInstance().selectFrom("users");
GcmCommon.register(this);
if(GcmCommon.isServerRegistered(this) && user != null){
NetworkEngine.getInstance().updateGcmDevice(DeviceUtil.getInstance(this).getID(), GcmCommon.getRegisterId(this), user.getId(), new Callback<JsonObject>() {
@Override
public void success(JsonObject jsonObject, Response response) {
}
@Override
public void failure(RetrofitError error) {
}
});
}
StoreUtil.getInstance().saveTo("deviceId", DeviceUtil.getInstance(this).getID());
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled || !isNetworkEnabled) {
showGPSSettingsAlert();
}else{
startService(new Intent(getApplicationContext(), LocationAPIService.class));
}
} catch (Exception e) {
e.printStackTrace();
}
btn_create_shop.setOnClickListener(this);
btn_create_shop.setImageDrawable(new IconicsDrawable(this)
.icon(GoogleMaterial.Icon.gmd_mode_edit)
.color(Color.WHITE)
.sizeDp(18));
if (user != null) {
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.header)
.addProfiles(
new ProfileDrawerItem().withName(user.getName() != null ? user.getName() : "").withEmail(user.getEmail() != null ? user.getEmail() : user.getPhone()).withIcon(user.getImage() != null && user.getImage().length() > 0 ? "http://foods.528go.com/users/x200/" + user.getImage() : "")
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
return false;
}
})
.build();
result = new DrawerBuilder()
.withSelectedItem(-1)
.withAccountHeader(headerResult)
.withActivity(this)
.withTranslucentStatusBar(true)
.withStatusBarColor(getResources().getColor(android.R.color.transparent))
.withToolbar(toolbar)
.addDrawerItems(
new PrimaryDrawerItem().withName(getResources().getString(R.string.str_nearby_promotion)).withIcon(GoogleMaterial.Icon.gmd_location_on).withIdentifier(1),
mCartOrderDrawerItem = new PrimaryDrawerItem().withName(getResources().getString(R.string.order_cart_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge("0").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent)).withIdentifier(2),
mOrderReceiveDrawerItem = new PrimaryDrawerItem().withName(getResources().getString(R.string.order_pending_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge("0").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent)).withIdentifier(3),
mOrderDrawerItem = new PrimaryDrawerItem().withName(getResources().getString(R.string.order_complete_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge("0").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent)).withIdentifier(4),
new DividerDrawerItem(),
//mCartBookingDrawerItem = new PrimaryDrawerItem().withName(getResources().getString(R.string.booking_cart_list)).withIcon(CommunityMaterial.Icon.cmd_cart).withBadge("0").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent)).withIdentifier(5),
mBookingReceiveDrawerItem = new PrimaryDrawerItem().withName(getResources().getString(R.string.booking_pending_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge("0").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent)).withIdentifier(6),
mBookingDrawerItem = new PrimaryDrawerItem().withName(getResources().getString(R.string.booking_complete_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge("0").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent)).withIdentifier(7),
new DividerDrawerItem(),
new PrimaryDrawerItem().withName(getResources().getString(R.string.profile)).withIcon(CommunityMaterial.Icon.cmd_account_box).withIdentifier(8),
new PrimaryDrawerItem().withName(getResources().getString(R.string.shop_list)).withIcon(FontAwesome.Icon.faw_home).withIdentifier(14),
new DividerDrawerItem(),
//new SecondaryDrawerItem().withName(getResources().getString(R.string.about)).withIcon(R.drawable.logo).withIdentifier(9),
//new SecondaryDrawerItem().withName(getResources().getString(R.string.feedback_drawer)).withIcon(GoogleMaterial.Icon.gmd_feedback).withIdentifier(10),
//new SecondaryDrawerItem().withName(getResources().getString(R.string.share)).withIcon(GoogleMaterial.Icon.gmd_share).withIdentifier(11),
new SecondaryDrawerItem().withName(getResources().getString(R.string.setting)).withIcon(GoogleMaterial.Icon.gmd_settings).withIdentifier(12),
new DividerDrawerItem(),
new SecondaryDrawerItem().withName(getResources().getString(R.string.logout)).withIcon(FontAwesome.Icon.faw_sign_out).withIdentifier(13)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem != null) {
Intent intent = null;
if (drawerItem.getIdentifier() == 1) {
intent = new Intent(FoodActivity.this, NearbyPromotionActivity.class);
}else if (drawerItem.getIdentifier() == 2) {
intent = new Intent(FoodActivity.this, OrderCartListActivity.class);
} else if (drawerItem.getIdentifier() == 3) {
intent = new Intent(FoodActivity.this, OrderPendingListActivity.class);
} else if (drawerItem.getIdentifier() == 4) {
intent = new Intent(FoodActivity.this, OrderCompleteListActivity.class);
} else if (drawerItem.getIdentifier() == 5) {
intent = new Intent(FoodActivity.this, BookingCartListActivity.class);
} else if (drawerItem.getIdentifier() == 6) {
intent = new Intent(FoodActivity.this, BookingPendingListActivity.class);
} else if (drawerItem.getIdentifier() == 7) {
intent = new Intent(FoodActivity.this, BookingCompleteListActivity.class);
} else if (drawerItem.getIdentifier() == 8) {
intent = new Intent(FoodActivity.this, ProfileActivity.class);
} else if (drawerItem.getIdentifier() == 14) {
if (user != null) {
if(user.getShops().size() > 0)
{
intent = new Intent(getApplicationContext(), ShopListActivity.class);
} else {
intent = new Intent(getApplicationContext(), CreateShopActivity.class);
}
} else {
SKToastMessage.showMessage(FoodActivity.this, getResources().getString(R.string.require_login_register), SKToastMessage.INFO);
intent = new Intent(getApplicationContext(), LoginActivity.class);
}
} else if (drawerItem.getIdentifier() == 9) {
intent = new Intent(FoodActivity.this, AboutActivity.class);
} else if (drawerItem.getIdentifier() == 10) {
intent = new Intent(FoodActivity.this, FeedbackActivity.class);
} else if (drawerItem.getIdentifier() == 12) {
intent = new Intent(FoodActivity.this, SettingActivity.class);
} else if (drawerItem.getIdentifier() == 13) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(FoodActivity.this);
alertDialogBuilder.setTitle(getResources().getString(R.string.logout_application))
.setMessage(getResources().getString(R.string.logout_application_description))
.setPositiveButton(getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
StoreUtil.getInstance().destroy("users");
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (intent != null) {
FoodActivity.this.startActivity(intent);
}
}
return false;
}
})
.build();
List<Food> recentOrders = StoreUtil.getInstance().selectFrom("recent_orders");
if (recentOrders != null) {
notificationCount = 0;
for (Food recentOrder : recentOrders) {
notificationCount += 1;
}
}
} else {
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.header)
.addProfiles(
new ProfileDrawerItem().withName("Welcome").withEmail("<EMAIL>").withIcon(R.drawable.profile3)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
return false;
}
})
.build();
result = new DrawerBuilder()
.withSelectedItem(-1)
.withAccountHeader(headerResult)
.withActivity(this)
.withTranslucentStatusBar(true)
.withStatusBarColor(getResources().getColor(android.R.color.transparent))
.withToolbar(toolbar)
.addDrawerItems(
new PrimaryDrawerItem().withName(getResources().getString(R.string.str_nearby_promotion)).withIcon(GoogleMaterial.Icon.gmd_location_on).withIdentifier(1),
new PrimaryDrawerItem().withName(getResources().getString(R.string.shop_list)).withIcon(FontAwesome.Icon.faw_home).withIdentifier(14),
new DividerDrawerItem(),
//new SecondaryDrawerItem().withName(getResources().getString(R.string.about)).withIcon(R.drawable.logo).withIdentifier(9),
//new SecondaryDrawerItem().withName(getResources().getString(R.string.feedback_drawer)).withIcon(GoogleMaterial.Icon.gmd_feedback).withIdentifier(10),
//new SecondaryDrawerItem().withName(getResources().getString(R.string.share)).withIcon(GoogleMaterial.Icon.gmd_share).withIdentifier(11),
new SecondaryDrawerItem().withName(getResources().getString(R.string.setting)).withIcon(GoogleMaterial.Icon.gmd_settings).withIdentifier(12),
new DividerDrawerItem(),
new SecondaryDrawerItem().withName(getResources().getString(R.string.drawer_login)).withIcon(FontAwesome.Icon.faw_sign_in).withIdentifier(13)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem != null) {
Intent intent = null;
if (drawerItem.getIdentifier() == 1) {
intent = new Intent(FoodActivity.this, NearbyPromotionActivity.class);
}else if (drawerItem.getIdentifier() == 9) {
intent = new Intent(FoodActivity.this, AboutActivity.class);
} else if (drawerItem.getIdentifier() == 10) {
intent = new Intent(FoodActivity.this, FeedbackActivity.class);
} else if (drawerItem.getIdentifier() == 12) {
intent = new Intent(FoodActivity.this, SettingActivity.class);
} else if (drawerItem.getIdentifier() == 13) {
intent = new Intent(FoodActivity.this, LoginActivity.class);
} else if (drawerItem.getIdentifier() == 14) {
intent = new Intent(FoodActivity.this, ShopListActivity.class);
}
if (intent != null) {
FoodActivity.this.startActivity(intent);
}
}
return false;
}
})
.build();
}
}
private void init(final List<FoodType> types) {
viewPager.getViewPager().setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return FoodRVFragment.newInstance(position, types.get(position));
}
@Override
public int getCount() {
return types.size();
}
@Override
public CharSequence getPageTitle(int position) {
String languages = StoreUtil.getInstance().selectFrom("languages");
if(languages.equals("mm") && types.get(position).getNameMM() != null){
return types.get(position).getNameMM();
}
return types.get(position).getName();
}
});
viewPager.setMaterialViewPagerListener(new MaterialViewPager.Listener() {
@Override
public HeaderDesign getHeaderDesign(int page) {
try {
foodCategories = types.get(page).getCategories();
if (types.get(page).getIcon() != null ) {
Picasso.with(getApplication()).load("http://foods.528go.com/foodTypes/" + types.get(page).getIcon().replace(" ","%20")).transform(new CircleTransform()).into(icon_header);
}
if(types.get(page).getImage() != null && types.get(page).getColor() != null){
return HeaderDesign.fromColorAndUrl(
Color.parseColor(types.get(page).getColor()),
"http://foods.528go.com/foodTypes/x400/" + types.get(page).getImage());
}
} catch (StringIndexOutOfBoundsException e) {
e.printStackTrace();
}
return null;
}
});
viewPager.getViewPager().setOffscreenPageLimit(viewPager.getViewPager().getAdapter().getCount());
viewPager.getPagerTitleStrip().setViewPager(viewPager.getViewPager());
}
public void printHashKey() {
try {
PackageInfo info = getPackageManager().getPackageInfo("com.smk.promotion", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.i("TEMPTAGHASH KEY:","FB HashKey : "+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
}
}
private void getFoodType() {
printHashKey();
NetworkEngine.getInstance().getFoodTypes(new Callback<List<FoodType>>() {
@Override
public void success(List<FoodType> types, Response response) {
StoreUtil.getInstance().saveTo("FoodTypes", types);
if(foodTypes == null){
foodTypes = new ArrayList<FoodType>();
foodTypes.addAll(types);
init(foodTypes);
}
}
@Override
public void failure(RetrofitError error) {
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(FoodActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private AdapterView.OnItemClickListener categoriesOnItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle bundle = new Bundle();
bundle.putString("keywords", foodCategories.get(position).getName());
startActivity(new Intent(getApplicationContext(), SearchResultActivity.class).putExtras(bundle));
}
};
/*private void getFoodCategory() {
NetworkEngine.getInstance().getFoodCategory(new Callback<List<FoodCategory>>() {
@Override
public void success(List<FoodCategory> categories, Response response) {
StoreUtil.getInstance().saveTo("foodCategories", categories);
foodCategories = new ArrayList<>();
foodCategories.addAll(categories);
FoodCategoriesAdapter foodCategoryAdapter = new FoodCategoriesAdapter(FoodActivity.this, foodCategories);
lst_suggestion.setAdapter(foodCategoryAdapter);
lst_suggestion.setOnItemClickListener(categoriesOnItemClickListener);
}
@Override
public void failure(RetrofitError error) {
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(FoodActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_create_shop:
if (user != null) {
if(user.getShops().size() > 0)
{
Intent intent = new Intent(getApplicationContext(), ShopListActivity.class);
startActivity(intent);
} else {
startActivity(new Intent(FoodActivity.this, CreateShopActivity.class));
}
} else {
SKToastMessage.showMessage(FoodActivity.this, getResources().getString(R.string.require_login_register), SKToastMessage.INFO);
startActivity(new Intent(FoodActivity.this, LoginActivity.class));
}
break;
default:
break;
}
}
@Override
protected void onResume() {
if (user != null) {
mCartOrderDrawerItem.withName(getResources().getString(R.string.order_cart_list)).withIcon(CommunityMaterial.Icon.cmd_cart).withBadge("" + notificationCount).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent));
result.updateItem(FoodActivity.mCartOrderDrawerItem);
/*mCartBookingDrawerItem.withName(getResources().getString(R.string.booking_cart_list)).withIcon(CommunityMaterial.Icon.cmd_cart).withBadge("" + notificationCount).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent));
result.updateItem(FoodActivity.mCartBookingDrawerItem);*/
NetworkEngine.getInstance().getUserNotiCount(user.getId(), new Callback<UserNotiCount>() {
@Override
public void success(UserNotiCount userNotiCount, Response response) {
mOrderReceiveDrawerItem.withName(getResources().getString(R.string.order_pending_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge(new StringHolder(userNotiCount.getOrderPending().toString())).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent));
result.updateItem(mOrderReceiveDrawerItem);
mOrderDrawerItem.withName(getResources().getString(R.string.order_complete_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge(new StringHolder(userNotiCount.getOrderComplete().toString())).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent));
result.updateItem(mOrderDrawerItem);
mBookingReceiveDrawerItem.withName(getResources().getString(R.string.booking_pending_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge(new StringHolder(userNotiCount.getBookingPending().toString())).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent));
result.updateItem(mBookingReceiveDrawerItem);
mBookingDrawerItem.withName(getResources().getString(R.string.booking_complete_list)).withIcon(CommunityMaterial.Icon.cmd_format_list_bulleted).withBadge(new StringHolder(userNotiCount.getBookingComplete().toString())).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.colorAccent));
result.updateItem(mBookingDrawerItem);
}
@Override
public void failure(RetrofitError error) {
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(FoodActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setVoiceSearch(true); //or false
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//Do some magic
Bundle bundle = new Bundle();
bundle.putString("keywords", query);
startActivity(new Intent(getApplicationContext(), SearchResultActivity.class).putExtras(bundle));
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//Do some magic
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
lst_suggestion.setVisibility(View.VISIBLE);
if(foodCategories != null && foodCategories.size() > 0){
FoodCategoriesAdapter foodCategoryAdapter = new FoodCategoriesAdapter(FoodActivity.this, foodCategories);
lst_suggestion.setAdapter(foodCategoryAdapter);
lst_suggestion.setOnItemClickListener(categoriesOnItemClickListener);
}
}
@Override
public void onSearchViewClosed() {
lst_suggestion.setVisibility(View.GONE);
}
});
searchView.setMenuItem(item);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches != null && matches.size() > 0) {
String searchWrd = matches.get(0);
if (!TextUtils.isEmpty(searchWrd)) {
searchView.setQuery(searchWrd, false);
}
}
return;
}
if(requestCode == OPEN_GPS){
startService(new Intent(getApplicationContext(), LocationAPIService.class));
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed() {
if (searchView.isSearchOpen()) {
searchView.closeSearch();
return;
}
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
return;
}
this.doubleBackToExitPressedOnce = true;
SKToastMessage.showMessage(FoodActivity.this, getResources().getString(R.string.press_again), SKToastMessage.INFO);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
<file_sep>package com.smk.promotion;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.mikepenz.community_material_typeface_library.CommunityMaterial;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.view.IconicsImageView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.smk.client.NetworkEngine;
import com.smk.model.User;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.CircleTransform;
import com.smk.utils.StoreUtil;
import com.soundcloud.android.crop.Crop;
import com.squareup.picasso.Picasso;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import pl.aprilapps.easyphotopicker.EasyImage;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.MultipartTypedOutput;
import retrofit.mime.TypedFile;
public class ProfileActivity extends BaseAppCompatActivity implements View.OnClickListener {
Toolbar toolbar;
IconicsImageView img_user;
MaterialEditText edt_name, edt_password, edt_phone_number;
Button btn_cancel, btn_save;
ZProgressHUD dialog;
private File destinationFile;
private MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
private String userImage;
private User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_profile));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
img_user = (IconicsImageView) findViewById(R.id.img_user);
edt_name = (MaterialEditText) findViewById(R.id.edt_name);
edt_password = (MaterialEditText) findViewById(R.id.edt_password);
edt_phone_number = (MaterialEditText) findViewById(R.id.edt_phone_number);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
btn_save = (Button) findViewById(R.id.btn_save);
addDrawable(edt_name, CommunityMaterial.Icon.cmd_account.toString());
addDrawable(edt_password, CommunityMaterial.Icon.cmd_account_key.toString());
addDrawable(edt_phone_number, GoogleMaterial.Icon.gmd_contact_phone.toString());
img_user.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
btn_save.setOnClickListener(this);
user = StoreUtil.getInstance().selectFrom("users");
if (user != null) {
edt_name.setText(user.getName());
edt_phone_number.setText(user.getPhone());
Picasso.with(this).load("http://foods.528go.com/users/x200/" + user.getImage()).placeholder(getIconicDrawable(GoogleMaterial.Icon.gmd_account_circle.toString())).transform(new CircleTransform()).into(img_user);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img_user:
showActionForUserPhoto();
break;
case R.id.btn_cancel:
finish();
break;
case R.id.btn_save:
if (checkField()) {
updateUser();
}
break;
default:
break;
}
}
private void showActionForUserPhoto() {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
alertBuilder.setTitle(getResources().getString(R.string.upload_photo));
alertBuilder.setMessage(getResources().getString(R.string.upload_photo_desc));
alertBuilder.setPositiveButton(getResources().getString(R.string.take_photo), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EasyImage.openCamera(ProfileActivity.this);
dialog.dismiss();
}
});
alertBuilder.setNegativeButton(getResources().getString(R.string.choose_photo), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Crop.pickImage(ProfileActivity.this);
dialog.dismiss();
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}
private void beginCrop(Uri source) {
destinationFile = new File(getCacheDir(), "cropped-" + getCurrentTimeStamp());
if (!destinationFile.exists()) {
try {
destinationFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Uri destination = Uri.fromFile(destinationFile);
Crop.of(source, destination).withMaxSize(400, 400).start(this);
}
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd-HHmmss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
Picasso.with(ProfileActivity.this).load(destinationFile).transform(new CircleTransform()).into(img_user);
multipartTypedOutput.addPart("image", new TypedFile("image/png", destinationFile));
uploadUserPhoto();
} else if (resultCode == Crop.RESULT_ERROR) {
SKToastMessage.showMessage(this, Crop.getError(result).getMessage(), SKToastMessage.ERROR);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new EasyImage.Callbacks() {
@Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
//Some error handling
}
@Override
public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
//Handle the image
Picasso.with(ProfileActivity.this).load(imageFile).transform(new CircleTransform()).into(img_user);
beginCrop(Uri.fromFile(imageFile));
}
@Override
public void onCanceled(EasyImage.ImageSource imageSource) {
//Cancel handling, you might wanna remove taken photo if it was canceled
if (imageSource == EasyImage.ImageSource.CAMERA) {
File photoFile = EasyImage.lastlyTakenButCanceledPhoto(ProfileActivity.this);
if (photoFile != null) photoFile.delete();
}
}
});
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
private void uploadUserPhoto() {
dialog = new ZProgressHUD(this);
dialog.setMessage("Uploading...");
dialog.show();
NetworkEngine.getInstance().uploadUserPhoto(multipartTypedOutput, new Callback<String>() {
@Override
public void success(String imageFileName, Response response) {
userImage = imageFileName;
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(ProfileActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private void updateUser() {
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().updateUser(user.getId(), edt_name.getText().toString(), edt_password.getText().toString(), edt_phone_number.getText().toString(), userImage, new Callback<User>() {
@Override
public void success(User user, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
StoreUtil.getInstance().saveTo("users", user);
startActivity(new Intent(ProfileActivity.this, FoodActivity.class));
finish();
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(ProfileActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private boolean checkField() {
if (edt_name.getText().length() == 0) {
edt_name.setError(getResources().getString(R.string.invalid_name));
edt_name.requestFocus();
return false;
}
if (edt_phone_number.getText().length() < 8) {
edt_phone_number.setError(getResources().getString(R.string.invalid_phone_number));
edt_phone_number.requestFocus();
return false;
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
}<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UserNotiCount {
@SerializedName("order_pending")
@Expose
private Integer orderPending;
@SerializedName("order_complete")
@Expose
private Integer orderComplete;
@SerializedName("booking_pending")
@Expose
private Integer bookingPending;
@SerializedName("booking_complete")
@Expose
private Integer bookingComplete;
/**
* @return The orderPending
*/
public Integer getOrderPending() {
return orderPending;
}
/**
* @param orderPending The order_pending
*/
public void setOrderPending(Integer orderPending) {
this.orderPending = orderPending;
}
/**
* @return The orderComplete
*/
public Integer getOrderComplete() {
return orderComplete;
}
/**
* @param orderComplete The order_complete
*/
public void setOrderComplete(Integer orderComplete) {
this.orderComplete = orderComplete;
}
/**
* @return The bookingPending
*/
public Integer getBookingPending() {
return bookingPending;
}
/**
* @param bookingPending The booking_pending
*/
public void setBookingPending(Integer bookingPending) {
this.bookingPending = bookingPending;
}
/**
* @return The bookingComplete
*/
public Integer getBookingComplete() {
return bookingComplete;
}
/**
* @param bookingComplete The booking_complete
*/
public void setBookingComplete(Integer bookingComplete) {
this.bookingComplete = bookingComplete;
}
}<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class OrderDetail {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("order_id")
@Expose
private Integer orderId;
@SerializedName("food_id")
@Expose
private Integer foodId;
@SerializedName("size_id")
@Expose
private Integer sizeId;
@SerializedName("qty")
@Expose
private Integer qty;
@SerializedName("price")
@Expose
private Integer price;
@SerializedName("sub_total")
@Expose
private Integer subTotal;
@SerializedName("note")
@Expose
private String note;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("deleted_at")
@Expose
private Object deletedAt;
@SerializedName("food")
@Expose
private Food food;
/**
* @return The id
*/
public Integer getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return The orderId
*/
public Integer getOrderId() {
return orderId;
}
/**
* @param orderId The order_id
*/
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
/**
* @return The foodId
*/
public Integer getFoodId() {
return foodId;
}
/**
* @param foodId The food_id
*/
public void setFoodId(Integer foodId) {
this.foodId = foodId;
}
/**
* @return The sizeId
*/
public Integer getSizeId() {
return sizeId;
}
/**
* @param sizeId The size_id
*/
public void setSizeId(Integer sizeId) {
this.sizeId = sizeId;
}
/**
* @return The qty
*/
public Integer getQty() {
return qty;
}
/**
* @param qty The qty
*/
public void setQty(Integer qty) {
this.qty = qty;
}
/**
* @return The price
*/
public Integer getPrice() {
return price;
}
/**
* @param price The price
*/
public void setPrice(Integer price) {
this.price = price;
}
/**
* @return The subTotal
*/
public Integer getSubTotal() {
return subTotal;
}
/**
* @param subTotal The sub_total
*/
public void setSubTotal(Integer subTotal) {
this.subTotal = subTotal;
}
/**
* @return The note
*/
public String getNote() {
return note;
}
/**
* @param note The note
*/
public void setNote(String note) {
this.note = note;
}
/**
* @return The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
* @param createdAt The created_at
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
* @return The updatedAt
*/
public String getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt The updated_at
*/
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return The deletedAt
*/
public Object getDeletedAt() {
return deletedAt;
}
/**
* @param deletedAt The deleted_at
*/
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
/**
* @return The food
*/
public Food getFood() {
return food;
}
/**
* @param food The food
*/
public void setFood(Food food) {
this.food = food;
}
}<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Shop implements Serializable {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("address")
@Expose
private String address;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("image")
@Expose
private String image;
@SerializedName("shop_type_id")
@Expose
private Integer shopTypeId;
@SerializedName("open_hr")
@Expose
private String openHr;
@SerializedName("lat")
@Expose
private Double lat;
@SerializedName("lng")
@Expose
private Double lng;
@SerializedName("total_ratings")
@Expose
private Double totalRatings;
@SerializedName("activation_code")
@Expose
private Integer activationCode;
@SerializedName("activated")
@Expose
private Boolean activated;
@SerializedName("total_reviews")
@Expose
private Integer totalReviews;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("deleted_at")
@Expose
private Object deletedAt;
public Shop(String name, Double totalRatings, Integer totalReviews, String phone, String address) {
this.name = name;
this.totalRatings = totalRatings;
this.totalReviews = totalReviews;
this.phone = phone;
this.address = address;
}
/**
* @return The id
*/
public Integer getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return The name
*/
public String getName() {
return name;
}
/**
* @param name The name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return The address
*/
public String getAddress() {
return address;
}
/**
* @param address The address
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return The phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone The phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return The image
*/
public String getImage() {
return image;
}
/**
* @param image The image
*/
public void setImage(String image) {
this.image = image;
}
/**
* @return The shopTypeId
*/
public Integer getShopTypeId() {
return shopTypeId;
}
/**
* @param shopTypeId The shop_type_id
*/
public void setShopTypeId(Integer shopTypeId) {
this.shopTypeId = shopTypeId;
}
/**
* @return The openHr
*/
public String getOpenHr() {
return openHr;
}
/**
* @param openHr The open_hr
*/
public void setOpenHr(String openHr) {
this.openHr = openHr;
}
/**
* @return The lat
*/
public Double getLat() {
return lat;
}
/**
* @param lat The lat
*/
public void setLat(Double lat) {
this.lat = lat;
}
/**
* @return The lng
*/
public Double getLng() {
return lng;
}
/**
* @param lng The lng
*/
public void setLng(Double lng) {
this.lng = lng;
}
/**
* @return The totalRatings
*/
public Double getTotalRatings() {
return totalRatings;
}
/**
* @param totalRatings The total_ratings
*/
public void setTotalRatings(Double totalRatings) {
this.totalRatings = totalRatings;
}
/**
* @return The totalReviews
*/
public Integer getTotalReviews() {
return totalReviews;
}
/**
* @param totalReviews The total_reviews
*/
public void setTotalReviews(Integer totalReviews) {
this.totalReviews = totalReviews;
}
public Integer getActivationCode() {
return activationCode;
}
public void setActivationCode(Integer activationCode) {
this.activationCode = activationCode;
}
public Boolean getActivated() {
return activated;
}
public void setActivated(Boolean activated) {
this.activated = activated;
}
/**
* @return The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
* @param createdAt The created_at
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
* @return The updatedAt
*/
public String getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt The updated_at
*/
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return The deletedAt
*/
public Object getDeletedAt() {
return deletedAt;
}
/**
* @param deletedAt The deleted_at
*/
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
}<file_sep>package com.smk.adapter;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.mikepenz.iconics.view.IconicsImageView;
import com.smk.model.FoodSize;
import com.smk.promotion.R;
import java.util.ArrayList;
public class FoodSizePriceListAdapter extends BaseAdapter {
Context ctx;
ArrayList<FoodSize> list = new ArrayList<FoodSize>();
private Callbacks mCallback;
public FoodSizePriceListAdapter(Context ctx, ArrayList<FoodSize> list) {
this.ctx = ctx;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public FoodSize getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListViewHolder view = (ListViewHolder) convertView;
if (view == null) {
view = new ListViewHolder(ctx);
}
FoodSize foodSize = getItem(position);
view.setLog(foodSize, position);
return view;
}
public void setOnCallbackListener(Callbacks callbacks){
this.mCallback = callbacks;
}
public interface Callbacks{
void onClickDelete(int position);
}
private class ListViewHolder extends LinearLayout {
Context mContext;
FoodSize mFoodSize;
public ListViewHolder(Context ctx) {
super(ctx);
mContext = ctx;
setup();
}
public ListViewHolder(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
mContext = ctx;
setup();
}
private void setup() {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.list_size_price, this);
}
public void setLog(FoodSize foodSize, final int position) {
mFoodSize = foodSize;
TextView txt_food_size = (TextView) findViewById(R.id.txt_food_size);
TextView txt_food_price = (TextView) findViewById(R.id.txt_food_price);
IconicsImageView btn_delete = (IconicsImageView) findViewById(R.id.btn_delete);
txt_food_size.setText(getResources().getString(R.string.food_size) + " \n" + mFoodSize.getSize());
txt_food_price.setText(getResources().getString(R.string.food_price) + " \n" + mFoodSize.getPrice());
btn_delete.setTag(position);
btn_delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int pos = (int) v.getTag();
if(mCallback != null){
mCallback.onClickDelete(pos);
}
}
});
}
}
}<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.smk.client.NetworkEngine;
import com.smk.model.FoodDiscount;
import com.smk.skalertmessage.SKToastMessage;
import com.thuongnh.zprogresshud.ZProgressHUD;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.util.Calendar;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class CreateFoodDiscountActivity extends BaseAppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
Toolbar toolbar;
MaterialEditText edt_discount_amount;
TextView txt_start_date, txt_end_date;
LinearLayout layout_start_date, layout_end_date;
Button btn_skip, btn_finish;
Integer food_id;
ZProgressHUD dialog;
Integer datePickerInput;
private Bundle extras;
private String startDate;
private String endDate;
private FoodDiscount foodDiscount;
private boolean doubleBackToExitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_food_discount);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_create_food_discount));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
edt_discount_amount = (MaterialEditText) findViewById(R.id.edt_discount_amount);
layout_start_date = (LinearLayout) findViewById(R.id.layout_start_date);
layout_end_date = (LinearLayout) findViewById(R.id.layout_end_date);
txt_start_date = (TextView) findViewById(R.id.txt_start_date);
txt_end_date = (TextView) findViewById(R.id.txt_end_date);
btn_skip = (Button) findViewById(R.id.btn_skip);
btn_finish = (Button) findViewById(R.id.btn_finish);
layout_start_date.setOnClickListener(this);
layout_end_date.setOnClickListener(this);
btn_skip.setOnClickListener(this);
btn_finish.setOnClickListener(this);
extras = getIntent().getExtras();
food_id = extras.getInt("food_id");
foodDiscount = new Gson().fromJson(extras.getString("discount"), FoodDiscount.class);
if(foodDiscount != null){
edt_discount_amount.setText(foodDiscount.getDiscount()+"");
txt_start_date.setText(foodDiscount.getStartDate());
txt_end_date.setText(foodDiscount.getEndDate());
startDate = foodDiscount.getStartDate();
endDate = foodDiscount.getEndDate();
btn_finish.setText(getResources().getString(R.string.str_update));
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.layout_start_date:
Calendar startNow = Calendar.getInstance();
DatePickerDialog sdpd = DatePickerDialog.newInstance(
CreateFoodDiscountActivity.this,
startNow.get(Calendar.YEAR),
startNow.get(Calendar.MONTH),
startNow.get(Calendar.DAY_OF_MONTH)
);
datePickerInput = v.getId();
sdpd.show(getFragmentManager(), "StartDatePickerDialog");
break;
case R.id.layout_end_date:
Calendar endNow = Calendar.getInstance();
DatePickerDialog edpd = DatePickerDialog.newInstance(
CreateFoodDiscountActivity.this,
endNow.get(Calendar.YEAR),
endNow.get(Calendar.MONTH),
endNow.get(Calendar.DAY_OF_MONTH)
);
datePickerInput = v.getId();
edpd.show(getFragmentManager(), "EndDatePickerDialog");
break;
case R.id.btn_skip:
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", extras.getString("shop"));
startActivity(intent);
finish();
break;
case R.id.btn_finish:
if(checkField())
if(foodDiscount != null){
editDiscount();
}else{
postDiscount();
}
break;
default:
break;
}
}
private boolean checkField(){
if(edt_discount_amount.getText().length() == 0){
edt_discount_amount.setError(getResources().getString(R.string.str_please_set_discount));
return false;
}
if(startDate == null || endDate == null){
SKToastMessage.showMessage(CreateFoodDiscountActivity.this,getResources().getString(R.string.str_please_set_date), SKToastMessage.ERROR);
return false;
}
return true;
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = year+ "-" + (++monthOfYear) + "-" +dayOfMonth;
switch (datePickerInput) {
case R.id.layout_start_date:
startDate = date;
txt_start_date.setText(date);
break;
case R.id.layout_end_date:
endDate = date;
txt_end_date.setText(date);
break;
default:
break;
}
}
private void postDiscount() {
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().postDiscount(food_id, Integer.valueOf(edt_discount_amount.getText().toString()), txt_start_date.getText().toString(), txt_end_date.getText().toString(), new Callback<FoodDiscount>() {
@Override
public void success(FoodDiscount food, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", extras.getString("shop"));
startActivity(intent);
finish();
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(CreateFoodDiscountActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
private void editDiscount() {
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().editDiscount(foodDiscount.getId(), food_id, Integer.valueOf(edt_discount_amount.getText().toString()), txt_start_date.getText().toString(), txt_end_date.getText().toString(), new Callback<FoodDiscount>() {
@Override
public void success(FoodDiscount foodDiscount, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", extras.getString("shop"));
startActivity(intent);
finish();
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(CreateFoodDiscountActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
@Nullable
@Override
public Intent getSupportParentActivityIntent() {
onBackPressed();
return super.getSupportParentActivityIntent();
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
SKToastMessage.showMessage(this, getResources().getString(R.string.press_again_cancel), SKToastMessage.INFO);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}<file_sep>package com.smk.promotion;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.smk.adapter.PromotionListAdapter;
import com.smk.model.GcmMessage;
import com.smk.model.SpecialDiscount;
import org.lucasr.twowayview.TwoWayView;
import java.util.ArrayList;
import java.util.List;
public class PromotionPopupActivity extends Activity {
private TextView txt_food_price;
private TextView txt_discount;
private ImageView img_food;
private TextView txt_food_name;
private TextView txt_title;
private TwoWayView lst_item;
private PromotionListAdapter adapter;
private List<SpecialDiscount> promotions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotion_popup);
Bundle bundle = getIntent().getExtras();
GcmMessage gcmMessage = new Gson().fromJson(bundle.getString("gcmMessage"), GcmMessage.class);
lst_item = (TwoWayView) findViewById(R.id.list_promotion);
if(gcmMessage != null){
promotions = new ArrayList<>();
promotions.addAll(gcmMessage.getSpecialDiscount());
adapter = new PromotionListAdapter(this, promotions, gcmMessage.getActionLocKey());
lst_item.setAdapter(adapter);
adapter.notifyDataSetChanged();
adapter.setOnCallbackLinstener(new PromotionListAdapter.Callbacks() {
@Override
public void onClickNoNeed(int position) {
promotions.remove(position);
adapter.notifyDataSetChanged();
}
@Override
public void onClickMore(int position) {
startActivity(new Intent(getApplication(), NearbyPromotionActivity.class));
}
});
}
}
}
<file_sep>package com.smk.promotion;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import com.github.florent37.materialviewpager.MaterialViewPagerHelper;
import com.google.gson.Gson;
import com.smk.adapter.ShopCustomersAdapter;
import com.smk.client.NetworkEngine;
import com.smk.database.DatabaseManager;
import com.smk.database.controller.UserController;
import com.smk.model.Shop;
import com.smk.model.User;
import com.smk.skalertmessage.SKToastMessage;
import com.smk.utils.EndlessRecyclerOnScrollListener;
import com.smk.utils.ItemClickSupport;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class ShopCustomerActivity extends BaseAppCompatActivity {
private Toolbar toolbar;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private ImageView img_no_food;
private ShopCustomersAdapter adapter;
private List<User> customerList = new ArrayList<>();
private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener;
private boolean isLoading;
private boolean isLoadMore;
private Shop shop;
private ZProgressHUD dialog;
private Integer offset = 1;
DatabaseManager<User> databaseManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_customer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.str_title_customer));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
img_no_food = (ImageView) findViewById(R.id.img_no_food);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
databaseManager = new UserController(getApplicationContext());
customerList = databaseManager.select();
adapter = new ShopCustomersAdapter(this,customerList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
Intent intent = new Intent(ShopCustomerActivity.this, ConversationActivity.class);
intent.putExtra("friend", new Gson().toJson(customerList.get(position)));
startActivity(intent);
}
});
endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int current_page) {
if (!isLoading && isLoadMore)
getCustomer();
}
};
recyclerView.addOnScrollListener(endlessRecyclerOnScrollListener);
Bundle bundle = getIntent().getExtras();
shop = new Gson().fromJson(bundle.getString("shop"), Shop.class);
dialog = new ZProgressHUD(this);
dialog.show();
getCustomer();
}
@Nullable
@Override
public Intent getSupportParentActivityIntent() {
finish();
return super.getSupportParentActivityIntent();
}
private void getCustomer() {
isLoading = true;
NetworkEngine.getInstance().getUsers(shop.getId(), offset, 12, new Callback<List<User>>() {
@Override
public void success(List<User> users, Response response) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithSuccess();
}
for(User user: users){
User existedUser = databaseManager.select(user.getId());
if(existedUser == null){
databaseManager.save(user);
customerList.add(user);
}
}
adapter.notifyDataSetChanged();
isLoading = false;
if (users.size() == 12) {
offset++;
isLoadMore = true;
} else {
isLoadMore = false;
}
}
@Override
public void failure(RetrofitError error) {
if (dialog != null && dialog.isShowing()) {
dialog.dismissWithFailure();
}
if (error.getResponse() != null) {
switch (error.getResponse().getStatus()) {
case 400:
String msg = (String) error.getBodyAs(String.class);
SKToastMessage.showMessage(ShopCustomerActivity.this, msg, SKToastMessage.ERROR);
break;
default:
break;
}
}
}
});
}
}
<file_sep>package com.smk.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.smk.promotion.R;
public class FeedsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
public FeedsFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static FeedsFragment newInstance() {
FeedsFragment fragment = new FeedsFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View convertView = inflater.inflate(R.layout.fragment_feeds, container, false);
return convertView;
}
}
<file_sep>package com.smk.promotion;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.smk.adapter.FoodPhotoAdapter;
import com.smk.client.NetworkEngine;
import com.smk.model.Food;
import com.smk.model.FoodPhoto;
import com.smk.model.UploadFoodPhoto;
import com.smk.skalertmessage.SKToastMessage;
import com.soundcloud.android.crop.Crop;
import com.thuongnh.zprogresshud.ZProgressHUD;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import pl.aprilapps.easyphotopicker.EasyImage;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.MultipartTypedOutput;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;
public class CreateFoodPhotoActivity extends BaseAppCompatActivity implements View.OnClickListener {
Toolbar toolbar;
FloatingActionButton btn_add_photo;
Button btn_next;
private GridView grid_photo;
private File destinationFile;
private List<UploadFoodPhoto> foodPhotos;
private FoodPhotoAdapter foodAdapter;
private ZProgressHUD dialog;
private MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
private int food_id;
private Bundle extras;
private Food food;
private boolean doubleBackToExitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_food_photo);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title_activity_create_food_photo));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
extras = getIntent().getExtras();
food_id = extras.getInt("food_id");
food = new Gson().fromJson(extras.getString("food"), Food.class);
grid_photo = (GridView) findViewById(R.id.lvList);
btn_add_photo = (FloatingActionButton) findViewById(R.id.btn_add_photo);
btn_next = (Button) findViewById(R.id.btn_next);
btn_add_photo.setOnClickListener(this);
foodPhotos = new ArrayList<>();
if(food != null && food.getFoodPhotos().size() > 0){
for(FoodPhoto foodPhoto: food.getFoodPhotos()){
foodPhotos.add(new UploadFoodPhoto(foodPhoto.getId(), foodPhoto.getImage(), null));
}
}
if(food != null){
btn_next.setText(getResources().getString(R.string.str_update));
}
foodAdapter = new FoodPhotoAdapter(this, foodPhotos);
grid_photo.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
foodAdapter.setOnCallbackListener(new FoodPhotoAdapter.Callbacks() {
@Override
public void onClickDelete(int position) {
if(food != null && foodPhotos.get(position).getId() != null){
deletePhoto(foodPhotos.get(position).getId(), position);
}else{
foodPhotos.remove(position);
foodAdapter.notifyDataSetChanged();
}
}
});
btn_next.setOnClickListener(this);
}
private void showActionForUserPhoto(){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setTitle(getResources().getString(R.string.upload_photo));
alertBuilder.setMessage(getResources().getString(R.string.upload_photo_desc));
alertBuilder.setPositiveButton(getResources().getString(R.string.take_photo), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
EasyImage.openCamera(CreateFoodPhotoActivity.this);
dialog.dismiss();
}
});
alertBuilder.setNegativeButton(getResources().getString(R.string.choose_photo), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Crop.pickImage(CreateFoodPhotoActivity.this);
dialog.dismiss();
}
});
alertBuilder.show();
}
private void beginCrop(Uri source) {
destinationFile = new File(getCacheDir(), "cropped-"+getCurrentTimeStamp());
if(!destinationFile.exists())
{
try {
destinationFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Uri destination = Uri.fromFile(destinationFile);
Crop.of(source, destination).withAspect(600,400).withMaxSize(600,400).start(this);
}
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd-HHmmss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
foodPhotos.add(new UploadFoodPhoto(destinationFile));
foodAdapter.notifyDataSetChanged();
} else if (resultCode == Crop.RESULT_ERROR) {
SKToastMessage.showMessage(this, Crop.getError(result).getMessage(), SKToastMessage.ERROR);
}
}
private void deletePhoto(Integer photoId, final int position){
dialog = new ZProgressHUD(this);
dialog.show();
NetworkEngine.getInstance().deletePhoto(photoId, new Callback<String>() {
@Override
public void success(String arg0, Response response) {
dialog.dismissWithSuccess();
foodPhotos.remove(position);
foodAdapter.notifyDataSetChanged();
}
@Override
public void failure(RetrofitError error) {
dialog.dismissWithFailure();
}
});
}
private void uploadPhoto(){
dialog = new ZProgressHUD(this);
dialog.show();
multipartTypedOutput.addPart("food_id",new TypedString(String.valueOf(food_id)));
int newPhoto = 0;
for(UploadFoodPhoto uploadFoodPhoto: foodPhotos){
if(uploadFoodPhoto.getPhoto() != null) {
multipartTypedOutput.addPart("image[]", new TypedFile("image/png", uploadFoodPhoto.getPhoto()));
++newPhoto;
}
}
if(newPhoto == 0){
dialog.dismiss();
SKToastMessage.showMessage(this, getResources().getString(R.string.str_alert_upload_photo), SKToastMessage.ERROR);
return;
}
NetworkEngine.getInstance().uploadFoodPhoto(multipartTypedOutput, new Callback<JsonObject>() {
@Override
public void success(JsonObject jsonObject, Response response) {
dialog.dismissWithSuccess();
if(food != null){
Intent intent = new Intent(getApplicationContext(), ShopFoodListActivity.class);
intent.putExtra("shop", extras.getString("shop"));
startActivity(intent);
}else{
Intent intent = new Intent(getApplicationContext(), CreateFoodDiscountActivity.class);
intent.putExtras(extras);
startActivity(intent);
}
finish();
}
@Override
public void failure(RetrofitError error) {
dialog.dismissWithFailure();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new EasyImage.Callbacks() {
@Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
//Some error handling
}
@Override
public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
//Handle the image
beginCrop(Uri.fromFile(imageFile));
}
@Override
public void onCanceled(EasyImage.ImageSource imageSource) {
//Cancel handling, you might wanna remove taken photo if it was canceled
if (imageSource == EasyImage.ImageSource.CAMERA) {
File photoFile = EasyImage.lastlyTakenButCanceledPhoto(CreateFoodPhotoActivity.this);
if (photoFile != null) photoFile.delete();
}
}
});
if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add_photo:
showActionForUserPhoto();
break;
case R.id.btn_next:
if(foodPhotos != null && foodPhotos.size() > 0)
uploadPhoto();
else
SKToastMessage.showMessage(CreateFoodPhotoActivity.this,getResources().getString(R.string.str_please_add_photo), SKToastMessage.ERROR);
break;
default:
break;
}
}
@Nullable
@Override
public Intent getSupportParentActivityIntent() {
onBackPressed();
return super.getSupportParentActivityIntent();
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
SKToastMessage.showMessage(this, getResources().getString(R.string.press_again_cancel), SKToastMessage.INFO);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
<file_sep>package com.smk.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class FoodDiscount implements Serializable{
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("food_id")
@Expose
private Integer foodId;
@SerializedName("discount")
@Expose
private Integer discount;
@SerializedName("start_date")
@Expose
private String startDate;
@SerializedName("end_date")
@Expose
private String endDate;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("deleted_at")
@Expose
private Object deletedAt;
@SerializedName("food")
@Expose
private Food food;
/**
* @return The id
*/
public Integer getId() {
return id;
}
/**
* @param id The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return The foodId
*/
public Integer getFoodId() {
return foodId;
}
/**
* @param foodId The food_id
*/
public void setFoodId(Integer foodId) {
this.foodId = foodId;
}
/**
* @return The discount
*/
public Integer getDiscount() {
return discount;
}
/**
* @param discount The discount
*/
public void setDiscount(Integer discount) {
this.discount = discount;
}
/**
* @return The startDate
*/
public String getStartDate() {
return startDate;
}
/**
* @param startDate The start_date
*/
public void setStartDate(String startDate) {
this.startDate = startDate;
}
/**
* @return The endDate
*/
public String getEndDate() {
return endDate;
}
/**
* @param endDate The end_date
*/
public void setEndDate(String endDate) {
this.endDate = endDate;
}
/**
* @return The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
* @param createdAt The created_at
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
* @return The updatedAt
*/
public String getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt The updated_at
*/
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @return The deletedAt
*/
public Object getDeletedAt() {
return deletedAt;
}
/**
* @param deletedAt The deleted_at
*/
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
/**
* @return The food
*/
public Food getFood() {
return food;
}
/**
* @param food The food
*/
public void setFood(Food food) {
this.food = food;
}
} | ead767646065e311a177bb2cd6706c7540008a6e | [
"Java",
"Gradle"
] | 36 | Java | SawMaineK/promotion | ccf0f11ca695a3fc8f3eef10dd40ba4d1e3ccdb7 | 62b7be2df4b0a53f298164b5314a090bc6fb4fe8 |
refs/heads/master | <repo_name>CXQ123943/com-javase-260<file_sep>/20200824/src/com/cxq/collection/ComparatorTest.java
package com.cxq.collection;
import org.junit.Test;
import java.util.Comparator;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/**
* @author CXQ
* @version 1.0
*/
public class ComparatorTest {
/**
* 实现Comparator接口 Comparator - compare
* */
class CustomComparator implements Comparator<Person> {
@Override
public int compare(Person personA, Person personB) {
int result = personA.getName().compareTo(personB.getName());
if (result == 0) {
result = Integer.compare(personA.getAge(), personB.getAge());
}
return result;
}
}
class Person {
private String name;
private Integer age;
Person(String name, int age){
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
//可重写可重写:阿里规范建议的
@Override
public int hashCode() {
return super.hashCode();
}
//可重写可重写:阿里规范建议的
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Test
public void sortByComparator() {
Set<Person> set = new TreeSet<>(new CustomComparator());
set.add(new Person("b", 18));
set.add(new Person("b", 15));
set.add(new Person("a", 9));
set.add(new Person("a", 9));
System.out.println(set);
}
/**
* 实现Comparable接口 Comparable - compareTo
* */
private static class Student implements Comparable<Student> {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student student) {
String prevName = this.name;
String nextName = student.getName();
int prevAge = this.age;
int nextAge = student.getAge();
return prevAge == nextAge ? nextName.compareTo(prevName) : nextAge - prevAge;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
String getName() {
return name;
}
int getAge() {
return age;
}
}
@Test
public void sortByComparable() {
TreeSet<Student> treeSet = new TreeSet<>();
Student studentA = new Student("a", 50);
Student studentB = new Student("c", 60);
Student studentC = new Student("b", 30);
treeSet.add(studentA);
treeSet.add(studentB);
treeSet.add(studentC);
System.out.println(treeSet);
}
}
<file_sep>/20200813/src/com/cxq/test/WeekReferenceTest.java
package com.cxq.test;
import java.io.IOException;
import java.lang.ref.WeakReference;
/**
* @author CXQ
* @version 1.0
*/
public class WeekReferenceTest {
public static void main(String[] args) throws IOException {
WeakReference<Demo> wrDemo = new WeakReference<>(new Demo());
System.out.println(wrDemo.get() == null);
System.gc();
System.out.println(wrDemo.get() == null);
}
static class Demo{
@Override
protected void finalize() throws Throwable {
System.out.println("GC会调用finalize()...");
}
}
}
<file_sep>/20200803/src/com/cxq/test/BitTest.java
package com.cxq.test;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class BitTest {
@Test
public void miec(){
System.out.println(Integer.toBinaryString(-2 >> 3));
System.out.println(Integer.toBinaryString(-2 / 8));
System.out.println(Integer.toString(-2 >> 3));
}
@Test
public void calculation1(){
//交换数值.
int a = 1;
int b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a);
System.out.println(b);
}
@Test
public void calculation2(){
int a = 1;
int b = 2;
b = ( a + b ) - ( a = b);
System.out.println(a);
System.out.println(b);
}
}
<file_sep>/20200807/src/com/cxq/test/ShallowCloneTest.java
package com.cxq.test;
import com.cxq.prototype.Sheep;
import org.junit.Test;
import java.util.Date;
/**
* @author CXQ
* @version 1.0
*/
public class ShallowCloneTest {
@Test
public void shallowclone(){
Date birth = new Date();
Sheep sheepA = new Sheep();
sheepA.setName("goatKing");
sheepA.setBirth(birth);
System.out.println("sheepA's name is " + sheepA.getName());
System.out.println("sheepA's birth is " + sheepA.getBirth());
//克隆出一个实例
Sheep sheepB = sheepA.shallowClone(sheepA);
//判断两个实例是否为同一个实例对象
System.out.println(sheepA == sheepB ? "sheepA与sheepB是同一只羊" : "sheepA与sheepB不是同一只羊");
sheepB.setName("dolly");
System.out.println("sheepB's name is " + sheepB.getName());
System.out.println("sheepB's birth is " + sheepB.getBirth());
birth.setTime(555555L);
System.out.println("sheepA's birth is " + sheepA.getBirth());
System.out.println("sheepB's birth is " + sheepB.getBirth());
}
}
<file_sep>/20200724/src/com/steven/test/ThisTest.java
package com.steven.test;
import com.steven.demo.ThisDemo;
import org.junit.Test;
import java.util.Arrays;
/**
* @author StevenChen
* @version 1.0
*/
public class ThisTest {
@Test
public void thisConstructor(){
ThisDemo cxq = new ThisDemo("cxq", 3, new double[]{4, 5, 3});
System.out.println(cxq);
System.out.println("=========================================");
cxq.setName("zds");
cxq.setAge(34);
cxq.setScore(new double[]{5432,543,6});
System.out.println(cxq.getName());
System.out.println(cxq.getAge());
System.out.println(Arrays.toString(cxq.getScore()));
}
}
<file_sep>/20200812/src/com/cxq/demo/ReferenceCountDemo.java
package com.cxq.demo;
/**
* @author CXQ
* @version 1.0
*/
public class ReferenceCountDemo {
private ReferenceCountDemo field;
public static void main(String[] args) {
ReferenceCountDemo instanceA = new ReferenceCountDemo();
ReferenceCountDemo instanceB = new ReferenceCountDemo();
// 让两个实例循环引用,此时两个实例的引用计数均为1
instanceA.field = instanceB;
instanceB.field = instanceA;
// 断开两个实例的堆栈联系,此时堆中的两个对象应为垃圾,但因为互相引用,永远无法被GC回收
instanceA = null;
instanceB = null;
// 事实上内存在GC之后变小了,说明jdk8使用的不是引用计数的回收方式
System.gc();
}
}
<file_sep>/20200824/src/com/cxq/homework/ClassTest.java
package com.cxq.homework;
import org.junit.Test;
import java.util.*;
public class ClassTest {
@Test
public void test01() {
Map<String, Object> map = new HashMap<>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
Set<String> strings = map.keySet();
for (String e : strings) {
Object value = map.get(e);
System.out.println("Key: " + e + " Value: " + value);
}
}
@Test
public void test02() {
HashMap<Character, Integer> hashMap = new HashMap<>(5);
char[] chars = "aabawebaaabbeecc".toCharArray();
Integer value = 0;
for (Character key : chars) {
value = hashMap.get(key);
if (value == null) {
hashMap.put(key, 1);
} else {
hashMap.put(key, ++value);
}
System.out.println("Key: " + key + " Value: " + value);
}
}
@Test
public void test03() {
int temp = 10000;
ArrayList<Integer> arr = new ArrayList<>();
long first01 = System.currentTimeMillis();
for (int i = 0; i < temp; i++) {
arr.add(0, 1);
}
long end01 = System.currentTimeMillis();
System.out.println(end01 - first01);
LinkedList<Integer> links = new LinkedList<>();
long first02 = System.currentTimeMillis();
for (int i = 0; i < temp; i++) {
links.add(0, 1);
}
long end02 = System.currentTimeMillis();
System.out.println(end02 - first02);
}
@Test
public void test04() {
TreeSet<Object> treeSet = new TreeSet<>(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return 1;
}
});
treeSet.add(1);
treeSet.add(4);
treeSet.add(3);
treeSet.add(2);
System.out.println(treeSet);
}
private static class StringDemo implements Comparable<StringDemo> {
private String value;
StringDemo(String value) {
this.value = value;
}
@Override
public int compareTo(StringDemo o) {
int prevLength = value.length();
int nextLength = o.value.length();
return prevLength == nextLength ? 1 : nextLength -prevLength ;
}
@Override
public String toString() {
return value ;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StringDemo that = (StringDemo) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
@Test
public void sortedByStringLength() {
Set<StringDemo> set = new TreeSet<>();
set.add(new StringDemo("a"));
set.add(new StringDemo("bc"));
set.add(new StringDemo("aaa"));
set.add(new StringDemo("aaaa"));
set.add(new StringDemo("bbab"));
set.add(new StringDemo("cdfa"));
set.add(new StringDemo("b"));
set.add(new StringDemo("c"));
System.out.println(set);
}
}<file_sep>/20200728/src/com/steven/myenum/Week.java
package com.steven.myenum;
/**
* @author CXQ
* @version 1.0
*/
public enum Week {
/**星期一到星期日*/
MON, TUE, WED, THU, FRI, SAT, SUN;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>/20200728/src/com/steven/incognito/UserService.java
package com.steven.incognito;
/**
* @author StevenChen
* @version 1.0
*/
public interface UserService {
/**添加数据*/
void create();
}
<file_sep>/20200728/src/com/steven/staticinnerclass/StaticClassTest.java
package com.steven.staticinnerclass;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class StaticClassTest {
@Test
public void staticInnerTest(){
// 获取静态内部类
StaticOuter.StaticInner staticInner = new StaticOuter.StaticInner();
// 用内部类实例访问内部类成员方法
staticInner.aMethod();
// 可以直接使用内部类的名字调用内部类的静态方法
StaticOuter.StaticInner.aStaticMethod();
}
}
<file_sep>/20200814/src/com/cxq/reflect/DynamicOperaTest.java
package com.cxq.reflect;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
* @author CXQ
* @version 1.0
*/
public class DynamicOperaTest {
public static void main(String[] args) throws Exception {
outputStreamReader();
String outPath = "D:" + File.separator + "HelloWorld.java";
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
int run = javac.run(null, null, null, outPath);
System.out.println(run == 0 ? "javac success" : "javac unsuccess");
if (run == 0){
dynamicRun();
}
}
private static void outputStreamReader() throws Exception{
String outPath = "D:" + File.separator + "HelloWorld.java";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outPath));
String str;
while ((str = bufferedReader.readLine()) != null) {
if ("".equalsIgnoreCase(str)){
break;
}
bufferedWriter.write(str);
}
bufferedReader.close();
bufferedWriter.flush();
bufferedWriter.close();
}
private static void dynamicRun() throws Exception {
URL url = new URL("file:" + File.separator + "D:" + File.separator);
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
Class<?> klass = urlClassLoader.loadClass("HelloWorld");
Method method = klass.getMethod("main", String[].class);
// main() is static, so p1 of invoke() must be null
// 这里必须强转成Object类型,否则String[]数组参数会被拆成"a"和"b",与main方法的参数个数不符合
method.invoke(null, (Object) new String[]{"a", "b"});
urlClassLoader.close();
File file01 = new File("D:" + File.separator + "HelloWorld.java");
file01.delete();
System.out.println("java文件删除成功");
File file02 = new File("D:" + File.separator + "HelloWorld.class");
file02.delete();
System.out.println("class文件删除成功");
}
}<file_sep>/20200804/src/com/cxq/io/RandomAccessFileTest.java
package com.cxq.io;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author CXQ
* @version 1.0
*/
public class RandomAccessFileTest {
@Test
public void wrideAndRead() throws IOException {
String name = "D:\\idea2018\\idea\\emp.txt";
RandomAccessFile randomAccessFile = new RandomAccessFile(name,"rw");
// 写
randomAccessFile.writeUTF("赵四");
randomAccessFile.writeInt(18);
randomAccessFile.writeUTF("刘能");
randomAccessFile.writeInt(28);
randomAccessFile.writeUTF("广坤");
randomAccessFile.writeInt(38);
// 移动指针位置为0
randomAccessFile.seek(24);
// 读
System.out.println(randomAccessFile.readUTF());
System.out.println(randomAccessFile.readInt());
//指针跳过指定的字节长度
randomAccessFile.skipBytes(12);
randomAccessFile.seek(0);
System.out.println(randomAccessFile.readUTF());
System.out.println(randomAccessFile.readInt());
randomAccessFile.close();
}
}
<file_sep>/20200723/src/com/steven/test/InstanceTest.java
package com.steven.test;
import com.steven.demo.Person;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class InstanceTest {
@Test
public void instance(){
// 变量类型 变量名 = new 构造器();
Person zhaosi = new Person();
System.out.println(zhaosi);
}
@Test
public void changeForNoStaticField(){
Person zhaosi = new Person();
Person liuneng = new Person();
zhaosi.id = 50;
System.out.println(liuneng.id);
}
@Test
public void changeForStaticField(){
Person zhaosi = new Person();
Person liuneng = new Person();
// 静态属性不属于某个实例,而是属于这个模板
Person.age = 50;
System.out.println(Person.age);
}
}
<file_sep>/20200727/src/com/steven/factorymethod/Car.java
package com.steven.factorymethod;
/**
* @author StevenChen
* @version 1.0
*/
public interface Car {
void drive();
}
<file_sep>/20200727/src/com/steven/abstractfactory/impl/GoodTiresImpl.java
package com.steven.abstractfactory.impl;
import com.steven.abstractfactory.Tires;
/**
* @author StevenChen
* @version 1.0
*/
public class GoodTiresImpl implements Tires {
@Override
public void info() {
System.out.println("好轮胎...");
}
}
<file_sep>/20200720/src/com/steven/test/ArraysTest.java
package com.steven.test;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class ArraysTest {
@Test
public void arraysMax(){
int[] arrs = {1,3,5,7,9,2,4,6,8,0};
int result = arrs[0];
for (int i = 0; i < arrs.length; i++) {
if (result < arrs[i]){
result = arrs[i];
}
}
System.out.println("最大值:" + result);
}
@Test
public void arraysMin(){
int[] arrs = {1,3,5,7,9,2,4,6,8,0};
int result= arrs[0];
for (int i = 0; i < arrs.length; i++) {
if (result > arrs[i]){
result = arrs[i];
}
}
System.out.println("最小值:" + result);
}
@Test
public void arraysavg(){
int[] arrs = {1,3,5,7,9,2,4,6,8,0};
double sum = 0;
for (int i = 0; i < arrs.length; i++) {
sum += arrs[i];
}
System.out.println("平均数:" + sum / arrs.length);
}
@Test
public void arrayTraverse01() {
int[] num = {1,2,3};
for (int i = 0, j = num.length; i < j; i++) {
System.out.print(num[i]);
}
}
@Test
public void arrayTraverse02() {
int[] num = {1,2,3};
for (int e: num){
System.out.print(e);
}
}
}
<file_sep>/20200806/src/com/cxq/io/OutputStreamWriterTest.java
package com.cxq.io;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* @author CXQ
* @version 1.0
*/
public class OutputStreamWriterTest {
@Test
public void outputSteamWriter() throws IOException {
String filePath = "D:" + File.separator + "idea2018" + File.separator + "idea"+ File.separator + "HelloWorld.txt";
OutputStreamWriter outputStreamWriter = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.write("你好");
System.out.println(outputStreamWriter.getEncoding());
outputStreamWriter.flush();
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"GBK");
outputStreamWriter.write("世界");
System.out.println(outputStreamWriter.getEncoding());
outputStreamWriter.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStreamWriter != null){
outputStreamWriter.close();
}
}
}
}
<file_sep>/20200727/src/com/steven/service/UserService.java
package com.steven.service;
/**
* @author StevenChen
* @version 1.0
*/
public interface UserService {
String NAME = "赵四";
String GENDER = "female";
/**
* 测试方法A
*/
void methodA();
}
<file_sep>/20200826/src/com/cxq/nio/BlockSocketClientByZh.java
package com.cxq.nio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
/**
* @author CXQ
* @version 1.0
*/
public class BlockSocketClientByZh {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9001));
CharBuffer charBuffer = CharBuffer.allocate(1024);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
CharsetEncoder charsetEncoder = StandardCharsets.UTF_8.newEncoder();
String str;
while ((str = br.readLine()) != null) {
charBuffer.put("=> " + str);
charBuffer.flip();
socketChannel.write(charsetEncoder.encode(charBuffer));
charBuffer.clear();
}
br.close();
socketChannel.close();
}
}<file_sep>/20200817/src/com/cxq/generic/SkipGenericTypeCheckTest.java
package com.cxq.generic;
import org.junit.Test;
import java.lang.reflect.Method;
/**
* @author CXQ
* @version 1.0
*/
public class SkipGenericTypeCheckTest {
public static class Point<T> {
private T value;
public T getValue() { return value; }
public void setValue(T value) { this.value = value; }
}
@Test
public void skipGenericTypeCheckByReflect() throws Exception {
Point<String> demo = new Point<>();
Class<?> klass = demo.getClass();
Method method = klass.getMethod("setValue", Object.class);
method.invoke(demo, 10);
Method method1 = klass.getMethod("getValue");
System.out.println(method1.invoke(demo));
}
}
<file_sep>/20200817/src/com/cxq/generic/MethodGenericTypeTest.java
package com.cxq.generic;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class MethodGenericTypeTest<T> {
private <V> V method(V v, T t) {
System.out.println("v:" + (v instanceof Integer));
System.out.println("t:" + (t instanceof String));
return v;
}
@Test
public void api() {
MethodGenericTypeTest<String> result01 = new MethodGenericTypeTest<>();
System.out.println("return: " + result01.method(15,"...."));
MethodGenericTypeTest<String> result02 = new MethodGenericTypeTest<>();
System.out.println("return: " + result02.method(15.5,"..."));
}
}
<file_sep>/20200805/src/com/cxq/io/FileReaderTest.java
package com.cxq.io;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* @author CXQ
* @version 1.0
*/
public class FileReaderTest {
@Test
public void fileReader() {
String filePath = "D:" + File.separator + "idea2018" + File.separator + "idea"+ File.separator + "HelloWorld.java";
try (FileReader fileReader = new FileReader(filePath)){
System.out.println("输入流编码为:" + fileReader.getEncoding());
int b;
while ((b = fileReader.read()) != -1){
System.out.print((char)b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/20200807/src/com/cxq/test/DeepCloneTest.java
package com.cxq.test;
import com.cxq.prototype.Sheep;
import org.junit.Test;
import java.util.Date;
/**
* @author CXQ
* @version 1.0
*/
public class DeepCloneTest {
@Test
public void deepClone(){
Date birth = new Date();
Sheep sheepA = new Sheep();
sheepA.setName("dorset");
sheepA.setBirth(birth);
//克隆出一个实例
Sheep sheepB = sheepA.deepClone(sheepA);
sheepB.setName("dolly");
birth.setTime(555555L);
}
}
<file_sep>/20200714/src/com/chenxiaoqiang/text/HelloWorld.java
package com.chenxiaoqiang.text;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class HelloWorld {
@Test
public void fun01(){
//ctrl + alt + l 快速对齐
//ctrl + d 快速复制上一行
//ctrl + shift + ? 多行注释
//ctrl q 查看方法的详细信息
System.out.println("我叫JoeZhou");
System.out.println("175471");
System.out.println("135631");
System.out.println("175765");
System.out.println("43255");
System.out.println("52345");
fun02();
}
@Test
public void fun02(){
System.out.println("2222");
}
@Test
public void fun03(){
System.out.println("2222");
System.out.println();
System.out.println("\n");
}
}
<file_sep>/20200813/src/com/cxq/reflect/GetArrayClassTest.java
package com.cxq.reflect;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class GetArrayClassTest {
@Test
public void arrayTypeTest() {
Class<?> class01 = int[].class;
Class<?> class02 = int[].class;
Class<?> class03 = int[][].class;
Class<?> class04 = double[].class;
System.out.println(class01.hashCode() == class02.hashCode());
System.out.println(class01.hashCode() == class03.hashCode());
System.out.println(class01.hashCode() == class04.hashCode());
}
}
<file_sep>/20200827/src/com/cxq/test/ForegroundThreadTest.java
package com.cxq.test;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class ForegroundThreadTest {
private static class SubThread extends Thread {
@Override
public void run() {
for (int i = 0, j = 10; i < j; i++) {
System.out.print(i);
}
}
}
@Test
public void buildByThread() {
SubThread customThread = new SubThread();
customThread.start();
}
@Test
public void buildByInnerThread() {
new Thread(() -> {
for (int i = 0, j = 10; i < j; i++) {
System.out.println(i);
}
}).start();
}
private static class SubRunnable implements Runnable {
@Override
public void run() {
for (int i = 0, j = 10; i < j; i++) {
System.out.print(i);
}
}
}
@Test
public void buildByRunnable() {
new Thread(new SubRunnable()).start();
}
@Test
public void buildByInnerRunnable() {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0, j = 10; i < j; i++) {
System.out.print(i);
}
}
}).start();
}
@Test
public void buildByLambda() {
new Thread(() -> {
for (int i = 0, j = 10; i < j; i++) {
System.out.print(i);
}
}).start();
}
}
<file_sep>/20200714/src/com/chenxiaoqiang/text/SoutTest.java
package com.chenxiaoqiang.text;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class SoutTest {
@Test
public void print(){
System.out.println("我叫" + "Steven" );
}
@Test
public void err(){
System.err.println("哎哟!!!");
System.out.println(10);
}
}
<file_sep>/20200807/src/com/cxq/prototype/Sheep.java
package com.cxq.prototype;
import java.io.*;
import java.util.Date;
/**
* @author CXQ
* @version 1.0
*/
public class Sheep implements Cloneable, Serializable{
private String name;
private Date birth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Sheep shallowClone(Sheep sheep){
Sheep result = null;
try {
result = (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return result;
}
public Sheep multipleShallowClone(Sheep sheep) {
Sheep result = null;
try {
result = (Sheep) super.clone();
Date date = (Date)sheep.birth.clone();
sheep.setBirth(date);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return result;
}
public Sheep deepClone(Sheep sheep) {
Sheep result = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(sheep);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ois = new ObjectInputStream(bais);
result = (Sheep) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
<file_sep>/20200724/src/com/steven/pojo/Manager.java
package com.steven.pojo;
import java.io.Serializable;
/**
* @author StevenChen
* @version 1.0
*/
public class Manager extends EmployeePojo implements Serializable {
private double bonus = 200;
public Manager() {
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
<file_sep>/20200727/src/com/steven/factorymethod/CarFactory.java
package com.steven.factorymethod;
/**
* @author StevenChen
* @version 1.0
*/
public interface CarFactory {
Car build();
}
<file_sep>/20200727/src/com/steven/gof/CarTest.java
package com.steven.gof;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class CarTest {
@Test
public void carTest(){
Car benz = CarFatory.getBenz();
Car bmw = CarFatory.getBmw();
benz.drive();
bmw.drive();
}
}
<file_sep>/20200723/src/com/steven/demo/AddNum.java
package com.steven.demo;
/**
* @author StevenChen
* @version 1.0
*/
public class AddNum {
public static int addNum(int a,int b){
return a + b;
}
}<file_sep>/20200728/src/com/steven/myenum/Element.java
package com.steven.myenum;
/**
* @author CXQ
* @version 1.0
*/
public enum Element {
/**
* 元素
*/
EARTH, VIND,
FIRE {
public String info() {
return "Hot";
}
};
public String into() {
return "element";
}
}
<file_sep>/20200717/src/com/chenxiaoqiang/text/RelationalOperatorTest.java
package com.chenxiaoqiang.text;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class RelationalOperatorTest {
@Test
public void relationalOperator(){
System.out.println(1 == 2 == true);
}
}
<file_sep>/20200827/src/com/cxq/classwork/ClassWork.java
package com.cxq.classwork;
import org.junit.Test;
import java.nio.ByteBuffer;
/**
* @author CXQ
* @version 1.0
*/
public class ClassWork {
@Test
public void markAndReset() {
String str = "encoder";
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(str.getBytes());
byteBuffer.flip();
byteBuffer.position(3).mark();
System.out.print((char) byteBuffer.get());
System.out.print((char) byteBuffer.get());
byteBuffer.reset();
System.out.print((char) byteBuffer.get());
System.out.print((char) byteBuffer.get());
}
}
<file_sep>/20200904/src/com/cxq/communication/CyclicBarrierTest.java
package com.cxq.communication;
import lombok.SneakyThrows;
import org.junit.After;
import org.junit.Test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* @author CXQ
* @version 1.0
*/
public class CyclicBarrierTest {
@Test
public void cyclicBarrier() {
CyclicBarrier cyclicBarrier = new CyclicBarrier(8, () -> {
System.out.println("broke the cyclicBarrier...");
});
synchronized (this) {
for (int i = 0, j = 9; i < j; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + ": ready...");
cyclicBarrier.await();
} catch (BrokenBarrierException | InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": go...");
}, "threadA-" + i).start();
}
}
synchronized (this) {
for (int i = 0, j = 9; i < j; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + ": ready...");
cyclicBarrier.await();
} catch (BrokenBarrierException | InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ": go...");
}, "threadA-" + i).start();
}
}
}
@SneakyThrows
@After
public void after() {
System.out.println(System.in.read());
}
}<file_sep>/20200901/src/com/cxq/sync/DoubleAdderTest.java
package com.cxq.sync;
import org.junit.Test;
import java.util.concurrent.atomic.DoubleAdder;
/**
* @author CXQ
* @version 1.0
*/
public class DoubleAdderTest {
private static DoubleAdder doubleAdder = new DoubleAdder();
@Test
public void longAdder() {
System.out.println("当前值:" + doubleAdder);
doubleAdder.add(5);
System.out.println("+5后的值:" + doubleAdder);
doubleAdder.sum();
System.out.println("sum后的值:" + doubleAdder);
}
}<file_sep>/20200806/src/com/cxq/io/ObjectStreamTest.java
package com.cxq.io;
import org.junit.Test;
import java.io.*;
/**
* @author CXQ
* @version 1.0
*/
class Student implements Serializable {
private String name;
/**属性不参与序列化过程,值不可见(为默认值)*/
private transient Integer age;
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
Integer getAge() {
return age;
}
void setAge(Integer age) {
this.age = age;
}
}
public class ObjectStreamTest {
@Test
public void objectStream(){
String filePath = "D:" + File.separator + "idea2018" + File.separator + "idea"+ File.separator + "student.txt";
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath))){
Student student = new Student();
student.setName("赵四");
student.setAge(18);
objectOutputStream.writeObject(student);
objectOutputStream.flush();
System.out.println("写入完成!");
Student o = (Student) objectInputStream.readObject();
System.out.println("name:" + o.getName());
System.out.println("age:" + o.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
<file_sep>/20200730/src/com/cxq/test/MyExceptionTest.java
package com.cxq.test;
import com.cxq.demo.MyException;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class MyExceptionTest {
@Test
public void myException() throws MyException {
throw new MyException("你触发了一个我自己写的异常...");
}
}
<file_sep>/20200716/src/com/joe/text/ConverTest.java
package com.joe.text;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class ConverTest {
@Test
public void converTest(){
long a = 10000000L;
int b = (int) a;
System.out.println("b");
}
}
<file_sep>/20200715/src/com/chenxiaoqiang/text/BaseText.java
package com.chenxiaoqiang.text;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class BaseText {
@Test
public void SpecialBase(){
System.out.println(0x782);
}
@Test
public void SpecialBase2(){
System.out.println(0775);
}
@Test
public void byteNum(){
byte a = 127;
System.out.println(a);
}
@Test
public void shortNum(){
short a = 12557;
System.out.println(a);
}
@Test
public void intNum(){
int a = 1543542557;
System.out.println(a);
}
@Test
public void longNum(){
long a = 1564366757;
System.out.println(a);
}
@Test
public void floatNum(){
float a = 646;
System.out.println(a);
}
@Test
public void doubleNum(){
double a = 1564366757;
System.out.println(a);
}
@Test
public void booleanNum(){
boolean a = true;
System.out.println(a);
}
@Test
public void charNum(){
char a = 89;
System.out.println(a);
}
}
<file_sep>/20200831/src/com/cxq/sync/ReentryTest.java
package com.cxq.sync;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class ReentryTest {
private synchronized void methodA() {
System.out.println("methodA()");
// 调用methodB时,发现是同一线程,允许重入
methodB();
}
private synchronized void methodB() {
System.out.println("methodB()");
}
@Test
public void reentry() {
// 主线程调用methodA()
new ReentryTest().methodA();
}
}<file_sep>/20200811/src/com/cxq/test/ByteCodeFirstTest.java
package com.cxq.test;
/**
* @author CXQ
* @version 1.0
*/
public class ByteCodeFirstTest {
private int num;
public int method() {
return num++;
}
}
<file_sep>/20200901/src/com/cxq/sync/LongAdderTest.java
package com.cxq.sync;
import org.junit.Test;
import java.util.concurrent.atomic.LongAdder;
/**
* @author CXQ
* @version 1.0
*/
public class LongAdderTest {
private static LongAdder longAdder = new LongAdder();
@Test
public void longAdder() {
System.out.println("当前值:" + longAdder);
longAdder.add(5);
System.out.println("+5后的值:" + longAdder);
longAdder.increment();
System.out.println("自增1后的值:" + longAdder);
longAdder.decrement();
System.out.println("自减1后的值:" + longAdder);
}
}
<file_sep>/20200828/src/com/cxq/test/OrderReorderingTest.java
package com.cxq.test;
import lombok.SneakyThrows;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class OrderReorderingTest {
private /*volatile*/ int x = 0, y = 0, a = 0, b = 0;
@SneakyThrows
@Test
public void orderReorder() {
int count = 0;
while (true) {
count++;
Thread threadA = new Thread(() -> {
a = 1;
x = b;
});
Thread threadB = new Thread(() -> {
b = 1;
y = a;
});
threadA.start();
threadB.start();
threadA.join();
threadB.join();
System.out.printf("第%d次:x=%d,y=%d\n", count, x, y);
if (x == 0 && y == 0) {
System.out.println("发生了指令重排,跳出循环");
break;
} else {
x = 0;
y = 0;
a = 0;
b = 0;
}
}
}
}
<file_sep>/20200723/src/com/steven/demo/Person.java
package com.steven.demo;
/**
* @author StevenChen
* @version 1.0
*/
public class Person {
public int id = 1;
String name = "张三";
public static int age = 23;
private String gender = "女";
}
<file_sep>/20200729/src/com/cxq/demo/Annotation.java
package com.cxq.demo;
import java.lang.annotation.*;
/**
* @author CXQ
* @version 1.0
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotation {
ElementType[] value();
}<file_sep>/20200814/src/com/cxq/reflect/ReflectAnnotationTest.java
package com.cxq.reflect;
import org.junit.Test;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @author CXQ
* @version 1.0
*/
public class ReflectAnnotationTest {
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
String name();
int age() default 18;
String[] course() default {"语文", "数学"};
}
@MyAnnotation(name = "赵四")
static class Student{
@MyAnnotation(name = "刘能", course = {"英语","数学"}, age = 19)
public void mothod(){}
}
@Test
public void reflectAnnotation1() {
Class<?> Klass= Student.class;
MyAnnotation declaredAnnotation = Klass.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(declaredAnnotation.age());
System.out.println(declaredAnnotation.name());
System.out.println(Arrays.toString(declaredAnnotation.course()));
}
@Test
public void reflectAnnotation2() {
try {
Class<?> Klass= Student.class;
Method mothod = Klass.getDeclaredMethod("mothod");
MyAnnotation declaredAnnotation = mothod.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(declaredAnnotation.age());
System.out.println(declaredAnnotation.name());
System.out.println(Arrays.toString(declaredAnnotation.course()));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
<file_sep>/20200817/src/com/cxq/test/CustomQueueTest.java
package com.cxq.test;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class CustomQueueTest {
private int[] arr = new int[0];
private boolean add(int value) {
int[] arrBack = arr;
int[] newArr = new int[arr.length + 1];
for (int i = 0, j = arr.length; i < j; i++) {
newArr[i] = arr[i];
}
newArr[arr.length] = value;
arr = newArr;
return arrBack.length != arr.length;
}
private Integer poll() {
if (arr.length == 0){
return null;
}
int firstElement = arr[0];
int[] newArr = new int[arr.length - 1];
for (int i = 0, j = newArr.length; i < j; i++) {
newArr[i] = arr[i + 1];
}
arr = newArr;
return firstElement;
}
private Integer peek() {
return arr.length <= 0 ? null : arr[0];
}
@Test
public void api() {
System.out.println(add(10) ? "add success" : "add fail");
System.out.println(add(20) ? "add success" : "add fail");
System.out.println(add(30) ? "add success" : "add fail");
System.out.println("poll: " + poll());
System.out.println("peek: " + peek());
}
}
<file_sep>/20200907/src/com/cxq/collection/SynchronizedListTest.java
package com.cxq.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author CXQ
* @version 1.0
*/
public class SynchronizedListTest {
@Test
public void vectorByDebug() {
Vector<String> vector = new Vector<>();
vector.add("zhao-si");
vector.add(0,"liu-neng");
vector.add("zhang-de-shuai");
vector.add(1,"wang-wu");
vector.set(1,"wang-de-fa");
System.out.println(vector.capacity());
System.out.println(vector.size());
System.out.println(vector.contains("wang-de-fa"));
System.out.println(vector.indexOf("zhang-de-shuai"));
vector.removeElementAt(1);
System.out.println(vector.remove(0));
vector.clear();
}
@Test
public void synchronizedList() {
List<String> arrayList = new ArrayList<>();
List<String> list = Collections.synchronizedList(arrayList);
list.add("赵四");
System.out.println(list.get(0));
}
@Test
public void copyOnWriteArrayList() {
List<String> list = new CopyOnWriteArrayList<>();
list.add("zhao-si");
System.out.println(list.get(0));
}
}
<file_sep>/20200901/src/com/cxq/sync/ThreadLocalTest.java
package com.cxq.sync;
import java.util.concurrent.TimeUnit;
/**
* @author CXQ
* @version 1.0
*/
public class ThreadLocalTest {
private static class Person {
private String name;
}
private static ThreadLocal<Person> personThreadLocal = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1L);
personThreadLocal.set(new Person());
System.out.println("1秒钟后Person设置完成...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2L);
System.out.println(personThreadLocal.get() == null ? "2秒钟后获取失败.." : "2秒钟后获取成功");
personThreadLocal.remove();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}<file_sep>/20200723/src/com/steven/test/AddNumTest.java
package com.steven.test;
import com.steven.demo.AddNum;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class AddNumTest {
@Test
public void addNumTest01(){
int result = adddNum(2,5);
System.out.println(result);
}
@Test
//这里是调用了了一个静态的AddNum类。
public void addNumTest02(){
int result01 = AddNum.addNum(4,6);
System.out.println(result01);
System.out.println("==========================");
AddNum addNum = new AddNum();
// int result02 = addNum.addNum(3,4);
int result02 = AddNum.addNum(6,4);
}
public int adddNum(int a,int b){
return a + b;
}
}
<file_sep>/20200717/src/com/chenxiaoqiang/text/NeicunTest.java
package com.chenxiaoqiang.text;
import org.junit.Test;
/**
* @author StevenChen
* @version 2.0
*/
public class NeicunTest {
@Test
public void comparisonOfBasicDataTypes(){
//内存存储比较
int a = 100;
double b = 10.5;
String str = new String("java");
}
@Test
public void selfCalculation(){
int a = 13 , b = 3;
System.out.println(++a + b);
System.out.println(a-- - b);
System.out.println(a);
System.out.println(b);
}
@Test
public void nullPointerException(){
String str1 = null;
System.out.println("".equals(str1));
//空指针异常
//System.out.println(str1.equals(""));
}
}
<file_sep>/20200728/src/com/steven/incognito/BaseServiceTest.java
package com.steven.incognito;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class BaseServiceTest {
@Test
public void baseServiceByInnerClass() {
//方法一
new BaseService() {
@Override
public void create() {
System.out.println("添加...");
}
}.create();
//方法二
BaseService baseService = new BaseService() {
@Override
void create() {
System.out.println("添加...");
}
};
baseService.create();
}
}
<file_sep>/20200804/src/com/cxq/io/WorkTest.java
package com.cxq.io;
/**
* @author CXQ
* @version 1.0
*/
import java.io.*;
public class WorkTest {
public static void main(String[] args) {
File dir = new File("D:\\dir");
dir.mkdir();
File f1 = new File(dir, "f1.txt");
try {
f1.createNewFile();
} catch (IOException e) { ; }
File newDir = new File("D:\\ewDir");
System.out.println(dir.renameTo(newDir) ? "目录改名成功" : "目录改名失败");
}
}<file_sep>/20200728/src/com/steven/staticinnerclass/StaticOuter.java
package com.steven.staticinnerclass;
/**
* @author CXQ
* @version 1.0
*/
public class StaticOuter {
private int field = 1;
private static int staticField = 2;
static class StaticInner {
private int field = 3;
private static int staticField = 4;
public void aMethod() {
System.out.println(field);
System.out.println(staticField);
System.out.println(new StaticOuter().field);
System.out.println(StaticOuter.staticField);
// 无法直接访问外部类非静态属性
// System.out.println(Outer.this.field);
}
public static void aStaticMethod() {
System.out.println(staticField);
System.out.println(new StaticOuter().field);
System.out.println(StaticOuter.staticField);
// 静态方法无法访问非静态属性
// System.out.println(field);
// 无法直接访问外部类非静态属性
// System.out.println(Outer.this.field);
}
}
}
<file_sep>/20200720/src/com/steven/homework/TextTest.java
package com.steven.homework;
import org.junit.Test;
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
* @author StevenChen
* @version 1.0
*/
public class TextTest {
@Test
public void oneTest(){
int bridePrice = 100000;
boolean temp = bridePrice == 100000;
if (temp){
System.out.println("你给了我" + bridePrice + "RMB,我愿意嫁给我!!");
}else{
System.out.println("你没给够我一百万,我不愿意嫁给你");
}
}
@Test
public void twoTest(){
String mountain = "山无棱";
String sky = "天地合";
if (mountain == "山无棱"){
if (sky == "天地合"){
System.out.println("山无棱,天地合,才敢与君绝!");
}else{
System.out.println("与君无缘");
}
}else{
System.out.println("与君无缘");
}
}
@Test
public void thirdTest(){
int age = 100;
String ageLevel = "童年";
if (age >= 0 & age <= 16){
ageLevel = "童年";
}else if (age <= 30) {
ageLevel = "青年";
}else if (age <= 50) {
ageLevel = "中年";
}else if (age <= 100) {
ageLevel = "老年";
}else {
ageLevel = "年龄有误!";
}
System.out.println(ageLevel);
}
//fourTest 第四题
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("选择查询人的性别:1.男 2.女;输入编号(1或2):");
int sex = scanner.nextInt();
System.out.println("输入一个年龄:");
int age = scanner.nextInt();
if (sex == 1){
if (age > 0 & age <=2){
System.out.println("男孩称谓为:襁褓");
}else if (age > 2 & age <= 3){
System.out.println("男孩称谓为:孩提");
}else if (age > 3 & age <= 7){
System.out.println("男孩称谓为:韶年");
}else if (age > 7 & age <= 10){
System.out.println("男孩称谓为:黄口");
}
}else {
if (age > 0 & age <=2){
System.out.println("女孩称谓为:襁褓");
}else if (age > 2 & age <= 3){
System.out.println("女孩称谓为:孩提");
}else if (age > 3 & age <= 7){
System.out.println("女孩称谓为:鬓年");
}else if (age > 7 & age <= 10){
System.out.println("女孩称谓为:黄口");
}
}
scanner.close();
}
@Test
public void fiveTest(){
int bookNumber = 03;
String result = "水浒传";
switch (bookNumber){
case 01:
result = "红楼梦";
break;
case 02:
result = "西游记";
break;
case 03:
result = "金瓶梅";
break;
case 04:
result = "水浒传";
break;
default:
result = "错误";
break;
}
System.out.println(result);
}
@Test
public void sixTest(){
float fraction = 48.5f;
int temp = (int)fraction/10;
String result = "";
switch (temp){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
result = "不及格";
break;
case 6:
case 7:
result = "及格";
break;
case 8:
case 9:
case 10:
result = "优秀";
break;
default:
result = "输入有误";
break;
}
System.out.println(result);
}
@Test
public void sevenTest(){
int i = 10;
while (i < 15){
i++;
System.out.print(i + "\t");
}
}
@Test
public void eightTest(){
int bridePrice = 600000;
int sellBloodMoney = 1000;
int frequency = 0;
while (sellBloodMoney < bridePrice){
frequency++;
sellBloodMoney = 1000 * frequency;
}
System.out.println(frequency);
}
@Test
public void nightTest() {
int xiaoBinAge = 13;
int daBinAge = 36;
int year = 0;
while (daBinAge != 2 * xiaoBinAge){
year ++;
xiaoBinAge ++;
daBinAge ++;
}
System.out.println(year);
}
@Test
public void tenTest() {
int i = 9;
do {
i++;
System.out.println(i);
}while (i < 15);
}
@Test
public void eleventTest() {
double principal = 10000;
double interest = 0;
double interestRate = 0.03;
int year = 1;
do {
interest = principal * interestRate;
principal = principal + interest;
year ++;
}while (year <= 5);
System.out.println(principal);
}
@Test
public void twelvetTest() {
int sum = 0;
int addend = 0;
do {
addend ++;
if (addend % 3 != 0){
sum = sum + addend;
}
}while (addend <100);
System.out.println(sum);
}
@Test
public void work08() {
// 求整数1-100的累加值,但要求第3,第6,第9...(3的倍数)个值,跳过不计算。
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
continue;
}
sum += i;
}
System.out.println(sum);
}
@Test
public void thirteenTest() {
for (int i = 1 ; i < 100 ; i++){
i ++;
if (i % 2 == 0){
System.out.println(i);
}
}
}
@Test
public void fourteenTest() {
int sum = 0;
int frequency = 1;
int temp = 0;
z:
for (; frequency < 10000; frequency++) {
if (sum < 130) {
temp = frequency * 5;
sum = temp;
}else {
break z;
}
}
System.out.println(frequency);
}
// int count = -1;
// for (int sum = 0 , total = 135; sum <= total; sum += 5) {
// count ++;
// }
// System.out.println(count);
// }
@Test
public void fiveteenTest() {
for (int i = 1; i <= 11; i++){
if (i == 4){
System.out.println(i + "号女嘉宾出场,i love you!");
break;
}
System.out.println(i + "号女嘉宾出场!");
}
}
@Test
public void work12() {
// 方法一:引入第三方变量的方法;
int a = 1, b = 2;
int temp = a;
a = b;
b = temp;
System.out.println(a);
System.out.println(b);
// 方法二:不引入第三方变量的方法
int a1 = 1, b1 = 2;
a1 = a1 + b1;
b1 = a1 - b1;
a1 = a1 - b1;
System.out.println(a1);
System.out.println(b1);
}
@Test
public void work13() {
boolean flag = false;
for (int i = 100; i <= 120; i++) {
if (i % 23 == 0) {
flag = true;
break;
}
}
System.out.println(flag ? "有能被23整除的数" : "没有能被23整除的数");
}
@Test
public void work14() {
int count = 0;
for (int i = 100; i <= 200; i++) {
if (i % 23 == 0) {
count++;
}
}
System.out.println("有" + count + "个能被23整除的数");
}
@Test
public void work15() {
// 求数组:{1, 3, 5, 7, 9, 2, 4, 6, 8, 0},的最小值,最大值和平均值。
int[] arr = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0};
int min = arr[0];
int max = arr[0];
double sum = 0;
for (int i = 0, j = arr.length; i < j; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum += arr[i];
}
System.out.println("最小值是:" + min);
System.out.println("最大值是:" + max);
System.out.println("平均值是:" + (sum / arr.length));
}
@Test
public void work16() {
// 输出数字串"18210210122"中的最大数字"8"和最小值数字"0"。
String numStr = "18210210122";
char[] numArr = numStr.toCharArray();
//数组升序
Arrays.sort(numArr);
System.out.println("theMinValue:" + numArr[0]);
System.out.println("theMaxValue:" + numArr[numArr.length - 1]);
}
@Test
public void work17() {
// 找出2个已知数组中相同的值:
// - int[] as = {2, 3, 6, 9, 11, 15, 19, 23, 35};
// - int[] bs = {1, 3, 7, 9, 11, 13, 14, 19, 35}。
int[] as = {2, 3, 6, 9, 11, 15, 19, 23, 35};
int[] bs = {1, 3, 7, 9, 11, 13, 14, 19, 35};
for (int e1 : as) {
for (int e2 : bs) {
if (e1 == e2) {
System.out.print(e1 + "\t");
}
}
}
}
@Test
public void work18() {
// 设计程序,要求可以从1到32随机生成不重复的7个数。
int[] nums = new int[32];
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
// 把数组打乱10000次
Random random = new Random();
for (int i = 0; i < 10000; i++) {
int posA = random.nextInt(32);
int posB = random.nextInt(32);
int temp = nums[posA];
nums[posA] = nums[posB];
nums[posB] = temp;
}
// 取前七个
for (int i = 0; i < 7; i++) {
System.out.print(nums[i] + "\t");
}
}
@Test
public void work19(){
int[] arr = new int[32];
for (int i = 0, j = arr.length; i < j; i++) {
arr[i] = i + 1;
}
System.out.println(Arrays.toString(arr));
}
}
<file_sep>/20200724/src/com/steven/test/AnimalAndBirdAndDogTest.java
package com.steven.test;
import com.steven.pojo.Bird;
import com.steven.pojo.Dog;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class AnimalAndBirdAndDogTest {
@Test
public void animalAndBirdAndDog(){
System.out.println(new Bird().getName());
new Dog().methodA();
}
}
<file_sep>/20200824/src/com/cxq/collection/EnumSetTest.java
package com.cxq.collection;
import org.junit.Test;
import java.util.EnumSet;
/**
* @author CXQ
* @version 1.0
*/
public class EnumSetTest {
public enum Color {
/**
* some color
* */
RED,GREEN,BIUE,BLACK,YELLOW,WHITE,PINK,GRAY;
}
@Test
public void enumToSet() {
EnumSet<Color> colors = EnumSet.allOf(Color.class);
for (Color e: colors) {
System.out.print(e.toString() + "\0");
}
}
}
<file_sep>/20200727/src/com/steven/demo/SonBaseDemo.java
package com.steven.demo;
/**
* @author StevenChen
* @version 1.0
*/
public class SonBaseDemo extends BaseStartDemo {
@Override
public void methodB() {
System.out.println("子类重写了methodB方法");
}
@Override
public void methodC() {
System.out.println("子类重写了methodC方法");
}
}
<file_sep>/20200831/src/com/cxq/sync/DclSingletonTest.java
package com.cxq.sync;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class DclSingletonTest {
/**
* 用了DCL模式还要使用volatile关键字吗? 必须要!!!!
*/
private static class DclSingleton {
private volatile static DclSingleton singleton = null;
private DclSingleton() {
}
private static DclSingleton getInstance() {
if (singleton == null) {
synchronized (DclSingleton.class) {
if (singleton == null) {
singleton = new DclSingleton();
}
}
}
return singleton;
}
}
@Test
public void dclSingleton() {
for (int i = 0, j = 10; i < j; i++) {
new Thread(() -> {
System.out.println(DclSingleton.getInstance());
}).start();
}
}
}
<file_sep>/20200721/src/com/steven/test/arraysTest.java
package com.steven.test;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class arraysTest {
@Test
public void arraysOne(){
int[][] arr = {{22,66,44},{77,33,88},{25,45,65},{11,66,99}};
int sum = 0;
for (int[] e1: arr){
for (int e2: e1){
sum = sum + e2;
}
}
System.out.println(sum);
}
@Test
public void arraysTwo(){
int i,j;
int a[][];
a=new int[10][10];
for(i=0;i<10;i++){
a[i][i]=1;
a[i][0]=1;
}
for(i=2;i<10;i++){
for(j=1;j<=i;j++){
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}
for(i=0;i<10;i++){
for(j=0;j<i;j++){
System.out.printf(" "+a[i][j]);
}
System.out.println();
}
}
/* @Test
public void arraysThree(){
int i, j;
int[][] arr = new int[10][10];
for (i = 0; i < 10; i++) {
arr[i][0] = 1;
arr[i][i] = 1;
}
for (i = 2; i < 10; i++){
for (j = 1; j <=i ;j++){
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
}
for (i = 0; i < 10; i++){
for (j = 0; j < i+1; j++){
System.out.printf(" " + arr[i][j]);
}
System.out.println();
}
}*/
}
<file_sep>/20200817/src/com/cxq/util/StackTest.java
package com.cxq.util;
import org.junit.Test;
import java.util.Stack;
/**
* @author CXQ
* @version 1.0
*/
public class StackTest {
@Test
public void api() {
Stack<Object> objects = new Stack<>();
System.out.println("push: " + objects.push(1));
System.out.println("push: " + objects.push(2));
System.out.println("push: " + objects.push(3));
System.out.println("push: " + objects.push(4));
System.out.println("peek: " + objects.peek());
System.out.println("search: " + objects.search(3));
System.out.print("for: ");
while (!objects.isEmpty()) {
System.out.print(objects.pop() + "\t");
}
}
}
<file_sep>/20200723/src/com/steven/test/TowerOfHanoi.java
package com.steven.test;
import org.junit.Test;
/**
* @author StevenChen
* @version 1.0
*/
public class TowerOfHanoi {
@Test
public void testHanoi() {
hanoi(10, 'A', 'B', 'C');
}
// num 是一共有多少个盘子、a b c是三根柱子
private void hanoi(int num, char a, char b, char c) {
if (num == 1) {
System.out.printf("1号:%s >> %s\n", a, c);
} else {
// 无论多少盘子都分成两部分,num-1的上面的部分(看成一个盘子)和 最后一个盘子
// 上面的盘子
int hanoiTopPart = num - 1;
// 将上面的盘子,从a途经c移到b
hanoi(hanoiTopPart, a, c, b);
System.out.printf("%s号:%s >> %s\n", num, a, c);
// 将上面的盘子,再从b途经a移到c
hanoi(hanoiTopPart, b, a, c);
}
}
}
<file_sep>/20200826/src/com/cxq/nio/BlockSocketServerByZh.java
package com.cxq.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
/**
* @author CXQ
* @version 1.0
*/
public class BlockSocketServerByZh {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()
.bind(new InetSocketAddress(9001));
System.out.println("ready to accept data...");
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
CharsetDecoder charsetDecoder = StandardCharsets.UTF_8.newDecoder();
while (socketChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
CharBuffer charBuffer = charsetDecoder.decode(byteBuffer);
for (int i = 0, j = charBuffer.limit(); i < j; i++) {
System.out.print(charBuffer.get());
}
System.out.println();
byteBuffer.clear();
}
socketChannel.close();
serverSocketChannel.close();
}
}<file_sep>/20200813/src/com/cxq/reflect/FieldTest.java
package com.cxq.reflect;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/**
* @author CXQ
* @version 1.0
*/
public class FieldTest {
private Class<?> Klass = FieldTest.class;
public String name;
private int gender = 0;
private int age = 0;
@Test
public void reflectFieldsOnlyPublic() {
for (Field field : Klass.getFields()) {
System.out.println(field);
}
}
@Test
public void reflectFields() {
for (Field field : Klass.getDeclaredFields()) {
System.out.println(field);
}
}
@Test
public void reflectFieldOnlyPublic() throws Exception {
System.out.println(Klass.getField("name"));
}
@Test
public void reflectField() throws Exception {
System.out.println(Klass.getDeclaredField("name"));
System.out.println(Klass.getDeclaredField("gender"));
}
@Test
public void usePublicField(){
try {
Object instanceA = Klass.getConstructor().newInstance();
Object instanceB = Klass.getConstructor().newInstance();
Field nameField = Klass.getField("age");
nameField.set(instanceA, 0);
nameField.set(instanceB, 1);
System.out.println(nameField.get(instanceA));
System.out.println(nameField.get(instanceB));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void usePrivateField() {
try {
Object instanceA = Klass.getDeclaredConstructor().newInstance();
Object instanceB = Klass.getDeclaredConstructor().newInstance();
Field ageField = Klass.getDeclaredField("gender");
//获取权限
ageField.setAccessible(true);
ageField.set(instanceA, 1);
ageField.set(instanceB, 2);
System.out.println(ageField.get(instanceA));
System.out.println(ageField.get(instanceB));
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/20200814/src/com/cxq/jpa/MyJPATest.java
package com.cxq.jpa;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class MyJPATest {
@Test
public void myJpaTest() {
new CreateTableTool(User.class).build();
}
}
<file_sep>/20200724/src/com/steven/pojo/Dog.java
package com.steven.pojo;
import java.io.Serializable;
/**
* @author StevenChen
* @version 1.0
*/
public class Dog extends Animal implements Serializable {
public Dog() {
super();
}
public void methodA(){
// move();
super.move();
}
}
<file_sep>/20200727/src/com/steven/service/AdditionService.java
package com.steven.service;
/**
* @author StevenChen
* @version 1.0
*/
public interface AdditionService {
/**
* 两个数相加的方法
*
* @param numA 加法运算的一个数字
* @param numB 加法运算的另一个数字
* @return 返回两个数相加的结果
*/
int add(int numA, int numB);
}
<file_sep>/20200813/src/com/cxq/reflect/GetClassTest.java
package com.cxq.reflect;
import org.junit.Test;
/**
* @author CXQ
* @version 1.0
*/
public class GetClassTest {
@Test
public void getClassByInstance(){
GetClassTest instance = new GetClassTest();
Class<? extends GetClassTest> class01 = instance.getClass();
Class<? extends GetClassTest> class02 = instance.getClass();
System.out.println(class01.hashCode() == class02.hashCode());
}
@Test
public void getClassByClassName(){
Class<GetClassTest> class01 = GetClassTest.class;
Class<GetClassTest> class02 = GetClassTest.class;
System.out.println(class01.hashCode() == class02.hashCode());
}
@Test
public void getClassByForNameMethod(){
String qualifiedName = "com.cxq.reflect.GetClassTest";
try {
Class<?> class01 = Class.forName(qualifiedName);
Class<?> class02 = Class.forName(qualifiedName);
System.out.println(class01.hashCode() == class02.hashCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
<file_sep>/20200729/src/com/cxq/demo/MyAnnotation.java
package com.cxq.demo;
import java.lang.annotation.*;
/**
* @author CXQ
* @version 1.0
*/
@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
// String name;
String name();
// int age = 18;
int age() default 18;
// String[] course = {"语文", "数学"}
String[] course() default {"语文", "数学"};
}
<file_sep>/20200724/src/com/steven/pojo/EmployeePojo.java
package com.steven.pojo;
import java.io.Serializable;
/**
* @author StevenChen
* @version 1.0
*/
public class EmployeePojo implements Serializable {
private double salary = 2000;
public EmployeePojo() {
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
<file_sep>/20200723/src/com/steven/test/funTest.java
package com.steven.test;
/**
* @author StevenChen
* @version 1.0
*/
public class funTest {
public static void main(String[] args){
Integer a = Integer.valueOf(3);
Integer b = 2;
System.out.println("a 和 b 的原始的值:"+a+" "+b);
swap(a,b);
System.out.println("a 和 b 的现在的值:"+a+" "+b);
}
private static void swap(Integer a, Integer b) {
// TODO Auto-generated method stub
Integer temp = 0;
temp = a;
a = b;
b = temp;
}
}
| 0bb9aea413fd8a8f5f54fbf387fe1705638f2708 | [
"Java"
] | 73 | Java | CXQ123943/com-javase-260 | 5203d576681923919d5ac824062e634843b0dd7a | c15861e5df96b42789f3045b25b804e137ca0777 |
refs/heads/master | <file_sep>#include "opencv2/opencv.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0);
if (!cap.isOpened())
return -1;
namedWindow("frame", cv::WINDOW_AUTOSIZE);
for (;;)
{
Mat frameIn;
cap >> frameIn;
imshow("frame", frameIn);
if (waitKey(30) >= 0) break;
}
return 0;
} | da473007dbfdaf02399f591d922b108f23332b15 | [
"C++"
] | 1 | C++ | HumorLogic/OpenCV | ad90f7ae69eac7dbe0c41ddd041e88b8f5dc5c7b | 3517df53595b45be019b5e55c4372786279e77b7 |
refs/heads/master | <file_sep>const fs = require('fs');
const path = require('path');
function loadFile(filename) {
const filepath = path.join(__dirname, `static/${filename}`);
// Load the file
const data = fs.readFileSync(filepath, 'UTF-8');
// Split on newline chars
const lines = data.split(/\r?\n/);
// Trim all the lines
lines.forEach((line, i) => {
lines[i] = line.trim();
});
return lines;
}
function getQuestions() {
let makeQuestions = (array) => {
let questions = [];
array.forEach((line) => {
questions.push(new Question(line));
});
return questions;
};
return {
appearance: makeQuestions(loadFile('appearance.txt')),
interests: makeQuestions(loadFile('interests.txt'))
}
}
function randomSelect(array, n = 1) {
if (n > array.length) {
throw `Cannot select ${n} elements from array with only ${array.length} elements.`;
}
if (n < 1) {
throw `Cannot select less than 1 element`;
}
let unusedQuestions = array.filter(q => !q.used);
n = unusedQuestions.length < n ? unusedQuestions.length : n;
// Generate n unique random numbers
let randomIndexes = [];
while (randomIndexes.length < n) {
let num = Math.floor(Math.random() * unusedQuestions.length);
if (randomIndexes.includes(num)) {
continue;
}
randomIndexes.push(num);
}
// Select the elements from the given array at each random index
let selection = [];
randomIndexes.forEach((i) => {
selection.push(unusedQuestions[i]);
});
return selection;
}
class Question {
constructor(text) {
this.text = text;
this.used = false;
let listRegex = /\[[A-Z ]*]/;
// this.hasOptions = regex.test(text);
if (listRegex.test(text)) {
this.hasOptions = 'optionList';
}
else if (/\{[A-Z ]*}/.test(text)) {
this.hasOptions = 'freefill';
}
else {
this.hasOptions = 'none';
}
if (this.hasOptions === 'optionList') {
// convert variable in question from form [VARIABLE NAME] to variable-name
let optionFileName = this.text.match(listRegex)[0];
optionFileName = optionFileName.replace(/\[|\]/g, '').replace(/ /, '-').toLowerCase();
// Load the file static/options/variable-name.txt
try {
this.options = loadFile(`options/${optionFileName}.txt`);
}
catch (err) {
console.error(`No options file found for ${optionFileName}. ("${this.text}")`);
}
}
}
use() {
this.used = true;
}
}
class QuestionPooler {
constructor(players = 2) {
this.players = players;
// this.waitingForAnswer = false;
this.pools = [];
for (let i = 0; i < players; i++) {
// Add a new pool
this.pools.push({
current: 0,
questions: getQuestions()
});
}
}
getNewQuestions(playerIndex, questionList, n = 3) {
playerIndex = parseInt(playerIndex);
if (playerIndex >= this.players || playerIndex < 0 || playerIndex === undefined) {
throw `playerIndex ${playerIndex} was out of range. Player count: ${this.players}.`;
}
let currentPool = this.pools[playerIndex];
let questionSelection = undefined;
if (questionList === 'appearance') {
questionSelection = randomSelect(currentPool.questions.appearance, n);
}
else if (questionList === 'interests') {
questionSelection = randomSelect(currentPool.questions.interests, n);
}
if (questionSelection === undefined) {
throw 'Unknown question list';
}
return questionSelection;
}
useQuestion(question, playerIndex) {
if (question === undefined) {
throw 'Question was undefined';
}
let currentPool = this.pools[playerIndex];
for (let q of currentPool.questions.appearance) {
if (q.text === question.text) {
q.use();
return;
}
}
for (let q of currentPool.questions.interests) {
if (q.text === question.text) {
q.use();
return;
}
}
}
getAll(playerIndex) {
if (playerIndex >= this.players || playerIndex < 0 || playerIndex === undefined) {
throw `playerIndex ${playerIndex} was out of range. Player count: ${this.players}.`;
}
return this.pools[playerIndex].questions;
}
}
const NO_QUESTION = new Question("empty");
module.exports.Pooler = QuestionPooler;
module.exports.NO_QUESTION = NO_QUESTION;
module.exports.Question = Question;
////// EXAMPLE CODE: //////
// let qp = new QuestionPooler();
// for (let i = 0; i < 20; i++) {
// let qs = qp.getNewQuestions(0);
// console.log(qs);
// console.log(`${i}: Got ${qs.length} questions back`);
// if (qs.length <= 0) break;
// qs[0].use();
// console.log(`used question "${qs[0].text}"`);
// }
// console.log(qp.getAll(0).appearance[0].options);<file_sep>#include <stdlib.h>
int main() {
system("pip install pyperclip");
system("cls");
system("python src/randomnumbers.py");
}<file_sep>import random, pyperclip
with open("src/A.txt", "r") as file_a:
questions_a = file_a.readlines()
with open("src/B.txt", "r") as file_b:
questions_b = file_b.readlines()
questions_a = [line.strip() for line in questions_a]
questions_b = [line.strip() for line in questions_b]
questions_a_red = questions_a.copy()
questions_b_red = questions_b.copy()
questions_a_blue = questions_a.copy()
questions_b_blue = questions_b.copy()
letters = ['A', 'B', 'C', 'D']
variables = ["[COLOUR]", "[NUMBER]", "[TV SHOW]", "[GENRE]", "[SPORTS]"]
commands = ['EXIT']
commands += letters
command = ""
iteration = random.randint(0, 1)
while command != "EXIT":
player = "red" if iteration % 2 == 0 else "blue"
copy_text = ""
copy_text += f"{player.capitalize()}:\n"
if (player == "red"):
pool_a = random.sample(questions_a_red, 2)
pool_b = random.sample(questions_b_red, 2)
elif (player == "blue"):
pool_a = random.sample(questions_a_blue, 2)
pool_b = random.sample(questions_b_blue, 2)
pool = pool_a + pool_b
for i in range(0, 4):
newline = "\n" if i != 3 else ""
copy_text += f"{letters[i]} - {pool[i]}{newline}"
pyperclip.copy(copy_text)
print(copy_text)
iteration += 1
command = ""
while command not in commands:
command = input("> ")
command = command.strip()
command = command.upper()
if command in letters:
remove = True
question = pool[letters.index(command)]
if any(variable in question for variable in variables):
command2 = ""
while command2.lower() not in ['yes', 'no', 'maybe']:
command2 = input("> ")
command2 = command2.strip()
command2 = command2.upper()
command2 = command2.strip()
if command2.lower() == "no" or command2.lower() == "maybe":
remove = False
if remove:
if player == "red":
if command.upper() in ["A" , "B"]:
questions_a_red.remove(question)
elif command.upper() in ["C" , "D"]:
questions_b_red.remove(question)
elif player == "blue":
if command.upper() in ["A" , "B"]:
questions_a_blue.remove(question)
elif command.upper() in ["C" , "D"]:
questions_b_blue.remove(question)
input("Playtest ended. Press enter to exit...")<file_sep># Installation
cd server
npm install
cd ../whoisit
npm install
# Dev'ing
Server
cd server
npm run serve
!!!! When visiting the server, it server the front-end from the build folder. So only after deploying the front-end, the changes will be visible in files served by the server. For deving, it's easier to use the built-in dev server in the front-end:
Front-End
cd whoisit
npm run serve
# Deploying
Front-End
cd whoisit
npm run build
Server
idk yet | f1f7d00a065cc4b042599e45b3ef12f95637736e | [
"JavaScript",
"C",
"Python",
"Markdown"
] | 4 | JavaScript | Creator13/ConnectForCoffee | 4848ac1fb97f1c4dafac13bc351b042485efe529 | e28eb6274d283e329cbde6d34e09ce66ac272a0d |
refs/heads/master | <repo_name>andrivet/z80-debug<file_sep>/src/tests/callserializer.tests.ts
//import * as assert from 'assert';
import { CallSerializer } from '../callserializer';
suite('CallSerializer', () => {
/*
setup( () => {
return dc.start();
});
teardown( () => dc.disconnect() );
*/
suite('execAll', () => {
test('1 func', (done) => {
CallSerializer.execAll(
cs => {
cs.endExec();
done();
}
);
});
test('2 funcs', (done) => {
CallSerializer.execAll(
cs => {
cs.endExec();
},
cs => {
cs.endExec();
done();
}
);
});
});
});<file_sep>/src/zesaruxemulator.ts
import * as assert from 'assert';
import { zSocket, ZesaruxSocket } from './zesaruxSocket';
import { Z80Registers } from './z80Registers';
import { Utility } from './utility';
import { Labels } from './labels';
import { Settings } from './settings';
import { RefList } from './reflist';
import { Log } from './log';
import { Frame } from './frame';
import { GenericWatchpoint, GenericBreakpoint } from './genericwatchpoint';
import { EmulatorClass, MachineType, EmulatorBreakpoint, EmulatorState, MemoryPage } from './emulator';
import { StateZ80 } from './statez80';
import { CallSerializer } from './callserializer';
import { ZesaruxCpuHistory } from './zesaruxCpuHistory';
//import * as lineRead from 'n-readlines';
/// Minimum required ZEsarUX version.
const MIN_ZESARUX_VERSION = 8.0;
// Some Zesarux constants.
class Zesarux {
static MAX_ZESARUX_BREAKPOINTS = 100; ///< max count of breakpoints.
static MAX_BREAKPOINT_CONDITION_LENGTH = 256; ///< breakpoint condition string length.
static MAX_MESSAGE_CATCH_BREAKPOINT = 4*32-1; ///< breakpoint condition should also be smaller than this.
}
/**
* The representation of the Z80 machine.
* It receives the requests from the EmulDebugAdapter and communicates with
* the EmulConnector.
*/
export class ZesaruxEmulator extends EmulatorClass {
/// Max count of breakpoints. Note: Number 100 is used for stepOut.
static MAX_USED_BREAKPOINTS = Zesarux.MAX_ZESARUX_BREAKPOINTS-1;
/// The breakpoint used for step-out.
static STEP_BREAKPOINT_ID = 100;
// Maximum stack items to handle.
static MAX_STACK_ITEMS = 100;
/// Array that contains free breakpoint IDs.
private freeBreakpointIds = new Array<number>();
/// The read ZEsarUx version number as float, e.g. 7.1. Is read directly after socket connection setup.
public zesaruxVersion = 0.0;
/// Handles the cpu history for reverse debugging
protected cpuHistory: ZesaruxCpuHistory;
/// The virtual stack used during reverse debugging.
protected reverseDbgStack: RefList;
/// We need a serializer for some tasks.
protected serializer = new CallSerializer('ZesaruxEmulator');
/// Set to true after 'terminate()' is called. Errors will not be sent
/// when terminating.
protected terminating = false;
/// Initializes the machine.
public init() {
super.init();
// Reverse debugging / CPU history
this.cpuHistory = new ZesaruxCpuHistory();
// Create the socket for communication (not connected yet)
this.setupSocket();
// Connect zesarux debugger
zSocket.connectDebugger();
}
/**
* Stops a machine/the debugger.
* This will disconnect the socket to zesarux and un-use all data.
* Called e.g. when vscode sends a disconnectRequest
* @param handler is called after the connection is disconnected.
*/
public disconnect(handler: () => void) {
// Terminate the socket
zSocket.quit(handler);
}
/**
* Terminates the machine/the debugger.
* This will disconnect the socket to zesarux and un-use all data.
* Called e.g. when the unit tests want to terminate the emulator.
* This will also send a 'terminated' event. I.e. the vscode debugger
* will also be terminated.
* @param handler is called after the connection is terminated.
*/
public terminate(handler: () => void) {
this.terminating = true;
this.clearInstructionHistory(); // delete all transaction log files
// The socket connection must be closed as well.
zSocket.quit(() => {
// Send terminate event (to Debug Session which will send a TerminateEvent to vscode. That in turn will create a 'disconnect')
this.emit('terminated');
handler();
});
}
/**
* Override removeAllListeners to remove listeners also from socket.
* @param event
*/
public removeAllListeners(event?: string|symbol|undefined): this {
super.removeAllListeners();
// Additionally remove listeners from socket.
zSocket.removeAllListeners();
return this;
}
/**
* Initializes the socket to zesarux but does not connect yet.
* Installs handlers to react on connect and error.
*/
protected setupSocket() {
ZesaruxSocket.Init();
zSocket.on('log', msg => {
// A (breakpoint) log message from Zesarux was received
this.emit('log', msg);
});
zSocket.on('warning', msg => {
if(this.terminating)
return;
// Error message from Zesarux
msg = "ZEsarUX: " + msg;
this.emit('warning', msg);
});
zSocket.on('error', err => {
if(this.terminating)
return;
// and terminate
err.message += " (Error in connection to ZEsarUX!)";
this.emit('error', err);
});
zSocket.on('close', () => {
if(this.terminating)
return;
this.listFrames.length = 0;
this.breakpoints.length = 0;
// and terminate
const err = new Error('ZEsarUX terminated the connection!');
this.emit('error', err);
});
zSocket.on('end', () => {
if(this.terminating)
return;
// and terminate
const err = new Error('ZEsarUX terminated the connection!');
this.emit('error', err);
});
zSocket.on('connected', () => {
if(this.terminating)
return;
let error: Error;
try {
// Initialize
zSocket.send('about');
zSocket.send('get-version', data => {
// e.g. "7.1-SN"
this.zesaruxVersion = parseFloat(data);
// Check version
if(this.zesaruxVersion < MIN_ZESARUX_VERSION) {
zSocket.quit();
const err = new Error('Please update ZEsarUX. Need at least version ' + MIN_ZESARUX_VERSION + '.');
this.emit('error', err);
return;
}
});
zSocket.send('get-current-machine', data => {
const machine = data.toLowerCase();
// Determine which ZX Spectrum it is, e.g. 48K, 128K
if(machine.indexOf('80') >= 0)
this.machineType = MachineType.ZX80;
else if(machine.indexOf('81') >= 0)
this.machineType = MachineType.ZX81;
else if(machine.indexOf('16k') >= 0)
this.machineType = MachineType.SPECTRUM16K;
else if(machine.indexOf('48k') >= 0)
this.machineType = MachineType.SPECTRUM48K;
else if(machine.indexOf('128k') >= 0)
this.machineType = MachineType.SPECTRUM128K;
else if(machine.indexOf('tbblue') >= 0)
this.machineType = MachineType.TBBLUE;
});
// Allow extensions
this.zesaruxConnected();
// Wait for previous command to finish
zSocket.executeWhenQueueIsEmpty(() => {
var debug_settings = (Settings.launch.skipInterrupt) ? 32 : 0;
zSocket.send('set-debug-settings ' + debug_settings);
// Reset the cpu before loading.
if(Settings.launch.resetOnLaunch)
zSocket.send('hard-reset-cpu');
/*
logfile name: File to store the log
enabled yes|no: Enable or disable the cpu transaction log. Requires logfile to enable it
autorotate yes|no: Enables automatic rotation of the log file
rotatefiles number: Number of files to keep in rotation (1-999)
rotatesize number: Size in MB to rotate log file (1-9999)
truncate yes|no: Truncate the log file. Requires value set to yes
datetime yes|no: Enable datetime logging
tstates yes|no: Enable tstates logging
address yes|no: Enable address logging. Enabled by default
opcode yes|no: Enable opcode logging. Enabled by default
registers yes|no: Enable registers logging
*/
// Enter step-mode (stop)
zSocket.send('enter-cpu-step');
// Load sna or tap file
const loadPath = Settings.launch.load;
if(loadPath)
zSocket.send('smartload ' + Settings.launch.load);
// Load obj file(s) unit
for(let loadObj of Settings.launch.loadObjs) {
if(loadObj.path) {
// Convert start address
const start = Labels.getNumberFromString(loadObj.start);
if(isNaN(start))
throw Error("Cannot evaluate 'loadObjs[].start' (" + loadObj.start + ").");
zSocket.send('load-binary ' + loadObj.path + ' ' + start + ' 0'); // 0 = load entire file
}
}
// Set Program Counter to execAddress
if(Settings.launch.execAddress) {
const execAddress = Labels.getNumberFromString(Settings.launch.execAddress);
if(isNaN(execAddress)) {
error = new Error("Cannot evaluate 'execAddress' (" + Settings.launch.execAddress + ").");
return;
}
// Set PC
this.setProgramCounter(execAddress);
}
// Initialize breakpoints
this.initBreakpoints();
// Code coverage
if(Settings.codeCoverageEnabled()) {
zSocket.send('cpu-code-coverage enabled yes');
zSocket.send('cpu-code-coverage clear');
}
else
zSocket.send('cpu-code-coverage enabled no');
// Reverse debugging.
this.cpuHistory.init(Settings.launch.history.reverseDebugInstructionCount);
// Enable extended stack
zSocket.send('extended-stack enabled no'); // bug in ZEsarUX
zSocket.send('extended-stack enabled yes');
// TODO: Ignore repetition of 'HALT'
});
zSocket.executeWhenQueueIsEmpty(() => {
// Check for console.error
if(error) {
this.emit('error', error);
}
else {
// Send 'initialize' to Machine.
this.state = EmulatorState.IDLE;
this.emit('initialized');
}
});
}
catch(e) {
// Some error occurred
this.emit('error', e);
}
});
}
/**
* Is called right after Zesarux has been connected and the version info was read.
* Can be overridden to check for extensions.
*/
protected zesaruxConnected() {
// For standard Zesarux do nothing special
}
/**
* Initializes the zesarux breakpoints.
* Override this if fast-breakpoints should be used.
*/
protected initBreakpoints() {
// Clear memory breakpoints (watchpoints)
zSocket.send('clear-membreakpoints');
// Clear all breakpoints
zSocket.send('enable-breakpoints');
this.clearAllZesaruxBreakpoints();
// Init breakpoint array
this.freeBreakpointIds.length = 0;
for(var i=1; i<=ZesaruxEmulator.MAX_USED_BREAKPOINTS; i++)
this.freeBreakpointIds.push(i);
}
/**
* Retrieve the registers from zesarux directly.
* From outside better use 'getRegisters' (the cached version).
* @param handler(registersString) Passes 'registersString' to the handler.
*/
public async getRegistersFromEmulator(handler: (registersString: string) => void) {
// Check if in reverse debugging mode
// In this mode registersCache should be set and thus this function is never called.
assert(this.cpuHistory);
assert(!this.cpuHistory.isInStepBackMode());
/*
if(this.cpuHistory.isInStepBackMode()) {
// Read registers from file
let line = await this.cpuHistory.getLine() as string;
assert(line);
let data = this.cpuHistory.getRegisters(line);
handler(data);
return;
}
*/
// Get new (real emulator) data
zSocket.send('get-registers', data => {
// convert received data to right format ...
// data is e.g: "PC=8193 SP=ff2d BC=8000 AF=0054 HL=2d2b DE=5cdc IX=ff3c IY=5c3a AF'=0044 BC'=0000 HL'=2758 DE'=369b I=3f R=00 F=-Z-H-P-- F'=-Z---P-- MEMPTR=0000 IM1 IFF-- VPS: 0 """
handler(data);
});
}
/**
* Sets the value for a specific register.
* @param name The register to set, e.g. "BC" or "A'". Note: the register name has to exist. I.e. it should be tested before.
* @param value The new register value.
* @param handler The handler that is called when command has finished.
*/
public setRegisterValue(name: string, value: number, handler?: (resp) => void) {
// set value
zSocket.send('set-register ' + name + '=' + value, data => {
// Get real value (should be the same as the set value)
if(handler)
Z80Registers.getVarFormattedReg(name, data, formatted => {
handler(formatted);
});
});
}
/**
* This is a very specialized function to find a CALL, CALL cc or RST opcode
* at the 3 bytes before the given address.
* Idea is that the 'addr' is a return address from the stack and we want to find
* the caller.
* @param addr The address.
* @param handler(k,caddr) The handler is called at the end of the function.
* k=3, addr: If a CALL was found, caddr contains the call address.
* k=2/1, addr: If a RST was found, caddr contains the RST address (p). k is the position,
* i.e. if RST was found at addr-k. Used to work also with esxdos RST.
* k=0, addr=0: Neither CALL nor RST found.
*/
/*
protected findCallOrRst(addr: number, handler:(k: number, addr: number)=>void) {
// Get the 3 bytes before address.
zSocket.send( 'read-memory ' + (addr-3) + ' ' + 3, data => { // subtract opcode + address (last 3 bytes)
// Check for Call
const opc3 = parseInt(data.substr(0,2),16); // get first of the 3 bytes
if(opc3 == 0xCD // CALL nn
|| (opc3 & 0b11000111) == 0b11000100) // CALL cc,nn
{
// It was a CALL, get address.
let callAddr = parseInt(data.substr(2,4),16)
callAddr = (callAddr>>8) + ((callAddr & 0xFF)<<8); // Exchange high and low byte
handler(3, callAddr);
return;
}
// Check if one of the 2 last bytes was a RST.
// Note: Not only the last byte is checkd bt also the byte before. This is
// a small "hack" to allow correct return addresses even for esxdos.
let opc12 = parseInt(data.substr(2,4),16); // convert both opcodes at once
let k = 1;
while(opc12 != 0) {
if((opc12 & 0b11000111) == 0b11000111)
break;
// Next
opc12 >>= 8;
k++;
}
if(opc12 != 0) {
// It was a RST, get p
const p = opc12 & 0b00111000;
handler(k, p);
return;
}
// Nothing found = -1
handler(0, 0);
});
}
*/
/**
* Returns the contents of (addr+1).
* It assumes that at addr there is a "CALL calladdr" instruction and it returns the
* callAddr.
* It retrieves the memory contents at addr+1 and calls 'handler' with the result.
* @param addr The address.
* @param handler(callAddr) The handler is called at the end of the function with the called address.
*/
protected getCallAddress(addr: number, handler:(callAddr: number)=>void) {
// Get the 3 bytes before address.
zSocket.send( 'read-memory ' + (addr+1) + ' 2', data => { // retrieve calladdr
// Get low byte
const lowByte = parseInt(data.substr(0,2),16);
// Get high byte
const highByte = parseInt(data.substr(2,2),16);
// Calculate address
const callAddr = (highByte<<8) + lowByte;
// Call handler
handler(callAddr);
});
}
/**
* Returns the address of (addr).
* It assumes that at addr there is a "RST p" instruction and it returns the
* callAddr, i.e. p.
* It retrieves the memory contents at addr, extract p and calls 'handler' with the result.
* @param addr The address.
* @param handler(callAddr) The handler is called at the end of the function with the called address.
*/
protected getRstAddress(addr: number, handler:(callAddr: number)=>void) {
// Get the 3 bytes before address.
zSocket.send( 'read-memory ' + (addr+1) + ' 1', data => { // retrieve p
// Get low byte
const p = parseInt(data.substr(0,2),16) & 0b00111000;
// Call handler
handler(p);
});
}
/**
* Helper function to prepare the callstack for vscode.
* Check if the
* The function calls itself recursively.
* Uses the zesarux 'extended-stack' feature. I.e. each data on the stack
* also has a type, e.g. push, call, rst, interrupt. So it is easy to tell which
* are the call addresses and even when an interrupt starts.
* Interrupts will be shown in a different 'thread'.
* An 'extended-stack' response from ZEsarUx looks like:
* 15F7H maskable_interrupt
* FFFFH push
* 15E1H call
* 0000H default
* @param frames The array that is sent at the end which is increased every call.
* @param zStack The original zesarux stack frame. Each line in zStack looks like "FFFFH push" or "15E1H call"
* @param address The address of the instruction, for the first call this is the PC.
* For the other calls this is retAddr-3 or similar.
* @param index The index in zStack. Is increased with every call.
* @param zStackAddress The stack start address (the SP).
* @param handler The handler to call when ready.
*/
private setupCallStackFrameArray(frames: RefList, zStack: Array<string>, address: number, index: number, zStackAddress: number, handler:(frames: Array<Frame>)=>void) {
// Check for last frame
if(index >= zStack.length) {
// Top frame
frames.addObject(new Frame(address, zStackAddress+2*index, '__MAIN__'));
// Use new frames
this.listFrames = frames;
// call handler
handler(frames);
return;
}
// Split address and type
const addrTypeString = zStack[index];
const retAddr = parseInt(addrTypeString,16);
const type = addrTypeString.substr(6);
// Check for CALL or RST
let k = 0;
let func;
if(type == "call") {
k = 3; // Opcode length for CALL
func = this.getCallAddress;
}
else if(type == "rst") {
k = 1; // Opcode length range for RST
func = this.getRstAddress;
}
else if(type.includes("interrupt")) {
// Find pushed values
const stack = new Array<number>();
for(let l=index-1; l>=0; l--) {
const addrTypeString = zStack[l];
if(!addrTypeString.includes('push'))
break; // Until something else than PUSH is found
const pushedValue = parseInt(addrTypeString,16);
stack.push(pushedValue);
}
// Save
const frame = new Frame(address, zStackAddress+2*(index-1), "__INTERRUPT__");
frame.stack = stack;
frames.addObject(frame);
// Call recursively
this.setupCallStackFrameArray(frames, zStack, retAddr, index+1, zStackAddress, handler);
return;
}
// Check if we need to add something to the callstack
if(func) {
const callerAddr = retAddr-k;
func(callerAddr, callAddr => {
// Now find label for this address
const labelCallAddrArr = Labels.getLabelsForNumber(callAddr);
const labelCallAddr = (labelCallAddrArr.length > 0) ? labelCallAddrArr[0] : Utility.getHexString(callAddr,4)+'h';
// Find pushed values
const stack = new Array<number>();
for(let l=index-1; l>=0; l--) {
const addrTypeString = zStack[l];
if(!addrTypeString.includes('push'))
break; // Until something else than PUSH is found
const pushedValue = parseInt(addrTypeString,16);
stack.push(pushedValue);
}
// Save
const frame = new Frame(address, zStackAddress+2*(index-1), labelCallAddr)
frame.stack = stack;
frames.addObject(frame);
// Call recursively
this.setupCallStackFrameArray(frames, zStack, callerAddr, index+1, zStackAddress, handler);
});
}
else {
// Neither CALL nor RST.
// Call recursively
this.setupCallStackFrameArray(frames, zStack, address, index+1, zStackAddress, handler);
}
}
/**
* Returns the stack frames.
* Either the "real" ones from ZEsarUX or the virtual ones during reverse debugging.
* @param handler The handler to call when ready.
*/
public stackTraceRequest(handler:(frames: RefList)=>void): void {
// Check for reverse debugging.
if(this.cpuHistory.isInStepBackMode()) {
// Return virtual stack
assert(this.reverseDbgStack);
handler(this.reverseDbgStack);
}
else {
// "real" stack trace
this.realStackTraceRequest(handler);
}
}
/**
* Returns the "real" stack frames from ZEsarUX.
* (Opposed to the virtual one during reverse debug mode.)
* Uses the zesarux 'extended-stack' feature. I.e. each data on the stack
* also has a type, e.g. push, call, rst, interrupt. So it is easy to tell which
* are the call addresses and even when an interrupt starts.
* Interrupts will be shown in a different 'thread'.
* An 'extended-stack' response from ZEsarUx looks like:
* 15F7H maskable_interrupt
* FFFFH push
* 15E1H call
* 0000H default
* @param handler The handler to call when ready.
*/
public realStackTraceRequest(handler:(frames: RefList)=>void): void {
// Create a call stack / frame array
const frames = new RefList();
// Get current pc
this.getRegisters(data => {
// Parse the PC value
const pc = Z80Registers.parsePC(data);
const sp = Z80Registers.parseSP(data);
// calculate the depth of the call stack
const tos = this.topOfStack
var depth = (tos - sp)/2; // 2 bytes per word
if(depth>ZesaruxEmulator.MAX_STACK_ITEMS)
depth = ZesaruxEmulator.MAX_STACK_ITEMS;
// Get 'extended-stack' from zesarux
zSocket.send('extended-stack get '+depth, data => {
Log.log('Call stack: ' + data);
data = data.replace(/\r/gm, "");
const zStack = data.split('\n');
zStack.splice(zStack.length-1); // ignore last (is empty)
// rest of callstack
this.setupCallStackFrameArray(frames, zStack, pc, 0, sp, handler);
});
});
}
/**
* 'continue' debugger program execution.
* @param contStoppedHandler The handler that is called when it's stopped e.g. when a breakpoint is hit.
* reason contains the stop reason as string.
* tStates contains the number of tStates executed and time is the time it took for execution,
* i.e. tStates multiplied with current CPU frequency.
*/
public async continue(contStoppedHandler: (reason: string, tStates?: number, time?: number)=>void) {
// Check for reverse debugging.
if(this.cpuHistory.isInStepBackMode()) {
// continue in reverse debugging will run until the start of the transaction log
// or until a breakpoint condition is true.
let reason = 'Break: Reached start of instruction history.';
try {
//this.state = EmulatorState.RUNNING;
//this.state = EmulatorState.IDLE;
// Get current line
let currentLine: string = this.RegisterCache as string;
assert(currentLine);
// Loop over all lines, reverse
while(true) {
// Handle stack
const nextLine = this.revDbgNext();
this.handleReverseDebugStackFwrd(currentLine, nextLine);
if(!nextLine)
break;
// Check for breakpoint
// TODO: ...
// Next
currentLine = nextLine;
}
}
catch(e) {
reason = 'Break: Error occurred: ' + e;
}
// Decoration
this.emitRevDbgHistory();
// Call handler
contStoppedHandler(reason, undefined, undefined);
return;
}
// Make sure that reverse debug stack is cleared
this.clearReverseDbgStack();
// Change state
this.state = EmulatorState.RUNNING;
// Handle code coverage
this.enableCpuTransactionLog(() => {
// Reset T-state counter.
zSocket.send('reset-tstates-partial', () => {
// Run
zSocket.sendInterruptableRunCmd(text => {
// (could take some time, e.g. until a breakpoint is hit)
// get T-State counter
zSocket.send('get-tstates-partial', data => {
const tStates = parseInt(data);
// get clock frequency
zSocket.send('get-cpu-frequency', data => {
const cpuFreq = parseInt(data);
this.state = EmulatorState.IDLE;
// Clear register cache
this.RegisterCache = undefined;
// Handle code coverage
this.handleCodeCoverage();
// The reason is the 2nd line
const reason = text.split('\n')[1];
assert(reason);
// Call handler
contStoppedHandler(reason, tStates, cpuFreq);
});
});
});
});
});
}
/**
* 'pause' the debugger.
*/
public pause(): void {
// Send anything through the socket
zSocket.sendBlank();
}
/**
* Clears the stack used for reverse debugging.
* Called when leaving the reverse debug mode.
*/
protected clearReverseDbgStack() {
this.reverseDbgStack = undefined as any;
}
/**
* Returns the pointer to the virtual reverse debug stack.
* If it does not exist yet it will be created and prefilled with the current
* (memory) stack values.
*/
protected prepareReverseDbgStack(handler:() => void) {
if(this.cpuHistory.isInStepBackMode()) {
// Call immediately
handler();
}
else {
// Prefill array with current stack
this.realStackTraceRequest(frames => {
this.reverseDbgStack = frames;
handler();
});
}
}
/**
* Handles the current instruction and the previous one and distinguishes what to
* do on the virtual reverse debug stack.
* Example: Normally only the top frame on the stack is changed for the new PC value.
* But if a "RET" instruction is found also the 'next' PC value is pushed
* to the stack.
* Note: We are not able to detect interrupts reliable. Therefore interrupts will not be put on
* the stack and RETI/RETN will not pop from the stack.
*
* @param currentLine The current line of the transaction log.
* @param prevLine The previous line of the transaction log. (The one that
* comes before currentLine). This can also be the cached register values for
* the first line.
*/
protected async handleReverseDebugStackBack(currentLine: string, prevLine: string) {
assert(this.reverseDbgStack.length > 0);
// Remove current frame
this.reverseDbgStack.shift();
// Sets the expected SP value.
//const currentSP = Z80Registers.parseSP(currentLine);
// Check for RET (RET cc and RETI/N)
if(this.cpuHistory.isRetAndExecuted(currentLine)) {
// Create new frame with better name on stack
const pc = Z80Registers.parsePC(currentLine);
const sp = Z80Registers.parseSP(currentLine);
// Add new frame to stack
const name = 'FRAME: RET @' + Utility.getHexString(pc,4);
const frame = new Frame(pc, sp, name);
this.reverseDbgStack.unshift(frame);
}
else if(this.cpuHistory.isCallAndExecuted(currentLine)) {
// Pop from call stack
assert(this.reverseDbgStack.length > 0);
this.reverseDbgStack.shift();
}
else if(this.cpuHistory.isRst(currentLine)) {
// Pop from call stack
assert(this.reverseDbgStack.length > 0);
this.reverseDbgStack.shift();
}
// Add current PC
const pc = Z80Registers.parsePC(currentLine);
const sp = Z80Registers.parseSP(currentLine);
const topFrame = new Frame(pc, sp, 'PC');
this.reverseDbgStack.unshift(topFrame);
}
/**
* Handles the current instruction and the next one and distinguishes what to
* do on the virtual reverse debug stack.
* Normally only the top frame on the stack is changed for the new PC value.
* But if e.g. a "CALL" or "RET" instruction is found the stack needs to be changed.
* Note: We are not able to detect interrupts reliable. Therefore interrupts will not be put on
* the stack and RETI/RETN will not pop from the stack.
*
* CALL, RST and RETx are the only instructions that should manipulate the call stack
* except for interrupts.
* Interrupt recognition is harder than it seems. Here it is done in the following way:
* If a CALL/RST/RETx is found the next expected SP (expSP) and the next expected PC (expPC)
* is calculated.
* There are 4 group of commands (branching means that a non-normal execution flow is chosen):
* - A = CALL/RST/RETx: Changing SP if executed. Potentially branching.
* - B = PUSH/POP, ADD SP...: Change SP, but not branching.
* - C = JP/JR: Not changing SP, but potentially branching.
* - D = Rest: Not changing SP, not branching.
*
* If an interrupt occurs it: changes SP and changes PC. I.e. this is like group A changing
* both: SP and branching.
*
* Now there are special cases:
* Interrupt happens just right after CALL/RST/RETx.
* In this case we need to distinguish:
* - CALL/RST: Next line: SP is decremented by 4 (expSP != SP). PC != expPC.
* - RETx: Next line: SP stays (incremented by 2+decremented by 2) (ExpSP != SP). PC != expPC.
*
* So the algorithm is:
* IF CALL/RST/RETx
* IF (expSP != SP) && (PC != expPC)
* // Interrupt occurred
* ENDIF
* ELSE
* IF SP changed
* IF PC != prevPC+instruction_size
* // Interrupt occurred
* ENDIF
* ENDIF
* ENDIF
*
* @param currentLine The current line of the transaction log.
* @param nextLine The next line of the transaction log. (The one that
* comes after currentLine.) If that is empty the start of the log has been reached.
* In that case the reverseDbgStack is cleared because the real stack can be used.
*/
protected handleReverseDebugStackFwrd(currentLine: string, nextLine: string|undefined) {
assert(currentLine);
// Check for end
if(!nextLine) {
this.reverseDbgStack = undefined as any;
return;
}
// Remove current frame
assert(this.reverseDbgStack.length > 0);
this.reverseDbgStack.shift();
// Sets the expected SP value.
//const currentSP = Z80Registers.parseSP(currentLine);
//let expectedSP = currentSP;
//const nextSP = Z80Registers.parseSP(nextLine);
// Check for RET (RET cc and RETI/N)
if(this.cpuHistory.isRetAndExecuted(currentLine)) {
//expectedSP += 2; // RET pops from the stack
// Pop from call stack
assert(this.reverseDbgStack.length > 0);
this.reverseDbgStack.shift();
}
else if(this.cpuHistory.isCallAndExecuted(currentLine)) {
//expectedSP -= 2; // CALL pushes to the stack
// Push to call stack
const pc = Z80Registers.parsePC(currentLine);
const currentSP = Z80Registers.parseSP(currentLine);
// Now find label for this address
const callAddr = Z80Registers.parsePC(nextLine);
const labelCallAddrArr = Labels.getLabelsForNumber(callAddr);
const labelCallAddr = (labelCallAddrArr.length > 0) ? labelCallAddrArr[0] : Utility.getHexString(callAddr,4)+'h';
const name = "CALL " + labelCallAddr;
const frame = new Frame(pc, currentSP, name);
this.reverseDbgStack.unshift(frame);
}
else if(this.cpuHistory.isRst(currentLine)) {
//expectedSP -= 2; // RST pushes to the stack
// Push to call stack
const pc = Z80Registers.parsePC(currentLine);
const currentSP = Z80Registers.parseSP(currentLine);
// Now find label for this address
const callAddr = Z80Registers.parsePC(nextLine);
const labelCallAddrArr = Labels.getLabelsForNumber(callAddr);
const labelCallAddr = (labelCallAddrArr.length > 0) ? labelCallAddrArr[0] : Utility.getHexString(callAddr,4)+'h';
const name = "RST " + labelCallAddr;
const frame = new Frame(pc, currentSP, name);
this.reverseDbgStack.unshift(frame);
}
// Check for interrupt
/*
if(expectedSP != nextSP) {
// Interrupt occurred. Push current PC to call stack.
const pc = Z80Registers.parsePC(currentLine);
// Now find label for this address
const intrptAddr = Z80Registers.parsePC(nextLine);
const labelCallAddrArr = Labels.getLabelsForNumber(intrptAddr);
const labelCallAddr = (labelCallAddrArr.length > 0) ? labelCallAddrArr[0] : Utility.getHexString(intrptAddr,4)+'h';
const name = "Interrupt " + labelCallAddr;
const frame = new Frame(pc, currentSP, name);
this.reverseDbgStack.unshift(frame);
}
*/
// Add current PC
const regs = nextLine;
const pc = Z80Registers.parsePC(regs);
const sp = Z80Registers.parseSP(regs);
const topFrame = new Frame(pc, sp, 'PC');
this.reverseDbgStack.unshift(topFrame);
}
/**
* 'reverse continue' debugger program execution.
* @param handler The handler that is called when it's stopped e.g. when a breakpoint is hit.
*/
public reverseContinue(handler:(reason: string)=>void) {
// Make sure the call stack exists
this.prepareReverseDbgStack(async () => {
let errorText: string|undefined;
let reason;
try {
// Loop over all lines, reverse
reason = 'Break: Reached end of instruction history.';
let prevLine = this.RegisterCache as string;
assert(prevLine);
while(true) {
// Get line
const currentLine = await this.revDbgPrev();
if(!currentLine)
break;
// Stack handling:
this.handleReverseDebugStackBack(currentLine, prevLine);
// Breakpoint handling:
// Check for breakpoint
// TODO: ...
// Next
prevLine = currentLine;
}
}
catch(e) {
errorText = e;
reason = 'Break: Error occurred: ' + errorText;
}
// Decoration
this.emitRevDbgHistory();
// Call handler
handler(reason);
});
}
/**
* 'step over' an instruction in the debugger.
* @param handler(disasm, tStates, cpuFreq) The handler that is called after the step is performed.
* 'disasm' is the disassembly of the current line.
* tStates contains the number of tStates executed.
* cpuFreq contains the CPU frequency at the end.
*/
public async stepOver(handler:(disasm: string, tStates?: number, cpuFreq?: number, error?: string)=>void) {
// Check for reverse debugging.
if(this.cpuHistory.isInStepBackMode()) {
// TODO: check for step over
/*
// Step over should skip all CALLs and RST.
// This is more difficult as it seems. It could also happen that an
// interrupt kicks in.
// The algorithm does work by checking the SP:
// 1. SP is read
// 2. switch to next line
// 3. SP is read
// 4. If SP has not changed stop
// 5. Otherwise switch to next line until SP is reached.
// Note: does not work for PUSH/POP or "LD SP". Therefore these are
// handled in a special way. However, if an interrupt would kick in when
// e.g. a "LD SP,(nnnn)" is done, then the "stepOver" would incorrectly
// work just like a "stepInto". However this should happen very seldomly.
// Get current instruction
let currentLine: string = await this.cpuHistory.getLineXXX() as string;
assert(currentLine);
let instruction = this.cpuHistory.getInstruction(currentLine);
// Read SP
const regs = this.cpuHistory.getRegisters(currentLine);
let expectedSP = Z80Registers.parseSP(regs);
let dontCheckSP = false;
// Check for changing SP
if(instruction.startsWith('PUSH'))
expectedSP -= 2;
else if(instruction.startsWith('POP'))
expectedSP += 2;
else if(instruction.startsWith('DEC SP'))
expectedSP --;
else if(instruction.startsWith('INC SP'))
expectedSP ++;
else if(instruction.startsWith('LD SP,')) {
const src = instruction.substr(6);
if(src.startsWith('HL'))
expectedSP = Z80Registers.parseHL(regs); // LD SP,HL
else if(src.startsWith('IX'))
expectedSP = Z80Registers.parseIX(regs); // LD SP,IX
else if(src.startsWith('IY'))
expectedSP = Z80Registers.parseIY(regs); // LD SP,IY
else if(src.startsWith('('))
dontCheckSP = true; // LD SP,(nnnn) -> no way to determine memory contents
else
expectedSP = parseInt(src, 16); // LD SP,nnnn
}
// Check for RET. There are 2 possibilities if RET was conditional.
let expectedSP2 = expectedSP;
if(instruction.startsWith('RET'))
expectedSP2 += 2;
*/
// Get current line
let currentLine: string = this.RegisterCache as string;
assert(currentLine);
let errorText;
try {
// Find next line with same SP
while(currentLine) {
// Handle stack
const nextLine = this.revDbgNext();
this.handleReverseDebugStackFwrd(currentLine, nextLine);
if(!nextLine)
break;
break; // for now
/*
if(dontCheckSP) {
// Break after first line
break;
}
*/
// TODO: need to check for breakpoint
// Read SP
/*
const regs = this.cpuHistory.getRegisters(currentLine);
const sp = Z80Registers.parseSP(regs);
// Check expected SPs
if(expectedSP == sp)
break;
if(expectedSP2 == sp)
break;
*/
// Next
currentLine = nextLine as string;
}
}
catch(e) {
errorText = e;
}
// Decoration
this.emitRevDbgHistory();
// Call handler
let instruction = '';
if(currentLine) {
const pc = Z80Registers.parsePC(currentLine);
instruction = ' ' + Utility.getHexString(pc, 4) + ' ' + this.cpuHistory.getInstruction(currentLine);
}
handler(instruction, undefined, undefined, errorText);
return;
}
// Make sure that reverse debug stack is cleared
this.clearReverseDbgStack();
// Zesarux is very special in the 'step-over' behavior.
// In case of e.g a 'jp cc, addr' it will never return
// if the condition is met because
// it simply seems to wait until the PC reaches the next
// instruction what, for a jp-instruction, obviously never happens.
// Therefore a 'step-into' is executed instead. The only problem is that a
// 'step-into' is not the desired behavior for a CALL.
// So we first check if the instruction is a CALL and
// then either execute a 'step-over' or a step-into'.
this.getRegisters(data => {
const pc = Z80Registers.parsePC(data);
zSocket.send('disassemble ' + pc, disasm => {
// Clear register cache
this.RegisterCache = undefined;
// Check if this was a "CALL something" or "CALL n/z,something"
const opcode = disasm.substr(7,4);
if(opcode == "RST ") {
// Use a special handling for RST required for esxdos.
// Zesarux internally just sets a breakpoint after the current opcode. In esxdos this
// address is used as parameter. I.e. the return address is tweaked after that address.
// Therefore we set an additional breakpoint 1 after the current address.
// Set action first (no action).
const bpId = ZesaruxEmulator.STEP_BREAKPOINT_ID;
zSocket.send('set-breakpointaction ' + bpId + ' prints step-over', () => {
// set the breakpoint (conditions are evaluated by order. 'and' does not take precedence before 'or').
const condition = 'PC=' + (pc+2); // PC+1 would be the normal return address.
zSocket.send('set-breakpoint ' + bpId + ' ' + condition, () => {
// enable breakpoint
zSocket.send('enable-breakpoint ' + bpId, () => {
// Run
this.state = EmulatorState.RUNNING;
this.cpuStepGetTime('cpu-step-over', (tStates, cpuFreq) => {
// takes a little while, then step-over RET
// Disable breakpoint
zSocket.send('disable-breakpoint ' + bpId, () => {
this.state = EmulatorState.IDLE;
handler(disasm, tStates, cpuFreq);
});
});
});
});
});
}
else {
// No special handling for the other opcodes.
const cmd = (opcode=="CALL" || opcode=="LDIR" || opcode=="LDDR") ? 'cpu-step-over' : 'cpu-step';
// Step
this.cpuStepGetTime(cmd, (tStates, cpuFreq) => {
// Call handler
handler(disasm, tStates, cpuFreq);
});
}
});
});
}
/**
* 'step into' an instruction in the debugger.
* @param handler(tStates, cpuFreq) The handler that is called after the step is performed.
* 'disasm' is the disassembly of the current line.
* tStates contains the number of tStates executed.
* cpuFreq contains the CPU frequency at the end.
*/
public async stepInto(handler:(disasm: string, tStates?: number, time?: number, error?: string)=>void) {
// Check for reverse debugging.
if(this.cpuHistory.isInStepBackMode()) {
let errorText;
let instr = '';
// Get current line
let currentLine: string = this.RegisterCache as string;
assert(currentLine);
try {
// Handle stack
const nextLine = this.revDbgNext();
this.handleReverseDebugStackFwrd(currentLine, nextLine);
}
catch(e) {
errorText = e;
}
// Decoration
this.emitRevDbgHistory();
// Call handler
handler(instr, undefined, undefined, errorText);
return;
}
// Make sure that reverse debug stack is cleared
this.clearReverseDbgStack();
// Normal step into.
this.getRegisters(data => {
const pc = Z80Registers.parsePC(data);
zSocket.send('disassemble ' + pc, disasm => {
// Clear register cache
this.RegisterCache = undefined;
this.cpuStepGetTime('cpu-step', (tStates, cpuFreq) => {
handler(disasm, tStates, cpuFreq);
});
});
});
}
/**
* Executes a step and also returns the T-states and time needed.
* @param cmd Either 'cpu-step' or 'cpu-step-over'.
* @param handler(tStates, cpuFreq) The handler that is called after the step is performed.
* tStates contains the number of tStates executed.
* cpuFreq contains the CPU frequency at the end.
*/
protected cpuStepGetTime(cmd: string, handler:(tStates: number, cpuFreq: number, error?: string)=>void): void {
// Handle code coverage
this.enableCpuTransactionLog(() => {
// Reset T-state counter etc.
zSocket.send('reset-tstates-partial', data => {
// Step into
zSocket.send(cmd, data => {
// get T-State counter
zSocket.send('get-tstates-partial', data => {
const tStates = parseInt(data);
// get clock frequency
zSocket.send('get-cpu-frequency', data => {
const cpuFreq = parseInt(data);
// Call handler
handler(tStates, cpuFreq);
// Handle code coverage
this.handleCodeCoverage();
});
});
});
});
});
}
/**
* If code coverage or reverse debugging enabled is enabled the ZEsarUX cpu-transaction-log is enabled
* before the 'handler' is called.
* If code coverage or reverse debugging is not enabled 'handler' is called immediately.
* @param handler Is called after the coverage commands have been sent.
*/
protected enableCpuTransactionLog(handler:()=>void): void {
// TODO: similar for reverse debug
/*
// Code coverage or reverse debugging enabled
if(Settings.codeCoverageEnabled()) {
// Enable logging
zSocket.send('cpu-code-coverage get', data => {
// Call handler
handler();
});
}
else
*/
{
// Call handler (without coverage)
handler();
}
}
/**
* Reads the coverage addresses and clears them in ZEsarUX.
*/
protected handleCodeCoverage() {
// Check if code coverage is enabled
if(!Settings.codeCoverageEnabled())
return;
// Get coverage
zSocket.send('cpu-code-coverage get', data => {
// Check for error
if(data.startsWith('Error'))
return;
// Parse data and collect addresses
const addresses = new Set<number>();
const length = data.length;
for(let k=0; k<length; k+=5) {
const addressString = data.substr(k,4);
const address = parseInt(addressString, 16);
addresses.add(address);
}
// Clear coverage in ZEsarUX
zSocket.send('cpu-code-coverage clear');
// Emit code coverage event
this.emit('coverage', addresses);
});
}
/**
* 'step out' of current call.
* @param handler(tStates, cpuFreq) The handler that is called after the step is performed.
* tStates contains the number of tStates executed.
* cpuFreq contains the CPU frequency at the end.
*/
public async stepOut(handler:(tStates?: number, cpuFreq?: number, error?: string)=>void) {
// Check for reverse debugging.
if(this.cpuHistory.isInStepBackMode()) {
// Step out will run until the start of the transaction log
// or until a "RETx" is found (one behind).
// To make it more complicated: this would falsely find a RETI event
// if stepout was not started form the ISR.
// To overcome this also the SP is observed. And we break only if
// also the SP is lower/equal to when we started.
// Get current line
let currentLine = await this.cpuHistory.getLineXXX() as string;
assert(currentLine);;
// Read SP
let regs = currentLine;
const startSP = Z80Registers.parseSP(regs);
// Do as long as necessary
let errorText;
try {
while(currentLine) {
// Handle stack
const nextLine = this.revDbgNext();
this.handleReverseDebugStackFwrd(currentLine, nextLine);
// Get current instruction
const instruction = this.cpuHistory.getInstructionOld(currentLine);
// Check for RET
if(instruction.startsWith('RET')) {
// Read SP
const regs = currentLine;
const sp = Z80Registers.parseSP(regs);
// Check SP
if(sp >= startSP) {
break;
}
}
// Next
currentLine = nextLine as string;
}
}
catch(e) {
errorText = e;
}
// Decoration
this.emitRevDbgHistory();
// Clear register cache
this.RegisterCache = undefined;
// Call handler
handler(undefined, undefined, errorText);
return;
}
// Zesarux does not implement a step-out. Therefore we analyze the call stack to
// find the first return address.
// Then a breakpoint is created that triggers when an executed RET is found the SP changes to that address.
// I.e. when the RET (or (RET cc) gets executed.
// Make sure that reverse debug stack is cleared
this.clearReverseDbgStack();
// Get current stackpointer
this.getRegisters( data => {
// Get SP
const sp = Z80Registers.parseSP(data);
// calculate the depth of the call stack
var depth = this.topOfStack - sp;
if(depth>ZesaruxEmulator.MAX_STACK_ITEMS) depth = ZesaruxEmulator.MAX_STACK_ITEMS;
if(depth == 0) {
// no call stack, nothing to step out, i.e. immediately return
handler();
return;
}
// get stack from zesarux
zSocket.send('extended-stack get '+depth, data => {
data = data.replace(/\r/gm, "");
const zStack = data.split('\n');
zStack.splice(zStack.length-1); // ignore last (is empty)
// Loop through stack:
let bpSp = sp;
for(const addrTypeString of zStack) {
// Increase breakpoint address
bpSp += 2;
// Split address and type
const type = addrTypeString.substr(6);
if(type == "call" || type == "rst" || type.includes("interrupt")) {
//const addr = parseInt(addrTypeString,16);
// Caller found, set breakpoint: when SP gets 2 bigger than the current value.
// Set action first (no action).
const bpId = ZesaruxEmulator.STEP_BREAKPOINT_ID;
zSocket.send('set-breakpointaction ' + bpId + ' prints step-out', () => {
// Set the breakpoint (conditions are evaluated by order. 'and' does not take precedence before 'or').
// Note: PC=PEEKW(SP-2) finds an executed RET.
const condition = 'PC=PEEKW(SP-2) AND SP>=' + bpSp;
zSocket.send('set-breakpoint ' + bpId + ' ' + condition, () => {
// Enable breakpoint
zSocket.send('enable-breakpoint ' + bpId, () => {
// Clear register cache
this.RegisterCache = undefined;
// Run
this.state = EmulatorState.RUNNING;
this.cpuStepGetTime('run', (tStates, cpuFreq) => {
// Disable breakpoint
zSocket.send('disable-breakpoint ' + bpId, () => {
this.state = EmulatorState.IDLE;
handler(tStates, cpuFreq);
});
});
});
});
});
// Return on a CALL etc.
return;
}
}
// If we reach here the stack was either empty or did not contain any call, i.e. nothing to step out to.
handler();
});
});
}
/**
* 'step backwards' the program execution in the debugger.
* @param handler(instruction, error) The handler that is called after the step is performed.
* instruction: e.g. "081C NOP"
* error: If not undefined t holds the exception message.
*/
public stepBack(handler:(instruction: string, error: string)=>void) {
// Make sure the call stack exists
this.prepareReverseDbgStack(async () => {
let errorText;
let instruction = '';
try {
// Remember previous line
let prevLine = this.RegisterCache as string;
assert(prevLine);
const currentLine = await this.revDbgPrev();
if(!currentLine)
throw Error('Reached end of instruction history.')
// Stack handling:
this.handleReverseDebugStackBack(currentLine, prevLine);
// Get instruction
const pc = Z80Registers.parsePC(currentLine);
instruction = ' ' + Utility.getHexString(pc, 4) + ' ' + this.cpuHistory.getInstruction(currentLine);
}
catch(e) {
errorText = e;
}
// Decoration
if(!errorText)
this.emitRevDbgHistory();
// Call handler
handler(instruction, errorText);
});
}
/**
* Sets the watchpoints in the given list.
* Watchpoints result in a break in the program run if one of the addresses is written or read to.
* It uses ZEsarUX new fast 'memory breakpoints' for this if the breakpoint ha no additional condition.
* If it has a condition the (slow) original ZEsarUX breakpoints are used.
* @param watchPoints A list of addresses to put a guard on.
* @param handler(bpIds) Is called after the last watchpoint is set.
*/
public setWatchpoints(watchPoints: Array<GenericWatchpoint>, handler?: (watchpoints:Array<GenericWatchpoint>) => void) {
// Set watchpoints (memory guards)
for(let wp of watchPoints) {
// Check if condition is used
if(wp.conditions.length > 0) {
// OPEN: ZEsarUX does not allow for memory breakpoints plus conditions.
// Will most probably never be implemented by Cesar.
// I leave this open mainly as a reminder.
// At the moment no watchpoint will be set if an additional condition is set.
}
else {
// This is the general case. Just add a breakpoint on memory access.
let type = 0;
if(wp.access.indexOf('r') >= 0)
type |= 0x01;
if(wp.access.indexOf('w') >= 0)
type |= 0x02;
// Create watchpoint with range
const size = wp.size;
let addr = wp.address;
zSocket.send('set-membreakpoint ' + addr.toString(16) + 'h ' + type + ' ' + size);
}
}
// Call handler
if(handler) {
zSocket.executeWhenQueueIsEmpty(() => {
// Copy array
const wps = watchPoints.slice(0);
handler(wps);
});
}
}
/**
* Enables/disables all WPMEM watchpoints set from the sources.
* @param enable true=enable, false=disable.
* @param handler Is called when ready.
*/
public enableWPMEM(enable: boolean, handler: () => void) {
if(enable) {
this.setWatchpoints(this.watchpoints);
}
else {
// Remove watchpoint(s)
//zSocket.send('clear-membreakpoints');
for(let wp of this.watchpoints) {
// Clear watchpoint with range
const size = wp.size;
let addr = wp.address;
zSocket.send('set-membreakpoint ' + addr.toString(16) + 'h 0 ' + size);
}
}
this.wpmemEnabled = enable;
zSocket.executeWhenQueueIsEmpty(handler);
}
/**
* Set all assert breakpoints.
* Called only once.
* @param assertBreakpoints A list of addresses to put an assert breakpoint on.
*/
public setAssertBreakpoints(assertBreakpoints: Array<GenericBreakpoint>) {
// not supported.
}
/**
* Enables/disables all assert breakpoints set from the sources.
* @param enable true=enable, false=disable.
* @param handler Is called when ready.
*/
public enableAssertBreakpoints(enable: boolean, handler: () => void) {
// not supported.
if(this.assertBreakpoints.length > 0)
this.emit('warning', 'ZEsarUX does not support ASSERTs in the sources.');
if(handler)
handler();
}
/**
* Set all log points.
* Called only once.
* @param logpoints A list of addresses to put a log breakpoint on.
* @param handler() Is called after the last logpoint is set.
*/
public setLogpoints(logpoints: Array<GenericBreakpoint>, handler: (logpoints: Array<GenericBreakpoint>) => void) {
// not supported.
}
/**
* Enables/disables all logpoints for a given group.
* @param group The group to enable/disable. If undefined: all groups.
* @param enable true=enable, false=disable.
* @param handler Is called when ready.
*/
public enableLogpoints(group: string, enable: boolean, handler: () => void) {
// not supported.
if(this.logpoints.size > 0)
this.emit('warning', 'ZEsarUX does not support LOGPOINTs in the sources.');
if(handler)
handler();
}
/**
* Converts a condition into the format that ZEsarUX uses.
* With version 8.0 ZEsarUX got a new parser which is very flexible,
* so the condition is not changed very much.
* Only the C-style operators like "&&", "||", "==", "!=" are added.
* Furthermore "b@(...)" and "w@(...)" are converted to "peek(...)" and "peekw(...)".
* And "!(...)" is converted to "not(...)" (only with brackets).
* Note: The original ZEsarUX operators are not forbidden. E.g. "A=1" is allowed as well as "A==1".
* Labels: ZESarUX does not not the labels only addresses. Therefore all
* labels need to be evaluated first and converted to addresses.
* @param condition The general condition format, e.g. "A < 10 && HL != 0".
* Even complex parenthesis forms are supported, e.g. "(A & 0x7F) == 127".
* @returns The zesarux format
*/
protected convertCondition(condition: string): string|undefined {
if(!condition || condition.length == 0)
return ''; // No condition
// Convert labels
let regex = /\b[_a-z][\.0-9a-z_]*\b/gi;
let conds = condition.replace(regex, label => {
// Check if register
if(Z80Registers.isRegister(label))
return label;
// Convert label to number.
const addr = Labels.getNumberForLabel(label);
// If undefined, don't touch it.
if(addr == undefined)
return label;
return addr.toString();;
});
// Convert operators
conds = conds.replace(/==/g, '=');
conds = conds.replace(/!=/g, '<>');
conds = conds.replace(/&&/g, ' AND ');
conds = conds.replace(/\|\|/g, ' OR ');
conds = conds.replace(/==/g, '=');
conds = conds.replace(/!/g, 'NOT');
// Convert hex numbers ("0x12BF" -> "12BFH")
conds = conds.replace(/0x[0-9a-f]+/gi, value => {
const valh = value.substr(2) + 'H';
return valh;
});
console.log('Converted condition "' + condition + '" to "' + conds);
return conds;
}
/*
* Sets breakpoint in the zesarux debugger.
* Sets the breakpoint ID (bpId) in bp.
* @param bp The breakpoint. If bp.address is >= 0 then it adds the condition "PC=address".
* @returns The used breakpoint ID. 0 if no breakpoint is available anymore.
*/
public setBreakpoint(bp: EmulatorBreakpoint): number {
// Check for logpoint (not supported)
if(bp.log) {
this.emit('warning', 'ZEsarUX does not support logpoints ("' + bp.log + '"). Instead a normal breakpoint is set.');
// set to unverified
bp.address = -1;
return 0;
}
// Get condition
let zesaruxCondition = this.convertCondition(bp.condition);
if(zesaruxCondition == undefined) {
this.emit('warning', "Breakpoint: Can't set condition: " + (bp.condition || ''));
// set to unverified
bp.address = -1;
return 0;
}
// get free id
if(this.freeBreakpointIds.length == 0)
return 0; // no free ID
bp.bpId = this.freeBreakpointIds[0];
this.freeBreakpointIds.shift();
// Create condition from address and bp.condition
let condition = '';
if(bp.address >= 0) {
condition = 'PC=0'+Utility.getHexString(bp.address, 4)+'h';
if(zesaruxCondition.length > 0) {
condition += ' and ';
zesaruxCondition = '(' + zesaruxCondition + ')';
}
}
if(zesaruxCondition.length > 0)
condition += zesaruxCondition;
// set action first (no action)
const shortCond = (condition.length < 50) ? condition : condition.substr(0,50) + '...';
zSocket.send('set-breakpointaction ' + bp.bpId + ' prints breakpoint ' + bp.bpId + ' hit (' + shortCond + ')', () => {
// set the breakpoint
zSocket.send('set-breakpoint ' + bp.bpId + ' ' + condition, () => {
// enable the breakpoint
zSocket.send('enable-breakpoint ' + bp.bpId);
});
});
// Add to list
this.breakpoints.push(bp);
// return
return bp.bpId;
}
/**
* Clears one breakpoint.
*/
protected removeBreakpoint(bp: EmulatorBreakpoint) {
// set breakpoint with no condition = disable/remove
//zSocket.send('set-breakpoint ' + bp.bpId);
// disable breakpoint
zSocket.send('disable-breakpoint ' + bp.bpId);
// Remove from list
var index = this.breakpoints.indexOf(bp);
assert(index !== -1, 'Breakpoint should be removed but does not exist.');
this.breakpoints.splice(index, 1);
this.freeBreakpointIds.push(index);
}
/**
* Disables all breakpoints set in zesarux on startup.
*/
protected clearAllZesaruxBreakpoints() {
for(var i=1; i<=Zesarux.MAX_ZESARUX_BREAKPOINTS; i++) {
zSocket.send('disable-breakpoint ' + i);
}
}
/**
* Set all breakpoints for a file.
* If system is running, first break, then set the breakpoint(s).
* But, because the run-handler is not known here, the 'run' is not continued afterwards.
* @param path The file (which contains the breakpoints).
* @param givenBps The breakpoints in the file.
* @param handler(bps) On return the handler is called with all breakpoints.
* @param tmpDisasmFileHandler(bpr) If a line cannot be determined then this handler
* is called to check if the breakpoint was set in the temporary disassembler file. Returns
* an EmulatorBreakpoint.
*/
public setBreakpoints(path: string, givenBps:Array<EmulatorBreakpoint>,
handler:(bps: Array<EmulatorBreakpoint>)=>void,
tmpDisasmFileHandler:(bp: EmulatorBreakpoint)=>EmulatorBreakpoint) {
this.serializer.exec(() => {
// Do most of the work
super.setBreakpoints(path, givenBps,
bps => {
// But wait for the socket.
zSocket.executeWhenQueueIsEmpty(() => {
handler(bps);
// End
this.serializer.endExec();
});
},
tmpDisasmFileHandler
);
});
}
/**
* Sends a command to ZEsarUX.
* @param cmd E.g. 'get-registers'.
* @param handler The response (data) is returned.
*/
public dbgExec(cmd: string, handler:(data)=>void) {
cmd = cmd.trim();
if(cmd.length == 0) return;
// Check if we need a break
this.breakIfRunning();
// Send command to ZEsarUX
zSocket.send(cmd, data => {
// Call handler
handler(data);
});
}
/**
* Reads a memory dump from zesarux and converts it to a number array.
* @param address The memory start address.
* @param size The memory size.
* @param handler(data, addr) The handler that receives the data. 'addr' gets the value of 'address'.
*/
public getMemoryDump(address: number, size: number, handler:(data: Uint8Array, addr: number)=>void) {
// Use chunks
const chunkSize = 0x10000;// 0x1000;
// Retrieve memory values
const values = new Uint8Array(size);
let k = 0;
while(size > 0) {
const retrieveSize = (size > chunkSize) ? chunkSize : size;
zSocket.send( 'read-memory ' + address + ' ' + retrieveSize, data => {
const len = data.length;
assert(len/2 == retrieveSize);
for(var i=0; i<len; i+=2) {
const valueString = data.substr(i,2);
const value = parseInt(valueString,16);
values[k++] = value;
}
});
// Next chunk
size -= chunkSize;
}
// send data to handler
zSocket.executeWhenQueueIsEmpty(() => {
handler(values, address);
});
}
/**
* Writes a memory dump to zesarux.
* @param address The memory start address.
* @param dataArray The data to write.
* @param handler(response) The handler that is called when zesarux has received the data.
*/
public writeMemoryDump(address: number, dataArray: Uint8Array, handler:() => void) {
// Use chunks
const chunkSize = 0x10000; //0x1000;
let k = 0;
let size = dataArray.length;
let chunkCount = 0;
while(size > 0) {
const sendSize = (size > chunkSize) ? chunkSize : size;
// Convert array to long hex string.
let bytes = '';
for(let i=0; i<sendSize; i++) {
bytes += Utility.getHexString(dataArray[k++], 2);
}
// Send
chunkCount ++;
zSocket.send( 'write-memory-raw ' + address + ' ' + bytes, () => {
chunkCount --;
if(chunkCount == 0)
handler();
});
// Next chunk
size -= chunkSize;
}
// call when ready
//zSocket.executeWhenQueueIsEmpty(() => {
// handler();
//});
}
/**
* Writes one memory value to zesarux.
* The write is followed by a read and the read value is returned
* in the handler.
* @param address The address to change.
* @param value The new value. (byte)
*/
public writeMemory(address:number, value:number, handler:(realValue: number) => void) {
// Write byte
zSocket.send( 'write-memory ' + address + ' ' + value, data => {
// read byte
zSocket.send( 'read-memory ' + address + ' 1', data => {
// call handler
const readValue = parseInt(data,16);
handler(readValue);
});
});
}
/**
* Reads the memory pages, i.e. the slot/banks relationship from zesarux
* and converts it to an arry of MemoryPages.
* @param handler(memoryPages) The handler that receives the memory pages list.
*/
public getMemoryPages(handler:(memoryPages: MemoryPage[])=>void) {
/* Read data from zesarux has the following format:
Segment 1
Long name: ROM 0
Short name: O0
Start: 0H
End: 1FFFH
Segment 2
Long name: ROM 1
Short name: O1
Start: 2000H
End: 3FFFH
Segment 3
Long name: RAM 10
Short name: A10
Start: 4000H
End: 5FFFH
...
*/
zSocket.send( 'get-memory-pages verbose', data => {
const pages: Array<MemoryPage> = [];
const lines = data.split('\n');
const len = lines.length;
let i = 0;
while(i+4 < len) {
// Read data
let name = lines[i+2].substr(12);
name += ' (' + lines[i+1].substr(11) + ')';
const startStr = lines[i+3].substr(7);
const start = Utility.parseValue(startStr);
const endStr = lines[i+4].substr(5);
const end = Utility.parseValue(endStr);
// Save in array
pages.push({start, end, name});
// Next
i += 6;
}
// send data to handler
handler(pages);
});
}
/**
* Change the program counter.
* @param address The new address for the program counter.
* @param handler that is called when the PC has been set.
*/
public setProgramCounter(address: number, handler?:() => void) {
this.RegisterCache = undefined;
zSocket.send( 'set-register PC=' + address.toString(16) + 'h', data => {
if(handler)
handler();
});
}
/**
* Called from "-state save" command.
* Stores all RAM + the registers.
* @param handler(stateData) The handler that is called after restoring.
*/
public stateSave(handler: (stateData) => void) {
// Create state variable
const state = StateZ80.createState(this.machineType);
if(!state)
throw new Error("Machine unknown. Can't save the state.")
// Get state
state.stateSave(handler);
}
/**
* Called from "-state load" command.
* Restores all RAM + the registers from a former "-state save".
* @param stateData Pointer to the data to restore.
* @param handler The handler that is called after restoring.
*/
public stateRestore(stateData: StateZ80, handler?: ()=>void) {
// Clear register cache
this.RegisterCache = undefined;
// Restore state
stateData.stateRestore(handler);
}
// ZX Next related ---------------------------------
/**
* Retrieves the TBBlue register value from the emulator.
* @param registerNr The number of the register.
* @param value(value) Calls 'handler' with the value of the register.
*/
public getTbblueRegister(registerNr: number, handler: (value)=>void) {
zSocket.send('tbblue-get-register ' + registerNr, data => {
// Value is returned as 2 digit hex number followed by "H", e.g. "00H"
const valueString = data.substr(0,2);
const value = parseInt(valueString,16);
// Call handler
handler(value);
});
}
/**
* Retrieves the sprites palette from the emulator.
* @param paletteNr 0 or 1.
* @param handler(paletteArray) Calls 'handler' with a 256 byte Array<number> with the palette values.
*/
public getTbblueSpritesPalette(paletteNr: number, handler: (paletteArray)=>void) {
const paletteNrString = (paletteNr == 0) ? 'first' : 'second';
zSocket.send('tbblue-get-palette sprite ' + paletteNrString + ' 0 256', data => {
// Palette is returned as 3 digit hex separated by spaces, e.g. "02D 168 16D 000"
const palette = new Array<number>(256);
for(let i=0; i<256; i++) {
const colorString = data.substr(i*4,3);
const color = parseInt(colorString,16);
palette[i] = color;
}
// Call handler
handler(palette);
});
}
/**
* Retrieves the sprites clipping window from the emulator.
* @param handler(xl, xr, yt, yb) Calls 'handler' with the clipping dimensions.
*/
public getTbblueSpritesClippingWindow(handler: (xl: number, xr: number, yt: number, yb: number)=>void) {
zSocket.send('tbblue-get-clipwindow sprite', data => {
// Returns 4 decimal numbers, e.g. "0 175 0 192 "
const clip = data.split(' ');
const xl = parseInt(clip[0]);
const xr = parseInt(clip[1]);
const yt = parseInt(clip[2]);
const yb = parseInt(clip[3]);
// Call handler
handler(xl, xr, yt, yb);
});
}
/**
* Retrieves the sprites from the emulator.
* @param slot The start slot.
* @param count The number of slots to retrieve.
* @param handler(sprites) Calls 'handler' with an array of sprite data (an array of an array of 4 bytes, the 4 attribute bytes).
*/
public getTbblueSprites(slot: number, count: number, handler: (sprites)=>void) {
zSocket.send('tbblue-get-sprite ' + slot + ' ' + count, data => {
// Sprites are returned one line per sprite, each line consist of 4x 2 digit hex values, e.g.
// "00 00 00 00"
// "00 00 00 00"
const spriteLines = data.split('\n');
const sprites = new Array<Uint8Array>();
for(const line of spriteLines) {
if(line.length == 0)
continue;
const sprite = new Uint8Array(4);
for(let i=0; i<4; i++) {
const attrString = line.substr(i*3,2);
const attribute = parseInt(attrString,16);
sprite[i] = attribute;
}
sprites.push(sprite);
}
// Call handler
handler(sprites);
});
}
/**
* Retrieves the sprite patterns from the emulator.
* @param index The start index.
* @param count The number of patterns to retrieve.
* @param handler(patterns) Calls 'handler' with an array of sprite pattern data.
*/
public getTbblueSpritePatterns(index: number, count: number, handler: (patterns)=>void) {
zSocket.send('tbblue-get-pattern ' + index + ' ' + count, data => {
// Sprite patterns are returned one line per pattern, each line consist of
// 256x 2 digit hex values, e.g. "E3 E3 E3 E3 E3 ..."
const patternLines = data.split('\n');
patternLines.pop(); // Last element is a newline only
const patterns = new Array<Array<number>>();
for(const line of patternLines) {
const pattern = new Array<number>(256);
for(let i=0; i<256; i++) {
const attrString = line.substr(i*3,2);
const attribute = parseInt(attrString,16);
pattern[i] = attribute;
}
patterns.push(pattern);
}
// Call handler
handler(patterns);
});
}
/**
* This is a hack:
* After starting the vscode sends the source file breakpoints.
* But there is no signal to tell when all are sent.
* So this function waits as long as there is still traffic to the emulator.
* @param timeout Timeout in ms. For this time traffic has to be quiet.
* @param handler This handler is called after being quiet for the given timeout.
*/
public executeAfterBeingQuietFor(timeout: number, handler: () => void) {
let timerId;
const timer = () => {
clearTimeout(timerId);
timerId = setTimeout(() => {
// Now there is at least 100ms quietness:
// Stop listening
zSocket.removeListener('queueChanged', timer);
// Load the initial unit test routine (provided by the user)
handler();
}, timeout);
};
// 2 triggers
zSocket.on('queueChanged', timer);
zSocket.executeWhenQueueIsEmpty(timer);
}
/**
* Calculates the required number of transaction log lines from the
* 'history' setting for reverse debugging and code coverage.
* @returns -1 = Infinite, 0 = disabled, >0 = number of lines
*/
protected numberOfHistoryLines(): number {
let covRotateLines;
if(Settings.launch.history.codeCoverageInstructionCountYoung < 0 || Settings.launch.history.codeCoverageInstructionCountElder < 0) {
covRotateLines = -1; // infinite
}
else {
covRotateLines = Settings.launch.history.codeCoverageInstructionCountYoung + Settings.launch.history.codeCoverageInstructionCountElder;
}
// Number of lines for history
const rdRotLines = Settings.launch.history.reverseDebugInstructionCount;
let totRotLines;
if(covRotateLines < 0 || rdRotLines < 0) {
totRotLines = -1; // infinite
}
else {
totRotLines = covRotateLines + rdRotLines;
}
// Infinity
if(totRotLines < 0)
totRotLines = 0x7FFFFFFF;
return totRotLines;
}
/**
* @returns true if either code coverage or reverse debugging is enabled.
*/
// TODO: REMOVE
protected isCpuTransactionLogEnabled(): boolean {
return Settings.codeCoverageEnabled() || (Settings.launch.history.reverseDebugInstructionCount != 0);
}
/**
* Clears the instruction history.
* For reverse debugging and code coverage.
* This will call 'cpu-transaction-log truncate yes' to clear the log in Zesarux.
* ZEsarUX has a 'truncaterotated' but this does not remove all log files it just
* empties them. And it would also not clear logs bigger than the set rotation.
* So that I will not use it but clear the logs on my own.
*/
public clearInstructionHistory() {
// TODO: REMOVE
super.clearInstructionHistory();
/*
zSocket.send('cpu-transaction-log truncate yes');
if(this.cpuTransactionLog)
this.cpuTransactionLog.deleteRotatedFiles();
*/
}
/**
* @returns Returns the previous line in the transaction log.
* If at end it returns undefined.
*/
protected async revDbgPrev(): Promise<string|undefined> {
let line = await this.cpuHistory.getPrevRegisters();
if(line) {
// Add to register cache
this.RegisterCache = line;
// Add to history for decoration
const addr = parseInt(line.substr(3,4), 16);
this.revDbgHistory.push(addr);
}
return line;
}
/**
* @returns Returns the next line in the transaction log.
* If at start it returns ''.
*/
protected revDbgNext(): string|undefined {
// Get line
let line = this.cpuHistory.getNextRegisters();
this.RegisterCache = line;
//if(line) {
// Remove one address from history
// assert(this.revDbgHistory.length > 0);
this.revDbgHistory.pop();
//}
return line;
}
}
<file_sep>/src/disassembler/basememory.ts
import * as assert from 'assert';
export const MAX_MEM_SIZE = 0x10000;
export class BaseMemory {
/// The resulting memory area.
protected memory: Uint8Array;
/// The start address.
protected startAddress: number;
// The size of the area.
protected size: number;
/**
* Constructor: Initializes memory.
* @param startAddress The start address of the memory area.
* @param size The size of the memory area.
*/
constructor (startAddress: number, size: number) {
this.memory = new Uint8Array(size);
this.startAddress = startAddress;
this.size = size;
}
/**
* Sets a value at an index.
* @param index The index into the memory buffer.
* @param value The value for the index.
*/
public setValueAtIndex(index: number, value: number) {
this.memory[index] = value;
}
/**
* Returns the memory value at address.
* @param address The address to retrieve.
* @returns It's value.
*/
public getValueAt(address: number) {
address &= (MAX_MEM_SIZE-1);
const index = address - this.startAddress;
assert(index >= 0, 'getValueAt 1');
assert(index < this.size, 'getValueAt 2');
return this.memory[index];
}
/**
* Returns the word memory value at address.
* @param address The address to retrieve.
* @returns It's value.
*/
public getWordValueAt(address: number) {
const word = this.getValueAt(address) + 256*this.getValueAt(address+1);
return word;
}
/**
* Returns the word memory value at address in big endian.
* @param address The address to retrieve.
* @returns It's value.
*/
public getBigEndianWordValueAt(address: number) {
const word = 256*this.getValueAt(address) + this.getValueAt(address+1);
return word;
}
}<file_sep>/src/decoration.ts
import * as vscode from 'vscode';
import { Labels } from './labels';
//import { Settings } from './settings';
import * as assert from 'assert';
/// Is a singleton. Initialize in 'activate'.
export let Decoration;
/**
* Each decoration type (coverage, reverse debug, break) gets its own
* instance of DecorationFileMap.
*/
class DecorationFileMap {
/// The decoration type for covered lines.
public decoType: vscode.TextEditorDecorationType;
/// Holds a map with filenames associated with the lines.
public fileMap: Map<string, Array<vscode.Range>|Array<vscode.DecorationOptions>>;
}
/**
* A singleton that holds the editor decorations for code coverage,
* reverse debugging andother decorations, e.g. 'break'.
*/
export class DecorationClass {
// Names to identify the decorations.
protected COVERAGE = "Coverage";
protected REVERSE_DEBUG_PREVIOUS = "RevDbgPrevious";
protected REVERSE_DEBUG = "RevDbg";
protected BREAK = "Break";
// Holds the decorations for coverage, reverse debug and breakpoints.
protected decorationFileMaps: Map<string, DecorationFileMap>;
/// Initialize. Call from 'activate' to set the icon paths.
public static Initialize(context: vscode.ExtensionContext) {
// Create new singleton
Decoration = new DecorationClass();
}
/**
* Register for a change of the text editor to decorate it with the
* covered lines.
*/
constructor() {
// Create the decoration types.
const coverageDecoType = vscode.window.createTextEditorDecorationType({
/*
borderWidth: '1px',
borderStyle: 'solid',
overviewRulerColor: 'blue',
overviewRulerLane: vscode.OverviewRulerLane.Right,
light: {
// this color will be used in light color themes
borderColor: 'darkblue'
},
dark: {
// this color will be used in dark color themes
borderColor: 'lightblue'
}
*/
isWholeLine: true,
gutterIconSize: 'auto',
light: {
// this color will be used in light color themes
backgroundColor: '#B0E090',
//gutterIconPath: context.asAbsolutePath('./images/coverage/gutter-icon-light.svg'),
},
dark: {
// this color will be used in dark color themes
backgroundColor: '#0C4004',
//gutterIconPath: context.asAbsolutePath('./images/coverage/gutter-icon-dark.svg'),
}
});
// For the elder lines a little lighter
const coverageElderDecoType = vscode.window.createTextEditorDecorationType({
isWholeLine: true,
gutterIconSize: 'auto',
light: {
// this color will be used in light color themes
backgroundColor: '#d5efc3',
},
dark: {
// this color will be used in dark color themes
backgroundColor: '#093003',
}
});
// Decoration for reverse debugging.
const revDbgDecoType = vscode.window.createTextEditorDecorationType({
isWholeLine: true,
gutterIconSize: 'auto',
borderWidth: '1px',
borderStyle: 'dashed', //'solid',
borderRadius: '5px',
/*
light: {
// this color will be used in light color themes
backgroundColor: '#A9E2F3',
},
dark: {
// this color will be used in dark color themes
backgroundColor: '#033563',
}
*/
});
// Decoration for 'Breaks'
const breakDecoType = vscode.window.createTextEditorDecorationType({
isWholeLine: true,
gutterIconSize: 'auto',
light: {
// this color will be used in light color themes
backgroundColor: '#ffff00',
},
dark: {
// this color will be used in dark color themes
backgroundColor: '#202000',
}
});
// Create the map
this.decorationFileMaps = new Map<string, DecorationFileMap>();
let decoFileMap = new DecorationFileMap();
decoFileMap.decoType = coverageDecoType;
decoFileMap.fileMap = new Map<string, Array<vscode.Range>>();
this.decorationFileMaps.set(this.COVERAGE, decoFileMap);
decoFileMap = new DecorationFileMap();
decoFileMap.decoType = coverageElderDecoType;
decoFileMap.fileMap = new Map<string, Array<vscode.Range>>();
this.decorationFileMaps.set(this.REVERSE_DEBUG_PREVIOUS, decoFileMap);
decoFileMap = new DecorationFileMap();
decoFileMap.decoType = revDbgDecoType;
decoFileMap.fileMap = new Map<string, Array<vscode.Range>>();
this.decorationFileMaps.set(this.REVERSE_DEBUG, decoFileMap);
decoFileMap = new DecorationFileMap();
decoFileMap.decoType = breakDecoType;
decoFileMap.fileMap = new Map<string, Array<vscode.DecorationOptions>>();
this.decorationFileMaps.set(this.BREAK, decoFileMap);
// Watch the text editors to decorate them.
vscode.window.onDidChangeActiveTextEditor(editor => {
// This is called for the editor that is going to hide and for the editor
// that is shown.
// Unfortunately there is no way to differentiate so both are handled.
this.setAllDecorations(editor);
});
}
/**
* Loops through all active editors and clear the coverage decorations.
*/
public clearCodeCoverage() {
this.clearDecorations(this.COVERAGE);
}
/**
* Loops through all active editors and clear the reverse debug decorations.
*/
public clearRevDbgHistory() {
this.clearDecorations(this.REVERSE_DEBUG_PREVIOUS);
this.clearDecorations(this.REVERSE_DEBUG);
}
/**
* Loops through all active editors and clear the 'break' decorations.
*/
public clearBreak() {
this.clearDecorations(this.BREAK);
}
/**
* Loops through all active editors and clear the decorations.
* @param mapName E.g. COVERAGE_IMMEDIATE, COVERAGE_ELDER, REVERSE_DEBUG
* or BREAK.
*/
protected clearDecorations(mapName: string) {
const map = this.decorationFileMaps.get(mapName) as DecorationFileMap;
map.fileMap.clear();
const editors = vscode.window.visibleTextEditors;
for(const editor of editors) {
editor.setDecorations(map.decoType, []);
}
}
/**
* Sets decorations for all types.
* Coverage, revers debug, breaks.
*/
protected setAllDecorations(editor: vscode.TextEditor|undefined) {
if(!editor)
return;
// Get filename
const edFilename = editor.document.fileName;
// Go through all coverage maps
for(const [,decoMap] of this.decorationFileMaps) {
// Get lines
const fileMap = decoMap.fileMap;
const decorations = fileMap.get(edFilename);
if(decorations) {
// Set all decorations
editor.setDecorations(decoMap.decoType, decorations);
}
}
}
/**
* Sets decorations for a specific type.
* Coverage, revers debug, breaks.
* @param fileMapName E.g. COVERAGE_IMMEDIATE, COVERAGE_ELDER, REVERSE_DEBUG
* or BREAK.
*/
protected setDecorations(editor: vscode.TextEditor, fileMapName: string) {
// Get filename
const edFilename = editor.document.fileName;
// Get file map
const decoMap = this.decorationFileMaps.get(fileMapName) as DecorationFileMap;
assert(decoMap);
// Get lines
const fileMap = decoMap.fileMap;
const decorations = fileMap.get(edFilename);
if(decorations) {
// Set decorations
editor.setDecorations(decoMap.decoType, decorations);
}
}
/**
* Shows (adds) the code coverage of the passed addresses.
* The active editors are decorated.
* The set is added to the existing ones to decorate another editor when the focus changes.
* Is called when the event 'covered' has been emitted by the Emulator.
* @param coveredAddresses All addresses to add (all covered addresses)
*/
public showCodeCoverage(coveredAddresses: Set<number>) {
// Get map name
const mapName = this.COVERAGE;
// Loop over all addresses
const decoMap = this.decorationFileMaps.get(mapName) as DecorationFileMap;
const fileMap = decoMap.fileMap;
//fileMap.clear();
coveredAddresses.forEach(addr => {
// Get file location for address
const location = Labels.getFileAndLineForAddress(addr);
const filename = location.fileName;
if(filename.length == 0)
return;
// Get filename set
let lines = fileMap.get(filename) as Array<vscode.Range>;
if(!lines) {
// Create a new
lines = new Array<vscode.Range>();
fileMap.set(filename, lines);
}
const lineNr = location.lineNr;
const range = new vscode.Range(lineNr,0, lineNr,1000);
// Add address to set
lines.push(range);
});
// Loop through all open editors.
const editors = vscode.window.visibleTextEditors;
for(const editor of editors) {
this.setDecorations(editor, this.COVERAGE);
}
}
/**
* Is called whenever the reverse debug history changes.
* Will set the decoration.
* @param addresses The addresses to decorate.
*/
public showRevDbgHistory(addresses: Array<number>) {
// Clear decorations
this.clearRevDbgHistory();
// Get file map
const decoMap = this.decorationFileMaps.get(this.REVERSE_DEBUG) as DecorationFileMap;
const fileMap = decoMap.fileMap;
// Loop over all addresses
addresses.forEach(addr => {
// Get file location for address
const location = Labels.getFileAndLineForAddress(addr);
const filename = location.fileName;
if(filename.length == 0)
return;
// Get filename set
let lines = fileMap.get(filename) as Array<vscode.Range>;
if(!lines) {
// Create a new
lines = new Array<vscode.Range>();
fileMap.set(filename, lines);
}
// Add address to set
const lineNr = location.lineNr;
const range = new vscode.Range(lineNr,0, lineNr,1000);
// Add address to set
lines.push(range);
});
// Loop through all open editors.
const editors = vscode.window.visibleTextEditors;
for(const editor of editors) {
this.setDecorations(editor, this.REVERSE_DEBUG_PREVIOUS);
this.setDecorations(editor, this.REVERSE_DEBUG);
}
}
/**
* Is called when a new 'break' should be shown.
* Will set the decorations.
* There are 1 to 2 decorations.
* If pc == breakAddress it is a normal break at the PC.
* In this case a simple decoration with the text is shown.
* If pc != breakAddress it is e.g. a break because of a memory watch.
* In this case the decoration at the breakAddress will contain the text and
* the decoration at the pc will also get the text and also a link to the
* breakAddress decoration.
* @param addresses The address to decorate.
*/
public showBreak(pc: number, breakAddress: number, text: string) {
// Get file map
const decoMap = this.decorationFileMaps.get(this.BREAK) as DecorationFileMap;
const fileMap = decoMap.fileMap;
fileMap.clear();
// Get file location for pc
const location = Labels.getFileAndLineForAddress(pc);
const filename = location.fileName;
if(filename.length > 0) {
// Get filename set
let lines = fileMap.get(filename) as Array<vscode.DecorationOptions>;
if(!lines) {
// Create a new
lines = new Array<vscode.DecorationOptions>();
fileMap.set(filename, lines);
}
const lineNr = location.lineNr;
const deco = {
range: new vscode.Range(lineNr,0, lineNr,1000),
hoverMessage: undefined,
renderOptions: {
after: {
contentText: text
},
},
};
// Add address to set
lines.push(deco);
}
// TODO: handle breakAdress: display the memory watch
// Loop through all open editors.
const editors = vscode.window.visibleTextEditors;
for(const editor of editors) {
this.setDecorations(editor, this.BREAK);
}
}
}
<file_sep>/src/zesaruxCpuHistory.ts
import * as assert from 'assert';
import { zSocket } from './zesaruxSocket';
import { Opcode } from './disassembler/opcode';
import { BaseMemory } from './disassembler/basememory';
import { Z80Registers } from './z80Registers';
/**
* This class takes care of the ZEsarUX cpu history.
* Each history instruction can be retrieved from ZEsarUx.
* The format of each line is:
* PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c
* which is very much the same as the line retrieved during each forward step. To compare, forward-step:
* PC=003a SP=ff42 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=07 F=-Z-H3P-- F'=-Z---P-- MEMPTR=0000 IM1 IFF-- VPS: 0 TSTATES: 46
* 003A LD HL,(5C78)
*
* These are the ZEsarUX cpu history zrcp commands:
* cpu-history ...:
* clear Clear the cpu history
* enabled yes|no Enable or disable the cpu history
* get index Get registers at position
* get-max-size Return maximum allowed elements in history
* get-pc start end Return PC register from position start to end
* get-size Return total elements in history
* is-enabled Tells if the cpu history is enabled or not
* is-started Tells if the cpu history is started or not
* started yes|no Start recording cpu history. Requires it to be enabled first
* set-max-size number Sets maximum allowed elements in history
*/
export class ZesaruxCpuHistory {
// Contains the cpu instruction (register) history.
// Starts with the youngest.
// At index 0 the current registers are cached.
protected history: Array<string>;
// The first time the index is searched. Afterwards the stored one is used.
protected pcIndex = -1;
/**
* Creates the object.
*/
constructor() {
this.history = Array<string>();
}
/**
* Init.
* @param size The max size of the history.
*/
public init(maxSize: number) {
if(maxSize > 0) {
zSocket.send('cpu-history enabled yes');
zSocket.send('cpu-history set-max-size ' + maxSize);
zSocket.send('cpu-history clear');
zSocket.send('cpu-history started yes');
}
else {
zSocket.send('cpu-history enabled no');
}
}
/**
* Retrieves the instruction from ZEsarUX cpu history.
* Is async.
* May throw an exception if wrong data is received.
* @returns A string with the instruction and registers.
*/
// REMOVE:
public async getLineXXX(): Promise<string|undefined> {
try {
let currentLine;
// Check if it is the first retrieved line
return currentLine;
}
catch(e) {
throw Error("Error retrieving the cpu history from ZEsarUX.");
}
}
/**
* Retrieves the registers at the previous instruction from ZEsarUX cpu history.
* Is async.
* @returns A string with the registers or undefined if at the end of the history.
*/
public async getPrevRegisters(): Promise<string|undefined> {
const currentLine = await this.getRegistersPromise(this.history.length);
if(currentLine)
this.history.push(currentLine);
return currentLine;
}
/**
* Retrieves the registers at the next instruction from ZEsarUX cpu history.
* Is async.
* @returns A string with the registers or undefined if at the start of the history.
*/
public getNextRegisters(): string|undefined {
// Remove last one
this.history.pop();
// Get previous item
const len = this.history.length;
let currentLine;
if(len > 0)
currentLine = this.history[len-1];
return currentLine;
}
/**
* Retrieves the instruction from ZEsarUX cpu history.
* Is async.
* @param index The index to retrieve. Starts at 0.
* @returns A string with the registers.
*/
protected getRegistersPromise(index: number): Promise<string> {
return new Promise<string>((resolve, reject) => {
assert(index >= 0);
zSocket.send('cpu-history get ' + index, data => {
if(data.substr(0,5).toLowerCase() == 'error')
resolve(undefined);
else
resolve(data);
}, true);
});
}
/**
* Input a line which was retrieved by 'cpu-history get N' and return the opcodes string.
* @param line E.g. "PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c"
* @return E.g. "e52a785c"
*/
public getOpcodes(line: string): string {
if(this.pcIndex < 0) {
this.pcIndex = line.indexOf('(PC)=');
assert(this.pcIndex >= 0);
this.pcIndex += 5;
}
const opcodes = line.substr(this.pcIndex, 8);
return opcodes;
}
/**
* Disassembles an instruction from the given opcode string.
* Uses 'PC=xxxx' and '(PC)=yyyyyyyy' from the input string.
* @param opcodes E.g. "PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c"
* @returns The instruction, e.g. "LD A,1E".
*/
public getInstruction(line: string): string {
// Prepare bytes to memory
const opcodes = this.getOpcodes(line);
const pc = Z80Registers.parsePC(line);
const buffer = new BaseMemory(pc, 4);
for(let i=0; i<4; i++) {
const opc = parseInt(opcodes.substr(i*2, 2), 16);
buffer.setValueAtIndex(i, opc);
}
// Get opcode
const opcode = Opcode.getOpcodeAt(buffer, pc);
// Disassemble
const opCodeDescription = opcode.disassemble();
const instr = opCodeDescription.mnemonic;
return instr;
}
/**
* @param line If given the instruction is taken from the line, otherwise
* 'getLine()' is called.
* @returns The instruction, e.g. "LD A,1E".
*/
// TODO: REMOVE
public getInstructionOld(line: string): string {
// E.g. "8000 LD A,1E PC=8000 SP=ff2b BC=8000 AF=0054 HL=2d2b DE=5cdc IX=ff3c IY=5c3a AF'=0044 BC'=0000 HL'=2758 DE'=369b I=3f R=01 F=-Z-H-P-- F'=-Z---P-- MEMPTR=0000 IM1 IFF-- VPS: 0
// Extract the instruction
const k = line.indexOf('PC=');
assert(k >= 0);
const instr = line.substr(5, k-5-1);
return instr;
}
/**
* @returns The address of the current line. Uses the first 4 digits simply.
*/
public getAddress(line: string): number {
line = line.substr(3,4);
// Convert address
const addr = parseInt(line, 16);
return addr;
}
/**
* @returns Returns true if in step back mode.
*/
public isInStepBackMode() {
return (this.history.length > 0);
}
/**
* Tests if the line includes a RET instruction and if it is
* conditional it tests if the condition was true.
* @param line E.g. "PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c"
* @returns false=if not RET (or RETI or RETN) or condition of RET cc is not met.
*/
public isRetAndExecuted(line: string): boolean {
// Get opcodes
const opcodes = this.getOpcodes(line);
// Check for RET
const opcode0 = parseInt(opcodes.substr(0,2),16);
if(0xC9 == opcode0)
return true;
// Check for RETI or RETN
const opcode01 = parseInt(opcodes.substr(0,4),16);
if([0xED4D, 0xED45].includes(opcode01))
return true;
// Now check for RET cc
const mask = 0b11000000;
if((opcode0 & mask) == mask) {
// RET cc, get cc
const cc = (opcode0 & ~mask) >> 3;
// Get flags
const AF = Z80Registers.parseAF(line);
// Check condition
const condMet = Z80Registers.isCcMetByFlag(cc, AF);
return condMet;
}
// No RET or condition not met
return false;
}
/**
* Tests if the line includes a CALL instruction and if it is
* conditional it tests if the condition was true.
* @param line E.g. "PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c"
* @returns false=if not CALL or condition of CALL cc is not met.
*/
public isCallAndExecuted(line: string): boolean {
// Get opcodes
const opcodes = this.getOpcodes(line);
// Check for CALL
const opcode0 = parseInt(opcodes.substr(0,2),16);
if(0xCD == opcode0)
return true;
// Now check for CALL cc
const mask = 0b11000100;
if((opcode0 & mask) == mask) {
// RET cc, get cc
const cc = (opcode0 & ~mask) >> 3;
// Get flags
const AF = Z80Registers.parseAF(line);
// Check condition
const condMet = Z80Registers.isCcMetByFlag(cc, AF);
return condMet;
}
// No CALL or condition not met
return false;
}
/**
* Tests if the line includes a RST instruction.
* @param line E.g. "PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c"
* @returns true=if RST
*/
public isRst(line: string): boolean {
// Get opcodes
const opcodes = this.getOpcodes(line);
// Check for RST
const opcode0 = parseInt(opcodes.substr(0,2),16);
const mask = 0b11000111;
if((opcode0 & mask) == mask)
return true;
// No RST
return false;
}
}
<file_sep>/src/genericwatchpoint.ts
/**
* Represents a watchpoint used by EmulDebugAdapter in a very generic form,
* i.e. not machine specific.
*/
export interface GenericWatchpoint {
address: number; ///< The start address
size: number; ///< The length of the area to watch
access: string; ///< The way of access, e.g. read='r', write='w', readwrite='rw'
conditions: string; ///< The additional conditions (emulator specific). '' if no condition set.
}
/**
* Represents a breakpoint used by EmulDebugAdapter in a very generic form,
* i.e. not machine specific.
*/
export interface GenericBreakpoint {
address: number; ///< The PC address to break on
conditions: string; ///< The additional conditions (emulator specific). '' if no condition set.
log: string|undefined; ///< If set the log will be printed instead of stopping execution.
}
<file_sep>/src/callserializer.ts
import { Log } from './log';
/**
* Class that serializes calls.
* I.e. this class takes care that asynchronous calls are executed one after the other.
*/
export class CallSerializer {
/// Call queue
private queue = new Array();
/// name of the queue, for debugging.
private name: string;
/// Time to print a log message that the queue is not "clean". In secs.
private timeout: number;
/// The timer for the log message.
private timer: any;
/// Enable/disable logging
private logEnabled: boolean;
/// A progress indicator for debugging. Set this in your function to check
/// later how far it got.
protected dbgProgressIndicator: string;
/**
* Constructor.
* @param name Name of the queue (logging)
* @param enableLog Enables/disables logging (logging)
* @param timeout The time to print a log message if queue is not "clean" (empty)
*/
constructor(name: string, enableLog?: boolean, timeout?: number) {
this.name = name;
this.timeout = (timeout == undefined) ? 5*1000: timeout*1000;
this.logEnabled = (enableLog == undefined) ? false : enableLog;
// this.timeout = 0;
}
/**
* Adds the method (call) to the queue.
* If this is the only call in the queue it is directly executed.
* @param func Function to executed (data that is passed is the call serializer (this))
* @param funcName A human redable name for debugging
*/
public exec(func: {(callserializer)} = (callserializer) => {}, funcName?: string) {
this.queue.push({func: func, name: funcName});
Log.log('Pushed (size=' + this.queue.length + ', name=' + funcName + '), ' + func);
// Timer to check that queue gets empty
if(this.timeout != 0 && this.logEnabled) {
// Cancel previous timer
//if(this.timer)
clearTimeout(this.timer);
// Restart timer
this.timer = setTimeout(() => {
if(this.queue.length > 0) {
this.log('\n==================================================');
this.log('Error: queue is not empty, still ' + this.queue.length + ' elements.');
// First entry
const entry = this.queue[0];
this.log('First entry: name=' + entry.funcName);
Log.log('' + entry.func);
this.log('\n==================================================\n');
}
clearTimeout(this.timer);
}, this.timeout);
this.timer.unref();
}
if(this.queue.length == 1) {
// Execute
this.runQueueFunction();
}
this.log('exec: queue.size = ' + this.queue.length);
}
/**
* Add several functions to the queue.
* @param funcs (variadic) a number of functions calls/anonymous functions separated by ",".
*/
public execAll(...funcs) {
funcs.forEach(func => { this.exec(func); });
}
/**
* Should be called from the asynchronous method to inform the call is
* finished.
*/
public endExec() {
// Remove first element = this method call
const entry = this.queue.shift();
// Log
Log.log('Popped (size=' + this.queue.length + ', name=' + entry.funcName + '), ' + entry.func);
// Execute next
if(this.queue.length != 0)
this.runQueueFunction();
this.log('endExec: queue.size = ' + this.queue.length);
}
/**
* Sets the debug progress indicator to some text.
* Can be used to check how far we got inside the function.
* @param text Some text.
*/
public setProgress(text: string) {
this.dbgProgressIndicator = text;
}
/**
* If there is an method in the queue than it is executed.
*/
private runQueueFunction() {
// Clear progress indicator
this.dbgProgressIndicator = "Start";
// execute directly
this.log('runQueueFunction ' + this.queue[0].name);
const method = this.queue[0].func;
//method.call(this);
method(this);
}
/**
* Logs the given args if logEnabled.
*/
private log(...args) {
if(!this.logEnabled)
return;
Log.log(this.name + '.CallSerializer: ', ...args);
Log.log(this.name + '.CallSerializer: ', ...this.queue);
}
/**
* Use for debugging.
* @returns{progress, func} the current and progress function. Use to debug where it hangs.
* progress contains the current value of the this.dbgProgressIndicator variable.
*/
public getCurrentFunction(): {progress: string, func: any} {
const method = {progress: this.dbgProgressIndicator, func: undefined};
if(this.queue.length > 0)
method.func = this.queue[0].func;
return method;
}
/**
* Use for debugging. Clears the complete selrializer queue.
*/
public clrQueue() {
this.queue.length = 0;
}
/**
* Static function to serialize several function calls.
* Creates a temporary CallSerializer object and adds the function calls to it.
* @param funcs (variadic) a number of functions calls/anonymous functions separated by ",".
*/
public static execAll(...funcs) {
const queue = new CallSerializer("TempSerializer");
queue.execAll(...funcs);
}
}
<file_sep>/documentation/EmulatorInterface.md
# TODO
- Interface von ShallowVar ändern. Die sollen über Machine gehen.
So dass ich in Machine alle Emulator spezifischen Dinge habe.
- Ich muss wohl eigenes lua script bauen, um erweiterte Befehle wie 'disassemble, step-over, change driver' zu benutzen. Dann kann ich auch gleich eigenes definieren. Wenn ich das gleiche wie bei ZEsarux verwende müsste ich nichts ändern! (Wunschdenken, e.g. unterschiedliches Breakpoint Nummer handling. Das funktioniert nicht: Machine abstrahiert den Emulator.).
- Register parsing muss nach 'Machine'.
- Vielleicht 'Machine' umbenennen nach 'Emulator'.
# Emulator Interface
This document describes the messages used to interface with the emulator(s).
# General
To interface to different emulators (e.g. MAME, ZEsarUX) the Machine classes are used. The specific 'Machine' implementations abstracts the emulator interface and the used "HW" (e.g. Spectrum 48, Spectrum 128, ...).
In general the following interfaces are required:
- start, stop, stepping
- reading, setting registers
- reading, setting memory
The 'Machine' instance is created in the 'create' function. Here a different Machine is chosen depending on the configuration.
The Machine interface to vscode via the 'EmulDebugAdapter'. The main interfaces are:
- init: Initialization of the Machine.
- continue, next, pause, stepOver, stepInto, stepOut, (reverseContinue, stepBack): Stepping through code. Called as reaction to clicking the correspondent vscode buttons.
- getRegisters, getRegisterValue: Returns register values. Called if the registers are updated, e.g. in the VARIABLES area on every step.
- setProgramCounter: Change the program counter. Used when the program counter is changed from the menu.
- stackTraceRequest: Retrieves the call stack. Called on every step.
- setBreakpoints: Called on startup and on every user change to the breakpoints.
- setWPMEM, enableWPMEM: setWPMEM is called at startup to set all memory watchpoints ("WPMEM") in the assembly sources. enableWPMEM is a debug console command to enable/disable these watchpoints.
- getDisassembly: Returns a disassembly of the code.
- dbgExec: Executes a command on the emulator.
- getMemoryDump: Retrieves a memory dump.
- writeMemory: Changes memory values.
- state save/restore: Saves and restores the complete machine state.
Apart from Machine there is another class collection that communicate with the emulator, the ShallowVar classes.
The ShallowVar classes represent variables shown e.g. in vscode's VARIABLES section ot the WATCHES section. Examples are: Disassembly, registers, watches.
Whenever the value should be updated, vscode requests the value and the ShallowVar sends teh request to the emulator and receives the value as response.
## MAME
### gdbstub
The Machine communicates with MAME via the gdb remote protocol via a socket. Mame needs to be started with the gdbstub lua script for this to work.
I.e. MAME uses gdb syntax for communicaton with z80-debug.
Here are the available commands:
- CTRL-C: Break (stop debugger execution)
- c: Continue
- s: Step into
- g: Read register
- G: Write register
- m: Read memory
- M: Write memory
- X: Load binary data
- z: Clear breakpoint/watchpoint
- Z: Set breakpoint/watchpoint
Missing:
- step-over, disassemble: not in serial protocol. done in gdb.
- machine info: not available.
- Possibility to change the 'driver', e.g. Spectrum 48k or Spectrum 128k
### Mame debugger (accessible through lua)
Init:
[MAME]>
debugger = manager:machine():debugger()
cpu = manager:machine().devices[":maincpu"]
space = cpu.spaces["program"]
consolelog = debugger.consolelog
errorlog = debugger.errorlog
consolelog can be read to retrieve the result of the commands (consolelog[#consolelog]).
errorlog is inclear how to use it.
- Get the state of the debugger: debugger.execution_state:
- "stop"
- "run"
Commands:
- Step:
- cpu:debug():step()
- debugger:command("step")
- Continue:
- cpu:debug():go()
- debugger:command("go")
- Stop:
- cpu:debug():step() (yes, step) or
- debugger.execution_state = "stop" or
- debugger:command("gvblank")
- Get register: e.g.
- print(cpu.state["HL"].value)
- debugger:command("print hl")
- Value is in consolelog which can be retrieved such: print(consolelog[#consolelog])
- Set register:
- cpu.state["BC"].value = tonumber("8000",16)
- disassemble:
- debugger:command("dasm file.asm,0, 10") - **does only write disassembly to a file. Unusable!**
- set-breakpoint / enable breakpoint
- debugger:command("bps 8000") - return it's number
- cpu:debug():bpset(0x8000)
- disable-breakpoint
- cpu:debug():bpclr(1)
- debugger:command("bpclear 1")
- watchpoint:
- cpu:debug():wpset(cpu.spaces["program"], "w", addr, 1)
- cpu:debug():wpclear(1)
- read-memory:
- print(space:read_log_u8(addr))
- there is no memory dump function: only saving to file. Could maybe done in lua.
- write-memory
- space:write_log_u8(32768,15)
- get-stack-backtrace: not as suchneed to be constructed through register and mem read.
- breakpoint action, i.e. bp logs: MAME can do a printf to console. That could be transmitted to z80-debug.
### Open (MAME)
- state save/restore: I haven't checked if that is availablethrough lua.
## ZEsarUX
The Machine communicates with the emulator via the ZEsaruxSocket.
The following commands are used.
### Machine
Initialization (after connection setup):
- about
- get-version
- get-current-machine
- set-debug-settings
- enter-cpu-step
Other:
- get-registers
- disassemble
- get-stack-backtrace
- run
- 'sendBlank' (to break running)
- cpu-step
- set-breakpointaction
- set-breakpoint
- enable-breakpoint
- disable-breakpoint
- read-memory
- write-memory
- set-register
### ShallowVar
- disassemble
- set-register
- write-memory-raw
- read-memory
<file_sep>/src/tests/zesaruxCpuHistory.tests.ts
import * as assert from 'assert';
import { ZesaruxCpuHistory } from '../zesaruxCpuHistory';
suite('ZesaruxCpuHistory', () => {
/*
setup( () => {
return dc.start();
});
teardown( () => dc.disconnect() );
*/
suite('disassemble', () => {
test('getOpcodes', () => {
const hist = new ZesaruxCpuHistory();
let result = hist.getOpcodes("PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=e52a785c");
assert.equal("e52a785c", result);
result = hist.getOpcodes("PC=0039 SP=ff44 AF=005c BC=ffff HL=10a8 DE=5cb9 IX=ffff IY=5c3a AF'=0044 BC'=174b HL'=107f DE'=0006 I=3f R=06 IM1 IFF-- (PC)=00123456");
assert.equal("00123456", result);
});
test('getInstruction 1-4 bytes', () => {
const hist = new ZesaruxCpuHistory();
let result = hist.getOpcodes("PC=0039 ... (PC)=e5000000");
assert.equal("e5000000", result);
result = hist.getInstruction("PC=0039 ... (PC)=e5000000");
assert.equal("PUSH HL", result);
result = hist.getInstruction("PC=0000 ... (PC)=ed610000");
assert.equal("OUT (C),H", result);
result = hist.getInstruction("PC=FEDC ... (PC)=cbb10000");
assert.equal("RES 6,C", result);
result = hist.getInstruction("PC=0102 ... (PC)=dd390000");
assert.equal("ADD IX,SP", result);
result = hist.getInstruction("PC=0039 ... (PC)=dd561200");
assert.equal("LD D,(IX+18)", result);
result = hist.getInstruction("PC=0039 ... (PC)=ddcb2006");
assert.equal("RLC (IX+32)", result);
result = hist.getInstruction("PC=0039 ... (PC)=fd390000");
assert.equal("ADD IY,SP", result);
result = hist.getInstruction("PC=0039 ... (PC)=fdcb2006");
assert.equal("RLC (IY+32)", result);
});
test('getInstruction RST', () => {
const hist = new ZesaruxCpuHistory();
let result = hist.getOpcodes("PC=0039 ... (PC)=e5000000");
assert.equal("e5000000", result);
result = hist.getInstruction("PC=0039 ... (PC)=cf000000");
assert.equal("RST 08h", result);
result = hist.getInstruction("PC=0039 ... (PC)=df000000");
assert.equal("RST 18h", result);
result = hist.getInstruction("PC=0039 ... (PC)=ef000000");
assert.equal("RST 28h", result);
result = hist.getInstruction("PC=0039 ... (PC)=ff000000");
assert.equal("RST 38h", result);
});
test('getInstruction CALL cc', () => {
const hist = new ZesaruxCpuHistory();
let result = hist.getOpcodes("PC=0039 ... (PC)=e5000000");
assert.equal("e5000000", result);
result = hist.getInstruction("PC=0039 ... (PC)=CD214300");
assert.equal("CALL 4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=C4214300");
assert.equal("CALL NZ,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=D4214300");
assert.equal("CALL NC,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=E4214300");
assert.equal("CALL PO,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=F4214300");
assert.equal("CALL P,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=CC214300");
assert.equal("CALL Z,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=DC214300");
assert.equal("CALL C,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=EC214300");
assert.equal("CALL PE,4321h", result);
result = hist.getInstruction("PC=0039 ... (PC)=FC214300");
assert.equal("CALL M,4321h", result);
});
test('getInstruction RET, RETI, RETN', () => {
const hist = new ZesaruxCpuHistory();
let result = hist.getOpcodes("PC=0039 ... (PC)=e5000000");
assert.equal("e5000000", result);
result = hist.getInstruction("PC=0039 ... (PC)=c9000000");
assert.equal("RET", result);
result = hist.getInstruction("PC=0039 ... (PC)=ed4d0000");
assert.equal("RETI", result);
result = hist.getInstruction("PC=0039 ... (PC)=ed450000");
assert.equal("RETN", result);
});
test('getInstruction RET cc', () => {
const hist = new ZesaruxCpuHistory();
let result = hist.getOpcodes("PC=0039 ... (PC)=e5000000");
assert.equal("e5000000", result);
result = hist.getInstruction("PC=0039 ... (PC)=c0000000");
assert.equal("RET NZ", result);
result = hist.getInstruction("PC=0039 ... (PC)=d0000000");
assert.equal("RET NC", result);
result = hist.getInstruction("PC=0039 ... (PC)=e0000000");
assert.equal("RET PO", result);
result = hist.getInstruction("PC=0039 ... (PC)=f0000000");
assert.equal("RET P", result);
result = hist.getInstruction("PC=0039 ... (PC)=c8000000");
assert.equal("RET Z", result);
result = hist.getInstruction("PC=0039 ... (PC)=d8000000");
assert.equal("RET C", result);
result = hist.getInstruction("PC=0039 ... (PC)=e8000000");
assert.equal("RET PE", result);
result = hist.getInstruction("PC=0039 ... (PC)=f8000000");
assert.equal("RET M", result);
});
});
suite('isRetCallRst', () => {
suite('isRetAndExecuted', () => {
test('isRetAndExecuted unconditional', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isRetAndExecuted("(PC)=c9000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("(PC)=01000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("(PC)=ed4d0000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("(PC)=ed450000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("(PC)=0ed110000")
assert.equal(false, result);
});
test('isRetAndExecuted NZ,Z', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isRetAndExecuted("AF=00BF (PC)=c0000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0040 (PC)=c8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=00BF (PC)=c8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0040 (PC)=c0000000")
assert.equal(true, result);
});
test('isRetAndExecuted NC,C', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isRetAndExecuted("AF=00FE (PC)=d0000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0001 (PC)=d8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=00FE (PC)=d8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0001 (PC)=d0000000")
assert.equal(true, result);
});
test('isRetAndExecuted PO,PE', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isRetAndExecuted("AF=00FB (PC)=e0000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0004 (PC)=e8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=00FB (PC)=e8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0004 (PC)=e0000000")
assert.equal(true, result);
});
test('isRetAndExecuted P,M', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isRetAndExecuted("AF=007F (PC)=f0000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0080 (PC)=f8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=007F (PC)=f8000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isRetAndExecuted("AF=0080 (PC)=f0000000")
assert.equal(true, result);
});
});
suite('isCallAndExecuted', () => {
test('isCallAndExecuted unconditional', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isCallAndExecuted("(PC)=cd000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=01000000")
assert.equal(false, result);
});
test('isCallAndExecuted NZ,Z', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isCallAndExecuted("AF=00BF (PC)=c4000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0040 (PC)=cc000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=00BF (PC)=cc000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0040 (PC)=c4000000")
assert.equal(true, result);
});
test('isCallAndExecuted NC,C', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isCallAndExecuted("AF=00FE (PC)=d4000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0001 (PC)=dc000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=00FE (PC)=dc000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0001 (PC)=d4000000")
assert.equal(true, result);
});
test('isCallAndExecuted PO,PE', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isCallAndExecuted("AF=00FB (PC)=e4000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0004 (PC)=ec000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=00FB (PC)=ec000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0004 (PC)=e4000000")
assert.equal(true, result);
});
test('isCallAndExecuted P,M', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isCallAndExecuted("AF=007F (PC)=f4000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0080 (PC)=fc000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=007F (PC)=fc000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("AF=0080 (PC)=f4000000")
assert.equal(true, result);
});
});
test('isRst', () => {
let hist = new ZesaruxCpuHistory();
let result = hist.isCallAndExecuted("(PC)=c7000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=cf000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=d7000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=df000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=e7000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=ef000000")
assert.equal(false, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=f7000000")
assert.equal(true, result);
hist = new ZesaruxCpuHistory();
result = hist.isCallAndExecuted("(PC)=ff000000")
assert.equal(false, result);
});
});
});
<file_sep>/src/zxnextspritesview.ts
import * as assert from 'assert';
import { Emulator } from './emulatorfactory';
import * as util from 'util';
import { EventEmitter } from 'events';
import { ZxNextSpritePatternsView, PatternGif } from './zxnextspritepatternsview';
/// Contains the sprite attributes in an converted form.
class SpriteData {
/// X-Position
public x = 0;
/// Y-Position
public y = 0;
/// X-Mirroring
public xMirrored = 0;
/// Y-Mirroring
public yMirrored = 0;
/// Rotated
public rotated = 0;
/// Palette offset
public paletteOffset = 0;
/// Pattern index
public patternIndex = 0;
/// Visible
public visible = false;
/// The pngimage created from the pattern.
public image: Array<number>;
/// Constructor
constructor(attributes: Uint8Array) {
this.x = attributes[0] + (attributes[2]&0x01)*256;
this.y = attributes[1];
this.xMirrored = (attributes[2] & 0b00001000) ? 1 : 0;
this.yMirrored = (attributes[2] & 0b00000100) ? 1 : 0;
this.rotated = (attributes[2] & 0b00000010) ? 1 : 0;
this.paletteOffset = attributes[2] & 0b11110000;
this.patternIndex = attributes[3] & 0b00111111;
this.visible = ((attributes[3] & 0b10000000) != 0);
}
/**
* Creates an image from the givven pattern.
* @param pattern 256 bytes, 16x16 pattern.
* @param palette 256 bytes, colors: rrrgggbbb
* @param transparentIndex The index used for transparency.
*/
public createImageFromPattern(pattern: Array<number>, palette: Array<number>, transparentIndex: number) {
let usedPattern = pattern;
// Rotate
if(this.rotated) {
const np = new Array<number>(256);
// Mirror
let k = 0;
for(let y=0; y<16; y++) {
for(let x=0; x<16; x++)
np[x*16+15-y] = usedPattern[k++];
}
// Use
usedPattern = np;
}
// X-mirror
if(this.xMirrored) {
const np = new Array<number>(256);
// Mirror
let k = 0;
for(let y=0; y<16; y++) {
for(let x=0; x<16; x++)
np[k++] = usedPattern[y*16+15-x];
}
// Use
usedPattern = np;
}
// Y-mirror
if(this.yMirrored) {
const np = new Array<number>(256);
// Mirror
let k = 0;
for(let y=0; y<16; y++) {
for(let x=0; x<16; x++)
np[k++] = usedPattern[(15-y)*16+x];
}
// Use
usedPattern = np;
}
// Convert to gif
this.image = PatternGif.createGifFromPattern(usedPattern, palette, transparentIndex);
}
}
/**
* A Webview that shows the ZX Next sprite slots and the associated pattern with it's palette.
* The view cannot be edited.
*
* The display consists of:
* - x/y position
* - Palette offset, mirroring, rotation.
* - Visibility
* - Pattern index
* - Pattern as image
*
* The range of the slot indices can be chosen. Eg. "5 10" or "5 10, 17 2".
* There exist a checkbox that allows for live update of the patterns and palettes.
* The sprite values themselves are always updated live.
*
*/
export class ZxNextSpritesView extends ZxNextSpritePatternsView {
/// Contains the sprite slots to display.
protected slotIndices: Array<number>;
/// The sprites, i.e. 64 slots with 4 bytes attributes each
protected sprites = Array<SpriteData|undefined>(64);
/// The previous sprites, i.e. the values here are used to check which attribute has changed
// so it can be printed in bold.
protected previousSprites = Array<SpriteData|undefined>(64);
/// Set if sprite clipping enabled.
protected clippingEnabled = false;
// Sprite clipping dimensions.
protected clipXl: number;
protected clipXr: number;
protected clipYt: number;
protected clipYb: number;
/**
* Creates the basic panel.
* @param parent The parent which may send 'update' notifications.
* @param title The title to use for this view.
* @param slotRanges Pairs of start slot/count. If undefined all visible sprites will be chosen (on each update).
*/
constructor(parent: EventEmitter, title: string, slotRanges: Array<number>|undefined) {
super(parent, title, []);
if(slotRanges) {
// Create array with slots
this.slotIndices = new Array<number>();
while(true) {
const start = slotRanges.shift();
if(start == undefined)
break;
let end = slotRanges.shift() || 0;
assert(end>0);
end += start;
for(let k=start; k<end; k++) {
if(k > 63)
break;
this.slotIndices.push(k);
}
}
}
// Title
this.vscodePanel.title = title;
}
/**
* Retrieves all sprites info from the emulator.
* Then sets the slotIndices accordingly: with only the visible slots.
*/
protected getAllVisibleSprites() {
this.serializer.exec(() => {
// Get sprites
Emulator.getTbblueSprites(0, 64, sprites => {
// Loop over all sprites
for(let k=0; k<64; k++) {
const attrs = sprites[k];
// Check if visible
let sprite;
if(attrs[3] & 0b10000000)
sprite = new SpriteData(attrs);
this.sprites[k] = sprite;
}
// end
this.serializer.endExec();
});
});
}
/**
* Retrieves the sprites info from the emulator.
* @param slotIndices Array with all the slots to retrieve.
*/
protected getSprites(slotIndices: Array<number>) {
// Get sprites
this.serializer.exec(() => {
// Clear all sprites
for(let k=0; k<64; k++)
this.sprites[k] = undefined;
const func = (k) => {
// Get slot
const slot = this.slotIndices[k];
if(slot == undefined) {
// end
this.serializer.endExec();
return;
}
// Execute
Emulator.getTbblueSprites(slot, 1, sprites => {
const attrs = sprites[0];
const sprite = new SpriteData(attrs);
this.sprites[slot] = sprite;
// Next
func(k+1);
});
};
// Start recursive function
func(0);
});
}
/**
* Check if clipping window is set.
* If YES it also retrieves the sprite clipping coordinates.
*/
protected getSpritesClippingWindow() {
this.serializer.exec(() => {
// Check if clippping is set (Layer priority)
Emulator.getTbblueRegister(21, value => {
this.clippingEnabled = (value & 0x02) == 0;
if(!this.clippingEnabled) {
// end
this.serializer.endExec();
return;
}
// Get clipping
Emulator.getTbblueSpritesClippingWindow( (xl, xr, yt, yb) => {
this.clipXl = xl;
this.clipXr = xr;
this.clipYt = yt;
this.clipYb = yb;
// end
this.serializer.endExec();
return;
});
});
});
}
/**
* Retrieves the sprite patterns from the emulator.
* It knows which patterns to request from the loaded sprites.
* And it requests only that data that has not been requested before.
*/
protected getSpritePatterns() {
this.serializer.exec(() => {
// Get all unique patterns (do not request the same pattern twice)
let patternSet = new Set<number>();
for(const sprite of this.sprites) {
if(sprite && sprite.visible) {
const index = sprite.patternIndex;
patternSet.add(index);
}
}
// Change to array
this.patternIds = Array.from(patternSet);
// end
this.serializer.endExec();
});
// Call super
super.getSpritePatterns();
// Set the sprite bitmaps according to pattern, palette offset, mirroring and rotation.
this.serializer.exec(() => {
const palette = ZxNextSpritePatternsView.staticGetPaletteForSelectedIndex(this.usedPalette);
assert(palette);
for(const sprite of this.sprites) {
if(!sprite)
continue;
const pattern = ZxNextSpritePatternsView.spritePatterns.get(sprite.patternIndex);
if(pattern) { // Calm the transpiler
// Get palette with offset
const offs = sprite.paletteOffset
let usedPalette;
if(offs == 0)
usedPalette = palette;
else {
const index = 3*offs;
const firstPart = palette.slice(index);
const secondPart = palette.slice(0, index);
usedPalette = firstPart;
usedPalette.push(...secondPart);
}
sprite.createImageFromPattern(pattern, usedPalette,ZxNextSpritePatternsView.spritesPaletteTransparentIndex);
}
}
// end
this.serializer.endExec();
});
}
/**
* Retrieves the memory content and displays it.
* @param reason The reason is a data object that contains additional information.
* E.g. for 'step' it contains { step: true };
* If 'step'==true the sprite patterns will not be generally updated for performance reasons.
* If 'step' not defined then all required sprite patterns will be retrieved from the
* emulator. I.e. if you do a "break" after letting the program run.
*/
public update(reason?: any) {
// Save previous data
this.previousSprites = this.sprites;
this.sprites = new Array<SpriteData|undefined>(64);
// Check if all visible sprites should be shown automatically
if(this.slotIndices) {
// Reload sprites given by user
this.getSprites(this.slotIndices);
}
else {
// Get all sprites to check which are visible
this.getAllVisibleSprites();
}
// Get clipping window
this.getSpritesClippingWindow();
// Call super
super.update(reason);
}
/**
* Creates the js scripts and the UI elements.
*/
protected createScriptsAndButtons(): string {
let html = super.createScriptsAndButtons();
html += `
<script>
var zxBorderColor;
var zxScreenBckgColor;
var zxScreenFgColor;
//----- To change also the background color of the screen -----
function spriteBckgSelected() {
// First call general function
bckgSelected();
// Set colors in canvas
let selectedId = bckgSelector.selectedIndex;
let color = bckgSelector.options[selectedId].value;
zxScreenBckgColor = color;
if(color == "black") {
zxBorderColor = "gray";
zxScreenFgColor = "white";
}
else if(color == "white") {
zxBorderColor = "gray";
zxScreenFgColor = "black";
}
else if(color == "gray") {
zxBorderColor = "lightgray";
zxScreenFgColor = "black";
}
drawScreen();
}
// Change the function called when the background dropdown is chosen.
bckgSelector.onchange = spriteBckgSelected;
</script>
`;
return html;
}
/**
* Returns a table cell (td) and inserts the first value.
* If first and second value are different then the cell is made bold.
* @param currentValue The currentvalue to show.
* @param prevValue The previous value.
*/
protected getTableTdWithBold(currentValue: any, prevValue: any): string {
let td = ' <td>';
td += (currentValue == prevValue) ? currentValue : '<b>' + currentValue + '</b>';
td += '</td>\n';
return td;
}
/**
* Creates one html table out of the sprites data.
*/
protected createHtmlTable(): string {
const format = `
<table style="text-align: center" border="1" cellpadding="0">
<colgroup>
<col width="35em">
<col width="35em">
<col width="35em">
<col width="35em">
<col width="35em">
<col width="35em">
<col width="35em">
<col width="35em">
<col width="35em">
</colgroup>
<tr>
<th>Slot</th>
<th>X</th>
<th>Y</th>
<th>Image</th>
<th>X-M.</th>
<th>Y-M.</th>
<th>Rot.</th>
<th>Pal.</th>
<th>Pattern</th>
</tr>
%s
</table>
`;
// Create a string with the table itself.
let table = '';
for(let k=0; k<64; k++) {
const sprite = this.sprites[k];
if(!sprite)
continue;
const prevSprite = this.previousSprites[k];
table += '<tr">\n'
table += ' <td>' + k + '</td>\n'
if(sprite.visible) {
table += this.getTableTdWithBold(sprite.x, (prevSprite) ? prevSprite.x : -1);
table += this.getTableTdWithBold(sprite.y, (prevSprite) ? prevSprite.y : -1);
// Sprite image - convert to base64
const buf = Buffer.from(sprite.image);
const base64String = buf.toString('base64');
table += ' <td class="classPattern"><img src="data:image/gif;base64,' + base64String + '"></td>\n'
// Attributes
table += this.getTableTdWithBold(sprite.xMirrored, (prevSprite) ? prevSprite.xMirrored : -1);
table += this.getTableTdWithBold(sprite.yMirrored, (prevSprite) ? prevSprite.yMirrored : -1);
table += this.getTableTdWithBold(sprite.rotated, (prevSprite) ? prevSprite.rotated : -1);
table += this.getTableTdWithBold(sprite.paletteOffset, (prevSprite) ? prevSprite.paletteOffset : -1);
table += this.getTableTdWithBold(sprite.patternIndex, (prevSprite) ? prevSprite.patternIndex : -1);
}
else {
// Invisible
table += ' <td> - </td>\n <td> - </td>\n <td> - </td>\n <td> - </td>\n <td> - </td>\n <td> - </td>\n <td> - </td>\n <td> - </td>\n'
}
table += '</tr>\n\n';
}
const html = util.format(format, table);
return html;
}
/**
* Creates one html canvas to display the sprites on the "screen".
* The screen also shows the border and the clipping rectangle.
* Additionally alls sprites are drawn into together with their slot index.
*/
protected createHtmlCanvas(): string {
const format = `
<canvas id="screen" width="320px" height="256px" style="border:1px solid #c3c3c3;">
<script>
function drawScreen() {
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.imageSmoothingEnabled = false;
ctx.lineWidth=1;
ctx.translate(0.5, 0.5);
ctx.fillStyle = zxBorderColor;
ctx.fillRect(0,0,320,256);
ctx.fillStyle = zxScreenBckgColor;
ctx.fillRect(32,32,320-2*32,256-2*32);
%s
ctx.strokeStyle = zxScreenFgColor;
ctx.fillStyle = zxScreenFgColor;
%s
}
</script>
`;
// Html text for clipping
let clipHtml = '';
if(this.clippingEnabled) {
clipHtml += 'ctx.beginPath();\n';
clipHtml += 'ctx.strokeStyle = "red";\n';
clipHtml += util.format('ctx.rect(%d,%d,%d,%d);\n', this.clipXl+32, this.clipYt+32, this.clipXr-this.clipXl+1, this.clipYb-this.clipYt+1);
clipHtml += 'ctx.closePath();\n';
clipHtml += 'ctx.stroke();\n\n';
}
// Create the sprites
let spritesHtml = 'ctx.beginPath();\n';
for(let k=0; k<64; k++) {
const sprite = this.sprites[k];
if(!sprite)
continue;
if(!sprite.visible)
continue;
// Surrounding rectangle
spritesHtml += util.format("ctx.rect(%d,%d,%d,%d);\n", sprite.x, sprite.y, 16, 16);
// The slot index
spritesHtml += util.format('ctx.fillText("%d",%d,%d);\n', k, sprite.x+16+2, sprite.y+16);
// The image
const buf = Buffer.from(sprite.image);
const base64String = buf.toString('base64');
spritesHtml += util.format('var img%d = new Image();\n', k);
spritesHtml += util.format('img%d.onload = function() { ctx.drawImage(img%d,%d,%d); };\n', k, k, sprite.x, sprite.y);
spritesHtml += util.format('img%d.src = "data:image/gif;base64,%s";\n', k, base64String);
}
spritesHtml += 'ctx.closePath();\n';
spritesHtml += 'ctx.stroke();\n\n';
// Put everything together
const html = util.format(format,
clipHtml,
spritesHtml,
this.usedBckgColor);
return html;
}
/**
* Sets the html code to display the sprites.
*/
protected setHtml() {
const format = this.createHtmlSkeleton();
// Add content
const ui = this.createScriptsAndButtons();
const table = this.createHtmlTable();
const canvas = this.createHtmlCanvas();
const content = ui + table + '\n<p style="margin-bottom:3em;"></p>\n\n' + canvas;
const html = util.format(format, content);
this.vscodePanel.webview.html = html;
}
}
<file_sep>/src/debugadapter.ts
import { EmulDebugSessionClass } from './emuldebugadapter';
EmulDebugSessionClass.run(EmulDebugSessionClass);
<file_sep>/src/baseview.ts
'use strict';
import * as assert from 'assert';
import * as vscode from 'vscode';
import { CallSerializer } from './callserializer';
import { EventEmitter } from 'events';
/**
* A Webview that serves as base class for other views like the MemoryDumpView or the
* ZxNextSpritesView.
*/
export class BaseView {
// STATIC:
/// Holds a list of all derived view classes.
/// Used to call the static update functions.
public static staticViewClasses = new Array<any>();
/// Holds a list of all open views.
protected static staticViews = new Array<BaseView>();
/**
* Is called on 'update' event.
* First calls the static update functions.
* Afterwards the update funcions of all views.
* @param reason The reason is a data object that contains additional information.
* E.g. for 'step' it contains { step: true };
*/
public static staticCallUpdateFunctions(reason?: any) {
// Loop all view classes
for(const viewClass of BaseView.staticViewClasses) {
viewClass.staticUpdate(reason);
}
// Loop all views
for(const view of BaseView.staticViews) {
view.update(reason);
}
}
/**
* Closes all opened views.
* Is called when the debugger closes.
*/
public static staticCloseAll() {
// Copy view array
const views = BaseView.staticViews.map(view => view);
// Dispose/close all views
for(const view of views) {
view.vscodePanel.dispose();
}
}
/**
* Returns a list of all open views for a given class.
* @param viewClass A classname.
* @return All open views for the given class.
*/
public static staticGetAllViews(viewClass: any) {
// Get all views of the given class
const views = BaseView.staticViews.filter(view => view instanceof viewClass);
return views;
}
// DYNAMIC:
protected vscodePanel: vscode.WebviewPanel; ///< The panel to show the base view in vscode.
protected parent: EventEmitter; ///< We listen for 'update' on this emitter to update the html.
protected serializer = new CallSerializer('ViewUpdate');
/**
* Creates the basic view.
* @param parent The parent which may send 'update' notifications.
* @param handler Thhandler is called before the 'update' function is registered.
* The purpose is to register a static 'update' funtion before the dynamic ones.
*/
constructor(parent: EventEmitter, handler?: ()=>void) {
// Init
this.parent = parent;
// Add to view list
BaseView.staticViews.push(this);
// create vscode panel view
this.vscodePanel = vscode.window.createWebviewPanel('', '', {preserveFocus: true, viewColumn: vscode.ViewColumn.Nine}, {enableScripts: true});
// Handle closing of the view
this.vscodePanel.onDidDispose(() => {
// Remove from list
const index = BaseView.staticViews.indexOf(this);
assert(index !== -1)
BaseView.staticViews.splice(index, 1);
// Call overwritable function
this.disposeView();
});
// Handle hide/unhide.
// this.vscodePanel.onDidChangeViewState(e => {
// });
// Handle messages from the webview
this.vscodePanel.webview.onDidReceiveMessage(message => {
console.log("webView command '"+message.command+"':", message);
this.webViewMessageReceived(message);
});
}
/**
* Dispose the view (called e.g. on close).
* Use this to clean up additional stuff.
* Normally not required.
*/
public disposeView() {
// Can be overwritten
}
/**
* The web view posted a message to this view.
* @param message The message. message.command contains the command as a string.
* This needs to be created inside the web view.
*/
protected webViewMessageReceived(message: any) {
// Overwrite
}
/**
* A message is posted to the web view.
* @param message The message. message.command should contain the command as a string.
* This needs to be evaluated inside the web view.
* @param webview The webview to post to. Can be omitted, default is 'this'.
*/
protected sendMessageToWebView(message: any, webview: BaseView = this) {
webview.vscodePanel.webview.postMessage(message);
}
/**
* Retrieves the memory content and displays it.
* @param reason The reason is a data object that contains additional information.
* E.g. for 'step' it contains { step: true };
*/
public update(reason?: any) {
// Overwrite this.
}
}
<file_sep>/design/reversedebugging.md
# Reverse Debugging
The main idea is to support not only the (normal) forward stepping but also stepping backwards in time.
Due to emulator restrictions a lightweight approach is chosen.
Fortunately ZEsarUx supports a cpu-transaction-log.
This can record for each executed opcode
- the address
- the opcode
- the registers contents
I.e. while stepping backwards it would be possible to show the correct register contents at that point in time.
The memory contents or other HW states are not recorded.
Therefore this is a lightweight solution.
Anyhow in most cases the reverse debugging feature is used in case we hit a breakpoint and have to step back some opcodes to see why we ended up there.
Of course, knowing the correct memory contents would be beneficially but also without it will be a good help.
# Design
The whole cpu-transaction-log logic is implemented in the ZesaruxEmulator.
I.e. it is hidden from the Emulator class.
The Emulator/ZesaruxEmulator class has to provide methods for step back and running reverse.
When the ZesaruxEmulator class receives a stepBack for the first time it will open the transaction log. and the system is in reverse debugging mode.
It now reads the last line of the cpu-transaction-log file and retrieve
- the address
- the registers
- the opcode (as string)
```puml
hide footbox
title User pressed "Step Back"
actor user
participant vscode
participant "Emul\nDebug\nSession" as session
participant "Emulator" as emul
participant "ZEsarUX" as zesarux
user -> vscode: "Step Back"
vscode -> session: stepBackRequest
session -> emul: stepBack
session <-- emul
vscode <-- session: response
vscode <-- session: StoppedEvent('step')
vscode -> session: ...
vscode -> session: variablesRequest
session -> emul: getRegisters
session <-- emul
session -> emul: getMemoryDump
emul -> zesarux: read-memory
emul <-- zesarux
session <-- emul
vscode <-- session: response
```
Note: The registers are caught by the Emulator instance and returned from the cpu-transcation-log.
All other requests (like memory dump requests) will still go to the real emulator (ZEsarUX).
I.e. these values will not change during reverse debugging and may be potentially wrong, or better, they contain the value at the last executed machine cycle.
# Stepping in Reverse Debugging Mode
Not only "StepBack" need to be considered in reverse debug mode the other (forward) stepping procedures should work as well:
- ContinueReverse
- Continue
- StepOver
- StepInto
- StepOut
## Backward
### StepBack
The MSC is shown above.
"StepBack" simply moves up the transaction log by one.
### ContinueReverse
"ContinueReverse" moves up the transaction log until
- a breakpoint is hit or
- the file ends
## Forward
The forward procedures all work basically in 2 modes.
- the normal mode: stepping/runnning in the emulator, ZEsarUX)
- the reverse mode: stepping/runnning through the transaction log
Below are only the reverse procedures described.
### Continue
"Continue" moves down in the transaction log until
- a breakpoint is hit or
- the file ends
Note: When the file ends "Continue" stops. It does not automatically move over into "normal" continue mode.
### StepOver
"StepOver" needs to step over "CALL"s and "RST"s. This is not so simple as it seems.
**Approach A: Using PC**
If a "CALLxxx" (conditional or unconditional) is found the next expected step-over address is current_PC+3 (PC=program counter).
If a "RST" is found the next expected address is PC+1. With ESXDOS RST implementation it is PC+2.
If a "JR"/"JP"/"DJNZ" is found it is either the next address or the jump-to-address.
If a "RETx" (conditional or unconditional) is found it is either the next address or some address from the stack.
I.e. with all this it is not possible to clarify if the next address(es) should be skipped because it is an interrupt or if "StepOver" should stop.
Example:
A "RET" is found. So there is no hint what address to expect next. If the same time the interrupt kicks in with some address "StepOver" would stop here and not skip it.
**Approach B: Using SP (better)**
The idea is that if a subroutine is "CALL"ed then the SP (stack pointeR) will decrease by 2.
I.e. if no subroutine is called the SP will not change.
I.e. the algorithm simply searches the transaction log downwards until a line with the same SP is found.
If an interrupt would kick in the SP changes and the interrupt would be skipped.
Some instructions change the SP intentionally. This instructions need special care:
- "PUSH": the expected_SP is SP-2
- "POP": the expected_SP is SP+2
- "DEC SP": the expected_SP is SP-1
- "INC SP": the expected_SP is SP+1
- "LD SP,nnnn": the expected_SP is nnnn
- "LD SP,HL": the expected_SP is HL
- "LD SP,IX": the expected_SP is IX
- "LD SP,IY": the expected_SP is IY
- "LD SP,(nnnn)": the expected_SP is unknown. In this case simply the next line is executed. This would be wrong only if an interrupt kicks in. As this command is used very rarely and it shouldn't be used while an interrupt is active this should almost never happen.
- "RETx": the expected_SP is either SP+2 or it could also be SP in case of a conditional RET. So both are checked. Note: for ease of implementation conditional and unconditonal RET is not distinguished.
Note: If during moving through the transaction log a breakpoint is hit "StepOver" stops.
### StepInto
"StepInto" simply moves down the transaction log by one.
If an interrupt kicks-in it steps into the interrupt.
### StepOut
"StepOut" moves down the transaction log until
- a breakpoint is hit or
- a "RETx" (conditional or unconditional) is found
**Approach A:**
If a "RETx" is found the SP value is stored and the next line is analysed.
if SP has been decremented by 2 the RET was executed. If so "StepOut" stops otherwise it continues.
Note:
If an interrupts happens right after the "RETx" it should be skipped because then the next SP wouldn't be decremented by 2.
Problems:
- If an interrupt kicks in anywhere else and returns then this "RETI" is found and "StepOut" stops.
One could ignore the "RETI" but then "StepOut" of an interrupt would not work.
**Approach B: (better)**
The current SP is is stored and the transaction log is analyzed until a "RET" is found and the next line contains an SP that is bigger than the original SP.
Notes:
- as POP etc. can also modify the SP, it is searched for a "RET" and the SP of the following line. This could go wrong if the SP changes w.g. because of a POP and then a "RET cc" (conditional) is not executed. In that case the algorthm will stop although we have not really stepped out.
- it is searched for an SP bigger than and not for an SP that is equal to the old SP+2 because it may happen that the stack is manipulated. In general manipulation could happen in both directions but in order to skip an kicking in interrupt it is only checked that it is bigger.
### Interrupts
The transaction log simply records the executed addressed. This also means that the interrupts are inserted when they occur.
### Breakpoints
During forward or reverse stepping/running the breakpoint addresses are evaluated.
If a breakpoint address is reached "execution" is stopped.
The breakpoint condition is **not** evaluated.
This has 2 reasons:
- effort for doing so would be quite high but the use case scenarios are limited
- even if implemented it could lead to false positives in case memory conditions are checked. The memory is not changed during reverse debugging, i.e. it may contain false value for the current PC address.
Of course, one could evaluate at lest the conditions without memory, i.e. the register related only, maybe this is done in the future.
# Other Requests
- scopesRequest: No special behavior.
- stackTraceRequest: No special behavior. As the memory contents changes are not known this will simply return the current memory state at the time the reverse debugging was entered.
- variablesRequest: No special behavior. The only special variables that change are the registers. These are special treated in the Emulator.
# Open
- Soll ich tstates Information anzeigen?
- müsste ich ja auch aufsummieren bei "reverseContinue" bis zum BreakPoint.
- init() vom ZesaruxTransactionLog ist in CodeCoverage Funktion. Das muss ich umdesignen.
- Wenn sowieso immer alle Register gebracht werden in dem CPU transaction log, dann ist die address Information redundant, da sie auch in den Registern vorhanden ist. Ich kann also 5 byte sparen, wenn ich die Adress Info nicht mehr explizit anfordere sondern aus "PC=xxxx" extrahiere.
## Pseudocode (ZEsarUX):
### Step back
1. "cpu-step-back" is received: Mode is changed to "reverse-debug-mode". The rl_index is decreased.
3. "get-registers" is received: The register values from the record_list[rl_index] is sent.
3. "get-stack-trace" is received: ??? need to check how this list is generated. If it is a simple memory lookup then I need to save the memory values for sure.
### Continue reverse
1. "run-reverse" is received: Mode is changed to "reverse-debug-mode". The rl_index is decreased in a loop until (this is done very fast)
a) the list start is reached
b) a breakpoint condition is met
2. "get-registers" is received: ... same as above
### Step (forward)
1. "cpu-step" is received while in "reverse-debug-mode". The rl_index is increased.
~~~
If rl_index > record_list then: leave "reverse-debug-mode".
~~~
2. "get-registers" is received: ... same as above
### Continue (forward)
1. "run" is received while in "reverse-debug-mode". The rl_index is increased in a loop until (this is done very fast)
a) the list end is reached: leave "reverse-debug-mode". Run normal "run" (i.e. continue seemingless with normal run mode).
b) a breakpoint condition is met
2. "get-registers" is received: ... same as above
### Get historic registers
1. "get-historic-register reg" is received: The record list is checked for changes in the register. The current and the past values are sent together with PC values and information when the change happened. E.g.
~~~
-> "get-historic-register DE"
<-
DE=5F8A
DE=34E9 PC=A123 dCount=15
DE=7896 PC=A089 dCount=2343
~~~
Note: dCount (differential count) is a decimal number, i.e. it can grow bigger than FFFFh.
vscode could show this when hovering above a register.
Note: this would require to read always the complete transaction-log.
# Length of the recording
The transaction log can become very big very fast. Each transaction will occupy about 100 bytes. I.e. at a 4MHZ clock speed we will generate about 100MB of data.
Or 1GB per 10 secs. A minute will generate 6GB and an hour generates 360GB.
In modern PCs this is manageable as normally one would require to run a program only for a few secs, maybe minutes.
But in some cases, when e.g. hunting a bug that very rarely occurs and were the system e.g. would have to run over night, it would be more beneficial to have an option to limit the max. length of the transaction log and store only the last transactions.
Like a queue that forgets the oldest entries.
<This is currently discussed with Cesar>.
# Reaching the End of the Recording
When reaching the end of the recording it is not possible to step back further.
# Breakpoints
Running inside the transaction log will, of course, not fire any of the ZEsarUX breakpoints. Neither when running backwards nor forward.
There are several options:
- ignore breakpoints: running would run til the end of the transaction log. This is not helpful. In fact it would be mean that running backward does not work only stepping backward.
- ignore breakpoint conditions (other than the PC): This would be simple to implement and would already cover a lot of use case.
- mimic the breakpoint conditions: the breakpoint conditions could be evaluated during running inside the transaction-log. This would be one of the best options although the most difficult to implement. It is also questionable how many use cases this will really include as the memory conditions can anyway not be tested. So we can only check on register values.
# Additional Features
Ideas:
- E.g. history of registers:
It would be possible to have a look at the registers, e.g. when they changed. With a click one could move to the source code location/time when the change happened.
| c71e4850377677d5819ba5caaec0b185c5bea7b8 | [
"Markdown",
"TypeScript"
] | 13 | TypeScript | andrivet/z80-debug | 7cd21f7a8af492010024739ac60df386d0e215ea | 98a5fc0c9718cff89d3fecff5c5554b867a68458 |
refs/heads/master | <file_sep>import { PixiComponent, applyDefaultProps, Container } from "@inlet/react-pixi";
import * as PIXI from 'pixi.js';
import * as particles from 'pixi-particles';
import { ComponentProps } from "react";
interface Props {
image: string;
config: particles.OldEmitterConfig | particles.EmitterConfig;
};
const ParticleEmitter = PixiComponent<Props & ComponentProps<typeof Container>, PIXI.ParticleContainer>("ParticleEmitter", {
create() {
return new PIXI.ParticleContainer();
},
applyProps(instance, oldProps: Props, newProps: Props) {
const { image, config, ...newP } = newProps;
// apply rest props to PIXI.ParticleContainer
applyDefaultProps(instance, oldProps, newP);
let emitter = (this as any)._emitter;
if (!emitter) {
emitter = new particles.Emitter(
instance,
[PIXI.Texture.from(image)],
config
);
let elapsed = performance.now();
const tick = () => {
emitter.raf = requestAnimationFrame(tick);
const now = performance.now();
emitter.update((now - elapsed) * 0.0003);
elapsed = now;
};
emitter.emit = true;
tick();
}
(this as any)._emitter = emitter;
},
willUnmount() {
if ((this as any)._emitter) {
(this as any)._emitter.emit = false;
cancelAnimationFrame((this as any)._emitter.raf);
}
}
});
export default ParticleEmitter;<file_sep># Conflict resolution
https://education21cc.github.io/conflictresolution/
`npm run start`: starts in local testing mode
`npm run deploy`: builds the 'player' version and deploys to https://education21cc.github.io/conflictresolution/
<file_sep>
export interface ConflictContent {
header: string;
position: number[];
description: string;
sequence: SequenceItem[];
scene: SceneElement[];
situationSpeech: string;
options: string[];
reactions: ConflictReaction[];
}
export interface SceneElement {
image?: string;
type?: SceneElementType;
position?: [number, number];
scale?: number;
flipped: boolean;
pose: AvatarPose;
}
export enum SceneElementType {
sprite = "sprite",
avatar = "avatar",
}
export enum AvatarPose {
angle = "angle",
front = "front",
side = "side",
angry = "angry"
}
export interface ConflictReaction {
correct: boolean,
text: string,
scene: SceneElement[];
confirmText: string,
yesText: string;
noText: string;
confirmImage?: string
}
export enum SequenceItemType {
caption = 'caption',
speech = 'speech',
image = 'image', // image, no speech
}
export interface SequenceItem {
type: SequenceItemType,
text: string,
balloonArrowPos?: number;
scene?: SceneElement[]; // optional override
}<file_sep>export interface GameData<T> {
userId: number;
settings: Settings;
content: T;
translations: Translation[];
levelsCompleted: Level[];
}
export interface Settings {
muted: boolean;
}
export interface Translation {
key: string;
value: string;
}
export interface Level {
level: number;
score: number;
maxScore: number;
} | 929e37dfe458f8fa2b704d202735be15c38ab985 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | education21cc/conflictresolution | 7ec02322afb2c1e0392db1413e26364db529b76b | fb41ecefbd780d5cabc3aa6a48bbc194429fc524 |
refs/heads/master | <file_sep>package org.onboarding.activities;
import java.util.Stack;
/**
* Methods ask for by On-boarding team at work
*
*/
public class Methods {
/**
* Checks to see if a credit card number is valid.
*
* The card number must be between 14 and 19 digits long and pass the Luhn algorithm
*
* @param card is the number tied to the card.
* @return true if card is between 14-19 digits long and lastDigit equals the calculatedSum.
*
* @author <NAME>
*/
public static boolean verifyCreditCard(Long card) {
StringBuilder cardForUse = new StringBuilder(card.toString());
if (cardForUse.length() < 14 || cardForUse.length() > 19) {
return false;
}
// take the last digit to check if the card number is a valid at the end
int lastDigit = (int)(card % 10);
// remove the check digit from the number to check against at the end
cardForUse.deleteCharAt(cardForUse.length() - 1);
cardForUse.reverse();
int sumOfCardNums = 0;
for (int i = 0; i < cardForUse.length(); i++) {
// get the next digit in the series
int num = Integer.parseInt(String.valueOf(cardForUse.charAt(i)));
// every second digit is multiplied by 2
num = ((i + 1) % 2 != 0) ? num * 2 : num;
// if digit became greater than 10, add the numbers together to produce a single digit
if (num >= 10) {
num = (num % 10) + (num / 10);
}
// add all the digits together
sumOfCardNums += num;
}
int calculatedSum = 10 - (sumOfCardNums %10);
// check the calculated sum against the check digit from before
if (lastDigit == calculatedSum) {
return true;
}else {
return false;
}
}
/**
* Encrypts a String using the ROT13 technique
*
* Letters will be changed to the 13th letter higher than the letter in question, wrapping from z to a if necessary.
* Characters that are not letters are not encrypted or changed.
*
* @param message is the String to be encrypted.
* @return a String that is the message with all the letters shifted 13 letters.
*
* @author <NAME>
*/
public static String encryptROT13(String message) {
// the char array is used to access the letters
char[] arr = message.toCharArray();
// the string builder will hold the encrypted letters until the end
StringBuilder sb = new StringBuilder();
for (char a : arr) {
// the current character is assigned to b and if it is a letter it will be encrypted
char b = a;
// if the character is not a letter it does not go through the encryption process
if (Character.isLetter(a)) {
// if the letter is smaller than n shift 13 places up the alphabet (b -> o)
if (a < 'n' && a >= 'a' || a < 'N' && a >= 'A' ) {
b = (char) (a + 13);
// otherwise shift the letter 13 places down the alphabet (s -> f) so to keep the letter a letter
}else {
b = (char) (a - 13);
}
}
// the character, letter or not, is assigned to the string builder to create the encrypted message
sb.append(b);
}
// return the encrypted message
return sb.toString();
}
/**
* Take a base 10 number and turns it into a base 8 number
*
* To turn a number from one base into the equivalent number in a different base,
* divide the original number number by the new base and take the remainder as the
* first digit in the new number. Repeat this until all that is left is a remainder
* and you will have the new number.
*
* @param decimal a number using base 10
*
* @return octal an integer number using base 8
*/
public static int decimalToOctal(int decimal) {
// will put each digit in a stack
Stack<Integer> stack = new Stack<Integer>();
// will put the digits from the stack into a string builder
StringBuilder sb = new StringBuilder();
// if keepGoing is true the do-while loop will continue
// if the decimal number is less than or equal to 8 keepGoing will be set to false
boolean keepGoing = true;
// converting the number for base 10 to base 8
do {
// if the last number is an 8, put a 10 in the stack instead of a 0
if (decimal <= 8) {
// time to end the do-while loop
keepGoing = false;
int temp = decimal % 8;
if (temp == 0) {
temp = 10;
}
stack.push(temp);
// if it is not the last number put the remainder of number divided by 8 into the stack
}else {
stack.push(decimal % 8);
}
// Divide by 8 to get the next number ready
decimal /= 8;
}while (keepGoing);
// assemble the new number from the stack
while (!stack.empty()) {
sb.append(stack.pop());
}
// turn the string builder number into an int
int octal = Integer.valueOf(sb.toString());
// return the new octal number
return octal;
}
}
<file_sep>package org.onboarding.activities;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Unit test for Methods.encryptROT13
*
* @author <NAME>
*
*/
public class ROT13Test {
/**
* Tests the method encryptROT13 using a single word
*/
@Test
public void testAWordEncryptROT13() {
String word = "Encrypted";
// use the encryption method to encrypt the word
String encryptedWord = Methods.encryptROT13(word);
// make sure they do not equal each other
assertFalse(word.equals(encryptedWord));
// make user that the encrypted word equals what it should
assertTrue(encryptedWord.equals("Rapelcgrq"));
}
/**
* Tests the method encryptROT13 using multiple words
*/
@Test
public void testMessageEncryptROT13() {
String word = "The quick brown fox jumped over the lazy dogs";
// use the encryption method to encrypt the message
String encryptedWord = Methods.encryptROT13(word);
// make sure they do not equal each other
assertFalse(word.equals(encryptedWord));
// make user that the encrypted message equals what it should
assertTrue(encryptedWord.equals("Gur dhvpx oebja sbk whzcrq bire gur ynml qbtf"));
}
/**
* Tests the method encryptROT13 using multiple words and symbols
*/
@Test
public void testMessageWithSymbolsEncryptROT13() {
String word = "These 10 words are 2 be encrypted but not $&!$#";
// use the encryption method to encrypt the message with symbols
String encryptedWord = Methods.encryptROT13(word);
// make sure they do not equal each other
assertFalse(word.equals(encryptedWord));
// make user that the encrypted message with symbols equals what it should
assertTrue(encryptedWord.equals("Gurfr 10 jbeqf ner 2 or rapelcgrq ohg abg $&!$#"));
}
}
| d4f91ada8b022f511a0f94873e7d02975d03da53 | [
"Java"
] | 2 | Java | Peter-Fowler/activities | d61462851822e256b8ae8e365592ed7fcaa2a0f5 | b50531b711afe8f01c75c95144947e6e9b20d2f3 |
refs/heads/master | <repo_name>marlomajor/Task_Manager<file_sep>/app/controllers/.#task_manager_app.rb
<EMAIL>major@Marlos-MacBook-Pro.local.96483<file_sep>/test/models/task_manager_test.rb
require_relative '../test_helper'
class TaskManagerTest < Minitest::Test
def test_it_creates_a_task
TaskManager.create({ :title => "My title",
:description => "get stuff done"})
task = TaskManager.find(1)
assert_equal 1, task.id
assert_equal "My title", task.title
assert_equal "get stuff done", task.description
end
def test_returns_all_method
TaskManager.create({ :title => "My title",
:description => "get stuff done"})
end
def test_it_updates_a_task
TaskManager.create({ :title => "My title",
:description => "get stuff done"})
TaskManager.update(1,
{ :title => "My title", :description => "Get MORE stuff done"})
task = TaskManager.find(1)
assert_equal 1, task.id
assert_equal "Get MORE stuff done", task.description
end
# def test_it_deletes_a_task
# TaskManager.create({ :title => "My title",
# :description => "get stuff done"})
# TaskManager.delete(1)
# task = TaskManager.find(1)
#
# assert_equal [], task.id
# assert_equal [], task.description
# end
end
<file_sep>/test/features/user_can_edit_a_task.rb
require_relative "../test_helper"
class EditTaskTest < FeatureTest
def user_can_edit_a_task
TaskManager.create(title: "New Task", description: "New Task Description")
visit "/tasks"
click_link "Edit"
assert_equal "/tasks/1/edit"
fill_in "task[title]", with: "Edited Task"
fill_in "task[description]", with: "Edited Task Description"
click_button "Update task"
assert_equal "/tasks", current_path
assert page.has_css?("tasks")
end
end
<file_sep>/test/features/user_creates_task_test.rb
require_relative '../test_helper'
class CreateTaskTest < FeatureTest
def test_user_can_create_a_task
save_and_open_page
visit "/tasks/new"
fill_in('task[title]', with:"My title")
fill_in('task[description]', with:"This is test content")
click_link_or_button("Submit")
assert_equal "/tasks", current_path
assert_equal
end
end
| e8403b27da677151937294f532d3b1d978eb1c8b | [
"Ruby"
] | 4 | Ruby | marlomajor/Task_Manager | 09c5946e4ebcee34d8308a54c6e356149acd5bff | 6faf414fe5c165b46059ca24f852d68368955ba1 |
refs/heads/master | <file_sep>package Introduction;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.mathmadesimple.R;
/**
* This Activity represents the first introduction and the introduction of the developer avatar
* Leading to activity Introduction 3
*/
public class Introduction2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_introduction2);
Button buttonToIntroduction3 = findViewById(R.id.buttonToIntroduction3);
buttonToIntroduction3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentToIntroduction3 = new Intent(getApplicationContext(), Introduction3.class);
startActivity(intentToIntroduction3);
}
});
}
}<file_sep>package SimpleMathOperations;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.mathmadesimple.R;
public class SimpleMathOperationsMain extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_math_operations_main);
}
}<file_sep>include ':app'
rootProject.name = "Math Made Simple"<file_sep>package MainMenu;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mathmadesimple.R;
/**
* This class is responsible for dynamically representing the topics of the Math-Made-Simple App visually through Buttons.
*/
public class MainMenuAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutinflaterMainMenu;
private String[] itemsMainMenu;
private int[] pictureItemsMainMenuIDs;
public MainMenuAdapter (Context contextMainMenu, String[] itemsMainMenu, int [] pictureItemsMainMenuIDs) {
context = contextMainMenu;
this.itemsMainMenu = itemsMainMenu;
this.pictureItemsMainMenuIDs = pictureItemsMainMenuIDs;
}
@Override
public int getCount() {
return itemsMainMenu.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (layoutinflaterMainMenu == null) {
layoutinflaterMainMenu = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = layoutinflaterMainMenu.inflate(R.layout.grid_menu_item, null);
}
ImageView logoMainMenu = convertView.findViewById(R.id.logo_main_menu);
TextView logoTextMainMenu = convertView.findViewById(R.id.main_menu_text);
logoMainMenu.setImageResource(pictureItemsMainMenuIDs[position]);
logoTextMainMenu.setText(itemsMainMenu[position]);
return convertView;
}
}
<file_sep>package MainMenu;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.mathmadesimple.R;
import SimpleMathOperations.SimpleMathOperationsMain;
/**
* This class represents the Main Menu and comes after the Introduction.
* This activity displays the various topics of the Math-Made-Simple App.
* With a click on either button you switch into the respective topic overview (= switching to the package with the topic name)
*/
public class MainMenu extends AppCompatActivity {
GridView gridViewMainMenu;
String[] itemsMainMenu = {"Geomotry", "Simple Math Operations", "Graphs", "Functions", "Fractions", "Percents", "Exercise", "Test"};
int[] pictureItemsMainMenuIDs = {R.drawable.logo_geometry, R.drawable.logo_simple_math_operations,R.drawable.logo_graphs, R.drawable.logo_functions, R.drawable.logo_fractions, R.drawable.logo_percents, R.drawable.logo_exercise, R.drawable.logo_test};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
gridViewMainMenu = findViewById(R.id.grid_view_main_menu);
MainMenuAdapter mainMenuAdapter = new MainMenuAdapter (MainMenu.this, itemsMainMenu, pictureItemsMainMenuIDs);
gridViewMainMenu.setAdapter(mainMenuAdapter);
gridViewMainMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "You clicked " + itemsMainMenu[i], Toast.LENGTH_SHORT).show();
switch (itemsMainMenu[i]) {
case "Simple Math Operations":
Intent intentToSimpleMathOperationsMain = new Intent(getApplicationContext(), SimpleMathOperationsMain.class);
startActivity(intentToSimpleMathOperationsMain);
break;
default:
Toast.makeText(getApplicationContext(), "You called an Item that was not available in the list", Toast.LENGTH_LONG).show();
break;
}
}
});
}
} | 9b55b212f76879316c092102e60fa151b2cf4567 | [
"Java",
"Gradle"
] | 5 | Java | Cpt-Aramus/Math_Made_Simple | f57507e5dce6375ed1d8294659beba0d444f7dc1 | b9e213ba6c29e220a83aadb422ba92ada0c9f48e |
refs/heads/master | <repo_name>fabio1079/my-configs<file_sep>/setup.sh
#!/bin/bash
cp .gitconfig ~
function setup_neovim() {
mkdir -p ~/.config/nvim
cp init.vim ~/.config/nvim/
sudo apt-get install neovim
curl -fLo ~/.local/share/nvim/site/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
nvim -c ":PlugInstall"
}
setup_neovim
cp .bash_config ~/.bash_config
echo "source ~/.bash_config" >> ~/.bashrc
<file_sep>/.bash_config
#!/bin/bash
function git_branch_name() {
git branch 2>/dev/null | grep -e '^*' | sed -E 's/^\* (.+)$/(\1) /'
}
function show_colored_git_branch_in_prompt() {
PS1="\[\033[01;32m\]\u@\h:\[\033[01;34m\]\w\[\033[31m\]\$(git_branch_name)\[\033[m\]$ "
}
show_colored_git_branch_in_prompt
alias doki="sudo docker images $@"
alias sdc="sudo docker-compose $@"
| 4ec82c81f55d4fc476e28c37b9dd41a9abf4fa76 | [
"Shell"
] | 2 | Shell | fabio1079/my-configs | 8f3438e475d55118213740284ffaf2b6598af0be | aa854c1532d24877289c3c333773f860f16ccf5d |
refs/heads/master | <repo_name>simont789/TestGUI-2<file_sep>/TestGUIBegin/LuceneApplication.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lucene.Net.Analysis; // for analyser
using Lucene.Net.Analysis.Standard; // for standard analyser
using Lucene.Net.Documents; // for document
using Lucene.Net.Index; //for index writer
using Lucene.Net.QueryParsers; // for query parser
using Lucene.Net.Search;
using Lucene.Net.Store; //for Directory
using System.IO;
namespace LuceneApplicationForIFN647Project
{
class LuceneApplication
{
Lucene.Net.Store.Directory directory;
Lucene.Net.Analysis.Analyzer analyzer;
Lucene.Net.Index.IndexWriter indexWriter;
IndexSearcher indexSearcher;
QueryParser queryParser;
Lucene.Net.Search.TopDocs topdocs;
const Lucene.Net.Util.Version VERSION = Lucene.Net.Util.Version.LUCENE_30;
const string DOCID_FN = "DocID";
const string TITLE_FN = "Title";
const string AUTHOR_FN = "Author";
const string BIBLIOGRAPHICINFORMATION_FN = "BibliographicInformation";
const string ABSTRACT_FN = "Abstract";
public LuceneApplication()
{
directory = null;
indexWriter = null;
indexSearcher = null;
queryParser = null;
analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(VERSION); ;
}
/// <summary>
/// Creates the index at indexPath
/// </summary>
/// <param name="indexPath">Directory path to create the index</param>
public void CreateIndexFrom(string indexPath)
{
IndexWriter.MaxFieldLength mfl = new IndexWriter.MaxFieldLength(IndexWriter.DEFAULT_MAX_FIELD_LENGTH);
directory = Lucene.Net.Store.FSDirectory.Open(indexPath);
indexWriter = new Lucene.Net.Index.IndexWriter(directory, analyzer, true, mfl);
}
public void ReadTextFilesAndIndexTextFrom(string collectionPath)
{
try
{
foreach (string file in System.IO.Directory.EnumerateFiles(collectionPath))
{
string acadamicPublicationFile = File.ReadAllText(file);
indexWriter.AddDocument(CreateDocWith(acadamicPublicationFile));
}
}
catch (Exception e) {
Console.WriteLine(e);
}
}
public Lucene.Net.Documents.Document CreateDocWith(string fileContent) {
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
string[] tags = { ".I", "\n.T\n", "\n.A\n", "\n.B\n", "\n.W\n" };
string[] splitedContentWithTags = fileContent.Split(tags, StringSplitOptions.None);
// edit indexing method here
doc.Add(new Field(DOCID_FN, splitedContentWithTags[0], Field.Store.NO, Field.Index.NO));
doc.Add(new Field(TITLE_FN, splitedContentWithTags[1], Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field(AUTHOR_FN, splitedContentWithTags[2], Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field(BIBLIOGRAPHICINFORMATION_FN,
splitedContentWithTags[4].Replace(splitedContentWithTags[1] + "\n", ""), // remove title from abstract
Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field(ABSTRACT_FN, splitedContentWithTags[4], Field.Store.YES, Field.Index.ANALYZED));
return doc;
}
/// <summary>
/// Flushes the buffer and closes the index
/// </summary>
public void CleanUpIndexer()
{
indexWriter.Optimize();
indexWriter.Flush(true, true, true);
indexWriter.Dispose();
}
public string ExpandQuery()
{
string result = "";
return result;
}
/// <summary>
/// Creates objects to start up the search
/// </summary>
public void SetupSearch()
{
indexSearcher = new IndexSearcher(directory);
// parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, TITLE_FN, analyzer);
// parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, AUTHOR_FN, analyzer); // activiy 6
// parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, PUBLISHER_FN, analyzer); // activity 6
queryParser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, new[] { AUTHOR_FN, TITLE_FN }, analyzer); // activity 8
}
/// <summary>
/// Cleans up afer a search
/// </summary>
public void CleanupSearch()
{
indexSearcher.Dispose();
}
public void SearchFor(string querytext)
{
querytext = querytext.ToLower();
Query query = queryParser.Parse(querytext);
topdocs = indexSearcher.Search(query, 100);
System.Console.WriteLine("Found " + results.TotalHits + " documents.");
}
public AcadamicPublication GetAcadamicPublicationAt(int rank)
{
ScoreDoc[] results = topdocs.ScoreDocs;
AcadamicPublication newAP = new AcadamicPublication();
Lucene.Net.Documents.Document doc = indexSearcher.Doc(results[i].Doc);
newAP.DocID = doc.Get(DOCID_FN);
newAP.Title = doc.Get(TITLE_FN);
newAP.Author = doc.Get(AUTHOR_FN);
newAP.BibliographicInformation = doc.Get(BIBLIOGRAPHICINFORMATION_FN);
newAP.Abstract = doc.Get(ABSTRACT_FN);
return newAP;
}
}
}<file_sep>/TestGUIBegin/GUIForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LuceneApplicationForIFN647Project;
namespace TestGUI
{
public partial class GUIForm : Form
{
LuceneApplication lapp;
protected int pageCount;
public GUIForm()
{
InitializeComponent();
lapp = new LuceneApplication();
pageCount = 0;
}
private void CreateIndexAtPathBottonHandler(object sender, EventArgs e)
{
lapp.CreateIndexFrom(IndexPathTextBox.Text);
lapp.ReadTextFilesAndIndexTextFrom(CollectionPathTextBox.Text);
lapp.CleanUpIndexer();
}
private void SearchButtonHandler(object sender, EventArgs e)
{
lapp.SetupSearch();
string expandedQeury = lapp.ExpandQuery(QueryTextBox.Text);
FinalQueryLabel.Text = expandedQeury;
topdocs = lapp.SearchFor(expandedQeury);
// search index with EXPANDED and WEIGHTED querytext from textbox
// show result in resultlabel, rank 1 to 10
}
private void SearchAsIsButtonHandler(object sender, EventArgs e)
{
lapp.SetupSearch();
FinalQueryLabel.Text = QueryTextBox.Text;
lapp.SearchFor(QueryTextBox.Text);
// show number of results number of results
// show index time
ShowResult();
}
private void ViewLastPageButtonHandler(object sender, EventArgs e)
{
pageCount += 10;
ShowResult();
}
private void ViewNextPageButtonHandler(object sender, EventArgs e)
{
pageCount -= 10;
ShowResult();
}
private void ShowResult()
{
for (int i = pageCount; i < (pageCount + 10); i++)
{
AcadamicPublication ap = lapp.GetAcadamicPublicationAt(i);
// print on labels
}
}
private void RestartSectionBottonHandler(object sender, EventArgs e)
{
}
private void SaveAsButtonHandler(object sender, EventArgs e)
{
}
}
}
<file_sep>/TestGUIBegin/QueryExpansion.cs
using System;
namespace TestGUIBegin
{
public class QueryExpansion
{
public QueryExpansion()
{
}
}
}
| 2a8fe97bcb5072c0212d25f57bfb81deaf6ddb2a | [
"C#"
] | 3 | C# | simont789/TestGUI-2 | e777777750c2fa1333a8d9a2e9bab4711d3cab6c | 8dcbe19acc3a6ba6d1bcf63257fc9f02f5c7fcd8 |
refs/heads/master | <repo_name>mur-ururu/searchTool<file_sep>/fuzzySearch/fsFuzzySearch.h
#pragma once
#include <string>
#include <vector>
namespace FS
{
//------------------------------------------------------------------------------
class Metrics
/*
** для двух строк - str и prefix -
** вычисляет расстояние Дамерау-Левенштейна (расстояние редактирования) методом Вагнера-Фишера;
** асимптотика : время - O(str.length()*prefix.length()), память - O( max(maxLength, prefix.length()) ).
** int max - максимально допустимое количество операций редактирования
** (вставка символа, замена символа, удаление символа, транспозация символов).
*/
{
public:
Metrics(int maxLength);
int getDistance (const std::string & str, const std::string & prefix, int max);
private:
std::vector <int> currentRow;
std::vector <int> previousRow;
std::vector <int> transpositionRow;
const int MaxDist;
};
//------------------------------------------------------------------------------
class FuzzySearcher
/*
** Jпределяет, является ли расстояние между строками допустимым;
** допустимое расстояние между строками
** зависит от длины подстроки, которую ищем.
**
*/
{
private:
const double MaxDistGrad;
Metrics M;
public:
FuzzySearcher() : MaxDistGrad (1 / 4.0), M(255) {}
bool FirstInSecond (const std::string & WhatToFind, const std::string & WhereToFind, int & dist);
};
//------------------------------------------------------------------------------
}
<file_sep>/fuzzySearch/fsSearch.cpp
#include "fsSearch.h"
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace fsUtility;
using namespace FS;
using namespace Precise_And_Fuzzy_Search;
//------------------------------------------------------------------------------
StrToFindMaster::StrToFindMaster (const string &StrToFind)
: WordsQuanDefault(4), WrongLayout(false)
{
ToFind = &StrToFind;
words.reserve(WordsQuanDefault);
SplitIntoWords(*ToFind, ' ', words);
if ( AM.IsLatin(*ToFind))
{
WrongLayout = true;
CyrillicCopy = *ToFind;
AM.ToCyrillic (CyrillicCopy);
boost::to_upper(CyrillicCopy);
}
}
//------------------------------------------------------------------------------
const string * StrToFindMaster::GetStrToFind()
{
return ToFind;
}
//------------------------------------------------------------------------------
MSP_Searcher::MSP_Searcher (const string &StrToFind)
: StrMaster (StrToFind), ResultsSizeDefault (16),
Founds(false), FoundsWithMistakes(false)
{
Matches.reserve(ResultsSizeDefault);
if (StrMaster.WrongLayout) {
Matches_If_WrongLayout.reserve(ResultsSizeDefault);
}
// По умолчанию результат будем искать среди точных совпадений.
Result = &Matches;
}
//------------------------------------------------------------------------------
void MSP_Searcher::AddResult(mspFuz & mspFuz)
{
Result->push_back(mspFuz);
}
//------------------------------------------------------------------------------
MSP_PreciseSearcher::MSP_PreciseSearcher (const string &StrToFind)
: MSP_Searcher (StrToFind)
{
}
//------------------------------------------------------------------------------
bool MSP_PreciseSearcher::DoesMatch(const string & WhereToFind)
{
bool res = false;
if (WhereToFind.find(*StrMaster.GetStrToFind()) != WhereToFind.npos) {
Result = &Matches;
res = true;
}
else if (StrMaster.WrongLayout
&& WhereToFind.find(StrMaster.CyrillicCopy) != WhereToFind.npos) {
Result = &Matches_If_WrongLayout;
res = true;
}
return res;
}
//------------------------------------------------------------------------------
void MSP_PreciseSearcher::GetResult()
{
if (!Matches.empty()) { Result = &Matches; Founds = true;}
// Для данной подстроки совпадений в базе не найдено.
// Проверим, нет ли совпадений для подстроки, обращенной в кириллицу.
else if (!Matches_If_WrongLayout.empty()) {
Result = &Matches_If_WrongLayout;
FoundsWithMistakes = true;
}
}
//------------------------------------------------------------------------------
MSP_FuzzySearcher::MSP_FuzzySearcher (const string & StrToFind)
: MSP_Searcher (StrToFind)
{
Matches_If_WrongLayout.reserve(ResultsSizeDefault);
}
//------------------------------------------------------------------------------
bool MSP_FuzzySearcher::DoesMatch(const string & StrWhereToFind)
{
bool res = false;
bool notFound = false;
// Сумма стоимостей редактирования всех слов строки, которую ищем.
int sumCost = 0;
// Для каждого слова проверим, входит ли оно в строку.
for(int i = 0; i < StrMaster.words.size();i++)
{
int cost = 0;
if (FS.FirstInSecond(StrMaster.words[i],StrWhereToFind,cost)==true)
sumCost += cost;
else {
// Если расстояние между одним из слов и строкой больше допустимого,
// прекращаем поиск.
notFound = true;
break;
}
}
if (notFound == false) {
if (sumCost==0)
// Строка содержит все слова подстроки, которую ищем.
Result = &Matches;
else
// Строка содержит слова подстроки с допустимым кол-вом несоответствий.
Result = &Matches_If_Mistakes;
res = true;
}else {
// Проверим, нет содержится ли подстрока, обращенная в кириллицу.
if (StrMaster.WrongLayout) {
if (StrWhereToFind.find(StrMaster.CyrillicCopy) != StrWhereToFind.npos) {
Result = &Matches_If_WrongLayout;
res = true;
}
}
}
return res;
}
//------------------------------------------------------------------------------
void MSP_FuzzySearcher::GetResult()
{
if (!Matches.empty()) { Result = &Matches; Founds = true;}
else if (!Matches_If_Mistakes.empty()) {
Result = &Matches_If_Mistakes;
FoundsWithMistakes = true;
} else if (!Matches_If_WrongLayout.empty()) {
Result = &Matches_If_WrongLayout;
FoundsWithMistakes = true;
}
}
//------------------------------------------------------------------------------
<file_sep>/fuzzySearch/fsFuzzySearch.cpp
#include "fsFuzzySearch.h"
#include <algorithm>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
using namespace FS;
//------------------------------------------------------------------------------
Metrics::Metrics(int maxLength) : MaxDist (2*1000000)
{
currentRow.resize (maxLength + 1);
previousRow.resize (maxLength + 1);
transpositionRow.resize(maxLength + 1);
}
//------------------------------------------------------------------------------
int Metrics::getDistance(const std::string & str, const std::string & prefix, int max)
{
int stringLength = str.length();
int prefixLength = prefix.length();
// если ошибочно передано отриц. расстояние
if (max < 0) max = prefixLength;
if (prefixLength == 0) return 0;
else if (stringLength == 0) return prefixLength;
if (stringLength < prefixLength - max) return max + 1;
if (prefixLength > currentRow.size()) {
currentRow.resize (prefixLength + 1);
previousRow.resize (prefixLength + 1);
transpositionRow.resize(prefixLength + 1);
}
//цена вставки в начало префикса равна +1
for (int i = 0; i <= prefixLength; i++)
previousRow[i] = i;
int distance = MaxDist;
char lastStrCh = 0;
for (int i = 1; i <= stringLength; i++) {
char strCh = str[i - 1];
//так как ищем подстроку, цена вставки в начало строки равна 0
currentRow[0] = 0;
int from = 1;
int to = prefixLength;
char lastPrefixCh = 0;
for (int j = from; j <= to; j++) {
char prefixCh = prefix[j - 1];
// вычисляем минимальную цену перехода в текущее состояние из предыдущих
// среди удаления, вставки и замены соответственно
int cost = prefixCh == strCh ? 0 : 1;
int value = std::min(std::min(currentRow[j - 1] + 1, previousRow[j] + 1),
previousRow[j - 1] + cost);
// если была транспозиция, учесть и её стоимость
if (prefixCh == lastStrCh && strCh == lastPrefixCh)
value = std::min(value, transpositionRow[j - 2] + cost);
currentRow[j] = value;
lastPrefixCh = prefixCh;
}
lastStrCh = strCh;
if (currentRow[prefixLength] < distance)
distance = currentRow[prefixLength];
// transpositionRow = бывший previousRow, previousRow = бывший currentRow
swap(transpositionRow, previousRow);
swap(previousRow,currentRow);
}
return distance;
}
//==============================================================================
bool FuzzySearcher::FirstInSecond (const std::string & WhatToFind, const std::string & WhereToFind,
int & dist)
{
int k = WhatToFind.length() * MaxDistGrad;
dist = M.getDistance(WhereToFind, WhatToFind, k);
if (dist <= k)
return true;
return false;
}
//------------------------------------------------------------------------------
<file_sep>/fuzzySearch/fsSearch.h
#pragma once
#include "fsUtility.h"
#include "fsFuzzySearch.h"
#include <string>
#include <vector>
namespace Precise_And_Fuzzy_Search
{
class StrToFindMaster
/*
** Для подстроки хранит:
** -её разбиение на слова,
** -результат её набора в русской раскладке клавиатуры.
*/
{
public:
explicit StrToFindMaster (const std::string &StrToFind);
const std::string * GetStrToFind();
std::vector <std::string> words;
std::string CyrillicCopy;
bool WrongLayout;
private:
const int WordsQuanDefault;
const std::string * ToFind;
fsUtility::AlphabetMaster AM;
};
//--------------------------------------------------------------------------
struct mspFuz
/*
** 1 результат запроса к базе
*/
{
unsigned short k;
unsigned short bz;
unsigned long p1;
unsigned long p2;
unsigned long p3;
unsigned long p4;
unsigned long p5;
unsigned long sp;
char n[200];
};
//--------------------------------------------------------------------------
class MSP_Searcher
/*
** Абстрактный класс для поиска подстроки в базе.
** Знает результат запроса.
** Классифицирует совпадения по степени точности, сохраняет их в контейнерах.
*/
{
public:
explicit MSP_Searcher (const std::string &StrToFind);
void AddResult(mspFuz & mspFuz);
virtual bool DoesMatch(const std::string & WhereToFind) = 0;
virtual void GetResult() = 0;
virtual ~MSP_Searcher() {};
bool Founds;
bool FoundsWithMistakes;
std::vector <mspFuz> * Result;
protected:
StrToFindMaster StrMaster;
const int ResultsSizeDefault;
std::vector <mspFuz> Matches;
std::vector <mspFuz> Matches_If_WrongLayout;
};
//--------------------------------------------------------------------------
class MSP_PreciseSearcher : public MSP_Searcher
/*
** Конкретный тип поисковика:
** осуществляет точный поиск подстроки в базе.
** Если необходимо, конвертирует подстроку в кириллицу.
*/
{
public:
explicit MSP_PreciseSearcher (const std::string &StrToFind);
bool DoesMatch(const std::string & WhereToFind);
void GetResult();
};
//--------------------------------------------------------------------------
class MSP_FuzzySearcher : public MSP_Searcher
/*
** Конкретный тип поисковика:
** осуществляет "нечеткий поиск" подстроки в базе.
** Если необходимо, конвертирует подстроку в кириллицу;
** но в этом случае ищет уже точную подстроку.
*/
{
public:
explicit MSP_FuzzySearcher (const std::string &StrToFind);
bool DoesMatch(const std::string & WhereToFind);
void GetResult();
private:
FS::FuzzySearcher FS;
std::vector <mspFuz> Matches_If_Mistakes;
};
}
<file_sep>/fuzzySearch/readme.txt
fuzzySearch предоставляет реализацию "нечеткого" поиска подстроки в строке и возможность его отключения (т.е.
переключения на точный поиск). В основе - метод Вагнера-Фишера, модифицированный для поиска отношения
"строка1_содержится_в_строке2". Использована метрика Левенштейна-Дамерау.
Краткое описание дизайна содержится в Search_Classes_Model_jpg.jpg<file_sep>/README.md
# searchTool
предоставляет реализацию "нечеткого" поиска подстроки в строке и возможность его отключения (т.е.
переключения на точный поиск). В основе - метод Вагнера-Фишера, модифицированный для поиска отношения
"строка1_содержится_в_строке2". Использована метрика Левенштейна-Дамерау.
Краткое описание дизайна содержится в Search_Classes_Model_jpg.jpg
<file_sep>/fuzzySearch/fsUtility.cpp
#include "fsUtility.h"
#include <string>
#include <vector>
using namespace fsUtility;
using namespace std;
//------------------------------------------------------------------------------
AlphabetMaster::AlphabetMaster ()
{
map['Q'] = 'Й';
map['W'] = 'Ц';
map['E'] = 'У';
map['R'] = 'К';
map['T'] = 'Е';
map['Y'] = 'Н';
map['U'] = 'Г';
map['I'] = 'Ш';
map['O'] = 'Щ';
map['P'] = 'З';
map['['] = 'Х';
map[']'] = 'Ъ';
map['A'] = 'Ф';
map['S'] = 'Ы';
map['D'] = 'В';
map['F'] = 'А';
map['G'] = 'П';
map['H'] = 'Р';
map['J'] = 'О';
map['K'] = 'Л';
map['L'] = 'Д';
map[';'] = 'Ж';
map['\''] = 'Э';
map['Z'] = 'Я';
map['X'] = 'Ч';
map['C'] = 'С';
map['V'] = 'М';
map['B'] = 'И';
map['N'] = 'Т';
map['M'] = 'Ь';
map[','] = 'Б';
map['.'] = 'Ю';
map['`'] = 'Ё';
}
//------------------------------------------------------------------------------
void AlphabetMaster::ToCyrillic (string &s)
/*
** Заменяет латинские символы кириллицей.
** Без анализа кодов клавиш -
** соответствие сохранено в хеше.
*/
{
for (size_t i = 0; i < s.length(); i++) {
char ch = s[i];
s[i] = map [ch];
}
}
//------------------------------------------------------------------------------
bool AlphabetMaster::IsLatin (const string &s)
/*
** определяет, набрано ли слово латиницей,
** в лоб - по наличию первого символа в хеш-таблице :
** GetKeyboardLayout не подходит, так как запрос нередко
** может быть набран латиницей при русской раскладке
** (например, в режиме удаленного доступа)
*/
{
if (s.length() > 0)
{
char ch = s[0];
if (map.find(ch) != map.end())
return true;
}
return false;
};
//------------------------------------------------------------------------------
void fsUtility::SplitIntoWords (const std::string & s, char delim, std::vector <std::string> & words)
/*
** разбивает строку на слова, символ конца слова - delim
*/
{
int begin = 0, end = 0;
// find_first_not_of (const string& str, size_t pos ),
// где pos индекс символа строки, с которого следует начать поиск
while ((begin = s.find_first_not_of(delim, end)) != s.npos) {
end = s.find_first_of(delim, begin);
words.push_back(s.substr(begin, end - begin));
begin = end;
}
}
//------------------------------------------------------------------------------
<file_sep>/fuzzySearch/testMetrics.h
#pragma once
#include "fsFuzzySearch.h"
class TestMetrics
{
public:
TestMetrics ();
void PerformAll();
private:
FS::Metrics M;
void PerfomTests (int k);
void TwoEquelStrings_ret_0 (int k);
void OneTransposition_ret_1 (int k);
void Two_Insertions_ret_2 (int k);
void Two_Deletions_ret_2 (int k);
void Is_Prefix_ret_0 (int k);
void Is_Postfix_ret_0 (int k);
void Is_Suffix_ret_0 (int k);
void Suffix_with_mistakes_ret_1 (int k);
void Suffix_with_mistakes_ret_2 (int k);
void Is_Suffix_with_long_prefix_ret_0 (int k);
void Is_Suffix_with_long_prefix_ret_1 (int k);
void Str_To_Find_Is_Longer_ret_7 (int k);
void Str_To_Find_Is_Longer_ret_5 (int k);
void General_ret_2 (int k);
void General_ret_1 (int k);
};<file_sep>/fuzzySearch/fsUtility.h
#pragma once
#include <string>
#include <vector>
#include <boost/unordered/unordered_map.hpp>
namespace fsUtility
{
class AlphabetMaster
/*
** Хранит таблицу соответствий латинских букв кириллическим.
** Определяет алфавит строки.
** Конвертирует строку в кириллицу in place.
*/
{
private:
boost::unordered_map <char, char> map;
public:
AlphabetMaster ();
bool IsLatin (const std::string &s) ;
void ToCyrillic (std::string &s) ;
};
//--------------------------------------------------------------------------
/* Делит строку на слова, записывает их в вектор. */
void SplitIntoWords (const std::string & s, char delim, std::vector <std::string> & words);
//------------------------------------------------------------------------------
}
<file_sep>/fuzzySearch/testFuzzySearcher.cpp
#include "TestFuzzySearcher.h"
#include<iostream>
using namespace std;
//------------------------------------------------------------------------------
void TestFuzzySearcher::PerformAll()
{
PerfomTests ();
}
//------------------------------------------------------------------------------
void TestFuzzySearcher::PerfomTests ()
{
TwoEquelStrings_5_ret_True ();
TwoEquelStrings_3_ret_True ();
TwoDifStrings_3_ret_False ();
TwoDifStrings_4_ret_True ();
TwoDifStrings_4_ret_False ();
TwoDifStrings_8_ret_False ();
TwoDifStrings_8_ret_True ();
General_1_ret_True ();
}
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoEquelStrings_5_ret_True ()
{
string S1 = "тесто";
string S2 = "тесто";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = true;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoEquelStrings_5_ret_True " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoEquelStrings_3_ret_True ()
{
string S1 = "wer";
string S2 = "wer";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = true;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoEquelStrings_3_ret_True " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoDifStrings_3_ret_False ()
{
string S1 = "wer";
string S2 = "rerty";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = false;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoDifStrings_3_ret_False " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoDifStrings_4_ret_True ()
{
string S1 = "wert";
string S2 = "rerty";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = true;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoDifStrings_4_ret_True " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoDifStrings_4_ret_False ()
{
string S1 = "werw";
string S2 = "rerty";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = false;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoDifStrings_4_ret_False " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoDifStrings_8_ret_False ()
{
string S1 = "tratapop";
string S2 = "rerty";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = false;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoDifStrings_8_ret_False " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::TwoDifStrings_8_ret_True ()
{
string S1 = "tratapop";
string S2 = "tratapr";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = true;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoDifStrings_8_ret_True " ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestFuzzySearcher::General_1_ret_True ()
{
string S1 = "Ливчен";
string S2 = "ДЮСШ Левченко <NAME>";
bool actual = FS.FirstInSecond(S1,S2,distToReturn);
bool expected = true;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! General_1_ret_True " << distToReturn;
cout << endl;
};
//------------------------------------------------------------------------------
<file_sep>/fuzzySearch/main.cpp
#include "testMetrics.h"
#include "TestFuzzySearcher.h"
#include "fsUtility.h"
#include "fsSearch.h"
#include <iostream>
using namespace std;
using namespace fsUtility;
#pragma argsused
//---------------------------------------------------------------------------
void main()
{
TestMetrics tM;
tM.PerformAll();
TestFuzzySearcher tFS;
tFS.PerformAll();
}
//---------------------------------------------------------------------------
<file_sep>/fuzzySearch/testMetrics.cpp
#include "testMetrics.h"
#include<iostream>
using namespace std;
//------------------------------------------------------------------------------
TestMetrics::TestMetrics () : M(255) {}
//------------------------------------------------------------------------------
void TestMetrics::PerformAll()
{
for(int i = 0; i<=10;i++)
PerfomTests (i);
}
//------------------------------------------------------------------------------
void TestMetrics::PerfomTests (int k)
{
TwoEquelStrings_ret_0 (k);
OneTransposition_ret_1 (k);
Two_Insertions_ret_2 (k);
Two_Deletions_ret_2 (k);
Is_Prefix_ret_0 (k);
Is_Postfix_ret_0 (k);
Is_Suffix_ret_0 (k);
Suffix_with_mistakes_ret_1 (k);
Suffix_with_mistakes_ret_2 (k);
Is_Suffix_with_long_prefix_ret_0 (k);
Is_Suffix_with_long_prefix_ret_1 (k);
Str_To_Find_Is_Longer_ret_7 (k);
Str_To_Find_Is_Longer_ret_5 (k);
General_ret_2 (k);
General_ret_1 (k);
}
//------------------------------------------------------------------------------
void TestMetrics::TwoEquelStrings_ret_0 (int k)
{
string S1 = "тесто";
string S2 = "тесто";
int actual = M.getDistance(S1,S2, k);
int expected = 0;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! TwoEquelStrings_ret_0 " << "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::OneTransposition_ret_1 (int k)
{
string S1 = "етсто";
string S2 = "тесто";
int actual = M.getDistance(S1,S2, k);
int expected = 1;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! OneTransposition_ret_1 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Two_Insertions_ret_2 (int k)
{
string S1 = "ткестко";
string S2 = "тесто";
int actual = M.getDistance(S1,S2, k);
int expected = 2;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Two_Insertions_ret_2 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Two_Deletions_ret_2 (int k)
{
string S1 = "тесто";
string S2 = "теоo";
int actual = M.getDistance(S1,S2, k);
int expected = 2;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Two_Deletions_ret_2 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Is_Prefix_ret_0 (int k)
{
string S1 = "тестомес";
string S2 = "тес";
int actual = M.getDistance(S1,S2, k);
int expected = 0;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Is_Prefix_ret_0 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Is_Postfix_ret_0 (int k)
{
string S1 = "тестомес";
string S2 = "омес";
int actual = M.getDistance(S1,S2, k);
int expected = 0;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Is_Postfix_ret_0 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Is_Suffix_ret_0 (int k)
{
string S1 = "тестопаровоз";
string S2 = "паров";
int actual = M.getDistance(S1,S2, k);
int expected = 0;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Is_Suffix_ret_0 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Suffix_with_mistakes_ret_1 (int k)
{
string S1 = "тестопаровоз";
string S2 = "пров";
int actual = M.getDistance(S1,S2, k);
int expected = 1;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Suffix_with_mistakes_ret_1 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Suffix_with_mistakes_ret_2 (int k)
{
string S1 = "тестопаровоз";
string S2 = "апровд";
int actual = M.getDistance(S1,S2, k);
int expected = 2;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Suffix_with_mistakes_ret_2 "<< "k = " << k ;;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Is_Suffix_with_long_prefix_ret_0 (int k)
{
string S1 = "тестопаровоз";
string S2 = "оз";
int actual = M.getDistance(S1,S2, k);
int expected = 0;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Is_Suffix_with_long_prefix_ret_0 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Is_Suffix_with_long_prefix_ret_1 (int k)
{
string S1 = "тестопаровоз";
string S2 = "озр";
int actual = M.getDistance(S1,S2, k);
int expected = 1;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Is_Suffix_with_long_prefix_ret_1 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Str_To_Find_Is_Longer_ret_7 (int k)
{
string S1 = "кот";
string S2 = "переезд";
int actual = M.getDistance(S1,S2, k);
int expected;
3 < 7 - k ? expected = k + 1 : expected = 7;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Str_To_Find_Is_Longer_ret_7 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::Str_To_Find_Is_Longer_ret_5 (int k)
{
string S1 = "кее";
string S2 = "переезд";
int actual = M.getDistance(S1,S2, k);
int expected;
3 < 7 - k ? expected = k + 1 : expected = 5;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! Str_To_Find_Is_Longer_ret_5 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::General_ret_2 (int k)
{
string S1 = "Д/С № 94 Московская Ирина Владимировна";
string S2 = "мирошни";
int actual = M.getDistance(S1,S2, k);
int expected = 2;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! General_ret_2 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
void TestMetrics::General_ret_1 (int k)
{
string S1 = "ДЮСШ <NAME>";
string S2 = "Ливчен";
int actual = M.getDistance(S1,S2, k);
int expected = 1;
actual==expected ? cout << "OK!" :
cout << actual << " ERROR! General_ret_1 "<< "k = " << k ;
cout << endl;
};
//------------------------------------------------------------------------------
<file_sep>/fuzzySearch/TestFuzzySearcher.h
#pragma once
#include "fsFuzzySearch.h"
class TestFuzzySearcher
{
public:
TestFuzzySearcher () : distToReturn(0) {}
void PerformAll();
private:
FS::FuzzySearcher FS;
int distToReturn;
void PerfomTests ();
void TwoEquelStrings_5_ret_True ();
void TwoEquelStrings_3_ret_True ();
void TwoDifStrings_3_ret_False ();
void TwoDifStrings_4_ret_True ();
void TwoDifStrings_4_ret_False ();
void TwoDifStrings_8_ret_False ();
void TwoDifStrings_8_ret_True ();
void General_1_ret_True ();
};
| be11bc1f1f853796f812256f8557de7b553adda3 | [
"Markdown",
"Text",
"C++"
] | 13 | C++ | mur-ururu/searchTool | 93ad469a5c1a7d7541de13f28434f2d61ecb893e | 5915d93e9688f64536a589cadcef52bd47e103e0 |
refs/heads/master | <repo_name>swunait/dmit2504-1203-coroutine-exercise<file_sep>/app/src/main/java/ca/nait/dmit/dmit2504/coroutineracinggame/MainActivity.kt
package ca.nait.dmit.dmit2504.coroutineracinggame
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
companion object {
const val MAX_TIME_SECONDS = 30
const val INCREMENT_TIME_MILLISECONDS = 1000L
}
private val timerTextView: TextView by lazy { findViewById(R.id.activity_main_timervalue_textview) }
private val timerProgressBar: ProgressBar by lazy { findViewById(R.id.activity_main_timer_progressbar) }
private val computerTextView: TextView by lazy { findViewById(R.id.activity_main_computervalue_textview) }
private val computerSeekBar: SeekBar by lazy { findViewById(R.id.activity_main_computer_seekbar) }
private val playerTextView: TextView by lazy { findViewById(R.id.activity_main_playervalue_textview) }
private val playerSeekBar: SeekBar by lazy { findViewById(R.id.activity_main_player_seekbar) }
private val startGameButton: Button by lazy { findViewById(R.id.activity_main_startgame_button) }
private val endGameButton: Button by lazy { findViewById(R.id.activity_main_endgame_button) }
private val runPlayerButton: Button by lazy { findViewById(R.id.activity_main_run_button) }
private var gameOver = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
resetGame()
}
fun onStartGameClick(view: View) {
startGameButton.visibility = View.GONE
endGameButton.visibility = View.VISIBLE
runPlayerButton.visibility = View.VISIBLE
gameOver = false
computerMove()
var timerValue = 1
timerProgressBar.isIndeterminate = true
while (!gameOver) {
Thread.sleep(INCREMENT_TIME_MILLISECONDS)
timerTextView.setText("$timerValue")
timerValue++
}
timerProgressBar.isIndeterminate = false
}
fun computerMove() {
// Computer moves every 500 to 1000 milliseconds
while (!gameOver) {
val randomProgress = Random.nextLong(100,500)
Thread.sleep(randomProgress)
computerSeekBar.incrementProgressBy(1)
computerTextView.setText("${computerSeekBar.progress}")
if (computerSeekBar.progress >= MAX_TIME_SECONDS) {
Toast.makeText(this,"Computer wins", Toast.LENGTH_LONG).show()
resetGame()
}
}
}
fun onEndGameClick(view: View) {
resetGame()
}
fun onRunPlayerClick(view: View) {
playerSeekBar.incrementProgressBy(1)
playerTextView.setText("${playerSeekBar.progress}")
if (playerSeekBar.progress >= MAX_TIME_SECONDS) {
Toast.makeText(this,"Player wins", Toast.LENGTH_LONG).show()
resetGame()
}
}
fun resetGame() {
gameOver = true
startGameButton.visibility = View.VISIBLE
endGameButton.visibility = View.GONE
runPlayerButton.visibility = View.GONE
timerProgressBar.isIndeterminate = false
timerTextView.setText("Timer Value")
computerSeekBar.progress = 1
computerTextView.setText("Computer Value")
playerSeekBar.progress = 1
playerTextView.setText("Player Value")
}
}<file_sep>/settings.gradle
rootProject.name = "CoroutineRacingGame"
include ':app'
| 4be4e5ff806b9f9f7e2f2af11e6ca0332f95287f | [
"Kotlin",
"Gradle"
] | 2 | Kotlin | swunait/dmit2504-1203-coroutine-exercise | 231f8606f8c8895dd7a6d929416643a10fda2ead | 2753278740bb9f54ef3f61cc2730101955c814f4 |
refs/heads/master | <repo_name>MarcyMagi/troll-filter<file_sep>/controllers/streamer.js
const config = require('../config/settings')
const twitchRequest = require('../requests/streamer')
const dbTables = require('../infrastructure/tables')
module.exports = app => {
app.get('/registerStreamerOAuth', (req, res) => {
if(req.query.state != config.clientOAuth()) {
return
}
twitchRequest.createToken(req.query.code)
.then(streamerOAuth => {
console.log(streamerOAuth)
twitchRequest.validateToken(streamerOAuth.access_token).then(streamerInfo => {
console.log(streamerInfo)
dbTables.insertIntoStreamer(streamerOAuth, streamerInfo)
dbTables.selectFromStreamer(streamerInfo.user_id)
.then(user => {
console.log(user)
if(user)
res.send('Ok!')
else
res.send('Rip')
}).catch(err => config.defaultErr(err))
}).catch(err => config.defaultErr(err))
}).catch(err => config.defaultErr(err))
})
app.get('/registerUser')
}<file_sep>/infrastructure/tables.js
const createTablesArr = [
`CREATE TABLE IF NOT EXISTS streamUser (
twitch_id int PRIMARY KEY,
access_token nvarchar(255) UNIQUE NOT NULL,
refresh_token nvarchar(255) UNIQUE NOT NULL
);`,
`CREATE TABLE IF NOT EXISTS viewerTwitchUser (
twitch_id int PRIMARY KEY,
discord_id int UNIQUE,
twitch_name nvarchar(255) NOT NULL,
twitch_access_token nvarchar(255) UNIQUE NOT NULL,
twitch_refresh_token nvarchar(255) UNIQUE NOT NULL,
FOREIGN KEY (discord_id) REFERENCES viewerDiscordUser (discord_id)
);`,
`CREATE TABLE IF NOT EXISTS viewerDiscordUser (
discord_id int PRIMARY KEY,
twitch_id int UNIQUE NOT NULL,
discord_access_token nvarchar(255) UNIQUE NOT NULL,
discord_refresh_token nvarchar(255) UNIQUE NOT NULL,
email nvarchar(255) NOT NULL,
username nvarchar(255) NOT NULL,
icon nvarchar(255) NOT NULL,
FOREIGN KEY (twitch_id) REFERENCES viewerTwitchUser (twitch_id)
);`,
`CREATE TABLE IF NOT EXISTS streamerViewerRel (
stream_id int NOT NULL,
viewer_id int NOT NULL,
relation int NOT NULL,
FOREIGN KEY (stream_id) REFERENCES streamUser (twitch_id),
FOREIGN KEY (viewer_id) REFERENCES viewerTwitchUser (twitch_id)
);`
]
const dropTableArr = [
'DROP TABLE IF EXISTS streamUser;',
'DROP TABLE IF EXISTS viewerTwitchUser;',
'DROP TABLE IF EXISTS viewerDiscordUser;',
'DROP TABLE IF EXISTS streamerViewerRel;'
]
module.exports = {
connection: db => {
if(!this.db)
this.db = db
return this.db
},
createTables: () => {
return new Promise((resolve, reject) => {
this.db.serialize(() => {
for(let i = 0; i < createTablesArr.length; i++) {
this.db.run(createTablesArr[i], err => {
if(err) {
reject(err)
}
})
}
resolve()
})
})
},
dropTables: () => {
return new Promise((resolve, reject) => {
this.db.serialize(() => {
for(let i = 0; i < dropTableArr.length; i++) {
this.db.run(dropTableArr[i], err => {
if(err) {
reject(err)
}
})
}
resolve()
})
})
},
insertIntoStreamer: (OAuth, user) => {
const streamTableInsert = [user.user_id, OAuth.access_token, OAuth.refresh_token]
const sql = 'INSERT OR REPLACE INTO streamUser(twitch_id, access_token, refresh_token) VALUES(?, ?, ?)'
return new Promise((resolve, reject) => {
this.db.serialize(() => {
this.db.run(sql, streamTableInsert, err => {
if(err) {
reject(err)
}
})
})
resolve()
})
},
selectFromStreamer: twitch_id => {
return new Promise((resolve, reject) => {
this.db.serialize(() => {
this.db.all('SELECT * FROM streamUser WHERE twitch_id = ?', [twitch_id], (err, rows) => {
if(!err)
resolve(rows[0])
else
reject(err)
})
})
})
},
insertIntoTwitchViewer: (twitchOAuth, twitchUser) => {
const userTableInsert = [twitchUser.user_id, twitchUser.login, twitchOAuth.access_token, twitchOAuth.refresh_token]
const sql = 'INSERT OR REPLACE INTO viewerTwitchUser(twitch_id, twitch_name, twitch_access_token, twitch_refresh_token) VALUES(?, ?, ?, ?)'
return new Promise((resolve, reject) => {
this.db.serialize(() => {
this.db.run(sql, userTableInsert, err => {
if(err) {
reject(err)
}
})
resolve()
})
})
},
selectFromTwitchViewer: twitch_id => {
return new Promise((resolve, reject) => {
this.db.serialize(() => {
this.db.all('SELECT * FROM viewerTwitchUser WHERE twitch_id = ?', [twitch_id], (err, rows) => {
if(!err)
resolve(rows[0])
else
reject(err)
})
})
})
},
insertIntoDiscordViewer: (discordOAuth, discordUser, twitch_id) => {
const userTableInsert = [discordUser.id, twitch_id, discordOAuth.access_token, discordOAuth.refresh_token, discordUser.email, `${discordUser.username}#${discordUser.discriminator}`, discordUser.avatar]
const sql = 'INSERT OR REPLACE INTO viewerDiscordUser(discord_id, twitch_id, discord_access_token, discord_refresh_token, email, username, icon) VALUES(?, ?, ?, ?, ?, ?, ?)'
return new Promise((resolve, reject) => {
this.db.serialize(() => {
this.db.run(sql, userTableInsert, err => {
if(err) {
reject(err)
}
})
})
const tsql = `UPDATE viewerTwitchUser SET discord_id = ${discordUser.id} WHERE twitch_id = ${twitch_id}`
this.db.serialize(() => {
this.db.run(tsql, err => {
if(err) {
reject(err)
}
})
resolve()
})
})
}
}<file_sep>/controllers/viewer.js
const config = require('../config/settings')
const viewerRequest = require('../requests/viewer')
const dbTables = require('../infrastructure/tables')
const discordOauth = require('../requests/viewer').OAuthURLDiscord
module.exports = app => {
app.get('/registerViewerOAuth/Twitch', (req, res) => {
if(req.query.state != config.clientOAuth()) {
return
}
viewerRequest.createTwitchToken(req.query.code)
.then(userTwitchOAuth => {
console.log(userTwitchOAuth)
viewerRequest.validateTwitchToken(userTwitchOAuth.access_token).then(userTwitchInfo => {
console.log(userTwitchInfo)
dbTables.insertIntoTwitchViewer(userTwitchOAuth, userTwitchInfo)
res.redirect(discordOauth + userTwitchInfo.user_id)
}).catch(config.defaultErr)
}).catch(config.defaultErr)
})
app.get('/registerViewerOAuth/Discord', (req, res) => {
const twitch_id = req.query.state
viewerRequest.createDiscordToken(req.query.code)
.then(userDiscordOAuth => {
viewerRequest.getDiscordInfo(userDiscordOAuth.access_token)[0].then(userDiscord => {
viewerRequest.getDiscordInfo(userDiscordOAuth.access_token)[1].then(guilds => {
console.log(userDiscordOAuth)
console.log(userDiscord)
console.log(guilds)
dbTables.insertIntoDiscordViewer(userDiscordOAuth, userDiscord, twitch_id).then(() => {
res.send('Ok!')
})
}).catch(config.defaultErr)
}).catch(config.defaultErr)
}).catch(config.defaultErr)
})
}<file_sep>/server.js
const customExpress = require('./config/customExpress')
const dbTables = require('./infrastructure/tables')
const dbConnection = require('./infrastructure/connection')
let app
module.exports = {
init: () => {
dbConnection.then((res) => {
dbTables.connection(res)
dbTables.dropTables()
dbTables.createTables()
app = customExpress()
app.listen(3000, () => {
console.log('Server Running')
})
})
}
}
<file_sep>/infrastructure/connection.js
const sqlite3 = require('sqlite3').verbose()
module.exports = new Promise((resolve) => {
const db = new sqlite3.Database('infrastructure/databaseTest.sql')
resolve(db)
}) <file_sep>/requests/viewer.js
const https = require('https')
const config = require('../config/settings')
const querystring = require('querystring')
const userOAuthSettings = config.twitchSettings().userOAuth
const clientIdTwitch = config.twitchSettings().clientId
const clientIdDiscord = config.discordSettings().clientId
module.exports = {
createTwitchToken: code => {
return new Promise((resolve, reject) => {
const reqData = JSON.stringify({
client_id: clientIdTwitch,
client_secret: process.env.TROLL_FILTER_SECRET_TWITCH,
code: code,
grant_type: 'authorization_code',
redirect_uri: userOAuthSettings.redirect
})
const reqOptions = {
hostname: 'id.twitch.tv',
port: 443,
path: '/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': reqData.length
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.write(reqData)
req.end()
})
},
validateTwitchToken: token => {
return new Promise((resolve, reject) => {
const reqOptions = {
hostname: 'id.twitch.tv',
port: 443,
path: '/oauth2/validate',
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'OAuth ' + token
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.end()
})
},
createDiscordToken: code => {
return new Promise((resolve, reject) => {
const reqData = querystring.stringify({
client_id: clientIdDiscord,
client_secret: process.env.TROLL_FILTER_SECRET_DISCORD,
grant_type: 'authorization_code',
code: code,
redirect_uri: config.discordSettings().redirect,
scope: config.discordSettings().scope.join(' ')
})
const reqOptions = {
hostname: 'discord.com',
port: 443,
path: '/api/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': reqData.length
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.write(reqData)
req.end()
})
},
getDiscordInfo: token => {
return [new Promise((resolve, reject) => {
const reqOptions = {
hostname: 'discord.com',
port: 443,
path: '/api/users/@me',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + token
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.end()
}), new Promise((resolve, reject) => {
const reqOptions = {
hostname: 'discord.com',
port: 443,
path: '/api/users/@me/guilds',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Bearer ' + token
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.end()
})]
},
OAuthURLTwitch:
'https://id.twitch.tv/oauth2/authorize' +
'?client_id=' + clientIdTwitch +
'&redirect_uri=' + userOAuthSettings.redirect +
'&response_type=code' +
'&scope=' + userOAuthSettings.scope.join('%20') +
'&force_verify=true&state=',
OAuthURLDiscord:
'https://discord.com/api/oauth2/authorize' +
'?client_id=' + clientIdDiscord +
'&redirect_uri=' + config.discordSettings().redirect +
'&response_type=code' +
'&scope=' + config.discordSettings().scope.join('%20') +
'&force_verify=true&state='
}<file_sep>/requests/client.js
const https = require('https')
const config = require('../config/settings')
const clientId = config.twitchSettings().clientId
module.exports = {
createClientToken: () => {
return new Promise((resolve, reject) => {
const reqData = JSON.stringify({
client_id: clientId,
client_secret: process.env.TROLL_FILTER_SECRET_TWITCH,
grant_type: 'client_credentials'
})
const reqOptions = {
hostname: 'id.twitch.tv',
port: 443,
path: '/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': reqData.length
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData).access_token)
})
})
req.on('error', err => {
reject(err)
})
req.write(reqData)
req.end()
})
},
}<file_sep>/requests/streamer.js
const https = require('https')
const config = require('../config/settings')
const streamerOAuthSettings = config.twitchSettings().streamerOAuth
const clientId = config.twitchSettings().clientId
module.exports = {
createToken: code => {
return new Promise((resolve, reject) => {
const reqData = JSON.stringify({
client_id: '7ut0fk3wl2mgi8egrnq5yhy4fkmebh',
client_secret: process.env.TROLL_FILTER_SECRET_TWITCH,
code: code,
grant_type: 'authorization_code',
redirect_uri: streamerOAuthSettings.redirect
})
const reqOptions = {
hostname: 'id.twitch.tv',
port: 443,
path: '/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': reqData.length
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.write(reqData)
req.end()
})
},
validateToken: token => {
return new Promise((resolve, reject) => {
const reqOptions = {
hostname: 'id.twitch.tv',
port: 443,
path: '/oauth2/validate',
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'OAuth ' + token
}
}
let rawData = ''
const req = https.request(reqOptions, res => {
res.on('data', data => {
rawData += data
})
res.on('end', () => {
resolve(JSON.parse(rawData))
})
})
req.on('error', err => {
reject(err)
})
req.end()
})
},
OAuthURL:
'https://id.twitch.tv/oauth2/authorize' +
'?client_id=' + clientId +
'&redirect_uri=' + streamerOAuthSettings.redirect +
'&response_type=code' +
'&scope=' + streamerOAuthSettings.scope.join('%20') +
'&force_verify=true&state='
}<file_sep>/config/settings.js
const fs = require('fs')
const settings = JSON.parse(fs.readFileSync('config/application.json'))
let clientOAuth
module.exports = {
clientOAuth: token => {
if(!clientOAuth)
clientOAuth = token
return clientOAuth
},
twitchSettings: () => {
return settings.twitch
},
discordSettings: () => {
return settings.discord
},
defaultErr: err => {
const db = require('../infrastructure/tables').connection()
console.log(err)
db.close()
process.exit(1)
}
} | 231906d89c4a9e29018630ad25cb98e718947fff | [
"JavaScript"
] | 9 | JavaScript | MarcyMagi/troll-filter | 8bb2d62fa57a607159bc2003b757106e53678aa3 | 523f02502b1b0e7960b1611c8e4e7fc62509ceda |
refs/heads/master | <file_sep><?php
echo "<pre>";
$email_body = " ";
$email_body .= "Name " . $name . "\n";
$email_body .= 'Name ' . $name . "\n";
echo 'Email ' . $email . "\n";
echo 'Details ' . $details . "\n";
echo "</pre>";
//To Do: Send email
$pageTitle='Thank you';
$section=null;
?>
<div class='section page'>
<h1>Thank You</h1>
<p>Thanks for the email! I’ll check out your suggestion soon!</p>
</div>
<file_sep><?php
$name=$_POST['name'];
$email=$_POST['email'];
$details=$_POST['details'];
?>
<file_sep><?php
include("inc/data.php");
include("inc/functions.php");
if(isset($_GET["id"])){
$id=$_GET["id"];
if(isset($catalog[$id])) {
$item=$catalog[$id];
}
}
if(!isset($item)) {
header("location:catalog.php");
exit;
}
$page_title="Full Catalog";
$section=null;
include("inc/header.php"); ?>
<div class='section page'>
<div class='wrapper'>
<div class='breadcrumbs'>
<a href='catalog.php'>Full Catalog</a>
> <a href='catalog.php?cat=<?php echo strtolower($item["category"]);?>'>
<?php echo $item["category"]; ?></a>
> <?php echo $item["title"];?>
</div>
<div class='media-picture'>
<span>
<img src='<?php echo $item["img"];?>' alt='<?php echo $item["title"];?>' />
</span>
</div>
<div class='media-details'>
<h1><?php echo $item["title"]; ?></h1>
<table>
<tr>
<th>Category</th>
<th><?php echo $item["category"]; ?></td>
</tr>
<tr>
<th>Year</th>
<td><?php echo $item["year"]; ?></td>
<tr>
</table>
</div>
</div>
</div>
</body>
</html>
<?php header("location:thanks.php'); ?>
echo "<pre>";
$email_body = " ";
$email_body .= "Name " . $name . "\n";
$email_body .= 'Name ' . $name . "\n";
echo 'Email ' . $email . "\n";
echo 'Details ' . $details . "\n";
echo "</pre>";
//To Do: Send email
$pageTitle='Thank you';
$section=null;
?>
<div class='section page'>
<h1>Thank You</h1>
<p>Thanks for the email! I’ll check out your suggestion soon!</p>
</div>
| 8a20ca51983f6dbf490fa16cca1912e3ffd850fb | [
"PHP"
] | 3 | PHP | jaselang/php_webpage_project | 7caf1ac9092824f8bbd7df4ef5e33a3f8f71b5fb | 616f19a0e95bcf41101c99b0e71a6a640b1b077f |
refs/heads/master | <file_sep>
function addition() {
var value1 = document.getElementById('firstnum').value;
var value2 = document.getElementById('secnum').value;
var x = +value1 + +value2;
document.getElementById("result").innerHTML = x;
console.log(x);
}
function subs() {
var value1 = document.getElementById('firstnum').value;
var value2 = document.getElementById('secnum').value;
var x = +value1 - +value2;
document.getElementById("result").innerHTML = x;
console.log(x);
}
function multi() {
var value1 = document.getElementById('firstnum').value;
var value2 = document.getElementById('secnum').value;
var x = value1 * value2;
document.getElementById("result").innerHTML = x;
console.log(x);
}
function divide() {
var value1 = document.getElementById('firstnum').value;
var value2 = document.getElementById('secnum').value;
var x = value1 / value2;
document.getElementById("result").innerHTML = x;
console.log(x);
}
function BMI() {
var Height = document.getElementById('bmi1').value;
var Weight = document.getElementById('bmi2').value;
var x = Weight / (Height*Height);
document.getElementById("resultbmi").innerHTML = x;
console.log(x);
}
function changeUnit(y) {
console.log(y.value);
var unit = y.value;
if (unit == "Imperial"){
document.getElementById('imp1').innerHTML = "Height (in)"
document.getElementById('imp2').innerHTML = "Weight (lb)"
}
else {
document.getElementById('imp1').innerHTML = "Height (m)"
document.getElementById('imp2').innerHTML = "Weight (kg)"
}
}
<file_sep># Sparta-global-Calculator
| 123956c126c7ae3bf0e8e42f2ec46d8d131607d8 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Jira-W/Sparta-global-Calculator | 0be78a0b05f4bd41024d037228db4af34fe3e3a2 | 4ed9a2135ff2620526693ce2964b347e8b4ae5ab |
refs/heads/master | <file_sep>package com.atguigu.gmall.user.cotroller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.gmall.bean.UserInfo;
import com.atguigu.gmall.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author zkd
* @date 2019/7/23 19:28
*/
@RestController
public class UserController {
@Reference
UserService userService;
@RequestMapping("userInfoList")
public ResponseEntity<List<UserInfo>>userInfoList() {
List<UserInfo> userInfoList = userService.userInfoList();
return ResponseEntity.ok(userInfoList);
}
}
| 25b36b431a4a00f14bf555a5fc484870a4feb559 | [
"Java"
] | 1 | Java | zhukedong/gmall0328 | 2ec23d60f883b539114dba0422697f28edd5bf12 | e88fc083d9a388462f12c90a24bf616b32c37edc |
refs/heads/master | <repo_name>gideon21/WebAR-project<file_sep>/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web.AR.</title>
<link rel="stylesheet" href="css/main.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@latest/dist/css/splide.min.css">
<script src="splide-2.4.21/dist/js/splide.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
new Splide('.splide').mount();
});
</script>
</head>
<body>
<div class="navbar">
<img src="images/web.AR_logo.png" class="webAR_logo" style="width:150px" title="Web.AR logo">
<a class="active" href="project.php" title="AR Projects">AR PROJECTS</a>
</div>
<div class="main">
<div class="contentOne">
<h2 class="abts" title="About">About</h2>
<h1>Web Augmented Reality</h1>
<p>An Augmented reality (AR) experience presented on a web browser</p>
<h2 class="kbts">Key benfits</h2>
<table>
<td>▸Increases engagement and interactivity
</td>
<td>▸Provide additional information on a given subject
</td>
<td>▸Makes learning fun
</td>
</table>
</div>
<div class="contentTwo">
<h2 id="hws" title="How it works">How it works</h2>
<div class="pict">
<img src="images/pictorial.jpg" alt="pictorial">
</div>
</div>
<div class="contentThree">
<h2 class="dmo" title="Demo">Demo</h2>
<div class="splide">
<div class="splide__track">
<ul class="splide__list">
<li class="splide__slide"><img src="images/arm.png" style="width: 320px;" /></li>
<li class="splide__slide"><img src="images/body.png" style="width: 320px;" /></li>
<li class="splide__slide"><img src="images/heart.png" style="width: 320px;" /></li>
<li class="splide__slide"><img src="images/thorax.png" style="width: 320px;" /></li>
</ul>
</div>
</div>
</div>
<div class="contentFour">
<h2 class="ttl" title="Tutorial">Tutorial</h2>
<p class="carp">Augmented Reality Projects</p>
<p class="arP">To experience more augmented reality download from<span
style="color: #0672FF; padding: 5; font-weight: 500; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
AR
projects</span></br>For others to experience your augmented reality projects uplaod to<span
style="color: #0672FF; padding: 5; font-weight: 500; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
AR
projects </span></p>
<img src="images/down-chevron.png" class="down_arrow">
<p class="learn">Learn how to create your own Augmented Reality experience</p>
<embed src="WebAR project.pdf" type="application/pdf" class="pdf_doc" width="700px" height="900" />
</div>
<div class="contentFive">
<h2 class="ttl" title="Reference">Reference</h2>
<p class="scmtl">Source Materials</p>
<a class="link" href="https://ar-js-org.github.io/AR.js-Docs/#:~:text=on%20the%20Web-,AR.,based%20AR%20and%20Marker%20tracking.">Ar.js</a>
<a class="link" href="https://www.qrcode-monkey.com/">QRcode-Monkey</a>
<a class="link" href="https://aframe.io/blog/arjs/">Creating Augmented Reality with AR.js and A-Frame</a>
<a class="link" href="https://aframe.io/docs/0.6.0/components/gltf-model.html">A-FRAME-glt-model</a>
<a class="link" href="https://aframe.io/docs/1.0.0/introduction/models.html">A-FRAME-3D Models</a>
<a class="link" href="https://au.gmented.com/app/marker/marker.php">Marker generator</a>
<p class="mdl">Sketchfab Models</p>
<a class="link"
href="https://sketchfab.com/3d-models/ecorche-anatomy-study-e402d3d541eb4b199c57d5410f5d3c57">Ecorche -
Anatomy study</a>
<a class="link" href="https://sketchfab.com/3d-models/anatomical-heart-codominance-42d07ac1517748ea82bb05b0a362b298">Anatomical heart</a>
<a class="link" href="https://sketchfab.com/3d-models/human-anatomy-heart-in-thorax-22ebd4abce9440639563807e72e5f8d1">Heart in thorax</a>
<a class="link" href="https://sketchfab.com/3d-models/simple-arm-anatomy-874c8868bdb942f1a0dab2f023e16ee3">Simple arm anatomy</a>
</div>
<footer>
<small style="line-height: 5;">© Copyright 2021 Web.AR. All Rights Reserved</small>
</footer>
</div>
</body>
</html><file_sep>/js/main.js
var Markers = {
fn: {
addMarkers: function() {
var target = $('#image-wrapper');
var data = target.attr('data-captions');
var captions = $.parseJSON(data);
var coords = captions.coords;
for (var i = 0; i < coords.length; i++) {
var obj = coords[i];
var top = obj.top;
var left = obj.left;
var text = obj.text;
$('<span class="marker"/>').css({
top: top,
left: left
}).html('<span class="caption">' + text + '</span>').
appendTo(target);
}
},
showCaptions: function() {
$('span.marker').live('click', function() {
var $marker = $(this),
$caption = $('span.caption', $marker);
if ($caption.is(':hidden')) {
$caption.slideDown(300);
} else {
$caption.slideUp(300);
}
});
}
},
init: function() {
this.fn.addMarkers();
this.fn.showCaptions();
}
};
$(function() {
Markers.init();
}); | 7708a83f8e447882802e7fbe0dfb8a4b4cf5a2ed | [
"JavaScript",
"PHP"
] | 2 | PHP | gideon21/WebAR-project | a6f3cf6eaac6a6da668a1b611bdece7d44270f69 | 6073ab23f4955f0600b1719b7926978c97161cbe |
refs/heads/master | <repo_name>sreebg04/snowflake_poc<file_sep>/schedule.py
import subprocess
import sys
import time
def process(command):
pro = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
pro.wait()
if pro.returncode == 0:
print("Monitoring Client folder")
else:
print("Run unsuccessfull")
sys.exit(1)
try:
while True:
process("python3 /mnt/c/scripts_with_monitor/client_monitor.py")
time.sleep(5)
except KeyboardInterrupt:
print ('KeyboardInterrupt')
<file_sep>/snowflake_main.py
#! /usr/bin/python
from splitfile import split
from config import Configure
import snowflake.connector
import datetime
import threading
from pathlib import Path
from os import listdir
from os.path import join, isdir
import os.path
import shutil
from snowflake.connector.errors import DatabaseError, ProgrammingError
from log import logger
def connect(config_file):
connection = ""
try:
cone = Configure(config_file)
config_data = cone.config()
connection = snowflake.connector.connect(
user=config_data["user"],
password=config_data["password"],
account=config_data["account"], )
logger.info("Connection established successfully")
except DatabaseError as db_ex:
if db_ex.errno == 250001:
print(f"Invalid username/password, please re-enter username and password...")
logger.warning(f"Invalid username/password, please re-enter username and password...")
else:
raise
except Exception as ex:
print(f"New exception raised {ex}")
logger.error(f"New exception raised {ex}")
raise
return connection
def upload(config_file, source_file, database):
cone = Configure(config_file)
config_data = cone.config()
connection = connect(config_file)
connection.cursor().execute("USE WAREHOUSE " + config_data["warehouse"])
connection.cursor().execute("USE DATABASE " + database)
connection.cursor().execute("USE SCHEMA " + config_data["schema"])
connection.cursor().execute("USE ROLE " + config_data["role"])
cs = connection.cursor()
try:
sql = "PUT file:///" + source_file + " @" + database + ";"
cs.execute(sql)
logger.info(sql + " executed")
except ProgrammingError as db_ex:
print(f"Programming error: {db_ex}")
logger.error(f"Programming error: {db_ex}")
raise
finally:
cs.close()
connection.close()
def main():
print("Split_start", datetime.datetime.now())
con = Configure("cred.json")
config_datas = con.config()
resultfiles = split(config_datas["source"])
thread_list = []
print("startupload: ", datetime.datetime.now())
logger.info(" Uploading files into Database stages")
for file in resultfiles:
for direc in listdir(config_datas["source"]):
if isdir(join(config_datas["source"], direc)) and str(direc) in file:
for dire in listdir(join(config_datas["source"])):
if dire in file:
thread = threading.Thread(target=upload, args=("cred.json", file, direc))
thread_list.append(thread)
for thr in thread_list:
thr.start()
for thre in thread_list:
thre.join()
def copy(config_file, database, table):
cone = Configure(config_file)
config_data = cone.config()
connection = connect(config_file)
connection.cursor().execute("USE WAREHOUSE " + config_data["warehouse"])
connection.cursor().execute("USE DATABASE " + database)
connection.cursor().execute("USE SCHEMA " + config_data["schema"])
connection.cursor().execute("USE ROLE " + config_data["role"])
cs = connection.cursor()
try:
sql = """COPY into table
FROM @stage
file_format = (type = csv field_optionally_enclosed_by='"' skip_header=1)
pattern = '.*table_[1-6].csv.gz'
on_error = 'ABORT_STATEMENT';"""
res = sql.replace("table", table, 2)
res_ = res.replace("stage", database, 1)
cs.execute(res_)
logger.info(res_ + " executed")
except ProgrammingError as db_ex:
print(f"Programming error: {db_ex}")
logger.error(f"Programming error: {db_ex}")
raise
finally:
cs.close()
connection.close()
def copy_main():
con = Configure("cred.json")
config_datas = con.config()
source = config_datas["source"]
thread_list = []
print("startcopy: ", datetime.datetime.now())
logger.info("Copying files into stage database")
for database in listdir(source):
if isdir(join(source, database)):
for table in listdir(join(source, database)):
if not isdir(join(join(source, database), table)):
thread = threading.Thread(target=copy, args=("cred.json", database, Path(table).stem))
thread_list.append(thread)
for thr in thread_list:
thr.start()
for thre in thread_list:
thre.join()
def remove_old_staged_files(config_file, database):
cone = Configure(config_file)
config_data = cone.config()
connection = connect(config_file)
connection.cursor().execute("USE WAREHOUSE " + config_data["warehouse"])
connection.cursor().execute("USE DATABASE " + database)
connection.cursor().execute("USE SCHEMA " + config_data["schema"])
connection.cursor().execute("USE ROLE " + config_data["role"])
cs = connection.cursor()
try:
sql = "REMOVE @" + database + " pattern='.*.csv.gz';"
cs.execute(sql)
logger.info(sql + " executed")
except ProgrammingError as db_ex:
print(f"Programming error: {db_ex}")
logger.error(f"Programming error: {db_ex}")
raise
finally:
cs.close()
connection.close()
def delete_old_staged_files():
con = Configure("cred.json")
config_datas = con.config()
source = config_datas["source"]
thread_list = []
print("remove old stage files: ", datetime.datetime.now())
logger.info("Deleting old staged files from database stages")
for database in listdir(source):
if isdir(join(source, database)):
thread = threading.Thread(target=remove_old_staged_files, args=("cred.json", database))
thread_list.append(thread)
for thr in thread_list:
thr.start()
for thre in thread_list:
thre.join()
def load_history(config_file, database):
cone = Configure(config_file)
config_data = cone.config()
connection = connect(config_file)
connection.cursor().execute("USE WAREHOUSE " + config_data["warehouse"])
connection.cursor().execute("USE DATABASE " + database)
connection.cursor().execute("USE SCHEMA " + config_data["schema"])
connection.cursor().execute("USE ROLE " + config_data["role"])
cs = connection.cursor()
try:
sql = "select * from information_schema.load_history order by last_load_time desc;"
cs.execute(sql)
result = cs.fetch_pandas_all()
res = result.loc[result['STATUS'] != "LOADED"]
if len(res.index) > 0:
print("Error: ", database)
else:
print("Loaded successfully: ", database)
logger.info("Copy/Load history for database has No error")
except ProgrammingError as db_ex:
print(f"Programming error: {db_ex}")
logger.error(f"Programming error: {db_ex}")
raise
finally:
cs.close()
connection.close()
def history():
con = Configure("cred.json")
config_datas = con.config()
source = config_datas["source"]
thread_list = []
print("Checking loading history: ", datetime.datetime.now())
logger.info("Getting Copy/Load history for each database")
for database in listdir(source):
if isdir(join(source, database)):
thread = threading.Thread(target=load_history, args=("cred.json", database))
thread_list.append(thread)
for thr in thread_list:
thr.start()
for thre in thread_list:
thre.join()
def archive():
con = Configure("cred.json")
config_datas = con.config()
source = config_datas["source"]
target = config_datas["archive"]
logger.info("Moving processed files from source to archive")
for file in listdir(source):
shutil.move(os.path.join(source, file), target)
| 6eabb72cd72183931953a42dcb83171d30b74065 | [
"Python"
] | 2 | Python | sreebg04/snowflake_poc | e82d360cd7ef63799bbefa0f1c332bc78eb72c6b | ee91fe735c6a5b5192e1933bde80e0b8b8a74b05 |
refs/heads/master | <file_sep>CREATE TABLE artist (
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
PRIMARY KEY(id)
);
DELETE FROM concert;
ALTER TABLE concert
ADD COLUMN artist_id BIGINT NOT NULL,
DROP COLUMN artist,
DROP COLUMN genre,
ADD FOREIGN KEY (artist_id) REFERENCES artist(id); | 27174b4079e97b7695c9cff6a387306918672e2c | [
"SQL"
] | 1 | SQL | zaans2/Workshop-JPA | a2535532106c6e0008f4e972cc22b672caad9ea0 | 5611bd49d286d8625eb4eef78361a7ee5f31dcb6 |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Jul 4 13:41:51 2020
@author: z003vrzk
"""
# Python imports
import datetime
# Third party imports
import pandas as pd
import numpy as np
# Local imports
from finance_graphing import (create_transaction_objects, Income,
plot_integral, calculate_gradients)
# Declarations
#%% Graphing
"""Creating income instances
Income instances can either be incomes or expenses. Enter a negative number
for expenses or a positive number for income
"""
# Basic income - $60,000 to $40,000 per year
INC1 = Income(60000*0.7, 365/365, datetime.date(2019,6,5), datetime.date(2023,6,5),
best_case=60000*0.7, worst_case=40000*0.7) #Income
# Single expense of $4,000, best $3,000 worst $5,000
INC2 = Income(-4000, 1/365,datetime.date(2019,10,1),datetime.date(2020,10,1),
best_case=-3000, worst_case=-5000, one_time=True)
# Single expense of $7,500
INC3 = Income(-7500,1/365,datetime.date(2021,10,20),datetime.date(2021,10,20),
one_time=True)
# Monthly expense of $2,000
INC4 = Income(-2000,31/365, datetime.date(2019,6,5), datetime.date(2025,6,5),
best_case=-1800, worst_case=-2100, one_time=True)
# Other income bi-weekly
INC5 = Income(450, 14/365, datetime.date(2019, 6, 5), datetime.date(2025, 6, 5),
best_case=500, worst_case=440)
# Single expense of $12,500 yearly over two years ($25,000 total expense)
# Range from $10,000 to $15,000 expense
INC6 = Income(-12500, 365/365, datetime.date(2023,6,5), datetime.date(2025,6,5),
best_case=-10000,worst_case=-15000)
# Import bank transactions .csv for projection of daily expenses
path = r'../writeup/Transaction_Data.csv'
transaction_dataframe = pd.read_csv(path)
incomes_auto = create_transaction_objects(transaction_dataframe,
value_col='Amount',
date_col='Date')
# Create an iterable of income objects
incomes = [INC1, INC2,INC3,INC4,INC5,INC6]
incomes.extend(incomes_auto)
# Define your plotting period
start_date = min([x.start_date for x in incomes])
end_date = datetime.date(2020,2,1)
# Calculate gradients and values
gradients, values = calculate_gradients(incomes, start_date, end_date)
#Plot the income objects
plot_integral(values, start_date, end_date, smooth=True, smooth_type='LSQ-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='bv-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='Smooth-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='wiener')
#%% Test 2
"""Creating income instances
Income instances can either be incomes or expenses. Enter a negative number
for expenses or a positive number for income
"""
# Simple
INC1 = Income(100, 1/365, datetime.date(2020,1,2), datetime.date(2020,1,3),
one_time=True)
# Simple
INC2 = Income(-100, 1/365, datetime.date(2020,1,3), datetime.date(2020,1,4),
one_time=True)
# Simple
INC3 = Income(100, 1/365, datetime.date(2020,1,4), datetime.date(2020,1,5),
one_time=True)
# Simple
INC4 = Income(100, 1/365, datetime.date(2020,1,5), datetime.date(2020,1,6),
one_time=True)
# Simple
INC5 = Income(-100, 1/365, datetime.date(2020,1,6), datetime.date(2020,1,7),
one_time=True)
# Create an iterable of income objects
incomes = [INC1,INC2,INC3,INC4,INC5]
# Define your plotting period
start_date = min([x.start_date for x in incomes])
end_date = max([x.end_date for x in incomes]) + datetime.timedelta(days=1)
# Calculate gradients and values
gradients, values = calculate_gradients(incomes, start_date, end_date)
#Plot the income objects
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='LSQ-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='bv-bspline')
plot_integral(values, start_date, end_date, smooth=True, smooth_type='Smooth-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='wiener')
# plot_integral(values, start_date, end_date, smooth=False)
#%% Test 3
"""Creating income instances
Income instances can either be incomes or expenses. Enter a negative number
for expenses or a positive number for income
"""
# Basic income
INC1 = Income(40000*0.7, 365/365, datetime.date(2019,6,5), datetime.date(2023,6,5),
best_case=40000*0.7, worst_case=20000*0.7) #Income
# Single expense of $4,000, best $3,000 worst $5,000
INC2 = Income(-4000, 1/365,datetime.date(2019,10,1),datetime.date(2020,10,1),
best_case=-3000, worst_case=-5000, one_time=True)
# Monthly expense of $2,000
INC3 = Income(-2000,31/365, datetime.date(2019,6,5), datetime.date(2025,6,5),
best_case=-1800, worst_case=-2100, one_time=True)
# Generate some random transaction values
_transactions1 = np.random.normal(loc=-30, scale=50, size=(100))
_transactions3 = np.random.normal(loc=-1000, scale=300, size=(25))
_transactions = np.concatenate((_transactions1, _transactions3))
incomes_auto = []
_days = np.linspace(1,28,28, dtype=np.int16)
_months = np.linspace(1,12,12,dtype=np.int16)
for _val in _transactions:
_year = np.random.choice([2019,2020,2021])
_month = np.random.choice(_months)
_day = np.random.choice(_days)
incomes_auto.append(Income(float(_val), 1/365,datetime.date(_year,_month,_day),None,one_time=True))
# Create an iterable of income objects
incomes = [INC1,INC2,INC3]
incomes.extend(incomes_auto)
# Define your plotting period
start_date = min([x.start_date for x in incomes])
end_date = datetime.date(2021,12,1)
# Calculate gradients and values
gradients, values = calculate_gradients(incomes, start_date, end_date)
#Plot the income objects
plot_integral(values, start_date, end_date, smooth=True, smooth_type='LSQ-bspline')
plot_integral(values, start_date, end_date, smooth=True, smooth_type='bv-bspline')
plot_integral(values, start_date, end_date, smooth=True, smooth_type='Smooth-bspline')
plot_integral(values, start_date, end_date, smooth=True, smooth_type='wiener')
plot_integral(values, start_date, end_date, smooth=False)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 15:04:54 2019
@author: z003vrzk
"""
# Python imports
import datetime, re
# Third party imports
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D, art3d, proj3d
from mpl_toolkits.mplot3d.axis3d import get_flip_min_max
from matplotlib.ticker import FuncFormatter
from scipy import interpolate, signal
import pandas as pd
# Local imports
# Declarations
#%%
class Income():
def __init__(self, income, period, start_date, end_date, best_case=None,
worst_case=None, probability=None, one_time=False):
"""Inputs
-------
income: (float/int) income you expect - define this per-period
period: (float) the time over you receive income. Format days/(365 days)
time_start: (datetime.date) start time for receiving this income
time_end: (datetime.date) end time for receiving this income
best_case: (float/int) best case income/expense scenario.
income = best_case if best_case is defined.
worst_case: (float/int) worst case income/expense scenario
probability: (list | np.array | iterable) probability distribution
between best and worst case.
Type list or np.array of shape (11,). Structure [1,p(n-1)..0].
Use this parameter to give the graph a different shape (risk distribution)
If best_case is defined and proba=None,
proba will be a liner gradient between [1 ... 0].
Try np.linspace(0,1,num=11)
one_time: (bool) if this is a one_time expense/income.
In this case use time_start to signify the date of expense"""
# Types
msg='Dates must be passed as datetime.date, got {}'
assert isinstance(start_date, datetime.date), msg.format(start_date)
assert isinstance(start_date, datetime.date), msg.format(end_date)
days = period * 365
error_msg_days = 'Enter a period greater than 1/365 and less than 365/365'
error_msg_type = 'Income must be int or float type'
assert (days >= 1 and days <= 365) is True, error_msg_days
assert (type(income)==int or type(income)==float), error_msg_type
income_msg='Income must be type int or float, got {}'
assert type(income) in [int, float], income_msg.format(type(income))
if not best_case is None:
msg='best_case worst_case must be type int or float, got {}'
assert type(best_case) in [int, float], msg.format(type(best_case))
if not worst_case is None:
msg='best_case worst_case must be type int or float, got {}'
assert type(worst_case) in [int, float], msg.format(type(worst_case))
# Keep track of base income
self.income = income
# Best case and worse case for plotting
if best_case is not None:
assert worst_case is not None, 'Please enter worst_case'
self.worst_case = worst_case
self.best_case = best_case
else:
self.best_case = income
self.worst_case = income
# Handle dates
if start_date == end_date:
"""The dates must be a gradient, and even through a transaction
Occurs on a date it must be represented by a gradient between two
Days"""
self.start_date = start_date
self.end_date = end_date + datetime.timedelta(days=1)
else:
self.start_date = start_date
self.end_date = end_date
# The period is how frequently the transaction occurs
if one_time:
self.period = 1/365
# Enforce the end_date is one day after start_date
self.end_date = start_date + datetime.timedelta(days=1)
else:
self.period = period
if probability is None:
self.probability = np.array([1,0.9,0.8,0.7,0.6,0.5,
0.4,0.3,0.2,0.1,0])
else:
msg='Length of probability array must be 11, got {}'
assert len(probability) == 11, msg.format(len(probability))
self.probability=probability
def run(self, run_time):
"""
inputs
-------
run_time: (datetime.timedelta) period you want to know derivative.
If not between self.time_start and self.time_end return 0
Return the derivative for the time period specified.
The period is by day by default. Integrating is the job of
a different class creating the graph
run_time: """
if (run_time > self.end_date or run_time < self.start_date):
return 0
else:
return self.calc_derivative()
def calc_derivative(self):
days = self.period * 365
income_proba = (self.best_case - self.worst_case)*(self.probability) + self.worst_case
income_rate = income_proba / days
return income_rate
def __repr__(self):
msg='<Income(income={}, best={}, worst={}, start={}, end={}, period={}/365>'
return msg.format(self.income,self.best_case,self.worst_case,
self.start_date,self.end_date,int(self.period * 365))
def __str__(self):
msg='{income:{},best_case:{},worst_case:{},start_date:{},end_date:{},period={}/365}'
return msg.format(self.income,self.best_case,self.worst_case,
self.start_date,self.end_date,int(self.period * 365))
def calculate_gradients(incomes, start_date, end_date):
"""Calculate the gradients from incomes
integrate the gradients from incomes to net worth
Consider a 3-dimensional space (date, risk, net value)
On each date in the future a person has a net value with projected risk
inputs
-------
incomes: (iterable) of income objects
start_date: (datetime.date) beginning date to calculate gradients from
income objects. If the date of an income is earlier than start_date,
then the income object will not appear in the resulting net worth
end_date: (datetime.date) ending date to calculate gradients from
income objects. If the date of an income is later than end_date,
then the income object will not appear in the resulting net worth
outputs
-------
gradients: (np.array) Derivative of cumulative worth distribution over
start_date to end_date
values: (np.array) Cumulative worth distribution over start_date to end_date"""
# Check income objects
lengths = []
for income in incomes:
lengths.append(len(income.probability))
msg='All income obects must have the same shape probability array. Got {}'
assert len(set(lengths)) == 1, msg.foramt(set(lengths))
# Income gradients per day
delta = end_date - start_date
dates = [(start_date + datetime.timedelta(days=i)) for i in range(delta.days)]
"""Keep track of values and gradients
values[i,1,k] is the net value at day i with risk probability k
values[i,1,:] is the net value distribution over a risk probability distribution
"""
n_days = len(dates)
risk_points = 11
values = np.zeros((n_days, 1, risk_points))
gradients = np.zeros((n_days, 1, risk_points))
"""Iterate through income objects and summate the income gradients
(Aka income/loss per day)"""
for income in incomes:
try:
index_start = dates.index(income.start_date)
except ValueError:
# Date not in list
if income.start_date <= start_date:
# Income start date is before graphing region
index_start = 0
else:
# Income start date is after graphing region
continue
try:
index_end = dates.index(income.end_date)
except ValueError:
# Date not in list
if income.end_date >= end_date:
# Income end date is after graphing region
index_end = len(dates) - 1
else:
# Income end date is before graphing region
continue
gradient = income.calc_derivative()
gradients[index_start:index_end,0,:] = gradients[index_start:index_end,0,:] + gradient
# values = integrate.cumtrapz(gradients, axis=0, initial=np.mean(gradients[0,0,:]))
values = np.cumsum(gradients, axis=0)
return gradients, values
class RotateTickLabel:
"""An event handler which subscribes to the 'draw_event' of a figure
Rotate axis labels every time the figures draw event is called"""
def __init__(self, axis, axes):
"""
Rotate a set of axis labels relative to the axis
Hold state information (axis) to define which axis ticklabels should
be redrawn
inputs
-------
axis: (mpl_toolkits.mplot3d.axis3d.Axis) This is the Axis object
you want to rotate tick labels to. It is NOT the AXES object -
see the plot example for what to pass
axes: (mpl_toolkits.mplot3d.axes3d.Axes3D) This is the Axes object
that is probably a subplot of a figure. See the plot
example below for arguments to pass"""
self.axis = axis
self.axes = axes
self.cid = axes.figure.canvas.mpl_connect('draw_event', self)
return None
def __call__(self, event):
self.set_axis_label_rotate(event)
return None
def set_axis_label_rotate(self, event):
"""Rotate a set of axis labels relative to the axis
inputs
-------
event: (matplotlib.backend_bases.DrawEvent)
https://matplotlib.org/3.2.2/api/backend_bases_api.html#matplotlib.backend_bases.DrawEvent"""
# Setup
renderer = event.renderer
axes = self.axes # Axes - includes axes.xaxis and axes.yaxis
axis = self.axis # Axis
info = axis._axinfo
mins, maxs, centers, deltas, tc, highs = axis._get_coord_info(renderer)
# Determine grid lines
minmax = np.where(highs, maxs, mins)
# Draw main axis line
juggled = info['juggled']
edgep1 = minmax.copy()
edgep1[juggled[0]] = get_flip_min_max(edgep1, juggled[0], mins, maxs)
edgep2 = edgep1.copy()
edgep2[juggled[1]] = get_flip_min_max(edgep2, juggled[1], mins, maxs)
pep = proj3d.proj_trans_points([edgep1, edgep2], renderer.M)
# Draw labels
"""The transAxes transform is used because the Text object
rotates the text relative to the display coordinate system.
Therefore, if we want the labels to remain parallel to the
axis regardless of the aspect ratio, we need to convert the
edge points of the plane to display coordinates and calculate
an angle from that."""
peparray = np.asanyarray(pep)
dx, dy = (axes.axes.transAxes.transform([peparray[0:2, 1]]) -
axes.axes.transAxes.transform([peparray[0:2, 0]]))[0]
# Rotate label
for tick_label in axis.get_majorticklabels():
angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
tick_label.set_rotation(angle)
return None
def spline_smoothing_factor(size):
high, low = (size - np.sqrt(2*size), size + np.sqrt(2*size))
return high, low
def value_label_formatter(x, pos):
"""Inputs
-------
x: (float) value of tick label
pos: () position of tick label
outputs
-------
(str) formatted tick label"""
if x > 100000000:
# 100,000,000
return '{:1.0e}'.format(x)
if x > 1000000:
# 1,000,000
return '{:1.0f}M'.format(x / 1e7)
elif x >= 1000:
return '{:1.0f}k'.format(x / 1e3)
else:
return '{:1.0f}'.format(x)
return str(x)
def plot_integral(values, start_date, end_date,
smooth=True, smooth_type='LSQ-bspline'):
"""
Plot cumulative net worth values over time
inputs
-------
values: (np.array) of cumulative net worth over time. See calculate_gradients()
start_date: (datetime.date) Start date of plotting
This MUST be the same start_date used to calculate values
end_date: (datetime.date) end date of plotting
This MUST be the same end_date used to calculate values
smooth: (bool) Apply smoothing to the 3D graph surface
smooth_type: (str) one of ['bv-bspline','LSQ-bspline','Smooth-bspline',
'wiener']. The smoothing method to apply to the 3-d surface
outputs
-------
None
"""
msg='values should be numpy array, got {}'
assert isinstance(values, np.ndarray), msg.format(type(values))
msg='date must be datetime.date, got {}'
assert isinstance(start_date, datetime.date),msg.format(type(start_date))
assert isinstance(end_date, datetime.date),msg.format(type(end_date))
# Dates for labeling x axis
delta = end_date - start_date
dates = [(start_date + datetime.timedelta(days=i)) for i in range(delta.days)]
#Apply b-spline fit to surface
if smooth:
if smooth_type == 'bv-bspline':
x = np.arange(values.shape[0]) # Dates
y = np.arange(values.shape[2]) # Probability
xy, yx = np.meshgrid(x,y)
xs = np.ravel(xy)
ys = np.ravel(yx)
# # Unpack in row-major order :)
z = values[:,0,:]
zs = np.ravel(values[:,0,:], order='F')
"""A sequence of length 5 returned by bisplrep containing the knot
locations, the coefficients, and the degree of the spline:
[tx, ty, c, kx, ky]."""
s = sum(spline_smoothing_factor(xs.shape[0])) / 2
tck = interpolate.bisplrep(xs, ys, zs, s=s*100, eps=1e-12)
z3d = interpolate.bisplev(x, y, tck)
elif smooth_type == 'LSQ-bspline':
# Least squares bivariate spline approximation
x = np.arange(values.shape[0]) # Dates
y = np.arange(values.shape[2]) # Probability
xy, yx = np.meshgrid(x,y)
xs = np.ravel(xy)
ys = np.ravel(yx)
# # Unpack in row-major order :)
z = values[:,0,:]
zs = np.ravel(values[:,0,:], order='F')
"""Weighted least-squares bivariate spline approximation
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.LSQBivariateSpline.html"""
# Find knots
# Knots are the intervals polynomials are broken into. More knots
# Mean a more precise spline
# knots = np.linspace(start, end, n_knots)
tx = np.linspace(0, x.shape[0], int(np.sqrt(2 * x.shape[0])))
ty = np.linspace(0, y.shape[0], int(np.sqrt(2 * x.shape[0])))
# Evaluate spline
LSQBSpline = interpolate.LSQBivariateSpline(xs,ys,zs,tx,ty)
z3d = LSQBSpline(x, y, grid=True)
elif smooth_type == 'Smooth-bspline':
# Smooth bivariate spline approximation
x = np.arange(values.shape[0]) # Dates
y = np.arange(values.shape[2]) # Probability
xy, yx = np.meshgrid(x,y)
xs = np.ravel(xy)
ys = np.ravel(yx)
# # Unpack in row-major order :)
z = values[:,0,:]
zs = np.ravel(values[:,0,:], order='F')
"""Smooth bivariate spline approximation
see https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.SmoothBivariateSpline.html"""
# s = sum(spline_smoothing_factor(xs.shape[0])) / 2
SmoothBSpline = interpolate.SmoothBivariateSpline(xs, ys, zs)
z3d = SmoothBSpline(x, y, grid=True)
elif smooth_type == 'wiener':
# Smooth bivariate spline approximation
x = np.arange(values.shape[0]) # Dates
y = np.arange(values.shape[2]) # Probability
xy, yx = np.meshgrid(x,y)
z = values[:,0,:]
z3d = signal.wiener(z, mysize=(25,1))
else:
x = np.arange(values.shape[0])
y = np.arange(values.shape[2])
xy, yx = np.meshgrid(x,y)
z3d = values[:,0,:]
# X labels - dates
num_ticks = 4
tick_index = np.linspace(min(x), max(x), num=num_ticks, dtype=np.int16)
xticks = x[tick_index]
xlabel_index = tick_index
xlabel_date = [dates[idx] for idx in xlabel_index]
xlabels = [x.isoformat() for x in xlabel_date]
# Y labels
yticks = [int(y.shape[0]/2)]
ylabels = ['Worst → Best Case']
"""2-dimensional plotting"""
fig2d = plt.figure(1)
ax2d = fig2d.add_subplot(111)
z2d = values.mean(axis=2)
line = ax2d.plot(x, z2d, label='Bank Value', linewidth=2)
ax2d.set_title('Mean Value Non-smoothed')
ax2d.set_xlabel('Date')
ax2d.set_ylabel('Total Value [$]')
ax2d.set_xticks(xticks)
ax2d.set_xticklabels(xlabels)
"""3-dimensional plotting"""
fig3d = plt.figure(2)
ax3d = fig3d.add_subplot(111, projection='3d')
surf = ax3d.plot_surface(xy, yx, z3d.transpose(), cmap='summer', linewidth=0,
antialiased=False)
# Label date axis
ax3d.set_xticks(xticks)
ax3d.set_xticklabels(xlabels)
# Label probability axis
ax3d.set_yticks(yticks)
ax3d.set_yticklabels(ylabels)
# Connect event to rotate probability axsi label
rotateTickLabel = RotateTickLabel(ax3d.yaxis, ax3d)
fig3d.canvas.mpl_connect('draw_event', rotateTickLabel)
# Label value axis
formatter = FuncFormatter(value_label_formatter)
ax3d.zaxis.set_major_formatter(formatter)
# ax3d.tick_params(pad=10)
# Label axis
fig3d.colorbar(surf, shrink=0.5, aspect=10)
ax3d.set_title('Value, Time, Risk')
ax3d.set_xlabel('Date', labelpad=15)
ax3d.set_zlabel('Total Value [$]', labelpad=10)
# Elev is in z plane, azim is in x,y plane
ax3d.view_init(elev=20, azim=125)
for angle in range(100,125):
ax3d.view_init(elev=20, azim=angle)
plt.draw()
plt.pause(0.003)
plt.show()
return None
def create_transaction_objects(transactions_dataframe,
value_col='Amount',
date_col='Date'):
"""
inputs
-------
transactions_dataframe: (pandas.DataFrame) of transaction records. Each
row should represent a single income/expense with information about the
value of the transaction, and date of the transaction
Example :
{
Date Amount Simple Description
0 6/3/2019 -52.29 H-E-B #388 AUSTIN TX
1 5/23/2019 -2.92 SQ *BAKERY LORRAINE Austin TX
2 5/20/2019 37.3 Transfer
}
value_col: (str) denotating which column the value of the transaction is
in. Above the value column is named 'Amount'
date_col: (str) denotating which column the date of the transaction is in.
Above the date column is named 'Date'
outputs
--------
transactions: (list) of Income objects for each transaction (row) in
transactions_dataframe
"""
incomes = []
date_format = r'%m/%d/%Y'
period = 1/365
reg = re.compile('[^0-9.-]')
for idx, row in transactions_dataframe.iterrows():
# TODO add more robust regex here
# Replace commas and '$' strings
income_str = row[value_col]
income_str = income_str.replace(',', '')
income = float(income_str)
date_str = row[date_col]
my_date = datetime.datetime.strptime(date_str, date_format) # datetime
my_date = my_date.date()
income_obj = Income(income, period, my_date, my_date,
one_time=True)
incomes.append(income_obj)
return incomes
def categorize_transactions(transaction_dataframe,
cat_col='Category',
date_col='Date',
value_col='Amount',
by_year=True):
"""Return a set of categories of expenses and average
spending on these categories over the timeframe from the imported
data.
inputs
-------
transaction_dataframe: (pd.DataFrame)
cat_col: (str)
date_col: (str)
value_col: (str)
by_year: (bool)
Returns
-------
categories: (dict) of category: expense/year
categories_year: (dict) of category: expense/year. This is not
averaged across the whold data period = returns a category for each
year
"""
cat_tags = list(set(transaction_dataframe[cat_col]))
categories = {}
categories_year = {}
dates = transaction_dataframe[date_col]
date_format = r'%m/%d/%Y'
dates = [datetime.strptime(x, date_format) for x in dates]
unique_years = list(set([x.year for x in dates]))
for cat in cat_tags:
cat_index = transaction_dataframe[cat_col] == cat
cat_vals = transaction_dataframe.loc[cat_index][value_col]
cat_vals = cat_vals.str.replace(',','').astype(float)
cat_val = cat_vals.sum()
categories[cat] = cat_val
date_series = pd.Series(dates)
year_series = date_series.map(lambda x: x.year)
for year in unique_years:
for cat in cat_tags:
cat_index = (transaction_dataframe[cat_col] == cat) & (year_series == year)
cat_vals = transaction_dataframe.loc[cat_index][value_col]
cat_vals = cat_vals.str.replace(',','').astype(float)
cat_val = cat_vals.sum()
new_cat = cat + '_' + str(year)
categories_year[new_cat] = cat_val
if by_year:
return categories_year
else:
return categories
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 19:39:44 2019
@author: z003vrzk
"""
# Python imports
import datetime, unittest, re
# Third party imports
import numpy as np
# Local imports
from finance_graphing import (create_transaction_objects, Income,
plot_integral, calculate_gradients)
#%%
class Testing(unittest.TestCase):
def test_gradients_values(self):
# 10 dollars a day
inc1 = Income(10, 1/365, datetime.date(2020,1,1), datetime.date(2020,1,5))
# Single 10 dollar expense
inc2 = Income(-20, 1/365, datetime.date(2020,1,2), datetime.date(2020,1,2), one_time=True)
# Calculate gradients over days
start_date = datetime.date(2020,1,1)
end_date = datetime.date(2020,1,5)
incomes = [inc1, inc2]
gradients, values = calculate_gradients(incomes, start_date, end_date)
"""Gradients should look like this
array([[[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]],
[[-10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10.]],
[[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]],
[[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]])"""
test_gradient =np.array([[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[-10., -10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[ 0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]]])
test_values = np.array([[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]]])
self.assertTrue(np.array_equal(test_gradient, test_gradient))
self.assertTrue(np.array_equal(test_values, test_values))
return None
def test_dates(self):
# 10 dollars a day
inc1 = Income(10, 1/365,
datetime.date(2020,1,1), datetime.date(2020,1,5))
# Single 10 dollar expense
inc2 = Income(-20, 1/365,
datetime.date(2020,1,2), datetime.date(2020,1,2), one_time=True)
# A range of dates should not be an issue
self.assertTrue(inc1.start_date == datetime.date(2020,1,1))
self.assertTrue(inc1.end_date == datetime.date(2020,1,5))
# One-time expenses should range multiple days even if it occurs on one day
# This is because a gradient needs to be calculated between days
self.assertTrue(inc2.start_date == datetime.date(2020,1,2))
self.assertTrue(inc2.end_date == datetime.date(2020,1,3))
return None
def test_income_gradient(self):
# 10 dollars a day
inc1 = Income(10, 1/365,
datetime.date(2020,1,1), datetime.date(2020,1,5))
# Single 10 dollar expense
inc2 = Income(-20, 1/365,
datetime.date(2020,1,2), datetime.date(2020,1,2), one_time=True)
# Test gradient
gradient1 = inc1.calc_derivative()
gradient2 = inc2.calc_derivative()
self.assertTrue(np.array_equal(gradient1, np.array([float(10)] * 11)))
self.assertTrue(np.array_equal(gradient2, np.array([float(-20)] * 11)))
return None
def test_calc_gradients(self):
# 10 dollars a day
inc1 = Income(10, 1/365, datetime.date(2020,1,1), datetime.date(2020,1,5))
# Single 10 dollar expense
inc2 = Income(-20, 1/365,
datetime.date(2020,1,2), datetime.date(2020,1,2), one_time=True)
# Test gradient
start_date = datetime.date(2020,1,1)
end_date = datetime.date(2020,1,5)
gradients1, values1 = calculate_gradients([inc1,inc2], start_date, end_date)
gradients_test1=np.array([[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[-10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.,-10.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]]])
values_test1=np.array([[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]]])
# Test gradient
start_date = datetime.date(2019,12,31)
end_date = datetime.date(2020,1,3)
gradients2, values2 = calculate_gradients([inc1,inc2], start_date, end_date)
gradients_test2=np.array([[
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]]])
values_test2=np.array([[
[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]],
[[10.,10.,10.,10.,10.,10.,10.,10.,10.,10.,10.]]])
self.assertTrue(np.array_equal(gradients1, gradients_test1))
self.assertTrue(np.array_equal(values1, values_test1))
self.assertTrue(np.array_equal(gradients2, gradients_test2))
self.assertTrue(np.array_equal(values2, values_test2))
return None
def test_income_probability(self):
# 10 dollars a day
inc1 = Income(10, 1/365, datetime.date(2020,1,1), datetime.date(2020,1,5))
# Confirm the default probability
a = np.array([1. , 0.9, 0.8, 0.7, 0.6, 0.5,0.4,0.3, 0.2, 0.1,0.])
self.assertTrue(np.array_equal(inc1.probability, a))
# Confirm custom probability
probability=[1,0.98,0.9,0.85,0.8,0.75,0.70,0.68,0.65,0.5,0.45]
inc2 = Income(10, 1/365, datetime.date(2020,1,1), datetime.date(2020,1,5),
probability=probability)
self.assertTrue(np.array_equal(inc2.probability, probability))
return None
def test_best_worst_case(self):
# Income of $100 to $50 over 10 days
period = 10/365
start_date=datetime.date(2020,1,1)
end_date=datetime.date(2020,1,2)
best_case = 100
worst_case = 50
inc1 = Income(income=100, period=period,
start_date=start_date, end_date=end_date,
best_case=best_case, worst_case=worst_case)
daily_gradient = inc1.calc_derivative()
value = (best_case - worst_case) * inc1.probability + worst_case
daily_gradient_test = value / (period * 365)
self.assertTrue(np.array_equal(daily_gradient,daily_gradient_test))
return None
def test_regex_match(self):
"""# TODO
This regex is weak. Lots of the test cases will output odd numbers.
I would have to test for lots of conditionals like
If more that (2) '.' appear in the string sequence
A number shouldn't be represnted like 2.334.05 (other countries maybe?)
If numbers are interrupted by characters other than ',' or '.'
This is not a valid number : 24A33.05
Even or odd numbers
This is negative : (5.45)
This is negative : -5.45
This is something : -(5.45)
This is positive : 5.45
This is positive : +5.45
Is the data formatted where 5.45 is a transaction out of account or into
account?
This is transaction out of account : -5.45
Or is this? : 5.45
"""
reg = re.compile('[^0-9.-]')
s1 = 'name ni4nvi $03,200.40'
s2 = '(-$32,43.22)'
s3 = '$4,300.00'
s4 = '-$4,300.00'
s5 = '+3i2nndfs!@#$%^&*()2.jnfinn%55'
s6 = '#4,304'
s7 = '#4.334455.0040'
s8 = ''
s9 = ''
s10 = ''
test_case = [s1,s2,s3,s4,s5,s6,s7,s8,s9,s10]
for test in test_case:
result = re.sub(reg, '', test)
print(result)
return None
if __name__ == '__main__':
unittest.main()
"""
~~ Order Filtering ~~
Domain acts as a mask over each pixel of x
For every non-zero element in the mask of x, a list is constructed
The list is sorted, and the 'rank' element from the list is selected
from scipy import signal
x = np.arange(25).reshape(5, 5)
domain = np.identity(3)
signal.order_filter(x, domain, 0)
signal.order_filter(x, domain, 1)
signal.order_filter(x, domain, 2)
Example 1
rank = 1
domain = [[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]
x = [[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]]
For element [0,0] the domain mask is centered, and the non-masked elements
are [0,0,6] (elements are zero when the mask is off of x).
Since rank is 1, the 1st element from the list is selected (0).
For element [1,2] the domain mask is centered, and the non-masked elements
are [1,7,13].
Since rank is 1, the 1st element from the list is selected (7).
~~ Median filter ~~
Same idea as above, but the median of the list is chosen
from scipy import signal
x = np.arange(25).reshape(5, 5)
kernel_size = 3
signal.medfilt(x, kernel_size=kernel_size)
Element [1,0]
Elements in list are [0, 0, 0, 0, 1, 5, 6, 10, 11]
The median of the list is 1
"""
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 22:44:35 2020
@author: z003vrzk
"""
# Python imports
import setuptools
#%%
with open('README.md', 'r') as f:
long_description = f.read()
short_description="3D graphing of incomes/expense versus risk"
setuptools.setup(
name="finance-graph", # Replace with your own username
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description=short_description,
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/johnvorsten/Finance-Calculator",
packages=setuptools.find_packages(),
license='MIT',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=['scikit-learn>=0.23.1',
'scipy',
'matplotlib',
'pandas',
'numpy']
)<file_sep>""""""
# Python imports
# Third party imports
import matplotlib as mpl
import numpy as np
from scipy.misc import comb
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Local imports
# Declarations
#%%
def bernstein_poly(i, n, t):
return comb(n, i) * (t**(n - i)) * (1 - t)**i
def generate_points_bezier_curve(points, nTimes=1000):
nPoints = len(points)
xPoints = np.array([p[0] for p in points])
yPoints = np.array([p[1] for p in points])
zPoints = np.array([p[2] for p in points])
t = np.linspace(0.0, 1.0, nTimes)
polynomial_array = np.array(
[bernstein_poly(i, nPoints - 1, t) for i in range(0, nPoints)])
xvals = np.dot(xPoints, polynomial_array)
yvals = np.dot(yPoints, polynomial_array)
zvals = np.dot(zPoints, polynomial_array)
return xvals, yvals, zvals
def plot_points_bezier_curve():
nPoints = 4
points = np.random.rand(nPoints, 3) * 200
xpoints = [p[0] for p in points]
ypoints = [p[1] for p in points]
zpoints = [p[2] for p in points]
xvals, yvals, zvals = bezier_curve(points, nTimes=1000)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(xvals, yvals, zvals, label='bezier')
ax.plot(xpoints, ypoints, zpoints, "ro")
for nr in range(len(points)):
ax.text(points[nr][0], points[nr][1], points[nr][2], nr)
plt.show()
return None
if __name__ == "__main__":
plot_points_bezier_curve()<file_sep># Finance-Calculator
Visualization of incomes and outcomes in a (3) dimensional space

Project Description
The goal of this project is to visualize income and expenses. The output visualization should give the viewer an understanding of :
1. Their income over time (past and future if desired)
2. How income is impacted by best-case and worst-case scenarios
This project was inspired by a discussion about finances. How much money do I have to spend, not only now, but at future dates?
Free cash is complicated by :
1. Current and future levels of income
2. Current and future expenses
3. Uncertainty of future expenses - Will my car break down?
What will future disposable income look like. This package has the following features :
1. Consider past expenses
2. Consider future projected expenses and incomes
a. Graph future expenses with a level of uncertainty. This will be the third axis – probability
3. Look presentation-worthy
4. Be able to parse historical data – aka take in a spreadsheet of historical bank transactions to make historical graphing easy
## Core functions and classes
### Income(income, period, start_date, end_date, best_case=None, worst_case=None, probability=None, one_time=False)
The income class models cash incomes and expenses. The class can handle transactions that occur over time (yearly incomes), or at one time (single purchases). It optionally accepts a probability matrix for projecting worst/best case scenarios.
Parameters
* income : (float/int) income you expect - define this per-period
* period : (float) the time over you receive income. Format days/(365 days)
* time_start : (datetime.date) start time for receiving this income
* time_end : (datetime.date) end time for receiving this income
* best_case : (float/int) best case income/expense scenario.
income = best_case if best_case is defined.
* worst_case : (float/int) worst case income/expense scenario
* probability : (list | np.array | iterable) probability distribution
between best and worst case.
Type list or np.array of shape (11,). Structure [1,p(n-1)..0].
Use this parameter to give the graph a different shape (risk distribution)
If best_case is defined and proba=None,
proba will be a liner gradient between [1 ... 0].
Try np.linspace(0,1,num=11)
* one_time : (bool) if this is a one_time expense/income.
In this case use time_start to signify the date of expense
### calculate_gradients(incomes, start_date, end_date)
Calculate the gradients from incomes and integrate the gradients from incomes to net worth
Parameters
* incomes : (iterable) of income objects
* start_date : (datetime.date) beginning date to calculate gradients from
income objects. If the date of an income is earlier than start_date,
then the income object will not appear in the resulting net worth
* end_date : (datetime.date) ending date to calculate gradients from
income objects. If the date of an income is later than end_date,
then the income object will not appear in the resulting net worth
outputs
* gradients : (np.array) Derivative of cumulative worth distribution over
start_date to end_date
* values : (np.array) Cumulative worth distribution over start_date to end_date
### plot_integral(values, start_date, end_date, smooth=True, smooth_type='LSQ-bspline')
Plot cumulative net worth values over time
Parameters
* values : (np.array) of cumulative net worth over time. See calculate_gradients()
* start_date : (datetime.date) Start date of plotting
This MUST be the same start_date used to calculate values
* end_date : (datetime.date) end date of plotting
This MUST be the same end_date used to calculate values
* smooth : (bool) Apply smoothing to the 3D graph surface
* smooth_type : (str) one of ['bv-bspline','LSQ-bspline','Smooth-bspline',
'wiener']. The smoothing method to apply to the 3-d surface
Outputs
* Graph (2D and 3D)
## Usage Example
1. Create income objects.
2. (Optional) Import bank transaction .csv file
3. Calculate net worth gradient
4. Graph net worth values
```python
# Basic income - $60,000 to $40,000 per year
INC1 = Income(60000*0.7, 365/365, datetime.date(2019,6,5), datetime.date(2023,6,5), best_case=60000*0.7, worst_case=40000*0.7) #Income
# Single expense of $4,000, best $3,000 worst $5,000
INC2 = Income(-4000, 1/365,datetime.date(2019,10,1),datetime.date(2020,10,1), best_case=-3000, worst_case=-5000, one_time=True)
# Single expense of $7,500
INC3 = Income(-7500,1/365,datetime.date(2021,10,20),datetime.date(2021,10,20), one_time=True)
# Monthly expense of $2,000
INC4 = Income(-2000,31/365, datetime.date(2019,6,5), datetime.date(2025,6,5), best_case=-1800, worst_case=-2100, one_time=True)
# Other income bi-weekly
INC5 = Income(450, 14/365, datetime.date(2019, 6, 5), datetime.date(2025, 6, 5), best_case=500, worst_case=440)
# Single expense of $12,500 yearly over two years ($25,000 total expense)
# Range from $10,000 to $15,000 expense
INC6 = Income(-12500, 365/365, datetime.date(2023,6,5), datetime.date(2025,6,5), best_case=-10000,worst_case=-15000)
# Import bank transactions .csv for projection of daily expenses
path = r'../path_to/Transaction_Data.csv'
transaction_dataframe = pd.read_csv(path)
incomes_auto = create_transaction_objects(transaction_dataframe, value_col='Amount',date_col='Date')
# Create an iterable of income objects
incomes = [INC1, INC2,INC3,INC4,INC5,INC6]
incomes.extend(incomes_auto)
# Define your plotting period
start_date = min([x.start_date for x in incomes])
end_date = datetime.date(2020,2,1)
# Calculate gradients and values
gradients, values = calculate_gradients(incomes, start_date, end_date)
#Plot the income objects
plot_integral(values, start_date, end_date, smooth=True, smooth_type='LSQ-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='bv-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='Smooth-bspline')
# plot_integral(values, start_date, end_date, smooth=True, smooth_type='wiener')
```
The plotting function outputs a 2D image as well as a 3D image

Transactions on a 1-day time period can make the graph appear “Choppy”. This is especially true for large transactions relative to the current account balance.

This figure shows the “probability” axis of the 3D image. Income can be projected in the worst case (0 probability) or best case (1 probability). Different distributions can be input besides a linear distribution.

<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 13:13:29 2019
@author: z003vrzk
"""
# Python imports
from math import factorial
# Third party imports
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from scipy import interpolate
from datetime import date, timedelta, datetime
# Local imports
# Declarations
#%%
time_start = date(2016, 9, 28)
time_end = date(2019, 6, 5)
delta = time_end - time_start
dates = [(time_start + timedelta(days=i)) for i in range(delta.days)]
m = delta.days
n = 11
_path = r".\JVImports\Finance_Graph_values.npy"
values = np.load(_path)
"""New Method"""
#1 use scipy scipy.interpolate.bisplev with scipy.interpolate.bisplrep
#2 OR calculate bezier surface directly
#Get vals to a points matrix of rank 2 [[x,y,z], [...]]
m, n = values.shape[0], values.shape[1]
pts = np.zeros((m*n, 3))
idx = 0
for _row in range(m):
for _col in range(n):
pts[idx, 0] = _row
pts[idx, 1] = _col
pts[idx, 2] = values[_row,_col]
idx += 1
sets = 20
_segment = min(sets*n, pts.shape[0]*0.1)
tck = interpolate.bisplrep(pts[:_segment,0], pts[:_segment,1], pts[:_segment,2])
x_grid = np.arange(0, values.shape[0], 1)
y_grid = np.linspace(1, values.shape[1],num=11)
vals = interpolate.bisplev(x_grid, y_grid, tck)
"""Plotting method"""
#Start doing plotting
fig3d = plt.figure(1)
#fig2d = plt.figure(2)
ax3d = fig3d.add_subplot(111, projection='3d')
#ax2d = fig2d.add_subplot(111)
smooth = True
if smooth:
m, n = values.shape[0], values.shape[1]
pts = np.zeros((m*n, 3))
idx = 0
for _row in range(m):
for _col in range(n):
pts[idx, 0] = _row
pts[idx, 1] = _col
pts[idx, 2] = values[_row,_col]
idx += 1
# sets = 100
# _segment = int(min(sets*n, pts.shape[0]*0.5))
# tck = interpolate.bisplrep(pts[:_segment,0], pts[:_segment,1], pts[:_segment,2])
tck = interpolate.bisplrep(pts[:,0], pts[:,1], pts[:,2])
x_grid = np.arange(0, values.shape[0], 1)
y_grid = np.linspace(1, values.shape[1],num=11)
Z3d = interpolate.bisplev(x_grid, y_grid, tck).transpose()
X_ = np.arange(0, len(dates), 1)
y_ = np.linspace(1, 0, num=11)
X, y = np.meshgrid(X_, y_)
else:
X_ = np.arange(0,len(dates), 1)
y_ = np.linspace(1,0,num=11)
X, y = np.meshgrid(X_, y_)
Z3d = values.transpose() #Get integrated values
#Z2d = values.mean(axis=1)
surf = ax3d.plot_surface(X, y, Z3d, cmap='summer', linewidth=0,
antialiased=False)
#line = ax2d.plot(X_, Z2d, label='Bank Value', linewidth=2)
num_ticks = 4
tick_index = np.linspace(min(X_), max(X_), num=num_ticks, dtype=np.int16)
#ticks = X[tick_index]
ticks = X_[tick_index]
ax3d.set_xticks(ticks) #Set the locations of tick marks from sequence ticks
#ax2d.set_xticks(ticks)
label_index = tick_index
label_date = [dates[idx] for idx in label_index]
labels = [x.isoformat() for x in label_date]
ax3d.set_xticklabels(labels) #Define the strings to be defined
#ax2d.set_xticklabels(labels)
fig3d.colorbar(surf, shrink=0.5, aspect=5)
ax3d.set_xlabel('Date')
ax3d.set_ylabel('Probability')
ax3d.set_zlabel('Total Value')
#ax2d.set_xlabel('Date')
#ax2d.set_ylabel('Total Value')
ax3d.view_init(elev=20, azim=125) #elev is in z plane, azim is in x,y plane
for angle in range(100,125):
ax3d.view_init(elev=20, azim=angle)
plt.draw()
plt.pause(0.003)
plt.show()
def bernstein_poly(i, n, t):
return (factorial(n)/(factorial(i)*factorial(n-i))) * t**i * (1 - t)**(n - i)
#"""Old plotting method"""
##Start doing plotting
#fig3d = plt.figure(1)
#fig2d = plt.figure(2)
#ax3d = fig3d.add_subplot(111, projection='3d')
#ax2d = fig2d.add_subplot(111)
#
#X_ = np.arange(0,len(dates), 1)
#y_ = np.linspace(1,0,num=11)
#X, y = np.meshgrid(X_, y_)
#Z3d = values.transpose() #Get integrated values
#Z2d = values.mean(axis=1)
#
#
#surf = ax3d.plot_surface(X, y, Z3d, cmap='summer', linewidth=0,
# antialiased=False)
#line = ax2d.plot(X_, Z2d, label='Bank Value', linewidth=2)
#
#num_ticks = 4
#tick_index = np.linspace(min(X_), max(X_), num=num_ticks, dtype=np.int16)
##ticks = X[tick_index]
#ticks = X_[tick_index]
#ax3d.set_xticks(ticks) #Set the locations of tick marks from sequence ticks
#ax2d.set_xticks(ticks)
#
#label_index = tick_index
#label_date = [dates[idx] for idx in label_index]
#labels = [x.isoformat() for x in label_date]
#ax3d.set_xticklabels(labels) #Define the strings to be defined
#ax2d.set_xticklabels(labels)
#fig3d.colorbar(surf, shrink=0.5, aspect=5)
#
#ax3d.set_xlabel('Date')
#ax3d.set_ylabel('Probability')
#ax3d.set_zlabel('Total Value')
#ax2d.set_xlabel('Date')
#ax2d.set_ylabel('Total Value')
#
#ax3d.view_init(elev=20, azim=125) #elev is in z plane, azim is in x,y plane
#
#for angle in range(100,125):
# ax3d.view_init(elev=20, azim=angle)
# plt.draw()
# plt.pause(0.003)
#
#plt.show() | f786e1b7a03bbddaf370ae6df317a74cf8475160 | [
"Markdown",
"Python"
] | 7 | Python | johnvorsten/Finance-Calculator | 2797a8861301ebbe0803dbdfe39488b66eb9f0f5 | 3d076450e6c78d128a43ad6be33b12d2142555fb |
refs/heads/master | <repo_name>Chutithep88/ManageInternSystem<file_sep>/repeatedly.php
<?php
session_start();
include_once 'dbconnect.php';
$iduseremail = $_SESSION['email'];
//ป้องกันไม่ให้เข้าถึงหน้านี้โดยไม่ผ่าน Login
if(!isset($_SESSION['email'])){
header("location: index.php");
return;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ไฟล์ซ้ำ</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
<meta name="description" content="A free template from http://ws-templates.com">
<meta name="keywords" content="keyword1,keyword2"/>
<link href="css/screen.css" media="screen" rel="stylesheet"/>
<link href="css/style.css" media="screen" rel="stylesheet"/>
<link rel="stylesheet" href="nivo-slider/default/default.css" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider/default/nivo-slider.css" type="text/css" media="screen" />
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 0px solid #cbcbcb;
}
#content1{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
a.p_Button{
display: block;
height:26px;
width:70px;
background-color:#84cdf7;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.p_Button2{
display: block;
height:26px;
width:70px;
background-color:#878c8f;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.red{
color:red;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
<script src="js/script.js"></script>
</head>
<body>
<br/>
<h3><center>เจอไฟล์ซ้ำ</center></h3>
<h4><center>คุณได้อัพโหลดไฟล์ไปแล้ว กรุณาแจ้งแอดมินถ้าต้องการอัพโหลดไฟล์เพิ่มเติม</center></h4>
<h4><center>Tel : 000-000-000-000-000</center></h4>
<div align="center">
<button class='btn btn-danger' >
<a href='detail.php' style='color:white' style=''>ย้อนกลับ</a>
</button>
</div>
</body>
</html><file_sep>/register.php
<?php
include_once 'dbconnect.php';
session_start();
if (isset($_POST['signup'])) {
//3.save data into posts table เก็บข้อมูลไว้ในตัวแปรของ posts table
$name = mysqli_real_escape_string($conn,$_POST['username']);
$email = $_POST['email'];
$passwd = $_POST['password'];
$cpasswd = $_POST['confirmpassword'];
$Fname = $_POST['firstname'];
$Lname = $_POST['lastname'];
$edu = $_POST['education'];
//ตัวนี้ไม่ใช้ตัวรับข้อมูล resume แต่เป็นการเก็บข้อมูล "ความสนใจในการฝึกงาน"
$resume = $_POST['resume'];
$detail = $_POST['detail'];
//เพิ่มข้อมูล(เช็คว่ามีการกรอกพาสเวิสเหมือนกันหรือไม่ และ ไอดี พาสเวิส รายละเอียดของนักศึกษาฝึกงานเข้าไปในดาต้าเบส)
if ($passwd != $cpasswd) {
$passwd_error = "Password and Confirm Password <PASSWORD>!";
} else {
//ตั้งให้ตัวแปรมีการเก็บค่า username and email เพื่อไปเช็คใน DB ว่ามีช้อมูลเดิมอยู่แล้วรึไม่
$chuser = "SELECT * FROM posts WHERE username = '$name' ";
$result1 = mysqli_query($conn,$chuser) or die(mysqli_error($conn));
$chemail = "SELECT * FROM posts WHERE email = '$email' ";
$result2 = mysqli_query($conn,$chemail) or die(mysqli_error($conn));
if(mysqli_num_rows($result2) > 0){
echo "อีเมล์นี้มีคนใช้แล้ว กรุณากรอกอีเมล์ใหม่ค่ะ";
$emailmiss = "<br/><br/><a href='register.php'>Click to Register again</a> ";
echo $emailmiss;
exit();
}else if(mysqli_num_rows($result1) > 0){
echo "นามแฝงนี้มีคนใช้แล้ว กรุณากรอกนามแฝงใหม่ค่ะ";
$emailmiss = "<br/><br/><a href='register.php'>Click to Register again</a> ";
echo $emailmiss;
exit();
}else{
echo "นามแฝงและอีเมล์ไม่ซ้้ำค่ะ";
}
//เพิ่มข้อมูลลง DB
$query = "INSERT INTO posts(username,email,password,Firstname,Lastname,Education,Resume,Detail,SIDd,Active,Pass)
VALUES('" . $name . "','" . $email . "','"
. md5($passwd) . "' ,
'" . $Fname . "' , '" . $Lname . "' ,
'" . $edu . "' , '" . $resume . "' ,
'" . $detail . "','" .session_id() . "','" . 'No' . "' , '" . '0' . "' )";
if (mysqli_query($conn,$query)) {
//$msg_success = "<br/><br/><h3><center><font color='white'>Successfully registered! <br/>Please check your email to activate account</font></center></h3>";
header("location: successregister.php");
//ปุ๋มล็อกอินของเก่า
//<br/><br/><center><button class='login100-form-btn'><a href='index.php'>Click here to login</a></button></center>
//ส่งอีเมล์ไปยัง user เพื่อแจ้งให้ Activate ID
//$Uid = mysqli_insert_id($conn);
// $strTo = $_POST['email'];
// $strSubject = "Activate Member account";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "Activate account click here.<br/>";
// $strMessage .= "http://localhost/pharmacyintern/activate.php?sid=".session_id()."&uid=".$Uid."<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
//ส่งเมล์แจ้งเตือนไปยัง Admin ว่ามี User ได้สมัครเข้ามาในระบบแล้ว
// $strTo = <EMAIL>;
// $strSubject = "มี User เข้ามาสมัครแล้ว";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "นักศึกษา.<br/>";
// $strMessage .= "http://localhost/pharmacyintern/activate.php?sid=".session_id()."&uid=".$Uid."<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
}else{
// $msg_error = "<br/><br/><h3><center><font color='white'>Error in registration, please try again!</font></center></h3>
// <br/><br/><center><button class='login100-form-btn'><a href='register.php'>Click here to Register again</a></button></center>";
//when user cant register correctly. it'll sent to failregister.php
header("location: failregister.php");
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>สมัครสมาชิก</title>
<link rel="stylesheet" href="css/w3.css">
<link rel="stylesheet" href="css/bootstrap.min">
<script src="scripts/bootstrap.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
font-family: Helvetica, Arial, sans-serif;
overflow: hidden;
}
.ghost {
position: absolute;
left: -100%;
}
.framed {
position: absolute;
top: 50%; left: 50%;
width: 25rem;
margin-left: -12.5rem;
}
.logo {
margin-top: -19em;
cursor: default;
}
.form {
margin-top: -13.0em;
transition: 1s ease-in-out;
}
.input {
-moz-box-sizing: border-box;
box-sizing: border-box;
font-size: 1.125rem;
line-height: 3rem;
width: 100%; height: 3rem;
color: #444;
background-color: rgba(255,255,255,.9);
border: 0;
border-top: 1px solid rgba(255,255,255,0.7);
padding: 0 1rem;
font-family: 'Open Sans', sans-serif;
}
.input:focus {
outline: none;
}
.input--top {
border-radius: 0.5rem 0.5rem 0 0;
border-top: 0;
}
.input--submit {
background-color: rgba(92,168,214,0.9);
color: #fff;
font-weight: bold;
cursor: pointer;
border-top: 0;
border-radius: 0 0 0.5rem 0.5rem;
margin-bottom: 1rem;
}
.text {
color: #fff;
text-shadow: 0 1px 1px rgba(0,0,0,0.8);
text-decoration: none;
}
.text--small {
opacity: 0.85;
font-size: 0.75rem;
cursor: pointer;
}
.text--small:hover {
opacity: 1;
}
.text--omega {
width: 200%;
margin: 0 0 1rem -50%;
font-size: 1.5rem;
line-height: 1.125;
font-weight: normal;
}
.text--centered {
display: block;
text-align: center;
}
.text--border-right {
border-right: 1px solid rgba(255,255,255,0.5);
margin-right: 0.75rem;
padding-right: 0.75rem;
}
.legal {
position: absolute;
bottom: 1.125rem; left: 1.125rem;
}
.photo-cred {
position: absolute;
right: 1.125rem; bottom: 1.125rem;
}
.fullscreen-bg {
position: fixed;
z-index: -1;
top:0; right:0; bottom:0; left:0;
background: url(img/register.jpg) center;
background-size: cover;
}
#toggle--login:checked ~ .form--signup { left:200%; visibility:hidden; }
#toggle--signup:checked ~ .form--login { left:-100%; visibility:hidden; }
@media (height:300px){.legal,.photo-cred{display:none}}
</style>
</head>
<body>
<input type="radio" checked id="toggle--login" name="toggle" class="ghost" />
<input type="radio" id="toggle--signup" name="toggle" class="ghost" />
<br />
<br />
<br />
<label><b><center><h1 style="background-color:#FCF3CF;" >สมัครสมาชิก</h1></center></b></label>
<form role="form" action="register.php" method="post" name="signupform" class="form form--login framed">
<input class="input" type="text" name="username" placeholder="Username">
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" class="input" />
<input class="input" type="<PASSWORD>" name="confirmpassword" placeholder="<PASSWORD>">
<span class="text-danger">
<?php
if (isset($passwd_error)){
echo $passwd_error;
}
?>
</span>
<input type="email" name="email" placeholder="Email" class="input input--top" />
<input class="input" type="text" name="firstname" placeholder="ชื่อ">
<input class="input" type="text" name="lastname" placeholder="นามสกุล">
<input class="input" type="text" name="education" placeholder="การศึกษา">
<input class="input" type="text" name="resume" placeholder="ความสนใจในการฝึกงาน">
<textarea class="input" type="text" name="detail" placeholder="รายละเอียดเกี่ยวกับตัวเอง(ไม่เกิน 300 ตัวอักษร)" wrap="hard" id="txt" onkeyup="checknum(document.getElementById('txt').value,document.getElementById('shownum'));"></textarea>
<span id="shownum"></span>
<input type="submit" name="signup" value="Register" class="input input--submit" />
<label><b><a href="index.php"><center>Login</center></a></b></label>
</form>
<div class="fullscreen-bg"></div>
</form>
<!--display message -->
<span class="text-success">
<?php
if (isset($msg_success)) {
echo $msg_success;
}
?>
</span>
<span class="text-danger">
<?php
if (isset($msg_error)) {
echo $msg_error;
}
?>
</span>
<!-- <div class="limiter">
<div class="container-login100" style="background-image: url('');">
<div class="wrap-login100">
<form class="login100-form validate-form" role="form" action="register.php" method="post" name="signupform">
<span class="login100-form-logo">
<i class="zmdi zmdi-landscape"></i>
</span>
<span class="login100-form-title p-b-34 p-t-27">
Register
</span>
<div class="wrap-input100 validate-input" data-validate="Enter username">
<input class="input100" type="text" name="username" placeholder="Username">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter password">
<input class="input100" type="<PASSWORD>" name="password" placeholder="<PASSWORD>">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter confirmpassword">
<input class="input100" type="<PASSWORD>" name="confirmpassword" placeholder="<PASSWORD>">
<span class="focus-input100" data-placeholder=""></span>
<span class="text-danger">
</span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter email">
<input class="input100" type="text" name="email" placeholder="Email">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Enter firstname">
<input class="input100" type="text" name="firstname" placeholder="ชื่อ">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Enter lastname">
<input class="input100" type="text" name="lastname" placeholder="นามสกุล">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Enter education">
<input class="input100" type="text" name="education" placeholder="การศึกษา">
<span class="focus-input100" data-placeholder=""></span>
</div>
<!- name ยังคงเป็นตัวแปร resume เหมือนเดิม ของจริงคือ ตัวเก็บข้อมูล ความสนใจในการฝึกงาน-->
<!-- <div class="wrap-input100 validate-input" data-validate = "Enter resume">
<input class="input100" type="text" name="resume" placeholder="ความสนใจในการฝึกงาน">
<span class="focus-input100" data-placeholder=""></span>
</div> -->
<!-- <div class="wrap-input100 validate-input" data-validate = "Enter datail">
<textarea class="input100" type="text" name="detail" placeholder="รายละเอียดเกี่ยวกับตัวเอง"
rows="10" cols="45"></textarea> -->
<!-- <form action="#" method="post" enctype="multipart/form-data">
<textarea placeholder="Content" name="content" rows="10" cols="45"></textarea><br />
</form> -->
<!-- <span class="focus-input100" data-placeholder=""></span>
</div>
<br />
<br/> -->
<!-- <div class="container-login100-form-btn">
<button type="submit" name="signup" value="Sign Up and Upload Image" class="login100-form-btn">
Confirm
</button>
        
<button class="login100-form-btn">
<a href="index.php">Cancel</a>
</button>
</div> -->
</form>
<!--display message -->
<span class="text-success">
<?php
if (isset($msg_success)) {
echo $msg_success;
}
?>
</span>
<span class="text-danger">
<?php
if (isset($msg_error)) {
echo $msg_error;
}
?>
</span>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<!--===============================================================================================-->
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/animsition/js/animsition.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/daterangepicker/moment.min.js"></script>
<script src="vendor/daterangepicker/daterangepicker.js"></script>
<!--===============================================================================================-->
<script src="vendor/countdowntime/countdowntime.js"></script>
<!--===============================================================================================-->
<script src="js/main.js"></script>
<script>
var passwd = document.getElementById("password").value
var cpasswd = document.getElementById("confirmpassword").value
if (passwd != cpasswd) {
document.getElementById("msg-cpasswd").innerHTML = "Password not match!"
}
</script>
<script>
function checknum(txt,span){
var len=txt.length;
document.getElementById('shownum').innerHTML=len;
}
</script>
</body>
</html><file_sep>/README.md
# ManageInternSystem
ManageInternSystem. Small Project.
ระบบการจัดการนักศึกษาฝึกงาน
*เขียนตอนฝึกงาน ร่วมกับการปฏิบัติการฝึกงานไปด้วยเพื่อเรียนรู้การเขียนระบบด้วยภาษา HTML , CSS , PHP , SQL เป็นต้น
(ที่เขียนระบบนี้เพราะต้องการศึกษาด้วยตัวเองเพิ่มเติมร่วมกับการปฏิบัติการฝึกงานเพื่อเรียนรู้มากขึ้นนอกจากการฝึกงานทั่วไป)
**ระบบนี้ยังไม่สมบูรณ์(ประมาณ 70 %)เนื่องจากพัฒนาภายในช่วงเวลา 1 เดือน โดยเน้นฟังก์ชั่นการทำงานหลักๆให้เสร็จจนเกือบหมดเพื่อให้ระบบสามารถพอใช้งานได้
ใน Folder SQL จะมีข้อมูลไอดี Admin ไว้ 1ชุด เพื่อไว้ทดสอบเท่านั้น
ID : <EMAIL>
PASS : <PASSWORD>
<file_sep>/accept.php
<?php
session_start();
include_once 'dbconnect.php';
//ป้องกันไม่ให้เข้าถึงหน้านี้โดยไม่ผ่าน Login
if(!isset($_SESSION['email'])){
header("location: index.php");
return;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Accept</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
</head>
<body>
<br/>
<h1 style='color:green'><center>คุณ <u>ได้</u> รับการเข้าฝึกงาน</center></h1>
<h2><center>ที่ ศูนย์เทคโนโลยีสารสนเทศ คณะเภสัชศาสตร์</center></h2>
<h3><center>เบอร์ติดต่อสอบถามเพิ่มเติม : 000-000-000</center></h3>
<h3><center><a href="logout.php" class="btn btn-danger">ออกจากระบบ</a></center></h3>
</body>
</html><file_sep>/adminpage.php
<?php
session_start();
include_once 'dbconnect.php';
$query = "SELECT * FROM posts ORDER BY IdPosts DESC";
$result = mysqli_query($conn,$query);
//ป้องกันไม่ให้เข้าถึงหน้านี้โดยไม่ผ่าน Login
if(!isset($_SESSION['emailadmin'])){
header("location: index.php");
return;
}
//delete record
if(isset($_GET['id'])){
$query = "DELETE FROM posts
WHERE IdPosts = ".$_GET['id'];
mysqli_query($conn,$query);
header("Location: adminpage.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<title>ส่วนการจัดการของแอดมิน</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 0px solid #cbcbcb;
}
#content1{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
a.p_Button{
display: block;
height:26px;
width:70px;
background-color:#84cdf7;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.p_Button2{
display: block;
height:26px;
width:70px;
background-color:#878c8f;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.red{
color:red;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
.label {
width: 150px;
}
.field, .label {
float: left;
border: 1px solid white;
padding: 40px;
margin: 4px;
}
.clear {
clear:both;
}
</style>
<script src="js/script.js"></script>
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- add header -->
<div class="navbar-header">
<!-- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button> -->
<!-- <a class="navbar-brand" href="index.php">Admin : Manage Users</a> -->
</div>
<!-- menu items -->
<!-- <div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<li><a href="login.php">Login</a></li>
<li><a href="register.php">Sign Up</a></li>
<li class="active"><a href="admin_login.php">Admin</a></li>
</ul>
</div> -->
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<legend>แสดงรายชื่อนักศึกษาฝึกงาน</legend>
<button class='btn btn-info' >
<a href='guideadmin.php' style='color:white'>คู่มือการใช้ระบบจัดการนักศึกษา(สำหรับAdmin)</a>
</button>
<h1></h1>
<br/>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>User Name</th>
<th>E-Mail</th>
<th>Password</th>
<th colspan="2" style="text-align:center">Actions</th>
<th >สถานะ</th>
<th>Resume File</th>
</tr>
</thead>
<tbody>
<tr>
<?php while ($row = mysqli_fetch_array($result)) {?>
<?php $id = $row['IdPosts']; $pass = $row['Pass']?>
<td><?php echo $row['IdPosts'];?></td>
<td><?php echo $row['username'];?> </td>
<td><?php echo $row['email'];?> </td>
<td><?php echo $row['password'];?> </td>
<td>
<?php
//ปุ๋มเปิดดูข้อมูล Users
$posts = "<div><h2><a href='detailuser.php?pid=$id' class='btn btn-success'>Open</a></h2></div>";
echo $posts;
?>
<!-- อันนี้มันทำค่า pid แล้วไล่ตาม $id ไม่ได้ เก็บไว้ก่อนเพื่อสามารถแก้ให้มันใช้ได้ -->
<!-- <input type="button" name="open" value="Open" class="btn btn-primary" onclick="open_user()" > -->
</td>
<td>
<div style="line-height:135%;">
<br>
</div>
<input type="button" name="delete" value="Delete" class="btn btn-primary" onclick="delete_user(<?php echo $row['IdPosts'];?>)">
</td>
<td>
<?php
//ตั้งค่าการแสดงผล ในหน้าแอดมิน 1 คือ รับ 2 คือ ไม่รับ 0 คือ รอการพิจารณา
if($row['Pass'] == '1'){
echo "รับ";
}elseif($row['Pass'] == '2'){
echo "ไม่รับ";
}else{
echo "รอพิจารณา";
}
?>
</td>
<td>
<?php
//ตั้งค่าการแสดงผล ในหน้าแอดมิน 0 คือ Insert ปกติ (ค่า Default) 1 คือ ปล่อยให้นักศึกษาสามารถUpdate File ได้
//และ 2 คือ กันไม่ให้นักศึกษา User อัพโหลดไฟล์หลังจากอัพโหลดไฟล์เสร็จสิ้นไปแล้ว
if($row['Fi'] == '0'){
echo "ยังไม่มีการอัพโหลด";
}elseif($row['Fi'] == '1'){
echo "ให้อัพเดทเพิ่ม";
}else{
echo "อัพโหลดไฟล์เรียบร้อย";
}
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<h1><center><a href="logout.php" class='btn btn-danger'>Log out</a></center></h1>
<!--display number of records -->
<div class="panel-footer"></div>
</div>
</div>
</div>
<script>
function delete_user(id){
if (confirm('Confirm to delete this ID')){
window.location.href="adminpage.php?id="+id;
}
}
</script>
</body>
</html>
<file_sep>/index.php
<?php
//start using session
session_start();
//connect with database
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
//ส่วน user
$email = mysqli_real_escape_string($conn,$_POST['email']);
$passwd = mysqli_real_escape_string($conn,$_POST['password']);
//ส่วน admin
$emailadmin = mysqli_real_escape_string($conn,$_POST['email']);
$passwdadmin = mysqli_real_escape_string($conn,$_POST['password']);
//sql command and ตั้งให้ ถ้า จะล็อกอิน ไอดีนั้นๆ ต้องมีค่า Active = Yes เท่านั้นมิเช่นนั้นจะ Login ไม่ได้
//ส่วน user
$query = "SELECT * FROM posts WHERE
email ='" . $email . "' AND
password ='" . md5($<PASSWORD>) . "' ";
//เก็บไว้ใช้เมื่อระบบ ล็อกอิน แบบยืนยันผ่านเมล์เสร็จ
//AND Active = '" . 'Yes' . "'
//ส่วน admin
$queryadmin = "SELECT * FROM admins WHERE
emailadmin ='" . $emailadmin . "' AND
password ='" . md5($<PASSWORD>) . "' ";
//execute sql command
$result = mysqli_query($conn, $query);
$resultadmin = mysqli_query($conn, $queryadmin);
//check whether there is result from table
if ($row = mysqli_fetch_array($result)) {
//store name in php session เทียบไอดีพาสในส่วนของ users
$_SESSION['email'] = $row['email'];
$em = $_SESSION['email'];
$rs = "SELECT * FROM posts";
$res = mysqli_query($conn ,$rs);
//em คือตัวแปรที่มีค่าเซสชั่น email ตอนล็อกอิน ใช้ฟังชั้นก์ if เพื่อดูคอลั่ม Pass วันอันไหนเป็นสถานะอะไร
// 0 คือ รอการพิจารณา , 1 คือ รับ , 2 คือ ไม่รับ
if($em){
if($row['Pass'] == '1'){
header("location: accept.php");
}
if($row['Pass'] == '2'){
header("location: notaccept.php");
}
if($row['Pass'] == '0'){
header("location: detail.php");
}
}
} elseif ($row = mysqli_fetch_array($resultadmin)){
//เทียบไอดีพาสในส่วนของ admins
$_SESSION['emailadmin'] = $row['emailadmin'];
header("location: adminpage.php");
} else {
$error_msg = "Incorrect email or password!";
echo $error_msg;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ระบบนักศึกษาฝึกงาน-PharmacyIntern</title>
<link rel="stylesheet" href="css/bootstrap.min">
<script src="scripts/bootstrap.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
font-family: Helvetica, Arial, sans-serif;
overflow: hidden;
}
.ghost {
position: absolute;
left: -100%;
}
.framed {
position: absolute;
top: 50%; left: 50%;
width: 25rem;
margin-left: -12.5rem;
}
.logo {
margin-top: -12em;
cursor: default;
}
.form {
margin-top: -4.5em;
transition: 1s ease-in-out;
}
.input {
-moz-box-sizing: border-box;
box-sizing: border-box;
font-size: 1.125rem;
line-height: 3rem;
width: 100%; height: 3rem;
color: #444;
background-color: rgba(255,255,255,.9);
border: 0;
border-top: 1px solid rgba(255,255,255,0.7);
padding: 0 1rem;
font-family: 'Open Sans', sans-serif;
}
.input:focus {
outline: none;
}
.input--top {
border-radius: 0.5rem 0.5rem 0 0;
border-top: 0;
}
.input--submit {
background-color: rgba(92,168,214,0.9);
color: #fff;
font-weight: bold;
cursor: pointer;
border-top: 0;
border-radius: 0 0 0.5rem 0.5rem;
margin-bottom: 1rem;
}
.text {
color: #fff;
text-shadow: 0 1px 1px rgba(0,0,0,0.8);
text-decoration: none;
}
.text--small {
opacity: 0.85;
font-size: 0.75rem;
cursor: pointer;
}
.text--small:hover {
opacity: 1;
}
.text--omega {
width: 200%;
margin: 0 0 1rem -50%;
font-size: 1.5rem;
line-height: 1.125;
font-weight: normal;
}
.text--centered {
display: block;
text-align: center;
}
.text--border-right {
border-right: 1px solid rgba(255,255,255,0.5);
margin-right: 0.75rem;
padding-right: 0.75rem;
}
.legal {
position: absolute;
bottom: 1.125rem; left: 1.125rem;
}
.photo-cred {
position: absolute;
right: 1.125rem; bottom: 1.125rem;
}
.fullscreen-bg {
position: fixed;
z-index: -1;
top:0; right:0; bottom:0; left:0;
background: url(img/index.png) center;
background-size: cover;
}
#toggle--login:checked ~ .form--signup { left:200%; visibility:hidden; }
#toggle--signup:checked ~ .form--login { left:-100%; visibility:hidden; }
@media (height:300px){.legal,.photo-cred{display:none}}
</style>
</head>
<body>
<input type="radio" checked id="toggle--login" name="toggle" class="ghost" />
<input type="radio" id="toggle--signup" name="toggle" class="ghost" />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<label><b><center><h1 style="background-color:#FCF3CF;" >ระบบจัดการนักศึกษาฝึกงาน</h1></center></b></label>
<form role="form" action="index.php" method="post" name="loginform" class="form form--login framed">
<input type="email" name="email" placeholder="Email" class="input input--top" />
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" class="input" />
<input type="submit" name="login" value="Log in" class="input input--submit" />
<label><b><a href="register.php"><center>Sign up</center></a></b></label>
<label><b><a href="guide.php"><center>คู่มือการเข้าใช้ระบบ(สำหรับนักศึกษา)</center></a></b></label>
<label><b><a href="about.php"><center>เกี่ยวกับผู้พัฒนาระบบจัดการนักศึกษาฝึกงาน</center></a></b></label>
</form>
<div class="fullscreen-bg"></div>
</body>
</html><file_sep>/Sql/phardb.sql
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 05, 2020 at 05:09 PM
-- Server version: 10.4.13-MariaDB
-- PHP Version: 7.4.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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: `phardb`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
`IdAdmin` int(11) NOT NULL,
`username` varchar(120) COLLATE utf8_unicode_ci NOT NULL,
`emailadmin` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(40) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `admins`
--
INSERT INTO `admins` (`IdAdmin`, `username`, `emailadmin`, `password`) VALUES
(1, 'adminjob', '<EMAIL>', '<PASSWORD>');
-- --------------------------------------------------------
--
-- Table structure for table `comment`
--
CREATE TABLE `comment` (
`IdCon` int(11) NOT NULL,
`Content` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `images`
--
CREATE TABLE `images` (
`IdImg` int(11) NOT NULL,
`Filen` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`uploaded_on` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`IdPosts` int(11) NOT NULL,
`pid` int(11) NOT NULL,
`username` varchar(120) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(120) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Firstname` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`Lastname` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`Education` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`Resume` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`Detail` varchar(300) COLLATE utf8_unicode_ci NOT NULL,
`Status` varchar(1) COLLATE utf8_unicode_ci NOT NULL,
`SIDd` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
`Active` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`Pass` int(11) NOT NULL,
`Fi` int(11) NOT NULL,
`uploaded_on` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
ADD PRIMARY KEY (`IdAdmin`);
--
-- Indexes for table `comment`
--
ALTER TABLE `comment`
ADD PRIMARY KEY (`IdCon`);
--
-- Indexes for table `images`
--
ALTER TABLE `images`
ADD PRIMARY KEY (`IdImg`);
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`IdPosts`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
MODIFY `IdAdmin` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `comment`
--
ALTER TABLE `comment`
MODIFY `IdCon` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
MODIFY `IdImg` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
MODIFY `IdPosts` int(11) NOT NULL AUTO_INCREMENT;
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>/guideadmin.php
<?php
session_start();
include_once 'dbconnect.php';
//ป้องกันไม่ให้เข้าถึงหน้านี้โดยไม่ผ่าน Login
if(!isset($_SESSION['emailadmin'])){
header("location: index.php");
return;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>คู่มือการเข้าใช้งานระบบจัดการนักศึกษาฝึกงาน</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 0px solid #cbcbcb;
}
#content1{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
a.p_Button{
display: block;
height:26px;
width:70px;
background-color:#84cdf7;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.p_Button2{
display: block;
height:26px;
width:70px;
background-color:#878c8f;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.red{
color:red;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
.label {
width: 150px;
}
.field, .label {
float: left;
border: 1px solid white;
padding: 40px;
margin: 4px;
}
.clear {
clear:both;
}
</style>
<script src="js/script.js"></script>
</head>
<body>
<br>
<center>
<h3>คู่มือการเข้าใช้งานระบบของแอดมิน</h3>
</center>
<table style='width:100%' border="1">
<b>ส่วนของการใช้งานเบื้องต้น</b>
<tr>
<td style="color:red">เมื่อเข้าระบบมาแล้วสามารถทำอะไรได้บ้าง</td>
<td style="color:green">สามารถดูรายชื่อนักศึกษาที่สมัครเข้ามาในระบบ ,
กดดูข้อมูลเพิ่มเติมได้ Open ,
Delete ลบข้อมูนักศึกษาได้,
ดูคู่มือการจัดการระบบแอดมิน ,
ตรวจสอบการสถานะการอัพโหลดไฟล์ของนักศึกษาได้ ,
ถ้ารับนักศึกษาแล้วก็ตรวจสอบตรง 'สถานะ' ว่ารับหรือยัง ,
Logout เพื่อออกจากระบบ
</td>
</tr>
<tr>
<td style="color:red">เมื่อ Open เข้าไปดูจะมีรายการจัดการเพิ่มขึ้นมา</td>
<td style="color:green">1.ส่วนของการจัดการ รับ ไม่รับ หรือตั้งรอพิจารณา นักศึกษาฝึกงาน
->กดรับ ไม่รับ นักศึกษา</td>
</tr>
<tr>
<td style="color:red">เมื่อ Open เข้าไปดูจะมีรายการจัดการเพิ่มขึ้นมา</td>
<td style="color:green">2.ส่วนการตั้งค่า การอัพโหลดไฟล์ หรือ อัพทเดทไฟล์ Resume ของนักศึกษา
->เมื่อนักศึกษาอัพโหลดไฟล์แต่ต้องการแก้ไขไฟล์เพิ่มเติม เมื่อกดปุ๋มจะเป็นการอนุญาติให้นักศึกษาอัพโหลดไฟล์ใหม่ได้อีกครั้ง
(นักศึกษาอัพโหลดไฟล์ได้แค่ครั้งเดียว ถ้าต้องการอัพโหลดแก้ไขต้องให้แอดมินอนุญาติ)</td>
</tr>
<tr>
<td style="color:red">เมื่อ Open เข้าไปดูจะมีรายการจัดการเพิ่มขึ้นมา</td>
<td style="color:green">3.ส่วนการโหลดไฟล์ Resume ของนักศึกษา</td>
</tr>
<tr>
<td style="color:red">เมื่อ Open เข้าไปดูจะมีรายการจัดการเพิ่มขึ้นมา</td>
<td style="color:green">4.ย้อนกลับ หรือ ออกจากระบบ</td>
</tr>
</table>
<br/>
<table style='width:100%' border="1">
<tbody>
<b>ส่วนของปัญหา</b>
<tr>
<td style="color:red">ทำไมโหลดไฟล์ไม่ใช้ไฟล์ Resumeของนักศึกษา?</td>
<td style="color:green">เพราะนักศึกษายังไม่ได้อัพโหลดไฟล์เข้าระบบ ตรวจสอบการสถานะการอัพโหลดไฟล์ของนักศึกษาได้ในหน้าจัดการแอดมิน</td>
</tr>
</tbody>
</table>
<br/>
<center>
<button class='btn btn-primary' >
<a href='adminpage.php' style='color:white'>ย้อนกลับ</a>
</button>
</center>
<br><br>
<center>
<button class='btn btn-danger' >
<a href='logout.php' style='color:white'>Logout</a>
</button>
</center>
</body>
</html><file_sep>/activate.php
<?php
include_once 'dbconnect.php';
$strSQL = "SELECT * FROM posts WHERE SID = '".trim($_GET['sid'])."' AND IdPosts = '".trim($_GET['uid'])."' ";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if(!$objResult)
{
echo "Activate Invalid !";
}
else
{
$strSQL = "UPDATE posts SET Active = 'Yes' WHERE SID = '".trim($_GET['sid'])."' AND IdPosts = '".trim($_GET['uid'])."' ";
$objQuery = mysql_query($strSQL);
echo "Activate Successfully !";
}
mysql_close();
?><file_sep>/detail.php
<?php
session_start();
include_once 'dbconnect.php';
$iduseremail = $_SESSION['email'];
//ป้องกันไม่ให้เข้าถึงหน้านี้โดยไม่ผ่าน Login
if(!isset($_SESSION['email'])){
header("location: index.php");
return;
}
if(isset($_POST['submit'])){
//upload file
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$targetFilePath = $target_dir . $target_file;
$target_file1 = basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//โค้ดสำหรับเช็คว่าที่อัพโหลดเป็นรูปใช่หรือไม่ (ทำให้เป็นคอมเม้นท์เนื่องจากเราไม่ได้ต้องการให้อัพโหลดแค่รูปถ่ายอย่างเดียว)
// // Check if image file is a actual image or fake image
// if(isset($_POST["submit"])) {
// $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
// if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
// $uploadOk = 1;
// } else {
// echo "File is not an image.";
// $uploadOk = 0;
// }
// }
// Check if file already exists
//ไปใช้สำหรับการ INSERT = 1 , UPDATE = 2 , DEFAULT = 0
// if (file_exists($target_file)) {
// echo "Sorry, file already exists.";
// $uploadOk = 0;
// }
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "pdf" && $imageFileType != "doc") {
echo "Sorry, only JPG, JPEG, PNG GIF PDF DOC files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}else{
//ระบบ update การอัพโหลด Resume กรณีที่ต้องการอัพโหลดแก้ไฟล์ Resume (ยังใช้งานไม่ได้)
//$Ids = mysqli_real_escape_string($conn,$_SESSION["email"]);
//echo $Id;
//exit();
//mysqli_real_escape_string($iduseremail);
$em = $_SESSION['email'];
$po = "SELECT * FROM posts WHERE email = '$em' ";
//echo $po;
//exit();
$res = mysqli_query($conn,$po);
while ($row = $res->fetch_assoc()) {
// echo $row['Fi'];
// exit();
if($row['Fi'] == '0'){
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " ได้อัพโหลดเข้าไปยังระบบแล้ว.";
$insert = $conn->query("INSERT into images (Filen,uploaded_on) VALUES ('".$target_file1."', NOW())");
$update = $conn->query("UPDATE posts SET Fi = '2' WHERE email = '$em' ");
}
}
if($row['Fi'] == '1'){
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " อัพเดทไฟล์เรียบร้อยแล้ว.";
$id = $row['IdPosts'];
$update = $conn->query("UPDATE images SET Filen = '$target_file1' WHERE IdImg = '$id' ");
$update = $conn->query("UPDATE posts SET Fi = '2' WHERE email = '$em' ");
}
}
if($row['Fi'] == '2'){
header("location: repeatedly.php");
$uploadOk = 0;
}
// if($row['Fi'] == '1'){
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " อัพเดทไฟล์เรียบร้อยแล้ว.";
// $update = $conn->query("UPDATE images SET Filen = '$target_file1' WHERE IdImg = '$iduseremail' ");
// $update = $conn->query("UPDATE posts SET Fi = '2' WHERE email = '$em' ");
// }
// }
// if($row['Fi'] == '2'){
// echo "เจอไฟล์ซ้ำ";
// $uploadOk = 0;
// exit();
// }else{
// echo "ขัดข้องจ้า";
// exit();
// }
}
// if(mysqli_num_rows($res) > 0){
// while($row = mysqli_fetch_assoc($res)){
// $fi = $row['Fi'];
// echo $fi;
// exit();
// if($fi == '0'){
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " ได้อัพโหลดเข้าไปยังระบบแล้ว.";
// $insert = $conn->query("INSERT into images (Filen,uploaded_on) VALUES ('".$target_file1."', NOW())");
// }
// }elseif($fi == '1'){
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " อัพเดทไฟล์ในระบบแล้ว.";
// $update = $conn->query("UPDATE images SET Filen = '$target_file1' WHERE IdImg = '$iduseremail' ");
// }
// }else{
// if(file_exists($target_file)){
// echo "Sorry, file already exists.";
// $uploadOk = 0;
// }
// }
// }
// }
// $pid = $row['IdPosts'];
// $imgs = "SELECT * FROM images WHERE IdImg = '$pid' ";
// $sqlqImg = mysqli_query($conn,$imgs);
// if(mysqli_num_rows($sqlqImg)> 0){
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been updated.";
// $insert = $conn->query("UPDATE images SET IdImg = '$pid' WHERE Filename");
// }
// else{
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
// $insert = $conn->query("INSERT into images (Filen,uploaded_on) VALUES ('".$target_file1."', NOW())");
// } else {
// echo "Sorry, there was an error uploading your file.";
// }
// }
// }
//dd
// if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
// $insert = $conn->query("INSERT into images (Filename,uploaded_on) VALUES ('".$target_file1."', NOW())");
// } else {
// echo "Sorry, there was an error uploading your file.";
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ข้อมูลประวัติส่วนตัว</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
<meta name="description" content="A free template from http://ws-templates.com">
<meta name="keywords" content="keyword1,keyword2"/>
<link href="css/screen.css" media="screen" rel="stylesheet"/>
<link href="css/style.css" media="screen" rel="stylesheet"/>
<link rel="stylesheet" href="nivo-slider/default/default.css" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider/default/nivo-slider.css" type="text/css" media="screen" />
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 0px solid #cbcbcb;
}
#content1{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
a.p_Button{
display: block;
height:26px;
width:70px;
background-color:#84cdf7;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.p_Button2{
display: block;
height:26px;
width:70px;
background-color:#878c8f;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.red{
color:red;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
<script src="js/script.js"></script>
</head>
<body>
<br/>
<h1><center>Welcome to User Page!</center></h1>
<br/>
<h2><center>รายละเอียดของนักศึกษา</center></h2>
<?php
$sql ="SELECT * FROM posts WHERE email = '$iduseremail' ";
$res = mysqli_query($conn , $sql) or die(mysqli_error($conn));
if(mysqli_num_rows($res)> 0){
while($row = mysqli_fetch_assoc($res)){
$id = $row['IdPosts'];
$username = $row['username'];
$email = $row['email'];
$Fname = $row['Firstname'];
$lname = $row['Lastname'];
$education = $row['Education'];
$resume = $row['Resume'];
$detail = $row['Detail'];
// <!--ไว้กด upload image ยังไม่สมบูรณ์ ไม่มี PHP-->
// เป็น HTML แยกออกมาเก็บไว้ก่อน
// <div class='middel_div_right' align='center'>
// <form method='post' enctype='multipart/form-data'>
// <input type='hidden' value='1000000' name='MAX_FILE_SIZE' />
// <input type='file' name='uploadfile' />
// <input type='submit' name='submit' value='Upload' style='margin-top:10px; height:35px; width:75px;' />
// </form>
// </div>
// ฟอร์มดั้งเดิมที่ไม่ใช้แล้ว
// <br/>
// <div><center>
// <h2>Username : $username</h2><br/>
// <h3>Email : $email</h3><br/><br/><br/>
// <h3>ชื่อ : $Fname</h3><br/>
// <h3>นามสกุล : $lname</h3><br/>
// <h3>การศึกษา : $education</h3><br/>
// <h3>ความสนใจในการฝึกงาน : $resume</h3><br/>
// <br/>
// <h3>อัพโหลดResume : <h5><form action='detail.php' method='post' enctype='multipart/form-data'>
// Select file to upload:
// <input type='file' name='fileToUpload' id='fileToUpload'>
// <input type='submit' value='Upload Image' name='submit'>
// </form></h5>
// </h3>
// <br/>
// <h3>รายละเอียดเกี่ยวกับตัวเอง : $detail</h3><br/>
// <br/>
$posts = "
<br/>
<table style='width:100%' >
<tr>
<th>หัวข้อ</th>
<th>ข้อมูล</th>
</tr>
<tr>
<td>Username : </td>
<td>$username</td>
</tr>
<tr>
<td>Email : </td>
<td>$email</td>
</tr>
<tr>
<td>ชื่อ : </td>
<td>$Fname</td>
</tr>
<tr>
<td>นามสกุล : </td>
<td>$lname</td>
</tr>
<tr>
<td>การศึกษา : </td>
<td>$education</td>
</tr>
<tr>
<td>ความสนใจในการฝึกงาน : </td>
<td>$resume</td>
</tr>
<tr>
<td>อัพโหลดResume : </td>
<td><h5><form action='detail.php' method='post' enctype='multipart/form-data'>
Select file to upload:
<input type='file' name='fileToUpload' id='fileToUpload'>
<input type='submit' value='Upload File' name='submit' class='btn btn-info'>
</form></h5></td>
</tr>
<tr>
<td>รายละเอียดเกี่ยวกับตัวเอง : </td>
<td>$detail</td>
</tr>
</table>
<div class='container-login100-form-btn'>
<button class='btn btn-warning' >
<a href='editdetail.php' style='color:white'>Edit</a>
</button>
<button class='btn btn-danger' >
<a href='logout.php' style='color:white'>Logout</a>
</button>
</div>
</div>";
}
echo $posts;
}else{
echo "<center><br/>There are no posts to display!</center>";
echo "<center><br/><a href='logout.php'>Logout</a></center>";
}
?>
</body>
</html><file_sep>/logout.php
<?php
session_start();
//clear session
if (isset($_SESSION['email'])) {
session_destroy();
unset($_SESSION['email']);
}
if (isset($_SESSION['emailadmin'])) {
session_destroy();
unset($_SESSION['emailadmin']);
}
//back to index.php
header("Location: index.php");
?><file_sep>/dbconnect.php
<?php
//1.create connection
$host = "localhost";
$db_username = "root";
$db_passwd = "";
$db_name = "phardb";
$conn;
try {
$conn = mysqli_connect($host, $db_username, $db_passwd, $db_name);
} catch (Exception $exp) {
echo "Connection error: " . $exp.getMessage();
}
?><file_sep>/editdetail.php
<?php
session_start();
include_once 'dbconnect.php';
$idemail = $_SESSION['email'];
//ป้องกันไม่ให้เข้าถึงหน้า edit โดยไม่ผ่านการ Login
if(!isset($_SESSION['email'])){
header("location: index.php");
return;
}
if(isset($_POST['update'])){
//ทำการเก็บค่าไว้ในตัวแปร PHP
$Fname = strip_tags($_POST['Firstname']);
$lname = strip_tags($_POST['Lastname']);
$education = strip_tags($_POST['Education']);
$resume = strip_tags($_POST['Resume']);
$detail = strip_tags($_POST['Detail']);
//ป้องกันการ SQL Injection
$Fname1 = mysqli_real_escape_string($conn,$Fname);
$lname1 = mysqli_real_escape_string($conn,$lname);
$education1 = mysqli_real_escape_string($conn,$education);
$resume1 = mysqli_real_escape_string($conn,$resume);
$detail1 = mysqli_real_escape_string($conn,$detail);
//นำตัวแปรที่มีการป้องกันการ SQL Injection มา query ในตัวแปร $sql
$sql = "UPDATE posts SET Firstname='$Fname1' , Lastname='$lname1' ,
Education='$education1' , Resume = '$resume1' , Detail = '$detail1'
WHERE email = '$idemail' ";
if($Fname1 == "" || $lname1 == ""){
echo "Please complete your post!";
return;
}
mysqli_query($conn,$sql);
header("location: detail.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>แก้ไขข้อมูลประวัติส่วนตัว</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
</head>
<body>
<div id="content1">
<div>
<br/>
<font color="#8B4513"><h1><center>Edit Post</center></h1></font>
</div>
<?php
$sql_get = "SELECT * FROM posts WHERE email = '$idemail' ";
$res = mysqli_query($conn,$sql_get);
if(mysqli_num_rows($res) > 0){
while ($row = mysqli_fetch_assoc($res)){
$Fname = $row['Firstname'];
$lname = $row['Lastname'];
$education = $row['Education'];
$resume = $row['Resume'];
$detail = $row['Detail'];
echo"<form action='editdetail.php' method='post' enctype='multipart/form-data'>";
echo"<b><center>ชื่อ :</b> <input placeholder='กรอกชื่อ' name='Firstname' type='text' value='$Fname' autofocus size='48'></center><br /><br />";
echo"<b><center>นามสกุล :</b> <input placeholder='กรอกนามสกุล' name='Lastname' type='text' value='$lname' autofocus size='48'></center><br /><br />";
echo"<b><center>การศึกษา :</b> <input placeholder='กรอกการศึกษา' name='Education' type='text' value='$education' autofocus size='48'></center><br /><br />";
echo"<b><center>ความสนใจในการฝึกงาน :</b> <input placeholder='กรอกresume' name='Resume' type='text' value='$resume' autofocus size='48'></center><br /><br />";
echo"<b><center>รายละเอียดเกี่ยวกับตัวเอง : </b> <textarea placeholder='กรอกข้อมูลที่เหลือ' name='Detail' type='text' value='$detail' rows='10' cols='45'></textarea></center><br /><br />";
//echo"<input placeholder='Content' name='content' rows='20' cols='50'>$content</textarea><br />";
//แบบเดิม เผื่อนำ css มาตกแต่ง
// echo"<form action='editdetail.php' method='post' enctype='multipart/form-data'>";
// echo"<b>ชื่อ :</b> <input placeholder='กรอกชื่อ' name='Firstname' type='text' value='$Fname' autofocus size='48'><br /><br />";
// echo"<b>นามสกุล :</b> <input placeholder='กรอกนามสกุล' name='Lastname' type='text' value='$lname' autofocus size='48'><br /><br />";
// echo"<b>การศึกษา :</b> <input placeholder='กรอกการศึกษา' name='Education' type='text' value='$education' autofocus size='48'><br /><br />";
// echo"<b>ความสนใจในการฝึกงาน :</b> <input placeholder='กรอกresume' name='Resume' type='text' value='$resume' autofocus size='48'><br /><br />";
// echo"<b>รายละเอียดเกี่ยวกับตัวเอง : </b> <textarea placeholder='กรอกข้อมูลที่เหลือ' name='Detail' type='text' value='$detail' rows='10' cols='45'></textarea><br /><br />";
}
}
?>
<div align="center">
<input name="update" type="submit" value="Update">
<a href="detail.php" style="font-size:12px;"> ย้อนกลับ</a>
</div>
<!--
<input name="update" type="submit" value="Update">
<a href="detail.php" style="font-size:12px;"> ย้อนกลับ</a> -->
</form>
</div>
</body>
</html><file_sep>/detailuser.php
<?php
session_start();
include_once 'dbconnect.php';
//$iduseremail = $_SESSION['email'];
//admin
//$sql ="SELECT * FROM admins WHERE email = '$iduseremail' ";
//แสดงข้อมูล
$query = "SELECT * FROM posts ORDER BY IdPosts DESC";
$result = mysqli_query($conn,$query);
ob_start();
//ป้องกันไม่ให้เข้าถึงหน้านี้โดยไม่ผ่าน Login
if(!isset($_SESSION['emailadmin'])){
header("location: index.php");
return;
}
//ฟังก์ชัน ส่งข้อความจากแอดมิน ถึง นักศึกษาฝึกงาน
if(isset($_POST['send'])){
$detail = $_POST['detail'];
$ch = "SELECT * FROM comment ";
$result = mysqli_query($conn,$ch) or die(mysqli_error($conn));
$query = "INSERT INTO comment(Content)
VALUES('" . $detail . "' )";
if (mysqli_query($conn, $query)) {
//$msg_success = "<br/><br/><h3><center><font color='white'>Successfully registered! <br/>Please check your email to activate account</font></center></h3>";
echo "ส่งข้อความเสร็จสิ้น";
//ปุ๋มล็อกอินของเก่า
//<br/><br/><center><button class='login100-form-btn'><a href='index.php'>Click here to login</a></button></center>
//ส่งอีเมล์ไปยัง user เพื่อแจ้งให้ Activate ID
//$Uid = mysqli_insert_id($conn);
// $strTo = $_POST['email'];
// $strSubject = "Activate Member account";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "Activate account click here.<br/>";
// $strMessage .= "http://localhost/pharmacyintern/activate.php?sid=".session_id()."&uid=".$Uid."<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
//ส่งเมล์แจ้งเตือนไปยัง Admin ว่ามี User ได้สมัครเข้ามาในระบบแล้ว
// $strTo = <EMAIL>;
// $strSubject = "มี User เข้ามาสมัครแล้ว";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "นักศึกษา.<br/>";
// $strMessage .= "http://localhost/pharmacyintern/activate.php?sid=".session_id()."&uid=".$Uid."<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
} else {
// $msg_error = "<br/><br/><h3><center><font color='white'>Error in registration, please try again!</font></center></h3>
// <br/><br/><center><button class='login100-form-btn'><a href='register.php'>Click here to Register again</a></button></center>";
//when user cant register correctly. it'll sent to failregister.php
echo "มีปัญหา กรุณาลองใหม่อีกครั้ง";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ข้อมูลของนักศึกษา</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="scripts/bootstrap.min.js"></script>
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
<meta name="description" content="A free template from http://ws-templates.com">
<meta name="keywords" content="keyword1,keyword2"/>
<link href="css/screen.css" media="screen" rel="stylesheet"/>
<link href="css/style.css" media="screen" rel="stylesheet"/>
<link rel="stylesheet" href="nivo-slider/default/default.css" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider/default/nivo-slider.css" type="text/css" media="screen" />
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 0px solid #cbcbcb;
}
#content1{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
a.p_Button{
display: block;
height:26px;
width:70px;
background-color:#84cdf7;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.p_Button2{
display: block;
height:26px;
width:70px;
background-color:#878c8f;
padding:8px 15px;
font-size:14px;
color:white;
margin-bottom: 15px;
text-align: center;
}
a.red{
color:red;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
.label {
width: 150px;
}
.field, .label {
float: left;
border: 1px solid white;
padding: 40px;
margin: 4px;
}
.clear {
clear:both;
}
#left {
float:left;
width:100px;
}
</style>
<script src="js/script.js"></script>
</head>
<body>
<br/>
<h1><center>Welcome to User Page!</center></h1>
<br/>
<h2><center>รายละเอียดของนักศึกษา</center></h2>
<?php
$pid = $_GET['pid'];
$sql ="SELECT * FROM posts WHERE IdPosts = '$pid' ";
$res = mysqli_query($conn , $sql) or die(mysqli_error($conn));
//เมื่อกดแล้วจะทำการเปลี่ยน field in posts , 0 = default , 1=accept , 2=Notaccept
if(isset($_POST['Asubmit'])){
$pid = $_GET['pid'];
$sqlup = "UPDATE posts SET Pass = '1' WHERE IdPosts = '$pid' ";
$res1 = mysqli_query($conn, $sqlup);
header("location: adminpage.php");
// เมื่่อแอดมินกดรับจะทำการส่งเมล์แจ้งเตือนว่า User ได้ถูกรับเข้าฝึกงานแล้ว
// $strTo = $_POST['email'];
// $strSubject = "ยินดีด้วย! คุณได้รับเข้าฝึกงานแล้ว";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "ได้รับเข้าฝึกงานแล้ว คลิ้กเว็บเพื่อเข้าระบบตรวจสอบอีกทีหนึ่ง.<br/>";
// $strMessage .= "http://localhost/pharmacyintern/index.php"<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
}
if(isset($_POST['Nsubmit'])){
$pid = $_GET['pid'];
$sqlup = "UPDATE posts SET Pass = '2' WHERE IdPosts = '$pid' ";
$res1 = mysqli_query($conn, $sqlup);
header("location: adminpage.php");
// เมื่่อแอดมินกดรับจะทำการส่งเมล์แจ้งเตือนว่า User ไม่ได้ถูกรับเข้าฝึกงานแล้ว
// $strTo = $_POST['email'];
// $strSubject = "ขอแสดงความเสียใจ คุณไม่ได้รับการเข้าฝึกงาน";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "คุณไม่ได้รับเข้าฝึกงานที่ศูนย์เทคโนโลยีสารสนเทศ คณะเภสัชศาสตร์ คลิ้กลิ้งเพื่อตรวจสอบเพิ่มเติม<br/>";
// $strMessage .= "http://localhost/pharmacyintern/index.php"<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
}
if(isset($_POST['Dsubmit'])){
$pid = $_GET['pid'];
$sqlup = "UPDATE posts SET Pass = '0' WHERE IdPosts = '$pid' ";
$res1 = mysqli_query($conn, $sqlup);
header("location: adminpage.php");
}
if(isset($_POST['update'])){
$pid = $_GET['pid'];
$sqlup = "UPDATE posts SET Fi = '1' WHERE IdPosts = '$pid' ";
$res1 = mysqli_query($conn, $sqlup);
header("location: adminpage.php");
// เมื่่อแอดมินกดรับจะทำการส่งเมล์แจ้งเตือนว่า User ได้ถูกรับเข้าฝึกงานแล้ว
// $strTo = $_POST['email'];
// $strSubject = "ยินดีด้วย! คุณได้รับเข้าฝึกงานแล้ว";
// $strHeader = "Content-type: text/html; charset=UTF-8";
// $strHeader .= "From: <EMAIL>\nReply-To: <EMAIL>";
// $strMessage= "";
// $strMessage .= "Welcome : ".$_POST['username']." <br/>";
// $strMessage .= "=================================<br>";
// $strMessage .= "ได้รับเข้าฝึกงานแล้ว คลิ้กเว็บเพื่อเข้าระบบตรวจสอบอีกทีหนึ่ง.<br/>";
// $strMessage .= "http://localhost/pharmacyintern/index.php"<br>";
// $strMessage .= "=================================<br>";
// $strMessage .= "PharmacyIntern PSU.com";
// $flgSend = mail($strTo,$strSubject,$strMessage,$strHeader);
}
if(mysqli_num_rows($res)> 0){
while($row = mysqli_fetch_assoc($res)){
$id = $row['IdPosts'];
$username = $row['username'];
$email = $row['email'];
$Fname = $row['Firstname'];
$lname = $row['Lastname'];
$education = $row['Education'];
$resume = $row['Resume'];
$detail = $row['Detail'];
}
}else{
echo "<center><br/>There are no posts to display!</center>";
echo "<center><br/><a href='logout.php'>Logout</a></center>";
}
?>
<br/>
<table style='width:100%' >
<tr>
<th>หัวข้อ</th>
<th>ข้อมูล</th>
</tr>
<tr>
<td>Username:</td>
<td><?php echo $username; ?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $email; ?></td>
</tr>
<tr>
<td>ชื่อ:</td>
<td><?php echo $Fname; ?></td>
</tr>
<tr>
<td>นามสกุล:</td>
<td><?php echo $lname; ?></td>
</tr>
<tr>
<td>การศึกษา:</td>
<td><?php echo $education; ?></td>
</tr>
<tr>
<td>ความสนใจในการฝึกงาน:</td>
<td><?php echo $resume; ?></td>
</tr>
<tr>
<td>รายละเอียดเกี่ยวกับตัวเอง:</td>
<td><?php echo $detail; ?></td>
</tr>
</table>
<!-- ระบบกรอกข้อคาวามเพื่อให้ขึ้นไปโผล้หน้าของ User ยังไม่สมบูรณ์จึงไม่นำมาใช้ออกมาก่อน -->
<!-- <div class='field'>
<form role="form" action="detailuser.php?pid=<?php //echo $id;?>" method="post" name="signupform">
<h3>กรอกข้อความ</h3>
<textarea class="input" type="text" name="detail" wrap="hard" id="txt" onkeyup="checknum(document.getElementById('txt').value,document.getElementById('shownum'));"></textarea>
<input type="submit" name="send" value="Send" class="input input--submit" />
</form>
</div> -->
<?php
$query = $conn->query("SELECT * FROM images WHERE IdImg = '$pid' ");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$fileURL = 'uploads/'.$row["Filen"];
}
if($query = $pid){
$msgdl = "<a href='$fileURL' download>Download PDF file</a>";
}
else{
$msgno = "None of PDF FIle";
echo $msgno;
}
}
$posts = "
<br/>
<div>
<form action='detailuser.php?pid=$id' method='post' name='form1'>
<div class='field'>
<h4>ส่วนของการจัดการ รับ ไม่รับ หรือตั้งรอพิจารณา นักศึกษาฝึกงาน</h4>
<br/>
<button type='submit' name='Asubmit' value='รับ' class='btn btn-success' >
รับ
</button>
<button type='submit' name='Nsubmit' value='ไม่รับ' class='btn btn-warning' style='color:white'>
ไม่รับ
</button>
<button type='submit' name='Dsubmit' value='ตั้งให้เป็นรอการพิจารณา' class='btn btn-info' >
ตั้งให้เป็นรอการพิจารณา
</button>
</div>
<div class='field'>
<h4>ส่วนการตั้งค่า การอัพโหลดไฟล์ หรือ อัพทเดทไฟล์ Resume ของนักศึกษา</h4>
<br/>
<button type='submit' name='update' value='Update' class='btn btn-success' style='color:white'>
ตั้งให้ Update
</button>
</div>
<div class='field'>
<h4>ส่วนการโหลดไฟล์ Resume ของนักศึกษา</h4>
<h5 style='color:red'>*ถ้าขึ้นแจ้งเตือนด้านใต้ตารางประมาณว่า</h5>
<h5 style='color:red'>Notice: Undefined variable: fileURL in C:\xampp\htdocs\PharmacyIntern\detailuser.php on line...</h5>
<h5 style='color:red'>หมายความว่านักศึกษายังไม่มีการอัพโหลดไฟล์เข้าระบบ*</h5>
<h5 style='color:green'>**แต่ถ้าไม่ขึ้นแจ้งเตือนและกดโหลดไฟล์ได้แสดงว่านักศึกษาได้อัพโหลดไฟล์แล้ว**</h5>
<br/>
<button class='btn btn-primary' >
<a href='$fileURL' style='color:white' download>Download PDF file</a>
</button>
</div>
<div class='field'>
<h4>ย้อนกลับ หรือ ออกจากระบบ</h4>
<br/>
<button class='btn btn-danger' >
<a href='logout.php' style='color:white'>ออกจากระบบ</a>
</button>
<button class='btn btn-default' >
<a href='adminpage.php' style='color:black'>ย้อนกลับ</a>
</button>
</div>
</form>
</div>
</div>
";
echo $posts;
?>
</body>
</html> | 8d15c223c2f2694e1d57338dec129ea1e327c10a | [
"Markdown",
"SQL",
"PHP"
] | 14 | PHP | Chutithep88/ManageInternSystem | c7c9a190ec08cd6aa35bfe07d5a7c5d19a07d244 | d4df7f2dcd5b6981fecea8cbcdebf537c1d018cd |
refs/heads/main | <repo_name>NaoakiUmedu/rustudy<file_sep>/ru_study/src/main.rs
// 次回は2.5から
fn main()
{
let _x = 100;
println!("x is {}", _x);
let _x = 200;
println!("x is {}", _x);
}
| 798fec36b299846fe48032dc35ae060b9e923c44 | [
"Rust"
] | 1 | Rust | NaoakiUmedu/rustudy | 3f8a57843e64bb3753fcd34bbf32d3d240b07620 | d5ae5db8ffdc7346d48cd5686174b20dcdba24db |
refs/heads/master | <repo_name>matcha/competitive-programming-solutions<file_sep>/Google Code Jam 2017/Qualification Round/Problem D - Fashion Show/Matrix.cs
namespace Gcj
{
static class Matrix
{
internal static bool[,] ToBoolMatrix(char[,] matrix, char charForTrue)
{
var n = matrix.GetLength(0);
var boolMatrix = new bool[n, n];
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (matrix[rowIndex, columnIndex] == charForTrue)
{
boolMatrix[rowIndex, columnIndex] = true;
}
}
}
return boolMatrix;
}
internal static char[,] ToCharMatrix(bool[,] matrix, char charForTrue, char charForFalse)
{
var n = matrix.GetLength(0);
var charMatrix = new char[n, n];
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
charMatrix[rowIndex, columnIndex] = matrix[rowIndex, columnIndex] ? charForTrue : charForFalse;
}
}
return charMatrix;
}
}
}<file_sep>/Google Code Jam 2018/Round 1C/Problem A - A Whole New Word.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gcj
{
static class Program
{
static void Main()
{
Solve();
}
static void Solve()
{
var testCaseCount = int.Parse(Console.ReadLine());
for (var testCaseId = 1; testCaseId <= testCaseCount; testCaseId++)
{
var tokens = Console.ReadLine().Split();
var N = int.Parse(tokens[0]);
var L = int.Parse(tokens[1]);
var css = new List<HashSet<char>>(L);
for (int i = 0; i < L; i++)
{
css.Add(new HashSet<char>());
}
var inputWords = new List<string>();
for (int i = 0; i < N; i++)
{
var inputWord = Console.ReadLine();
inputWords.Add(inputWord);
var cs = inputWord.ToCharArray();
for (var j = 0; j < L; j++)
{
css[j].Add(cs[j]);
}
}
var foundNewWord = false;
foreach (var word in CreateWords(new[] { "" }, css))
{
if (!inputWords.Contains(word))
{
Console.WriteLine($"Case #{testCaseId}: {word}");
foundNewWord = true;
break;
}
}
if (!foundNewWord)
{
Console.WriteLine($"Case #{testCaseId}: -");
}
}
}
static IEnumerable<string> CreateWords(IEnumerable<string> words, IEnumerable<IEnumerable<char>> listOfCandidateChars)
{
if (listOfCandidateChars.Any())
{
var candidateChars = listOfCandidateChars.First();
listOfCandidateChars = listOfCandidateChars.Skip(1);
return candidateChars.SelectMany(candidateChar => CreateWords(words.Select(word => word + candidateChar), listOfCandidateChars));
}
return words;
}
}
}<file_sep>/SRM 688/ParenthesesDiv2Medium.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
public class ParenthesesDiv2Medium
{
public int[] correct(string s)
{
var cs = s.ToCharArray();
var count = 0;
var flips = new List<int>();
for (var i = 0; i < cs.Length; i++)
{
if (cs[i] == '(')
{
var closeCount = cs.Skip(i).Count(c => c == ')');
if (count > closeCount)
{
flips.Add(i);
count--;
}
else
{
count++;
}
}
else
{
if (count == 0)
{
flips.Add(i);
count++;
}
else
{
count--;
}
}
}
return flips.ToArray();
}
}<file_sep>/Google Code Jam 2017/Round 1A/Problem A - Alphabet Cake/Grid.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace Gcj
{
class Grid<T> where T : IComparable
{
protected T[,] Xss;
internal int Length => Xss.Length;
internal int RowLength => Xss.GetLength(0);
internal int ColumnLength => Xss.GetLength(1);
internal T this[int ri, int ci] => Xss[ri, ci];
protected Grid() { }
Grid(T[,] xss)
{
Xss = xss;
}
internal int Count(T item)
{
var count = 0;
for (var ri = 0; ri < RowLength; ri++)
{
for (var ci = 0; ci < ColumnLength; ci++)
{
if (Xss[ri, ci].CompareTo(item) == 0)
{
count++;
}
}
}
return count;
}
internal Grid<T> CreateSubgrid(int startRowIndex, int startColumnIndex, int rowLength = -1, int columnLength = -1)
{
if (rowLength == -1)
{
rowLength = RowLength - startRowIndex;
}
if (columnLength == -1)
{
columnLength = ColumnLength - startColumnIndex;
}
var xss = new T[rowLength, columnLength];
for (var ri = 0; ri < rowLength; ri++)
{
for (var ci = 0; ci < columnLength; ci++)
{
xss[ri, ci] = Xss[startRowIndex + ri, startColumnIndex + ci];
}
}
return new Grid<T>(xss);
}
internal void Fill(T item)
{
for (var ri = 0; ri < RowLength; ri++)
{
for (var ci = 0; ci < ColumnLength; ci++)
{
Xss[ri, ci] = item;
}
}
}
internal T[,] ToTwoDimensionalArray()
{
return Xss;
}
internal void Write(StreamWriter sw)
{
for (var ri = 0; ri < RowLength; ri++)
{
for (var ci = 0; ci < ColumnLength; ci++)
{
sw.Write(Xss[ri, ci]);
}
sw.WriteLine();
}
}
}
}<file_sep>/Google Code Jam 2017/Round 1B/Problem B - Stable Neigh-bors.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Gcj
{
static class Program
{
[STAThread]
static void Main()
{
const string inputFile = @"B-large-practice.in";
const string outputFile = @"Output.txt";
Solve(inputFile, outputFile);
Process.Start(outputFile);
Clipboard.SetText(Path.GetFullPath(outputFile));
}
static void Solve(string inputPath, string outputPath)
{
var lines = File.ReadLines(inputPath).ToList();
var t = int.Parse(lines[0]);
lines = lines.Skip(1).ToList();
(int, int, int, int, int, int, int) GetSeven(IReadOnlyList<int> xs) => (xs[0], xs[1], xs[2], xs[3], xs[4], xs[5], xs[6]);
using (var sw = new StreamWriter(outputPath))
{
for (var ti = 0; ti < t; ti++)
{
var (n, r, o, y, g, b, v) = GetSeven(lines[0].Split().Select(int.Parse).ToList());
lines = lines.Skip(1).ToList();
string result;
if (r == 0 && 0 < o && y == 0 && g == 0 && v == 0)
{
result = o == b ? Repeat("OB", o) : "IMPOSSIBLE";
}
else if (o == 0 && y == 0 && 0 < g && b == 0 && v == 0)
{
result = g == r ? Repeat("GR", g) : "IMPOSSIBLE";
}
else if (r == 0 && o == 0 && g == 0 && b == 0 && 0 < v)
{
result = v == y ? Repeat("VY", v) : "IMPOSSIBLE";
}
else if (0 < o && b <= o
|| 0 < g && r <= g
|| 0 < v && y <= v)
{
result = "IMPOSSIBLE";
}
else
{
b -= o;
r -= g;
y -= v;
n = r + y + b;
if (Math.Floor(n / 2.0) < new[] { r, y, b }.Max())
{
result = "IMPOSSIBLE";
}
else
{
var xs = new List<(char, int)> { ('R', r), ('Y', y), ('B', b) }.OrderBy(x => x.Item2).ToList();
var ss = Enumerable.Repeat(xs[0].Item1, xs[0].Item2)
.Concat(Enumerable.Repeat(xs[1].Item1, xs[1].Item2))
.Concat(Enumerable.Repeat(xs[2].Item1, xs[2].Item2))
.Select(c => c.ToString()).ToList();
if (0 < o)
{
for (var i = 0; i < n; i++)
{
if (ss[i] == "B")
{
ss[i] = Repeat("BO", o) + "B";
break;
}
}
}
if (0 < g)
{
for (var i = 0; i < n; i++)
{
if (ss[i] == "R")
{
ss[i] = Repeat("RG", g) + "R";
break;
}
}
}
if (0 < v)
{
for (var i = 0; i < n; i++)
{
if (ss[i] == "Y")
{
ss[i] = Repeat("YV", v) + "Y";
break;
}
}
}
var stack = new Stack<string>(ss);
for (var i = 0; i < n; i += 2)
{
ss[i] = stack.Pop();
}
for (var i = 1; i < n; i += 2)
{
ss[i] = stack.Pop();
}
result = string.Concat(ss);
}
}
sw.WriteLine($"Case #{ti + 1}: {result}");
}
}
}
static string Repeat(string s, int n) => string.Concat(Enumerable.Repeat(s, n));
}
}<file_sep>/Google Code Jam 2017/Qualification Round/Problem D - Fashion Show/Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Gcj
{
static class Program
{
[STAThread]
static void Main()
{
const string inputFile = @"D-large-practice.in";
const string outputFile = @"Output.txt";
Solve(inputFile, outputFile);
Process.Start(outputFile);
Clipboard.SetText(Path.GetFullPath(outputFile));
}
static void Solve(string inputPath, string outputPath)
{
const char bishopSign = '+';
const char rookSign = 'x';
const char queenSign = 'o';
const char blankSign = '*';
var lines = File.ReadLines(inputPath).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
(int, int) GetTwo(IReadOnlyList<int> xs) => (xs[0], xs[1]);
using (var sw = new StreamWriter(outputPath))
{
for (var ti = 0; ti < t; ti++)
{
var (n, m) = GetTwo(lines[0].Split().Select(int.Parse).ToList());
var rookMatrix = new bool[n, n];
var bishopMatrix = new bool[n, n];
var xs = lines.GetRange(1, m).Select(s => s.Split()).ToList();
foreach (var x in xs)
{
var rowIndex = int.Parse(x[1]) - 1;
var columnIndex = int.Parse(x[2]) - 1;
switch (char.Parse(x[0]))
{
case bishopSign:
bishopMatrix[rowIndex, columnIndex] = true;
break;
case rookSign:
rookMatrix[rowIndex, columnIndex] = true;
break;
case queenSign:
bishopMatrix[rowIndex, columnIndex] = true;
rookMatrix[rowIndex, columnIndex] = true;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
var newBishopMatrix = Bishop.GetBishopsWithExtra(Matrix.ToCharMatrix(bishopMatrix, bishopSign, blankSign));
var newRookMatrix = Rook.GetRooksWithExtra(Matrix.ToCharMatrix(rookMatrix, rookSign, blankSign));
var extraModels = new HashSet<(char, int, int)>();
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (bishopMatrix[rowIndex, columnIndex] != newBishopMatrix[rowIndex, columnIndex])
{
extraModels.Add(newRookMatrix[rowIndex, columnIndex] ? (queenSign, rowIndex, columnIndex) : (bishopSign, rowIndex, columnIndex));
}
if (rookMatrix[rowIndex, columnIndex] != newRookMatrix[rowIndex, columnIndex])
{
extraModels.Add(newBishopMatrix[rowIndex, columnIndex] ? (queenSign, rowIndex, columnIndex) : (rookSign, rowIndex, columnIndex));
}
}
}
sw.WriteLine($"Case #{ti + 1}: {GetStylePoints(newBishopMatrix) + GetStylePoints(newRookMatrix)} {extraModels.Count}");
foreach (var (modelSign, rowIndex, columnIndex) in extraModels)
{
sw.WriteLine($"{modelSign} {rowIndex + 1} {columnIndex + 1}");
}
lines = lines.Skip(1 + m).ToList();
}
}
}
static int GetStylePoints(bool[,] matrix)
{
var n = matrix.GetLength(0);
var stylePoints = 0;
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (matrix[rowIndex, columnIndex])
{
stylePoints++;
}
}
}
return stylePoints;
}
}
}<file_sep>/Google Code Jam 2018/Round 1C/Problem B - Lollipop Shop.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace GCJ
{
static class Program
{
static void Main()
{
Solve();
}
static void Solve()
{
var testCaseCount = int.Parse(Console.ReadLine());
for (var testCaseId = 1; testCaseId <= testCaseCount; testCaseId++)
{
var n = int.Parse(Console.ReadLine());
var flavorOccurrences = new List<int>();
for (int i = 0; i < n; i++)
{
flavorOccurrences.Add(0);
}
var remainingFlavors = Enumerable.Range(0, n).ToList();
for (int i = 0; i < n; i++)
{
var tokens = Console.ReadLine().Split().Select(s => int.Parse(s)).ToList();
if (tokens[0] == 0)
{
Console.WriteLine(-1);
continue;
}
var hisFavoriteFlavors = tokens.Skip(1).ToList();
foreach (var hisFavoriteFlavor in hisFavoriteFlavors)
{
flavorOccurrences[hisFavoriteFlavor] += 1;
}
var sellableFlavors = remainingFlavors.Intersect(hisFavoriteFlavors).ToList();
if (sellableFlavors.Any())
{
var flavor = GetLeastPopularFlavor(sellableFlavors, flavorOccurrences);
Console.WriteLine(flavor);
remainingFlavors = remainingFlavors.Where(x => x != flavor).ToList();
}
else
{
Console.WriteLine(-1);
}
}
}
}
static int GetLeastPopularFlavor(List<int> sellableFlavors, List<int> flavorOccurrences)
{
var min = flavorOccurrences[sellableFlavors[0]];
var indexOfMin = 0;
var n = sellableFlavors.Count;
for (var i = 1; i < n; i++)
{
var occurrence = flavorOccurrences[sellableFlavors[i]];
if (occurrence < min)
{
min = occurrence;
indexOfMin = i;
}
}
return sellableFlavors[indexOfMin];
}
}
}<file_sep>/Google Code Jam 2016/Qualification Round/ProblemC - Coin Jam.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Gcj
{
internal static class Program
{
private static void Main()
{
const string inputFile = @"C-large-practice.in";
const string outputFile = @"output.txt";
var xs = File.ReadLines(inputFile).Skip(1).First().Split();
var n = int.Parse(xs[0]);
var j = int.Parse(xs[1]);
var result = new List<string>(j + 1) { "Case #1:" };
for (var i = 0; i < n - 10; i++)
{
for (var k = 0; k < n - 10 - i; k++)
{
for (var l = 0; l < n - 10 - i - k; l++)
{
var m = n - 10 - i - k - l;
var jamcoin = $"11{new string('0', i)}11{new string('0', k)}11{new string('0', l)}11{new string('0', m)}11";
const string divisors = "3 2 5 2 7 2 3 2 11";
result.Add($"{jamcoin} {divisors}");
if (--j == 0)
{
File.WriteAllLines(outputFile, result);
}
}
}
}
}
}
}<file_sep>/Google Code Jam 2016/Round 1B/ProblemB - Close Match.cs
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace Gcj
{
internal static class Program
{
private static long _minDiff;
private static string _answer;
private static void Main()
{
const string inputFile = @"B-large-practice.in";
const string outputFile = @"output.txt";
var lines = File.ReadLines(inputFile).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
var result = new string[t];
for (var ti = 0; ti < t; ti++)
{
var xs = lines[ti].Split().ToList();
var c = new StringBuilder(xs[0]);
var j = new StringBuilder(xs[1]);
var n = c.Length;
_minDiff = long.MaxValue;
_answer = "";
for (var i = 0; i < n; i++)
{
if (c[i] != '?' && j[i] != '?')
{
if (c[i] < j[i])
{
UpdateMinDiffAndAnswer(c.ToString().Replace('?', '9'), j.ToString().Replace('?', '0'));
}
else
{
UpdateMinDiffAndAnswer(c.ToString().Replace('?', '0'), j.ToString().Replace('?', '9'));
}
}
else if (c[i] == '?' && j[i] == '?')
{
UpdateMinDiffAndAnswer(new StringBuilder(c.ToString()) { [i] = '0' }.ToString().Replace('?', '9'),
new StringBuilder(j.ToString()) { [i] = '1' }.ToString().Replace('?', '0'));
UpdateMinDiffAndAnswer(new StringBuilder(c.ToString()) { [i] = '1' }.ToString().Replace('?', '0'),
new StringBuilder(j.ToString()) { [i] = '0' }.ToString().Replace('?', '9'));
c[i] = '0';
j[i] = '0';
}
else if (c[i] == '?' && j[i] != '?')
{
if (j[i] != '9')
{
UpdateMinDiffAndAnswer(new StringBuilder(c.ToString()) { [i] = ToChar(ToInt(j[i]) + 1) }.ToString().Replace('?', '0'),
new StringBuilder(j.ToString()).ToString().Replace('?', '9'));
}
if (j[i] != '0')
{
UpdateMinDiffAndAnswer(new StringBuilder(c.ToString()) { [i] = ToChar(ToInt(j[i]) - 1) }.ToString().Replace('?', '9'),
new StringBuilder(j.ToString()).ToString().Replace('?', '0'));
}
c[i] = j[i];
}
else
{
if (c[i] != '9')
{
UpdateMinDiffAndAnswer(new StringBuilder(c.ToString()).ToString().Replace('?', '9'),
new StringBuilder(j.ToString()) { [i] = ToChar(ToInt(c[i]) + 1) }.ToString().Replace('?', '0'));
}
if (c[i] != '0')
{
UpdateMinDiffAndAnswer(new StringBuilder(c.ToString()).ToString().Replace('?', '0'),
new StringBuilder(j.ToString()) { [i] = ToChar(ToInt(c[i]) - 1) }.ToString().Replace('?', '9'));
}
j[i] = c[i];
}
}
UpdateMinDiffAndAnswer(c.ToString(), j.ToString());
result[ti] = $"Case #{ti + 1}: {_answer}";
}
File.WriteAllLines(outputFile, result);
}
private static void UpdateMinDiffAndAnswer(string s1, string s2)
{
var diff = Math.Abs(long.Parse(s1) - long.Parse(s2));
var candidate = s1 + ' ' + s2;
if (diff < _minDiff || diff == _minDiff && string.Compare(candidate, _answer, StringComparison.Ordinal) < 0)
{
_minDiff = diff;
_answer = candidate;
}
}
private static int ToInt(int c)
{
return c - '0';
}
private static char ToChar(int x)
{
return x.ToString()[0];
}
}
}<file_sep>/SRM 688/ParenthesesDiv2Easy.cs
public class ParenthesesDiv2Easy
{
public int getDepth(string s)
{
var count = 0;
var maxCount = 0;
foreach (var c in s)
{
if (c == '(')
{
if (maxCount < ++count)
{
maxCount = count;
}
}
else
{
count--;
}
}
return maxCount;
}
}<file_sep>/Google Code Jam 2017/Qualification Round/Problem C - Bathroom Stalls.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Gcj
{
static class Program
{
[STAThread]
static void Main()
{
const string inputFile = @"C-large-practice.in";
const string outputFile = @"Output.txt";
Solve(inputFile, outputFile);
Process.Start(outputFile);
Clipboard.SetText(Path.GetFullPath(outputFile));
}
static void Solve(string inputPath, string outputPath)
{
var lines = File.ReadLines(inputPath).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
using (var sw = new StreamWriter(outputPath))
{
for (var ti = 0; ti < t; ti++)
{
var (n, k) = GetTwo(lines[ti].Split().Select(long.Parse).ToList());
var hs = new HashSet<long> { n };
var c = new Dictionary<long, long> { { n, 1 } };
long p = 0;
while (true)
{
var x = hs.Max();
long x0;
long x1;
if (x % 2 == 0)
{
x0 = x / 2;
x1 = (x - 2) / 2;
}
else
{
x0 = (x - 1) / 2;
x1 = (x - 1) / 2;
}
p += c[x];
if (k <= p)
{
sw.WriteLine($"Case #{ti + 1}: {x0} {x1}");
break;
}
hs.Remove(x);
hs.Add(x0);
hs.Add(x1);
Add(c, x0, c[x]);
Add(c, x1, c[x]);
}
}
}
}
static (long, long) GetTwo(IReadOnlyList<long> xs)
{
return (xs[0], xs[1]);
}
static void Add(IDictionary<long, long> d, long key, long valueToAdd)
{
if (d.ContainsKey(key))
{
d[key] += valueToAdd;
}
else
{
d.Add(key, valueToAdd);
}
}
}
}
<file_sep>/Google Code Jam 2016/Qualification Round/ProblemB - Revenge of the Pancakes.cs
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Gcj
{
internal static class Program
{
private static void Main()
{
const string inputFile = @"B-large-practice.in";
const string outputFile = @"output.txt";
var xs = File.ReadLines(inputFile).ToList();
var t = int.Parse(xs[0]);
var s = xs.GetRange(1, t).ToList();
var result = new string[t];
for (var ti = 0; ti < t; ti++)
{
var groupedHeight = 1 + CountSubstring(s[ti], "-\\+") + CountSubstring(s[ti], "\\+-");
result[ti] = $"Case #{ti + 1}: {(s[ti].EndsWith("-") ? groupedHeight : groupedHeight - 1)}";
}
File.WriteAllLines(outputFile, result);
}
private static int CountSubstring(string s, string substring)
{
return Regex.Matches(s, substring, RegexOptions.IgnoreCase).Count;
}
}
}<file_sep>/Google Code Jam 2017/Qualification Round/Problem D - Fashion Show/Rook.cs
namespace Gcj
{
static class Rook
{
const char RookSign = 'x';
const char RookControl = '!';
const char BlankSign = '*';
internal static bool[,] GetRooksWithExtra(char[,] rookMatrix)
{
var n = rookMatrix.GetLength(0);
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (rookMatrix[rowIndex, columnIndex] == RookSign)
{
FillRookControl(rookMatrix, rowIndex, columnIndex);
}
}
}
while (true)
{
var isRookAdded = false;
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (rookMatrix[rowIndex, columnIndex] != BlankSign)
{
continue;
}
rookMatrix[rowIndex, columnIndex] = RookSign;
isRookAdded = true;
FillRookControl(rookMatrix, rowIndex, columnIndex);
}
}
if (!isRookAdded)
{
break;
}
}
return Matrix.ToBoolMatrix(rookMatrix, RookSign);
}
static void FillRookControl(char[,] matrix, int rowIndex, int columnIndex)
{
for (var i = 0; i < matrix.GetLength(0); i++)
{
if (matrix[rowIndex, i] == BlankSign)
{
matrix[rowIndex, i] = RookControl;
}
if (matrix[i, columnIndex] == BlankSign)
{
matrix[i, columnIndex] = RookControl;
}
}
}
}
}
<file_sep>/Google Code Jam 2016/Round 1B/ProblemA - Getting the Digits.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Gcj
{
internal static class Program
{
private static readonly string[] Zero = { "Z", "E", "R", "O" };
private static readonly string[] One = { "O", "N", "E" };
private static readonly string[] Two = { "T", "W", "O" };
private static readonly string[] Three = { "T", "H", "R", "E", "E" };
private static readonly string[] Four = { "F", "O", "U", "R" };
private static readonly string[] Five = { "F", "I", "V", "E" };
private static readonly string[] Six = { "S", "I", "X" };
private static readonly string[] Seven = { "S", "E", "V", "E", "N" };
private static readonly string[] Eight = { "E", "I", "G", "H", "T" };
private static readonly string[] Nine = { "N", "I", "N", "E" };
private static void Main()
{
const string inputFile = @"A-large-practice.in";
const string outputFile = @"output.txt";
var lines = File.ReadLines(inputFile).ToList();
var t = int.Parse(lines[0]);
lines = lines.Skip(1).ToList();
var result = new string[t];
for (var ti = 0; ti < t; ti++)
{
var numbers = new List<int>();
var s = lines[ti];
while (s != "")
{
var s0 = s;
if (s.Contains("Z"))
{
s = RemoveSubstrings(s, Zero);
numbers.Add(0);
}
if (s.Contains("W"))
{
s = RemoveSubstrings(s, Two);
numbers.Add(2);
}
if (s.Contains("U"))
{
s = RemoveSubstrings(s, Four);
numbers.Add(4);
}
if (s.Contains("X"))
{
s = RemoveSubstrings(s, Six);
numbers.Add(6);
}
if (s.Contains("G"))
{
s = RemoveSubstrings(s, Eight);
numbers.Add(8);
}
if (s0 == s)
{
break;
}
}
while (s != "")
{
var s0 = s;
if (s.Contains("O"))
{
s = RemoveSubstrings(s, One);
numbers.Add(1);
}
if (s.Contains("H"))
{
s = RemoveSubstrings(s, Three);
numbers.Add(3);
}
if (s.Contains("F"))
{
s = RemoveSubstrings(s, Five);
numbers.Add(5);
}
if (s.Contains("S"))
{
s = RemoveSubstrings(s, Seven);
numbers.Add(7);
}
if (s0 == s)
{
break;
}
}
while (s != "")
{
s = RemoveSubstrings(s, Nine);
numbers.Add(9);
}
numbers.Sort();
result[ti] = $"Case #{ti + 1}: {string.Join("", numbers)}";
}
File.WriteAllLines(outputFile, result);
}
private static string RemoveSubstrings(string s0, IEnumerable<string> substrings)
{
return substrings.Aggregate(s0, (s, substring) => s.Remove(s.IndexOf(substring, StringComparison.OrdinalIgnoreCase), 1));
}
}
}<file_sep>/Google Code Jam 2017/Qualification Round/Problem D - Fashion Show/Bishop.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gcj
{
static class Bishop
{
const char BishopSign = '+';
const char BishopControl = '!';
const char BlankSign = '*';
internal static bool[,] GetBishopsWithExtra(char[,] bishopMatrix)
{
var n = bishopMatrix.GetLength(0);
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (bishopMatrix[rowIndex, columnIndex] == BishopSign)
{
FillBishopControl(bishopMatrix, GetMainDiagonalId(rowIndex, columnIndex), GetAntidiagonalId(rowIndex, columnIndex));
}
}
}
while (true)
{
var blankCells = new SortedDictionary<int, HashSet<(int, int)>>();
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (bishopMatrix[rowIndex, columnIndex] != BlankSign)
{
continue;
}
var v = rowIndex + columnIndex;
var key = Math.Min(v, 2 * n - 2 - v);
if (blankCells.ContainsKey(key))
{
blankCells[key].Add((rowIndex, columnIndex));
}
else
{
blankCells.Add(key, new HashSet<(int, int)> { (rowIndex, columnIndex) });
}
}
}
if (!blankCells.Any())
{
break;
}
var (rowIndex1, columnIndex1) = blankCells.First().Value.First();
bishopMatrix[rowIndex1, columnIndex1] = BishopSign;
FillBishopControl(bishopMatrix, GetMainDiagonalId(rowIndex1, columnIndex1), GetAntidiagonalId(rowIndex1, columnIndex1));
}
return Matrix.ToBoolMatrix(bishopMatrix, BishopSign);
}
static void FillBishopControl(char[,] matrix, int mainDiagonalId, int antiDiagonalId)
{
var n = matrix.GetLength(0);
for (var rowIndex = 0; rowIndex < n; rowIndex++)
{
for (var columnIndex = 0; columnIndex < n; columnIndex++)
{
if (matrix[rowIndex, columnIndex] == BishopSign)
{
continue;
}
if (mainDiagonalId == GetMainDiagonalId(rowIndex, columnIndex))
{
matrix[rowIndex, columnIndex] = BishopControl;
}
else if (antiDiagonalId == GetAntidiagonalId(rowIndex, columnIndex))
{
matrix[rowIndex, columnIndex] = BishopControl;
}
}
}
}
static int GetMainDiagonalId(int rowIndex, int columnIndex) => rowIndex - columnIndex;
static int GetAntidiagonalId(int rowIndex, int columnIndex) => rowIndex + columnIndex;
}
}
<file_sep>/Google Code Jam 2017/Round 1A/Problem A - Alphabet Cake/CharGrid.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gcj
{
sealed class CharGrid : Grid<char>
{
const char Blank = '?';
CharGrid(Grid<char> grid)
{
Xss = grid.ToTwoDimensionalArray();
}
internal CharGrid(IReadOnlyList<string> ss)
{
Xss = new char[ss.Count, ss[0].Length];
for (var ri = 0; ri < Xss.GetLength(0); ri++)
{
var cs = ss[ri].ToCharArray();
for (var ci = 0; ci < Xss.GetLength(1); ci++)
{
Xss[ri, ci] = cs[ci];
}
}
}
internal CharGrid CreateCharSubgrid(int startRowIndex, int startColumnIndex, int rowLength = -1, int columnLength = -1)
{
return new CharGrid(CreateSubgrid(startRowIndex, startColumnIndex, rowLength, columnLength));
}
internal void SetSubgrid(CharGrid xss, int startRowIndex = 0, int startColumnIndex = 0)
{
for (var ri = 0; ri < xss.RowLength; ri++)
{
for (var ci = 0; ci < xss.ColumnLength; ci++)
{
Xss[startRowIndex + ri, startColumnIndex + ci] = xss[ri, ci];
}
}
}
internal bool MoreThanTwoColumnsHaveNonBlank()
{
var hs = new HashSet<int>();
for (var ri = 0; ri < RowLength; ri++)
{
for (var ci = 0; ci < ColumnLength; ci++)
{
if (Xss[ri, ci] == Blank)
{
continue;
}
if (hs.Any() && hs.First() != ci)
{
return true;
}
hs.Add(ci);
}
}
return false;
}
internal Tuple<int, int> GetIndexOfLeftmostNonBlank()
{
for (var ci = 0; ci < ColumnLength; ci++)
{
for (var ri = 0; ri < RowLength; ri++)
{
if (Xss[ri, ci] != Blank)
{
return Tuple.Create(ri, ci);
}
}
}
throw new InvalidOperationException();
}
internal void FillWithNonBlank()
{
for (var ri = 0; ri < RowLength; ri++)
{
for (var ci = 0; ci < ColumnLength; ci++)
{
if (Xss[ri, ci] != Blank)
{
Fill(Xss[ri, ci]);
return;
}
}
}
throw new InvalidOperationException();
}
}
}<file_sep>/Google Code Jam 2016/Round 1B/ProblemC - Technobabble.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Gcj
{
internal static class Program
{
private static void Main()
{
const string inputFile = @"C-large-practice.in";
const string outputFile = @"output.txt";
var lines = File.ReadLines(inputFile).ToList();
var t = long.Parse(lines[0]);
var firsts = new HashSet<string>();
var seconds = new HashSet<string>();
var edges = new Dictionary<string, HashSet<string>>();
var result = new string[t];
var offset = 1;
for (var ti = 0; ti < t; ti++)
{
firsts.Clear();
seconds.Clear();
edges.Clear();
var n = int.Parse(lines[offset]);
for (var i = 0; i < n; i++)
{
var xs = lines[offset + 1 + i].Split();
var first = xs[0];
var second = xs[1];
firsts.Add(first);
seconds.Add(second);
if (edges.ContainsKey(first))
{
edges[first].Add(second);
}
else
{
edges.Add(first, new HashSet<string> { second });
}
}
result[ti] = $"Case #{ti + 1}: {n - (firsts.Count + ModifiedHopcroftKarp(firsts, seconds, edges))}";
offset += 1 + n;
}
File.WriteAllLines(outputFile, result);
}
private static bool HasAugmentingPath(IEnumerable<string> lefts,
IReadOnlyDictionary<string, HashSet<string>> edges,
IReadOnlyDictionary<string, string> toMatchedRight,
IReadOnlyDictionary<string, string> toMatchedLeft,
IDictionary<string, long> distances,
Queue<string> q)
{
foreach (var left in lefts)
{
if (toMatchedRight[left] == "")
{
distances[left] = 0;
q.Enqueue(left);
}
else
{
distances[left] = long.MaxValue;
}
}
distances[""] = long.MaxValue;
while (0 < q.Count)
{
var left = q.Dequeue();
if (distances[left] < distances[""])
{
foreach (var right in edges[left])
{
var nextLeft = toMatchedLeft[right];
if (distances[nextLeft] == long.MaxValue)
{
distances[nextLeft] = distances[left] + 1;
q.Enqueue(nextLeft);
}
}
}
}
return distances[""] != long.MaxValue;
}
private static bool TryMatching(string left,
IReadOnlyDictionary<string, HashSet<string>> edges,
IDictionary<string, string> toMatchedRight,
IDictionary<string, string> toMatchedLeft,
IDictionary<string, long> distances)
{
if (left == "")
{
return true;
}
foreach (var right in edges[left])
{
var nextLeft = toMatchedLeft[right];
if (distances[nextLeft] == distances[left] + 1)
{
if (TryMatching(nextLeft, edges, toMatchedRight, toMatchedLeft, distances))
{
toMatchedLeft[right] = left;
toMatchedRight[left] = right;
return true;
}
}
}
distances[left] = long.MaxValue;
return false;
}
private static int ModifiedHopcroftKarp(HashSet<string> lefts,
IEnumerable<string> rights,
IReadOnlyDictionary<string, HashSet<string>> edges)
{
var distances = new Dictionary<string, long>();
var q = new Queue<string>();
var toMatchedRight = lefts.ToDictionary(s => s, s => "");
var toMatchedLeft = rights.ToDictionary(s => s, s => "");
while (HasAugmentingPath(lefts, edges, toMatchedRight, toMatchedLeft, distances, q))
{
foreach (var unmatchedLeft in lefts.Where(left => toMatchedRight[left] == ""))
{
TryMatching(unmatchedLeft, edges, toMatchedRight, toMatchedLeft, distances);
}
}
return toMatchedLeft.Count(kvp => kvp.Value == "");
}
}
}
<file_sep>/Google Code Jam 2017/Qualification Round/Problem A - Oversized Pancake Flipper.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Gcj
{
static class Program
{
[STAThread]
static void Main()
{
const string inputFile = @"A-large-practice.in";
const string outputFile = @"output.txt";
Solve(inputFile, outputFile);
Process.Start(outputFile);
Clipboard.SetText(Path.GetFullPath(outputFile));
}
static void Solve(string inputFile, string outputFile)
{
var lines = File.ReadLines(inputFile).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
using (var sw = new StreamWriter(outputFile))
{
for (var ti = 0; ti < t; ti++)
{
var xs = lines[ti].Split();
var pancakes = xs[0].ToCharArray().Select(c => c == '+').ToList();
var flipperSize = long.Parse(xs[1]);
var flippingCount = 0;
while (pancakes.Any())
{
if (pancakes[0])
{
pancakes.RemoveAt(0);
continue;
}
if (pancakes.Count < flipperSize)
{
break;
}
for (var i = 0; i < flipperSize; i++)
{
pancakes[i] = !pancakes[i];
}
flippingCount++;
pancakes.RemoveAt(0);
}
sw.WriteLine(pancakes.Any()
? $"Case #{ti + 1}: IMPOSSIBLE"
: $"Case #{ti + 1}: {flippingCount}");
}
}
}
}
}<file_sep>/SRM 688/ParenthesesDiv2Hard.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class ParenthesesDiv2Hard
{
public int minSwaps(string s, int[] L, int[] R)
{
var openToClose = 0;
var closeToOpen = 0;
for (var i = 0; i < L.Length; i++)
{
var l = L[i];
var r = R[i];
if ((r - l) % 2 == 0)
{
return -1;
}
var cs2 = s.Substring(l, r - l + 1).ToCharArray();
var count = 0;
for (var j = 0; j < cs2.Length; j++)
{
if (cs2[j] == '(')
{
if (count > cs2.Skip(j).Count(c => c == ')'))
{
openToClose++;
count--;
}
else
{
count++;
}
}
else
{
if (count == 0)
{
closeToOpen++;
count++;
}
else
{
count--;
}
}
}
}
var used = new bool[s.Length];
for (var i = 0; i < L.Length; i++)
{
for (var j = L[i]; j <= R[i]; j++)
{
used[j] = true;
}
}
if (openToClose == closeToOpen)
{
return openToClose;
}
var cs = s.ToCharArray();
var unusedOpen = 0;
var unusedClose = 0;
for (var i = 0; i < s.Length; i++)
{
if (!used[i])
{
if (cs[i] == '(')
{
unusedOpen++;
}
else
{
unusedClose++;
}
}
}
if (openToClose > closeToOpen)
{
if (openToClose - closeToOpen <= unusedClose)
{
return openToClose;
}
}
if (closeToOpen > openToClose)
{
if (closeToOpen - openToClose <= unusedOpen)
{
return closeToOpen;
}
}
return -1;
}
}
<file_sep>/Google Code Jam 2017/Round 1A/Problem A - Alphabet Cake/Program.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Gcj
{
static class Program
{
static void Main()
{
const string inPath = @"A-large-practice.in";
const string outPath = @"Output.txt";
Solve(inPath, outPath);
Process.Start(outPath);
}
static void Solve(string inPath, string outPath)
{
var lines = File.ReadLines(inPath).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
using (var sw = new StreamWriter(outPath))
{
for (var ti = 0; ti < t; ti++)
{
sw.WriteLine($"Case #{ti + 1}:");
var r = int.Parse(lines[0].Split()[0]);
Fill(new CharGrid(lines.GetRange(1, r).ToList())).Write(sw);
lines = lines.Skip(1 + r).ToList();
}
}
}
static CharGrid Fill(CharGrid cg)
{
var questionCount = cg.Count('?');
if (questionCount == 0)
{
return cg;
}
if (questionCount == cg.Length - 1)
{
cg.FillWithNonBlank();
return cg;
}
if (cg.MoreThanTwoColumnsHaveNonBlank())
{
var t1 = cg.GetIndexOfLeftmostNonBlank();
cg.SetSubgrid(Fill(cg.CreateCharSubgrid(0, 0, cg.RowLength, t1.Item2 + 1)));
cg.SetSubgrid(Fill(cg.CreateCharSubgrid(0, t1.Item2 + 1)), 0, t1.Item2 + 1);
}
else
{
var t1 = cg.GetIndexOfLeftmostNonBlank();
cg.SetSubgrid(Fill(cg.CreateCharSubgrid(0, 0, t1.Item1 + 1, cg.ColumnLength)));
cg.SetSubgrid(Fill(cg.CreateCharSubgrid(t1.Item1 + 1, 0)), t1.Item1 + 1);
}
return cg;
}
}
}<file_sep>/Google Code Jam 2016/Qualification Round/ProblemD - Fractiles.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Gcj
{
internal static class Program
{
private static void Main()
{
const string inputFile = @"D-large-practice.in";
const string outputFile = @"output.txt";
var lines = File.ReadLines(inputFile).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
var tiles = new List<long>();
var result = new string[t];
for (var ti = 0; ti < t; ti++)
{
var xs = lines[ti].Split().Select(long.Parse).ToList();
var k = xs[0];
var c = xs[1];
var s = xs[2];
if (s * c < k)
{
result[ti] = $"Case #{ti + 1}: IMPOSSIBLE";
continue;
}
tiles.Clear();
for (long j = 1; j < k + 1; j += c)
{
long p = 1;
for (long m = 0; m < c; m++)
{
p = (p - 1) * k + Math.Min(j + m, k);
}
tiles.Add(p);
}
result[ti] = $"Case #{ti + 1}: {string.Join(" ", tiles)}";
}
File.WriteAllLines(outputFile, result);
}
}
}<file_sep>/SRM 690/DoubleString.cs
public class DoubleString
{
public string check(string S)
{
var i = S.Length / 2;
return S.Substring(0, i) == S.Substring(i) ? "square" : "not square";
}
}<file_sep>/Google Code Jam 2016/Round 1C/ProblemA - Senate Evacuation.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Gcj
{
internal static class Program
{
private static void Main()
{
const string inputFile = @"A-large-practice.in";
const string outputFile = @"output.txt";
var lines = File.ReadLines(inputFile).ToList();
var t = int.Parse(lines[0]);
var evacuees = new List<string>();
var result = new string[t];
for (var ti = 0; ti < t; ti++)
{
var ps = lines[2 + 2 * ti].Split().Select(long.Parse).ToList();
evacuees.Clear();
while (3 < ps.Sum())
{
evacuees.Add(Pop(ps) + Pop(ps));
}
if (ps.Sum() == 3)
{
evacuees.Add(Pop(ps));
}
evacuees.Add(Pop(ps) + Pop(ps));
result[ti] = $"Case #{ti + 1}: {string.Join(" ", evacuees)}";
}
File.WriteAllLines(outputFile, result);
}
private static string Pop(IList<long> xs)
{
var i = IndexOfMax(xs);
xs[i]--;
return ((char)('A' + i)).ToString();
}
private static int IndexOfMax(IList<long> xs)
{
var max = xs[0];
var indexOfMax = 0;
var n = xs.Count;
for (var i = 1; i < n; i++)
{
if (max < xs[i])
{
max = xs[i];
indexOfMax = i;
}
}
return indexOfMax;
}
}
}<file_sep>/SRM 690/GerrymanderEasy.cs
public class GerrymanderEasy
{
public double getmax(int[] A, int[] B, int K)
{
long n = A.Length;
var maxRatio = 0.0;
for (var i = 0; i < n; i++)
{
var denominator = 0.0;
var numerator = 0.0;
for (var j = i; j < n; j++)
{
numerator += B[j];
denominator += A[j];
if (K <= j - i + 1)
{
var ratio = numerator / denominator;
if (maxRatio < ratio)
{
maxRatio = ratio;
}
}
}
}
return maxRatio;
}
}
<file_sep>/Google Code Jam 2017/Qualification Round/Problem B - Tidy Numbers.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Gcj
{
static class Program
{
[STAThread]
static void Main()
{
const string inputFile = @"B-large-practice.in";
const string outputFile = @"Output.txt";
Solve(inputFile, outputFile);
Process.Start(outputFile);
Clipboard.SetText(Path.GetFullPath(outputFile));
}
static void Solve(string inputPath, string outputPath)
{
var lines = File.ReadLines(inputPath).ToList();
var t = long.Parse(lines[0]);
lines = lines.Skip(1).ToList();
using (var sw = new StreamWriter(outputPath))
{
for (var ti = 0; ti < t; ti++)
{
var xs = lines[ti].ToCharArray().Select(c => c - '0').ToList();
while (true)
{
var unsortedIndex = GetUnsortedIndex(xs);
if (unsortedIndex == -1)
{
sw.WriteLine($"Case #{ti + 1}: {string.Join("", xs)}");
break;
}
xs[unsortedIndex - 1] -= 1;
for (var i = unsortedIndex; i < xs.Count; i++)
{
xs[i] = 9;
}
xs = string.Join("", xs).TrimStart('0').ToCharArray().Select(c => c - '0').ToList();
}
}
}
}
static int GetUnsortedIndex(IReadOnlyList<int> xs)
{
for (var i = 1; i < xs.Count; i++)
{
if (xs[i] < xs[i - 1])
{
return i;
}
}
return -1;
}
}
}<file_sep>/Google Code Jam 2017/Round 1B/Problem A - Steed 2 Cruise Control.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Gcj
{
static class Program
{
[STAThread]
static void Main()
{
const string inputFile = @"A-large-practice.in";
const string outputFile = @"Output.txt";
Solve(inputFile, outputFile);
Process.Start(outputFile);
Clipboard.SetText(Path.GetFullPath(outputFile));
}
static void Solve(string inputPath, string outputPath)
{
var lines = File.ReadLines(inputPath).ToList();
var t = int.Parse(lines[0]);
lines = lines.Skip(1).ToList();
(int, int) GetPair(IReadOnlyList<int> xs) => (xs[0], xs[1]);
using (var sw = new StreamWriter(outputPath))
{
for (var ti = 0; ti < t; ti++)
{
var (d, n) = GetPair(lines[0].Split().Select(int.Parse).ToList());
sw.WriteLine($"Case #{ti + 1}: {d / lines.GetRange(1, n).Select(s => s.Split().Select(int.Parse).ToList()).Select(xs => new { K = xs[0], S = xs[1] }).Max(h => (double)(d - h.K) / h.S):#.000000}");
lines = lines.Skip(1 + n).ToList();
}
}
}
}
}<file_sep>/Google Code Jam 2016/Qualification Round/ProblemA - Counting Sheep.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Gcj
{
internal static class Program
{
private static void Main()
{
const string inputFile = @"A-large-practice.in";
const string outputFile = @"output.txt";
var xs = File.ReadLines(inputFile).ToList();
var t = int.Parse(xs[0]);
var ns = xs.GetRange(1, t).Select(long.Parse).ToList();
var result = new string[t];
for (var ti = 0; ti < t; ti++)
{
if (ns[ti] == 0)
{
result.Add($"Case #{ti + 1}: INSOMNIA");
continue;
}
var founds = new bool[10];
long result2;
for (var i = 1; ; i++)
{
result2 = ns[ti] * i;
var digits = result2.ToString().ToCharArray().Select(c => (int)char.GetNumericValue(c));
foreach (var d in digits)
{
founds[d] = true;
}
if (founds.All(b => b))
{
break;
}
}
result[ti] = $"Case #{ti + 1}: {result2}";
}
File.WriteAllLines(outputFile, result);
}
}
} | 617d9b67616ee93d289e269d5d966565cc76790b | [
"C#"
] | 27 | C# | matcha/competitive-programming-solutions | f2cff28cf7a4accae35e6d0df0540608357ed219 | 1cf23dd60197f24e7ad8b3411e1590bb773add80 |
refs/heads/master | <repo_name>1329555958/otter<file_sep>/README.md
# 配置表说明
使用script.js生成批量配置脚本
## data_media 数据表配置
## data_media_pair 数据同步映射配置
# 常用命令
```
SHOW VARIABLES LIKE '%server%';
SHOW VARIABLES LIKE '%binlog%';
SHOW MASTER STATUS;
SELECT * FROM information_schema.PROCESSLIST p WHERE p.COMMAND = 'Binlog Dump';
```
# 流程
- MysqlConnection.dump
receiveBuffer
连接到主库,主库发送数据,canal属于被动接收
- MemoryEventStoreWithBuffer.tryPut(List<Event> data)
存入缓冲区
- MemoryEventStoreWithBuffer.get
# cpu 100%
```
"nioEventLoopGroup-2-3" #109 prio=10 os_prio=0 tid=0x00007fea843d0ee0 nid=0x209c runnable [0x00007feb5c15f000]
java.lang.Thread.State: RUNNABLE
at io.netty.util.internal.PlatformDependent0.copyMemory(PlatformDependent0.java:415)
at io.netty.util.internal.PlatformDependent.copyMemory(PlatformDependent.java:552)
at io.netty.buffer.UnsafeByteBufUtil.setBytes(UnsafeByteBufUtil.java:552)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:260)
at io.netty.buffer.AbstractByteBuf.discardReadBytes(AbstractByteBuf.java:210)
at com.alibaba.otter.canal.parse.driver.mysql.socket.SocketChannel.writeCache(SocketChannel.java:32)
- locked <0x00000000c0679028> (a java.lang.Object)
at com.alibaba.otter.canal.parse.driver.mysql.socket.SocketChannelPool$BusinessHandler.channelRead(SocketChannelPool.java:93)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:373)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:351)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:373)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:129)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:651)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:574)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:488)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:450)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:873)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:748)
```
正常
```
"destination = aliyun , address = /10.65.215.12:3306 , EventParser" #680 daemon prio=5 os_prio=0 tid=0x00007f503c01f000 nid=0x2091 runnable [0x00007f51de3e2000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:197)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
- locked <0x00000000c133f4b8> (a java.lang.Object)
at com.alibaba.otter.canal.parse.inbound.mysql.dbsync.DirectLogFetcher.fetch0(DirectLogFetcher.java:154)
at com.alibaba.otter.canal.parse.inbound.mysql.dbsync.DirectLogFetcher.fetch(DirectLogFetcher.java:78)
at com.alibaba.otter.canal.parse.inbound.mysql.MysqlConnection.dump(MysqlConnection.java:121)
at com.alibaba.otter.canal.parse.inbound.AbstractEventParser$3.run(AbstractEventParser.java:209)
at java.lang.Thread.run(Thread.java:748)
```
# 参数说明
- 获取批次数据超时时间(毫秒)
如果想按照消费批次大小来进行消费,需要设置canal的ITEMSIZE模式且超时时间设置为0
# 调优说明
## canal
- 内存存储batch获取模式
使用ITEMSIZE,用个数进行限制不直接使用大小限制,因为大小不好控制
- 内存存储buffer记录数
这个要比消费批次大,否则不够一次读取的会影响效率,消费批次*10大概就可以了
## Pipeline
- 并行度
无需调整,默认5就可以了,增大并行度只会增加内存并不会增加速度,因为并行度达到最大只会就会消费一个取一个跟当前有多少个并行无关
- 数据载入线程数
可以适当调大,差不多运行服务器cpu*2 可以最大限度的增加写入并行度
- 消费批次大小
可以适当调大,当缓冲区满了之后就会一下获取到最大数据了,再使用数据载入线程进行写入数据库,每个线程50x线程数x4
- 映射关系表
表的个数不要太多,太多可以把数据均分一下配置不同的pipeline
# 修改说明
- com.alibaba.otter.canal.parse.driver.mysql.socket.SocketChannel
添加netty 缓冲区最大内存限制,直接内存过大并不会提升性能而且会增加回收内存的性能消耗
- com.alibaba.otter.node.etl.load.loader.db.DbLoadAction
表太多并且每张表的记录比较少的时候按照表来划分线程批次就会有问题,现在改为直接执行sql语句的形式来来批量提交多张表
- com.alibaba.otter.node.common.statistics.impl.StatisticsClientServiceImpl
合并表状态及吞吐量数据,一分钟发送一次,因为表太多的时候好像管理端会有很大延迟估计要对这些数据进行计算
# 注意
- lib/install.sh可以解决包依赖问题
- 源数据必须开启binlog,并且ROW模式
- 主库server_id必须配置
- 必须使用.*能包含所有的创建表操作ddl才会被同步
- 出错3次会挂起,查看日志记录,可以修改自动恢复次数
- 添加源码时把所有代码全部添加,包含包名和导入
- 扩展打印日志 ,修改`node/conf/logback.xml`
- 获取批次数据超时时间(毫秒)
# 打印扩展日志
## 修改node日志配置 node/conf/logback.xml
```
<appender name="EXTEND-ROOT" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<Key>otter</Key>
<DefaultValue>node</DefaultValue>
</discriminator>
<sift>
<appender name="FILE-${otter}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>../logs/${otter}/extend.log</File>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>../logs/${otter}/%d{yyyy-MM-dd}/extend-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>30MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{56} - %msg%n
</pattern>
</encoder>
</appender>
</sift>
</appender>
<logger name="com.alibaba.otter.node.extend.processor" additivity="false">
<level value="INFO" />
<appender-ref ref="EXTEND-ROOT" />
</logger>
```
<h1>环境搭建 & 打包</h1>
<strong>环境搭建:</strong>
<ol>
<li>进入$otter_home目录</li>
<li>执行:mvn clean install</li>
<li>导入maven项目。如果eclipse下报"Missing artifact com.oracle:ojdbc14:jar:10.2.0.3.0",修改$otter_home/pom.xml中"${user.dir}/lib/ojdbc14-10.2.0.3.0.jar"为绝对路径,比如"d:/lib/ojdbc14-10.2.0.3.0.jar" </li>
</ol>
<strong>打包:</strong>
<ol>
<li>进入$otter_home目录</li>
<li>执行:mvn clean install -Dmaven.test.skip -Denv=release</li>
<li>发布包位置:$otter_home/target</li>
</ol>
<h1>
<a name="%E9%A1%B9%E7%9B%AE%E8%83%8C%E6%99%AF" class="anchor" href="#%E9%A1%B9%E7%9B%AE%E8%83%8C%E6%99%AF"><span class="octicon octicon-link"></span></a>项目背景</h1>
<p>
阿里巴巴B2B公司,因为业务的特性,卖家主要集中在国内,买家主要集中在国外,所以衍生出了杭州和美国异地机房的需求,同时为了提升用户体验,整个机房的架构为双A,两边均可写,由此诞生了otter这样一个产品。 </p>
<p>
otter第一版本可追溯到04~05年,此次外部开源的版本为第4版,开发时间从2011年7月份一直持续到现在,目前阿里巴巴B2B内部的本地/异地机房的同步需求基本全上了otte4。
</p>
<strong>目前同步规模:</strong>
<ol>
<li>同步数据量6亿</li>
<li>文件同步1.5TB(2000w张图片)</li>
<li>涉及200+个数据库实例之间的同步</li>
<li>80+台机器的集群规模</li>
</ol>
<h1>
<a name="%E9%A1%B9%E7%9B%AE%E4%BB%8B%E7%BB%8D" class="anchor" href="#%E9%A1%B9%E7%9B%AE%E4%BB%8B%E7%BB%8D"><span class="octicon octicon-link"></span></a>项目介绍</h1>
<p>名称:otter ['ɒtə(r)]</p>
<p>译意: 水獭,数据搬运工</p>
<p>语言: 纯java开发</p>
<p>定位: 基于数据库增量日志解析,准实时同步到本机房或异地机房的mysql/oracle数据库. 一个分布式数据库同步系统</p>
<p> </p>
<h1>
<a name="%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86" class="anchor" href="#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="octicon octicon-link"></span></a>工作原理</h1>
<p><img width="848" src="https://camo.githubusercontent.com/2988fbbc7ddfe94ed027cd71720b1ffa5912a635/687474703a2f2f646c322e69746579652e636f6d2f75706c6f61642f6174746163686d656e742f303038382f313138392f64343230636131342d326438302d336435352d383038312d6239303833363036613830312e6a7067" height="303" alt=""></p>
<p>原理描述:</p>
<p>1. 基于Canal开源产品,获取数据库增量日志数据。 什么是Canal, 请<a href="https://github.com/alibaba/canal">点击</a></p>
<p>2. 典型管理系统架构,manager(web管理)+node(工作节点)</p>
<p> a. manager运行时推送同步配置到node节点</p>
<p> b. node节点将同步状态反馈到manager上</p>
<p>3. 基于zookeeper,解决分布式状态调度的,允许多node节点之间协同工作. </p>
<h3>
<a name="%E4%BB%80%E4%B9%88%E6%98%AFcanal-" class="anchor" href="#%E4%BB%80%E4%B9%88%E6%98%AFcanal-"><span class="octicon octicon-link"></span></a>什么是canal? </h3>
otter之前开源的一个子项目,开源链接地址:<a href="http://github.com/alibaba/canal">http://github.com/alibaba/canal</a>
<p> </p>
<h1>
<a name="introduction" class="anchor" href="#introduction"><span class="octicon octicon-link"></span></a>Introduction</h1>
<p>See the page for introduction: <a class="internal present" href="https://github.com/alibaba/otter/wiki/Introduction">Introduction</a>.</p>
<h1>
<a name="quickstart" class="anchor" href="#quickstart"><span class="octicon octicon-link"></span></a>QuickStart</h1>
<p>See the page for quick start: <a class="internal present" href="https://github.com/alibaba/otter/wiki/QuickStart">QuickStart</a>.</p>
<p> </p>
<h1>
<a name="adminguide" class="anchor" href="#adminguide"><span class="octicon octicon-link"></span></a>AdminGuide</h1>
<p>See the page for admin deploy guide : <a class="internal present" href="https://github.com/alibaba/otter/wiki/Adminguide">AdminGuide</a></p>
<p> </p>
<h1>
<a name="%E7%9B%B8%E5%85%B3%E6%96%87%E6%A1%A3" class="anchor" href="#%E7%9B%B8%E5%85%B3%E6%96%87%E6%A1%A3"><span class="octicon octicon-link"></span></a>相关文档</h1>
<p>See the page for 文档: <a class="internal present" href="https://github.com/alibaba/otter/wiki/%E7%9B%B8%E5%85%B3ppt%26pdf">相关PPT&PDF</a></p>
<p> </p>
<h1>
<a name="%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98" class="anchor" href="#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98"><span class="octicon octicon-link"></span></a>常见问题</h1>
<p>See the page for FAQ: <a class="internal present" href="https://github.com/alibaba/otter/wiki/Faq">FAQ</a></p>
<p> </p>
<h1>
<a name="%E7%89%88%E6%9C%AC%E7%9B%B8%E5%85%B3-" class="anchor" href="#%E7%89%88%E6%9C%AC%E7%9B%B8%E5%85%B3-"><span class="octicon octicon-link"></span></a>版本相关: </h1>
<p>1. 建议版本:4.2.15 (otter开源版本从内部演变而来,所以初始版本直接从4.x开始) </p>
<p>2. 下载发布包:<a href="https://github.com/alibaba/otter/releases">download </a></p>
<p>3. maven依赖 : 暂无 </p>
<h1>相关开源</h1>
<ol>
<li>阿里巴巴mysql数据库binlog的增量订阅&消费组件:<a href="http://github.com/alibaba/canal">http://github.com/alibaba/canal</a></li>
<li>阿里巴巴去Oracle数据迁移同步工具(目标支持MySQL/DRDS):<a href="http://github.com/alibaba/yugong">http://github.com/alibaba/yugong</a></li>
</ol>
<p> </p>
<h1>
<a name="%E9%97%AE%E9%A2%98%E5%8F%8D%E9%A6%88" class="anchor" href="#%E9%97%AE%E9%A2%98%E5%8F%8D%E9%A6%88"><span class="octicon octicon-link"></span></a>问题反馈</h1>
<h3>
<a name="%E6%B3%A8%E6%84%8Fcanalotter-qq%E8%AE%A8%E8%AE%BA%E7%BE%A4%E5%B7%B2%E7%BB%8F%E5%BB%BA%E7%AB%8B%E7%BE%A4%E5%8F%B7161559791-%E6%AC%A2%E8%BF%8E%E5%8A%A0%E5%85%A5%E8%BF%9B%E8%A1%8C%E6%8A%80%E6%9C%AF%E8%AE%A8%E8%AE%BA" class="anchor" href="#%E6%B3%A8%E6%84%8Fcanalotter-qq%E8%AE%A8%E8%AE%BA%E7%BE%A4%E5%B7%B2%E7%BB%8F%E5%BB%BA%E7%AB%8B%E7%BE%A4%E5%8F%B7161559791-%E6%AC%A2%E8%BF%8E%E5%8A%A0%E5%85%A5%E8%BF%9B%E8%A1%8C%E6%8A%80%E6%9C%AF%E8%AE%A8%E8%AE%BA"><span class="octicon octicon-link"></span></a>注意:canal&otter QQ讨论群已经建立,群号:161559791 ,欢迎加入进行技术讨论。</h3>
<p>1. <span>qq交流群: 161559791</span></p>
<p><span>2. </span><span>邮件交流: <EMAIL></span></p>
<p><span>3. </span><span>新浪微博: agapple0002</span></p>
<p><span>4. </span><span>报告issue:</span><a href="https://github.com/alibaba/otter/issues">issues</a></p>
<p> </p>
<pre>
【招聘】阿里巴巴中间件团队招聘JAVA高级工程师
岗位主要为技术型内容(非业务部门),阿里中间件整个体系对于未来想在技术上有所沉淀的同学还是非常有帮助的
工作地点:杭州、北京均可. ps. 阿里待遇向来都是不错的,有意者可以QQ、微博私聊.
具体招聘内容:https://job.alibaba.com/zhaopin/position_detail.htm?positionId=32666
</pre>
<file_sep>/script.js
/**
* 用来生成批量插入脚本
*/
var fs = require("fs");
var DATA = fs.readFileSync('tables') + '';
var LINES = DATA.split('\r\n');
var SPLIT_SCHEMA_TABLE = ".";
var SQL = [];
//从数据库读取到的数据源配置文件
var SOURCE = {
"mode": "SINGLE",
"name": "",
"namespace": "cmf2",
"source": {
"driver": "com.mysql.jdbc.Driver",
"encode": "UTF8",
"gmtCreate": new Date().getTime(),
"gmtModified": new Date().getTime(),
"id": 1,
"name": "Source",
"password": "<PASSWORD>",
"type": "MYSQL",
"url": "jdbc:mysql://10.65.215.12:3306",
"username": "root"
}
}, TARGET = {
"mode": "SINGLE",
"name": "tt_inst_notify_log",
"namespace": "cmf2",
"source": {
"driver": "com.mysql.jdbc.Driver",
"encode": "UTF8",
"gmtCreate": new Date().getTime(),
"gmtModified": new Date().getTime(),
"id": 2,
"name": "Target",
"password": "<PASSWORD>",
"type": "MYSQL",
"url": "jdbc:mysql://10.65.215.37:3306",
"username": "root"
}
};
/**
* 生成数据表
*/
function genDataMediaSql() {
SQL = [];
LINES.forEach(function (line) {
line = line.trim();
let cols = line.split(SPLIT_SCHEMA_TABLE);
if (!cols || cols.length < 2) {
return;
}
var schema = cols[0], table = cols[1];
SOURCE.name = table;
SOURCE.namespace = schema;
TARGET.name = table;
TARGET.namespace = schema;
genTableSqlWithSource(SOURCE);
genTableSqlWithSource(TARGET)
});
saveSql('data-media.sql');
}
function genTableSqlWithSource(source) {
var sql = ["INSERT INTO DATA_MEDIA(name,namespace,properties,data_media_source_id,gmt_create) VALUES ("
, '\'', source.name, '\',\'', source.namespace, '\',\'', JSON.stringify(source), '\',', source.source.id, ',', "NOW());"];
SQL.push(sql.join(''));
}
//生成配对配置,与生成配置表的配置配合使用,记得修改start及count值
function genPairSql() {
var pipeline = 1;
SQL = [];
//SELECT AUTO_INCREMENT FROM information_schema.`TABLES` WHERE TABLE_SCHEMA='otter' AND TABLE_NAME='data_media';
var start = 1, count = LINES.length; //配置表的源id
for (var i = 0; i < count; i++) {
var sql = [
'INSERT INTO `DATA_MEDIA_PAIR` (`PULLWEIGHT`, `PUSHWEIGHT`, `SOURCE_DATA_MEDIA_ID`, `TARGET_DATA_MEDIA_ID`, `PIPELINE_ID`, `COLUMN_PAIR_MODE`, `GMT_CREATE`, `GMT_MODIFIED`) values(NULL',
"'5'",
start++, start++
, pipeline,"'INCLUDE','2018-01-30 18:23:54','2018-01-30 18:23:54');"
];
SQL.push(sql.join(','))
}
//SQL.push("UPDATE DATA_MEDIA_PAIR SET resolver = (SELECT t.data FROM data_bak t WHERE t.name = 'resolver-null'),FILTER = (SELECT t.data FROM data_bak t WHERE t.name = 'filter-del');");
saveSql('pair.sql');
}
/**
* 生成清空表数据sql
*/
function truncateTable() {
SQL = [];
LINES.forEach(line => {
line = line.trim();
let cols = line.split(SPLIT_SCHEMA_TABLE);
if (!cols || cols.length < 2) {
return;
}
var schema = cols[0], table = cols[1];
SQL.push('TRUNCATE TABLE ' + schema + '2.' + table + ';');
});
saveSql('truncate.sql');
}
function saveSql(filename = 'sql.sql') {
fs.writeFile(filename, SQL.join("\r\n"), function (err) {
if (err) {
console.error(err);
} else {
console.log('写入成功:' + filename);
}
});
}
//genDataMediaSql();
genPairSql();
//truncateTable();
//target
//gop t_transit_fund_change_detail
//tss t_in_transit_fund_message
//UPDATE data_media_pair SET resolver = (SELECT t.data FROM data_bak t WHERE t.name = 'resolver-null'),FILTER = (SELECT t.data FROM data_bak t WHERE t.name = 'filter-del')
//filter {"blank":false,"extensionDataType":"SOURCE","notBlank":true,"sourceText":"package com.alibaba.otter.node.extend.processor;import com.alibaba.otter.shared.etl.extend.processor.EventProcessor;import com.alibaba.otter.shared.etl.model.EventData;import com.alibaba.otter.shared.etl.model.EventType;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class TestEventProcessor implements EventProcessor { static Logger LOG = LoggerFactory.getLogger(TestEventProcessor.class); @Override public boolean process(EventData eventData) { if (EventType.DELETE.equals(eventData.getEventType())) { LOG.info(\"{}\", eventData); return false; } return true; }}","timestamp":1517307834203}
//resolver {"blank":true,"clazzPath":"","extensionDataType":"CLAZZ","notBlank":false,"timestamp":1517307834203}<file_sep>/node/deployer/README.md
CanalInstanceWithManager.CanalInstanceWithManager
AbstractEventParser.AbstractEventParser()
consumeTheEventAndProfilingIfNecessary
# 读取binlog速度比较慢
MysqlConnection.dump -> AbstractEventParser.SinkFunction 解析binlog比较慢
bufferSize / batchSize 不要超过50
bufferSize 事件缓存数量,达到一定量才进行解析
batchSize 多线程解析时,多少划分为一个批次,每个解析大概1ms,所以10000比较合适 | 9b8987f3fad7ef26ffc2e56286d3b264cb3f742e | [
"Markdown",
"JavaScript"
] | 3 | Markdown | 1329555958/otter | f7afdf35e30080266080c840adf84e0ad78abce0 | c88b531c00df2f2ef35c5af36d460af8e9e88d0f |
refs/heads/master | <repo_name>myagoo/Hello-PHP<file_sep>/core/config.php
<?php
class config {
//Niveau de déboguage (0 = Prod, >1 = Dev)
static $debug = 1;
//Instanciation des données de connexion aux base de données
static $databases = array(
'default' => array(
'host' => 'localhost',
'database' => 'hellophp',
'user' => 'root',
'password' => ''
)
);
//Le controller chargé par défaut si PATH_INFO n'est pas défini
static $default_controller = 'posts';
//L'action appelée par défaut si PATH_INFO n'est pas défini
static $default_action = 'index';
}
?>
<file_sep>/webroot/foot.php
<footer>
<div class="row">
<div class="span16 columns">
<h2><a href="<?php echo BASE_URL.DS ?>">Blog title</a> <small>Some footer content</small></h2>
</div>
</div>
</footer>
</div>
</body>
</html>
<file_sep>/core/functions.php
<?php
function debug($var){
if(config::$debug > 0){
$backtrace = debug_backtrace();
echo '<p><a href="#" onclick="$(this).parent().next(\'ol\').slideToggle(); return false"><strong>'.$backtrace[0]['file'].'</strong> line '.$backtrace[0]['line'].'</a></p>';
echo '<ol style="display:none">';
foreach($backtrace as $key => $value){
if($key > 0){
echo '<li><strong>'.$backtrace[$key]['file'].'</strong> line '.$backtrace[$key]['line'].'</li>';
}
}
echo '</ol>';
echo '<pre>';
print_r($var);
echo '</pre>';
}
}
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
?>
<file_sep>/controllers/users.controller.php
<?php
class users extends controller {
public $models = array('user', 'group');
public $helpers = array('session');
public function login() {
if(!empty($this->request->data['user'])) {
$user = $this->request->data['user'];
if($this->user->find(array(
'conditions' => 'users.username = "' . $user['username'] . '" AND users.password = "' . sha1($user['password']) . '"'
))) {
$this->session->data('user', time());
$this->session->flash('Vous êtes maintenant connecté !');
$to = $this->session->data('from');
if(!empty($to)){
$this->session->del('from');
router::redirect($to);
} else {
router::redirect();
}
} else {
$this->session->flash('Le nom d\'utilisateur et/ou le mot de mot de passe saisi est incorrect', 'error');
}
}
}
public function logout() {
$this->session->del('user');
$this->session->flash('Vous êtes maintenant déconnecté.', 'error');
router::redirect();
}
public function signup() {
$user = $this->request->data['user'];
if(!empty($user)) {
$data['user'] = $this->request->data['user'];
if($data['user']['password'] == $data['user']['confirm']) {
if(!$this->user->find(array(
'conditions' => 'users.username = "' . $data['user']['username'] . '"'
))) {
unset($data['user']['confirm']);
$data['user']['password'] = sha1($data['user']['password']);
$this->user->save($data['user']);
$this->session->flash('Vous pouvez maintenant vous connecter.');
router::redirect();
}
} else {
$this->set($data); # Permet à l'utilisateur de ne pas retaper certaines informations déjà saisies malgré l'erreur
$this->session->flash('Le mot de passe et le mot de passe de confirmation sont différents', 'error');
}
} else {
$data['user']['username'] = '';
$data['user']['email'] = '';
$this->set($data);
}
}
public function index() {
$data['users'] = $this->user->find();
$this->set($data);
}
//Récupère un article
public function view($id) {
$data['user'] = $this->user->find(array(
'conditions' => 'users.id = ' . $id
));
$data['user'] = $data['user'][0];
$this->set($data);
$this->render('view');
}
//Supprime un article
public function delete($id) {
$this->user->delete($id);
$this->index();
}
public function edit($id=null) {
if(isset($_POST['user'])) {
$id = $this->user->save($_POST['user']);
}
$data['groups'] = $this->group->find();
if(!empty($id)) {
$data['user'] = $this->user->find(array(
'conditions' => 'users.id = ' . $id
));
$data['user'] = $data['user'][0];
} else {
$data['user']['username'] = '';
$data['user']['password'] = '';
$data['user']['email'] = '';
}
$this->set($data);
$this->render('edit');
}
}
?>
<file_sep>/webroot/head.php
<!DOCTYPE html>
<html class="no-js" lang="fr">
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/modernizr.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/bootstrap/bootstrap-alerts.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/bootstrap/bootstrap-dropdown.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/bootstrap/bootstrap-modal.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/bootstrap/bootstrap-popover.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/bootstrap/bootstrap-tabs.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/bootstrap/bootstrap-twipsy.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>/scripts/markitup/skins/simple/style.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>/scripts/markitup/sets/default/style.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>/styles/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>/scripts/css/flick/jquery-ui-1.8.16.custom.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>/styles/style.css"/>
<title><?php echo isset($title_for_layout) ? $title_for_layout : "Blog title" ?></title>
</head>
<body>
<script type="text/javascript" src="<?php echo BASE_URL; ?>/scripts/markitup/sets/default/set.js"></script>
<script type="text/javascript">
$(function(){
//Initialisation de markItUp
$(".markItUp").markItUp(mySettings);
//Initialisation de la recherche par autocomplete
$("#search").autocomplete({
source: '<?php echo BASE_URL; ?>/autocomplete.php'
});
$().alert();
//Placeholders Fix
if(!Modernizr.input.placeholder){
$("input").each(function(){
if(!$(this).attr("value") && $(this).attr("placeholder")){
$(this).val($(this).attr("placeholder")).focus(function(){
if($(this).val()==$(this).attr("placeholder")){
$(this).val("");
}
}).blur(function(){
if($(this).val()==""){
$(this).val($(this).attr("placeholder"));
}
});
}
});
}
});
</script>
<div class="topbar" style="position:static;">
<div class="fill">
<div class="container">
<h3><a href="<?php echo BASE_URL; ?>">Blog title</a></h3>
<ul class="nav">
<li><a href="#">Nav...</a></li>
<li><a href="#">Nav...</a></li>
<li><a href="#">And nav...</a></li>
</ul>
<form>
<input type="text" id="search" placeholder="Search">
</form>
<ul class="nav secondary-nav">
<li><a href="<?php echo BASE_URL; ?>/users/login">Login</a></li>
<li><a href="<?php echo BASE_URL; ?>/users/signup">Sign up</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="hero-unit" style="margin-top:20px;">
<h1>Hello</h1>
<p>This is a demonstration of the Hello PHP framework</p>
<p><a href="#" class="btn primary large">More</a></p>
</div>
<file_sep>/views/users/edit.view.php
<form method="POST">
<input type="hidden" name="user[id]" value="<?php echo empty($user['id']) ? '' : $user['id']; ?>">
<input type="text" name="user[username]" value="<?php echo $user['username']; ?>" placeholder="Pseudo">
<input type="text" name="user[password]" value="<?php echo $user['password']; ?>" placeholder="Mot de passe">
<input type="text" name="user[email]" value="<?php echo $user['email']; ?>" placeholder="Adresse email">
<select name="user[group_id]">
<?php foreach($groups as $group){ ?>
<option value="<?php echo $group['id']; ?>" <?php echo $group['id'] == $user['group_id'] ? 'selected' : '' ?>><?php echo $group['name']; ?></option>
<?php } ?>
</select>
<input type="submit" value="Enregistrer" name="submited">
</form>
<file_sep>/core/coreController.php
<?php
class coreController {
private $vars;
//Variables à faire passer à la vue
private $rendered = false;
//Permet de savoir si la vue a déjà été rendu
public $layout = 'default';
public $request;
public function __construct($request = null) {
$this->vars = array();
if(isset($request)) {
$this->request = $request;
}
if(!empty($this->models)) {
$this->loadModel($this->models);
}
if(!empty($this->helpers)) {
$this->loadHelper($this->helpers);
}
}
/**
* Affiche la vue correspondante au controller à l'écran, renvoie false en cas d'erreur
* @param type $view
* @return boolean
*/
public function render($view) {
# On ne peut rendre une vue qu'une seule fois
if($this->rendered) {
return false;
}
if(strpos($view, '/') === 0) {
$view = ROOT . DS . 'views' . $view . '.view.php';
} else {
$view = ROOT . DS . 'views' . DS . get_class($this) . DS . $view . '.view.php';
}
extract($this->vars);
ob_start();
require($view);
$content_for_layout = ob_get_clean();
if($this->layout == false) {
echo $content_for_layout;
} else {
require(ROOT . DS . 'views' . DS . 'layout' . DS . $this->layout . '.php');
}
$this->rendered = true;
}
/**
* Concatène les variables passées en paramêtre avec les variables déjà présentes dans le controller
* @param mixed $key
* @param mixed $value
*/
public function set($key, $value = null) {
if(isset($this))
if(is_array($key)) {
$this->vars = array_merge($this->vars, $key);
} else {
$this->vars[$key] = $value;
}
}
/**
* Permet de charger un model dans un controller
* Cette méthode est appelée à la construction du controller mais peut aussi être appelée de manière ponctuelle
* @param mixed $model
*/
public function loadModel($model) {
if(is_array($model)) {
foreach ($model as $m) {
require_once(ROOT . DS . 'models' . DS . $m . '.model.php');
if(!isset($this->$m)) {
$this->$m = new $m();
}
}
} else {
require_once(ROOT . DS . 'models' . DS . $model . '.model.php');
if(!isset($this->$model)) {
$this->$model = new $model();
}
}
}
/**
* Permet de charger un helper dans un controller
* Cette méthode est appelée à la construction du controller mais peut aussi être appelée de manière ponctuelle
* @param mixed $helper
*/
public function loadHelper($helper) {
if(is_array($helper)) {
foreach ($helper as $h) {
require_once(ROOT . DS . 'helpers' . DS . $h . '.helper.php');
if(!isset($this->$h)) {
$this->$h = new $h($this->request);
}
}
} else {
require_once(ROOT . DS . 'helpers' . DS . $helper . '.helper.php');
if(!isset($this->$helper)) {
$this->$helper = new $helper();
}
}
}
}
?>
<file_sep>/models/category.model.php
<?php
class category extends Model{
public function __construct(){
$this->table = 'categories';
$this->key = 'id';
$this->displayField = 'name';
$this->hasMany = array('post');
parent::__construct();
}
}
?>
<file_sep>/core/model.php
<?php
class model {
static $db = 'default';
//Serveur MySQL sur lequel se connecter
public $table;
//Table correspondant au modèle
public $key = 'id';
//Nom de la clé primaire
public $id; //Variable utilisée
/**
*
*
* */
public function __construct() {
$this->connect(); // Connection à la base de données
$query = 'DESCRIBE ' . $this->table;
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$fieldName = $row['Field'];
unset($row['Field']);
$this->fields[$fieldName] = $row; //Récupération des infos des champs de la table dans $this->fields
}
}
/**
* Permet une lecture rapide d'un modèle grace à son identifiant
* */
public function read($fields=null) {
if (empty($fields)) {
$fields = '*';
}
$query = 'SELECT ' . $fields . ' FROM ' . $this->table . ' WHERE ' . $this->key . ' = "' . $this->id . '"';
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($results)) {
$data = mysql_fetch_assoc($result);
foreach ($data as $key => $value) {
$this->$key = $value;
}
return true;
} else {
return false;
}
}
public function save($data) {
//Si l'id est rempli, il s'agit d'un UPDATE, sinon INSERT
if ( (!empty($data[$this->key]) && count($data) > 1) || (empty($data[$this->key]) && count($data) > 0) ) {
if ( !empty($data[$this->key]) ) {
$type = 'UPDATE';
}
else {
$type = 'INSERT';
}
$query = $type;
//Construction de la requête
$query .= ' ' . $this->db . '.' . $this->table . ' SET ';
foreach ( $data as $key => $value ) {
if ( $key != $this->key && isset($this->fields[$key]) ) {
$query.= $key . ' = ?, ';
$values[] = $value;
}
}
$query = substr($query, 0, -2);
//Mise à jour des champs updated et created
if ( !empty($data[$this->key]) ) {
if ( isset($this->fields['updated']) ) {
$query .= ', updated = ?';
$values[] = date('Y-m-d H:i:s');
}
$query.=' WHERE ' . $this->key . ' = ?';
$values[] = $data[$this->key];
}
else {
if ( isset($this->fields['created']) ) {
$query .= ', created = ?';
$values[] = date('Y-m-d H:i:s');
}
}
//Execution de la requete
if ( $this->connection->prepare($query)->execute($values) ) {
if ( empty($data[$this->key]) ) {
$this->id = $this->connection->lastInsertId();
}
else {
$this->id = $data[$this->key];
}
return array(
'type' => $type,
'id' => $this->id
);
}
else {
return false;
}
}
else {
return false;
}
}
public function find($options = array()) {
$conditions = '1=1';
$fields = '*';
if (!empty($this->fields)) {
$fields = '';
foreach ($this->fields as $fieldName => $informations) {
$fields .= $this->table . '.' . $fieldName . ' as ' . get_Class($this) . '_' . $fieldName . ', ';
}
$fields = substr($fields, 0, -2);
}
$limit = '';
$order = $this->table . '.' . $this->key . ' ASC';
$left_outer = '';
//
if (!empty($this->belongsTo)) {
foreach ($this->belongsTo as $modelName) {
$model = $this->load($modelName);
//E.G. : , posts.id as post_id
$fields .= ', ' . $model->table . '.' . $model->key . ' as ' . $modelName . '_' . $model->key;
$fields .= ', ' . $model->table . '.' . $model->displayField . ' as ' . $modelName . '_' . $model->displayField;
$left_outer .= ' LEFT OUTER JOIN ' . $model->table . ' ON ' . $this->table . '.' . $modelName . '_id = ' . $model->table . '.id';
}
}
//
if (!empty($options['conditions'])) {
$conditions = $options['conditions'];
}
if (!empty($options['fields'])) {
$fields = $options['fields'];
}
if (!empty($options['limit'])) {
$limit = ' LIMIT ' . $options['limit'];
}
if (!empty($options['order'])) {
$order = $this->table . '.' . $options['order'];
}
$query = 'SELECT ' . $fields . ' FROM ' . $this->table . $left_outer . ' WHERE ' . $conditions . ' ORDER BY ' . $order . $limit;
$results = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($results)) {
$i = 0;
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $fieldName => $value) {
$pos = strpos($fieldName, '_');
$prefix = substr($fieldName, 0, $pos);
$sufix = substr($fieldName, $pos + 1, strlen($fieldName));
if ($prefix == get_Class($this)) {
$data[$i][$sufix] = $value;
} else {
$data[$i][$prefix][$sufix] = $value;
}
}
$i++;
}
return $data;
} else {
return false;
}
}
public function delete($id=null) {
if ( empty($id) ) {
//$id = $this->current;
return false;
}
$query = 'DELETE FROM ' . $this->db . '.' . $this->table . ' WHERE ' . $this->key . ' = ?';
$values[] = $id;
if ( $this->connection->prepare($query)->execute($values) ) {
return true;
}
else {
return false;
}
}
static function load($name) {
return new $name();
}
static function connect() {
if (isset($this)) {
$db_data = config::$databases[$this->$db];
} else {
$db_data = config::$databases[self::$db];
}
$db_data = config::$databases[self::$db];
$connection = mysql_connect($db_data['host'], $db_data['user'], $db_data['password']);
if (!empty($connection)) {
if (!mysql_select_db($db_data['database'], $connection)) {
echo "Erreur dans la sélection de la base de données";
}
} else {
echo "Impossible de se connecter à MySQL.";
}
}
}
?>
<file_sep>/helpers/session.helper.php
<?php
class session {
public function __construct() {
if(!isset($_SESSION)) {
session_start();
}
}
public function flash($message = null, $type = 'success') {
if(isset($message)) {
$_SESSION['flashes'][] = array(
'message' => $message,
'type' => $type
);
} else {
if(isset($_SESSION['flashes'])) {
$html = '';
foreach ($_SESSION['flashes'] as $flash) {
$html .= '<div class="alert-message ' . $flash['type'] . ' fade in" data-alert="alert"><a class="close" href="#">×</a><p>' . $flash['message'] . '</p></div>';
}
unset($_SESSION['flashes']);
return $html;
}
}
}
public function data($key = null, $value = null) {
if(!isset($key) && !isset($value)) {
return $_SESSION;
} else {
if(isset($value)) {
$_SESSION[$key] = $value;
return true;
} elseif(isset($_SESSION[$key])) {
return $_SESSION[$key];
}
}
}
public function isLogged() {
return isset($_SESSION['user']);
}
public function del($key = null) {
if(isset($key)) {
if(isset($_SESSION[$key])) {
unset($_SESSION[$key]);
return true;
} else {
return false;
}
} else {
session_destroy();
return true;
}
}
}
?>
<file_sep>/views/users/signup.view.php
<form method="POST" class="form-stacked">
<fieldset>
<legend>Create your account</legend>
<div class="clearfix">
<label>Username</label>
<div class="input">
<input type="text" value="<?php echo $user['username'] ?>" name="user[username]" placeholder="Username">
</div>
</div>
<div class="clearfix">
<label>Password</label>
<div class="input">
<input type="<PASSWORD>" name="user[password]" placeholder="<PASSWORD>">
</div>
</div>
<div class="clearfix">
<label>Confirm password</label>
<div class="input">
<input type="password" name="user[confirm]" placeholder="<PASSWORD> your password">
</div>
</div>
<div class="clearfix">
<label>Email</label>
<div class="input">
<input type="text" value="<?php echo $user['email'] ?>" name="user[email]" placeholder="Email">
</div>
</div>
<div class="actions">
<input type="submit" value="Sign Up" name="submited" class="btn primary">
<button class="btn" type="reset">Cancel</button>
</div>
<fieldset>
</form>
<file_sep>/webroot/index.php
<?php
$start = microtime(true);
define('DS', DIRECTORY_SEPARATOR);
define('WEBROOT', dirname(__FILE__));
define('ROOT', dirname(WEBROOT));
define('CORE',ROOT.DS.'core');
define('BASE_URL','http://'.$_SERVER['HTTP_HOST'].str_replace('/webroot/index.php','',$_SERVER['SCRIPT_NAME']));
require_once(CORE.DS.'includes.php');
$dispatcher = new dispatcher();
if(config::$debug > 0){
echo 'Page generated in '.round((microtime(true) - $start), 5).' seconds.';
}
?>
<file_sep>/helpers/form.helper.php
<?php
class form {
public $controller;
public function __construct($controller = null) {
$this->controller = $controller;
}
// render <form> opening tag
public static function open($options = array()) {
$legend = '';
if (isset($options['legend'])) {
$legend .= '<legend>' . $options['legend'] . '</legend>';
unset($options['legend']);
}
$attributes = '';
foreach ($options as $k => $v) {
$attributes .= ' ' . $k . '="' . $v . '"';
}
$html = '<form method="POST"' . $attributes . '>';
$html .= '<fieldset>';
$html.= $legend;
return $html;
}
// render <input> tag
public static function input($name, $value, $options = array()) {
$begin = '<div class="clearfix">';
# Liste des options qui ne sont pas des attributs de l'input
if (isset($options['label'])) {
$begin .= '<label for="input_' . $name . '">' . $options['label'] . '</label>';
unset($options['label']);
}
if (isset($options['type'])) {
$type = $options['type'];
unset($options['type']);
}
if (isset($options['reset'])) {
$reset = $options['reset'];
unset($options['reset']);
}
$begin .='<div class="input">';
$end = '</div></div>';
$attributes = '';
foreach ($options as $k => $v) {
$attributes .= ' ' . $k . '="' . $v . '"';
}
if (isset($type)) {
if ($type == 'textarea') {
$input = '<textarea id="input_' . $name . '" name="' . $name . '"' . $attributes . '>' . $value . '</textarea>';
} elseif ($type == 'hidden') {
$begin = '';
$input = '<input type="hidden" id="input_' . $name . '" name="' . $name . '" value="' . $value . '"' . $attributes . '>';
$end = '';
} elseif ($type == 'submit') {
$begin = '<div class="actions">';
$input = '<input type="submit" class="btn primary" id="input_' . $name . '" name="' . $name . '" value="' . $value . '"' . $attributes . '>';
if (isset($reset)) {
$input.= ' <button class="btn" type="reset">' . $reset . '</button>';
}
$end = '</div>';
}
} else {
$input = '<input type="text" id="input_' . $name . '" name="' . $name . '" value="' . $value . '"' . $attributes . '>';
}
$html = $begin . $input . $end;
return $html;
}
public static function select($name, $value, $options, $params) {
$html = '<div class="clearfix">';
if (isset($params['label'])) {
$html .= '<label for="input_' . $name . '">' . $params['label'] . '</label>';
unset($params['label']);
}
$html .='<div class="input">';
$attributes = '';
foreach ($params as $k => $v) {
$attributes .= ' ' . $k . '="' . $v . '"';
}
$html .= '<select name="' . $name . '"' . $attributes . '>';
foreach ($options as $k => $v) {
$selected = '';
if ($value == $k) {
$selected = ' SELECTED';
}
$html .= '<option value="' . $k . '"' . $selected . '>' . $v . '</option>';
}
$html .= '</select>';
$html.='</div>';
$html.='</div>';
return $html;
}
// render </form> closing tag
public static function close() {
$html = '</fieldset>';
$html .= '</form>';
return $html;
}
}
// End Form class
<file_sep>/webroot/autocomplete.php
<?php
define('DS', DIRECTORY_SEPARATOR);
define('WEBROOT', dirname(__FILE__));
define('ROOT', dirname(WEBROOT));
define('CORE',ROOT.DS.'core');
define('BASE_URL','http://'.$_SERVER['HTTP_HOST'].str_replace('/webroot/index.php','',$_SERVER['SCRIPT_NAME']));
require_once(CORE.DS.'includes.php');
//Initialisation d'une connexion à MySQL
model::connect();
header('Content-type: text/html; charset=UTF-8');
$query='SELECT title FROM posts WHERE title LIKE "%'.mysql_real_escape_string($_GET["term"]).'%"';
$results=mysql_query($query);
$i=0;
$datas = array();
while($row = mysql_fetch_assoc($results)){
$datas[$i]=$row["title"];
$i++;
}
echo json_encode($datas);
?>
<file_sep>/core/dispatcher.php
<?php
class dispatcher{
public $request; //URL appelée par l'utilisateur
public function __construct(){
$this->request = new request();
router::parse($this->request);
if($controller = $this->loadController()){
if(in_array($this->request->action, array_diff(get_class_methods($controller), get_class_methods(get_parent_class($controller))))){
call_user_func_array(array($controller, $this->request->action), $this->request->params);
$controller->render($this->request->action);
} else {
$this->error('Le controller '.$this->request->controller.' n\'a pas de méthode '.$this->request->action);
}
}else{
$this->error('Le controller '.$this->request->controller.' n\'existe pas');
}
}
private function error($flash){
$controller = new Controller($this->request);
$controller->loadHelper('html');
$controller->set('flash', $flash);
$controller->render(DS.'errors'.DS.'404');
}
private function loadController($name = null){
if(!isset($name)){
$name = strtolower($this->request->controller);
}
$file = ROOT.DS.'controllers'.DS.$name.'.controller.php';
if(file_exists($file)){
require_once($file);
return new $name($this->request);
}else{
return false;
}
}
}
?>
<file_sep>/Sample.sql
-- phpMyAdmin SQL Dump
-- version 3.3.10deb1
-- http://www.phpmyadmin.net
--
-- Serveur: localhost
-- Généré le : Ven 16 Septembre 2011 à 01:48
-- Version du serveur: 5.1.54
-- Version de PHP: 5.3.5-1ubuntu7.2
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!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 utf8 */;
-- --------------------------------------------------------
--
-- Structure de la table `categories`
--
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(60) CHARACTER SET utf8 NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `comments`
--
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`body` text NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`comment_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `groups`
--
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(60) NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Structure de la table `posts`
--
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(60) CHARACTER SET utf8 NOT NULL,
`body` text CHARACTER SET utf8 NOT NULL,
`user_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(60) CHARACTER SET utf8 NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(50) CHARACTER SET utf8 NOT NULL,
`group_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
<file_sep>/models/group.model.php
<?php
class group extends model{
public function __construct(){
$this->table = 'groups';
$this->key = 'id';
$this->displayField = 'name';
$this->hasMany = array('user');
parent::__construct();
}
}
?>
<file_sep>/core/request.php
<?php
class request {
public $url;
public $page;
public $data = null;
public function __construct() {
$this->url = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/' . config::$default_controller . '/' . config::$default_action;
if(isset($_GET['page'])) {
$this->page = $_GET['page'];
}
if(isset($_POST)) {
$this->data = $_POST;
}
}
}
?>
<file_sep>/views/users/index.view.php
<?php foreach($users as $user){ ?>
<h1><a href="<?php echo WEBROOT; ?>users/view/<?php echo $user['id']; ?>"><?php echo $user['username']; ?></a></h1>
<?php } ?>
<file_sep>/views/errors/404.view.php
<h1>Page not found</h1>
<p><?php echo $flash; ?></p>
<file_sep>/controllers/posts.controller.php
<?php
class posts extends controller {
public $models = array('post', 'category', 'user');
public $helpers = array('session', 'html', 'form');
//Liste les 5 derniers articles
public function index() {
$data['posts'] = $this->post->getLast();
$this->set($data);
}
//Récupère un article
public function view($id) {
$data['post'] = $this->post->find(array(
'conditions' => 'posts.id = ' . $id
));
$data['post'] = $data['post'][0];
$data['post']['created'] = date('d/m/Y', strtotime($data['post']['created']));
$this->set($data);
$this->render('view');
}
//Supprime un article
public function delete($id) {
$this->needLogin();
$this->post->delete($id);
$this->session->flash('L\'article a bien été suprimmé');
router::redirect();
}
public function edit($id = null) {
# Cette action ne sera accessible qu'apres authentification
$this->needLogin();
# Si des données sont postées
if (!empty($this->request->data)) {
$post = $this->request->data['post'];
$id = $this->post->save($post);
$this->session->flash('Votre article a bien été enregistré');
router::redirect(BASE_URL . '/posts/edit/' . $id);
}
# Used to select the category of the post in the view
$data['categories'] = $this->category->find();
if ($data['categories'] !== false) {
foreach ($data['categories'] as $category){
$array[$category[$this->category->key]] = $category[$this->category->displayField];
}
$data['categories'] = $array;
unset($array);
}else{
$data['categories'] = array();
}
# Used to select the author of the post in the view
$data['users'] = $this->user->find();
if ($data['users'] !== false) {
foreach ($data['users'] as $user){
$array[$user[$this->user->key]] = $user[$this->user->displayField];
}
$data['users'] = $array;
unset($array);
}else{
$data['users'] = array();
}
if (!empty($id)) {
$data['post'] = $this->post->find(array(
'conditions' => 'posts.id = ' . $id
));
$data['post'] = $data['post'][0];
} else {
$data['post']['title'] = '';
$data['post']['body'] = '';
}
$this->set($data);
}
}
?>
<file_sep>/core/includes.php
<?php
require_once(CORE.DS.'config.php');
require_once(CORE.DS.'dispatcher.php');
require_once(CORE.DS.'functions.php');
require_once(CORE.DS.'model.php');
require_once(ROOT.DS.'controllers'.DS.'controller.php');
require_once(CORE.DS.'request.php');
require_once(CORE.DS.'router.php');
?>
<file_sep>/models/twitter.model.php
<?php
class twitter extends model {
public $username = 'ben_myagoo';
public $tweetsUrl = 'http://twitter.com/statuses/user_timeline.json';
public $userUrl = 'http://api.twitter.com/1/users/show.json';
public function __construct() {
return false;
}
/**
* Permet une lecture rapide d'un modèle grace à son identifiant
* */
public function read($fields=null) {
return false;
}
public function save($data, $html=false) {
return false;
}
public function find($options = array()) {
if (isset($options['request']) && $options['request'] == 'user') {
$url = $this->userUrl;
} else {
$url = $this->tweetsUrl;
}
$first = true;
if (!isset($options['screen_name']) && !isset($options['user_id'])) {
$options['screen_name'] = $this->username;
}
foreach ($options as $option => $value) {
if ($first) {
$url .= '?';
$first = false;
} else {
$url .= '&';
}
$url .= $option . '=' . $value;
}
$this->twitter = curl_init();
curl_setopt($this->twitter, CURLOPT_URL, $url);
curl_setopt($this->twitter, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->twitter, CURLOPT_TIMEOUT_MS, 1500);
$data = json_decode(curl_exec($this->twitter));
curl_close($this->twitter);
return objectToArray($data);
}
public function delete($id=null) {
return false;
}
}
?>
<file_sep>/core/router.php
<?php
class router{
/**
* Permet de parser une url
* @param $url Url à parser
* @param $request Objet request à completer
* @return tableau contenant les paramètres
**/
static function parse($request){
$url = trim($request->url, '/');
$params = explode('/', $url);
$request->controller = $params[0];
$request->action = isset($params[1]) ? $params[1] : 'index';
$request->params = array_slice($params, 2);
return true;
}
static function redirect($url = null){
if(isset($url)){
die(header('Location: '.$url));
} else {
die(header('Location: '.BASE_URL));
}
}
}
?>
<file_sep>/views/posts/edit.view.php
<?php
# Ouverture du formulaire
echo $this->form->open(array('class' => 'form-stacked', 'legend' => 'Edit this post'));
# ID du post
echo $this->form->input('post[id]', isset($post['id']) ? $post['id'] : '', array('type' => 'hidden'));
# Titre du post
echo $this->form->input('post[title]', isset($post['title']) ? $post['title'] : '', array('placeholder' => 'Titre', 'label' => 'Title'));
# Corps du post
echo $this->form->input('post[body]', isset($post['body']) ? $post['body'] : '', array('type' => 'textarea', 'class' => 'markItUp', 'placeholder' => 'Corps de l\'article', 'label' => 'Body'));
# Categorie du post
echo $this->form->select('post[category_id]', isset($post['category_id']) ? $post['category_id'] : '', $categories, array('label' => 'Category'));
# Auteur du post
echo $this->form->select('post[user_id]', isset($post['user_id']) ? $post['user_id'] : '', $users, array('label' => 'User'));
# Bouton de soumission et d'annulation
echo $this->form->input('submited', 'Save', array('type' => 'submit', 'reset' => 'Cancel'));
# fermeture du formulaire
echo $this->form->close();
?><file_sep>/models/post.model.php
<?php
class post extends model{
public $table = 'posts';
public $key = 'id';
public $displayField = 'title';
public $belongsTo = array('category', 'user');
public function getLast($count = 5){
return $this->find(array(
'limit' => $count,
'order' => 'created DESC'
));
}
}
?>
<file_sep>/views/categories/index.view.php
<?php
echo '<h1>Index des catégories</h1>';
if(!empty($categories)) {
foreach ($categories as $category) {
echo '<h1><a href="' . BASE_URL . DS . 'categories/view/' . $category['id'] . '">' . $category['name'] . '</a></h1>';
}
} else {
echo '<h3>';
echo 'Aucune catégorie';
echo '</h3>';
}
echo '<small>';
echo ' ' . $this->html->anchor(BASE_URL.'/categories/edit', 'Créer une nouvelle catégorie');
echo '</small>';
?>
<file_sep>/controllers/controller.php
<?php
require (CORE . DS . 'coreController.php');
/**
* Cette classe sera étendue par l'ensemble de vos controllers, vous pouvez alors y intégrer vos propres communes à tous les controllers
*/
class controller extends coreController {
public function __construct($request = null) {
parent::__construct($request);
$this->beforeAll();
}
/**
* Teste si l'utilisateur est connecté.
* Si ce n'est pas le cas, il est alors redirigé vers la page de connexion, sinon, la méthode parente reprend le controle
*/
public function needLogin() {
$this->loadHelper('session');
$user = $this->session->data('user');
if(empty($user)) {
$this->session->flash('Vous devez être authentifié pour effectuer cette action');
$this->session->data('from', BASE_URL . $this->request->url);
router::redirect(BASE_URL . '/users/login');
}
}
/**
* Appelée tout de suite aprè la construction d'un controller, cette méthode offre un comportement commun à tous les controllers
*/
public function beforeAll() {
$this->loadModel('twitter');
$this->loadHelper('html');
$data['twitter']['user'] = $this->twitter->find(array('request' => 'user'));
$data['twitter']['tweets'] = $this->twitter->find(array('count' => 5));
# TODO : Vérifier que les tweets ont bien été reçus
foreach ($data['twitter']['tweets'] as &$tweet) {
$tweet['text'] = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1">$1</a>', $tweet['text']);
$tweet['text'] = preg_replace('/\s+#(\w+)/', ' <a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $tweet['text']);
$tweet['text'] = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1">@$1</a>', $tweet['text']);
}
$this->set($data);
}
}
?><file_sep>/views/categories/edit.view.php
<form method="POST" class="form-stacked">
<fieldset>
<legend>Edit this category</legend>
<input type="hidden" name="category[id]" value="<?php echo empty($category['id']) ? '' : $category['id']; ?>">
<div class="clearfix">
<label>Name</label>
<div class="input">
<input type="text" name="category[name]" value="<?php echo $category['name']; ?>" placeholder="Nom">
</div>
</div>
<div class="actions">
<input type="submit" value="Save" name="submited" class="btn primary">
<button class="btn" type="reset">Cancel</button>
</div>
</fieldset>
</form>
<file_sep>/views/layout/default.php
<?php require(WEBROOT.DS.'head.php'); ?>
<?php if(isset($this->session)){
echo $this->session->flash();
} ?>
<div class="row">
<div class="span12 columns">
<?php echo $content_for_layout; ?>
</div>
<div class="span4 columns">
<?php if(!empty($twitter['tweets']) && !isset($twitter['tweets']['error'])){ ?>
<h4>Last tweets from
<?php
echo $this->html->anchor('http://twitter.com/#!/'.$twitter['user']['screen_name'], '@'.$twitter['user']['screen_name']);
echo $this->html->img($twitter['user']['profile_image_url'], array('title' => $twitter['user']['screen_name']));
?>
</h4>
<ul>
<?php foreach($twitter['tweets'] as $tweet){ ?>
<li><?php echo $tweet['text']; ?></li>
<?php } ?>
</ul>
<?php } ?>
<h3>Another Sidebar</h3>
<ul>
<li><a href="#">Nav...</a></li>
<li><a href="#">Nav...</a></li>
<li><a href="#">And nav...</a></li>
</ul>
</div>
</div>
<?php require(WEBROOT.DS.'foot.php'); ?>
<file_sep>/views/posts/index.view.php
<?php
echo '<h1>Posts index</h1>';
if (!empty($posts)) {
foreach ($posts as $post) {
echo '<h3>' . $this->html->anchor('posts/view/' . $post['id'], $post['title']) . '<br/>';
echo '<small>';
echo ' par ' . $this->html->anchor('users/view/' . $post['user_id'], $post['user']['username']);
echo ' dans la catégorie ' . $this->html->anchor('categories/view/' . $post['category_id'], $post['category']['name']);
echo '</small>';
echo '</h3>';
}
} else {
echo '<h3>';
echo 'Aucun article';
echo '<small>';
echo ' '.$this->html->anchor('posts/edit', 'Créer un article');
echo '</small>';
}
?>
<file_sep>/helpers/html.helper.php
<?php
class html{
public function anchor($url, $label, $attributes = array()){
$html = '<a href="';
if(preg_match('@^(?:http://)?([^/]+)@i', $url)){
$html .= $url;
} else {
if(substr($url,0,1) == '/'){
$html .= BASE_URL.$url;
} else {
$html .= BASE_URL.'/'.$url;
}
}
$html .= '"';
if(!empty($attributes)){
foreach($attributes as $attribute => $value){
$html .= ' '.$attribute.'="'.$value.'"';
}
}
$html .= '>'.$label.'</a>';
return $html;
}
public function img($url, $attributes = array()){
$html = '<img src="';
if(preg_match('@^(?:http://)?([^/]+)@i', $url)){
$html .= $url;
} else {
if(substr($url,0,1) == '/'){
$html .= BASE_URL.$url;
} else {
$html .= BASE_URL.'/'.$url;
}
}
$html .= '"';
if(!empty($attributes)){
foreach($attributes as $attribute => $value){
$html .= ' '.$attribute.'="'.$value.'"';
}
}
$html .= '>';
return $html;
}
}
?>
<file_sep>/Readme.md
###Create web applications easily with the Hello PHP framework
TEST !!!
# FEATURES
- MVC architecture
- Shipped with an existing project
# USAGE
To begin, edit the core/config.php file, then create your models, controllers and views using the examples.
## Roadmap
- Comments
- Doc
- Cache
- More helpers
- Recursive SQL joins
- ...
## Authors
<NAME>
<file_sep>/models/user.model.php
<?php
class user extends model{
public function __construct(){
$this->table = 'users';
$this->key = 'id';
$this->displayField = 'username';
$this->belongsTo = array('group');
$this->hasMany = array('post');
parent::__construct();
}
}
?>
<file_sep>/controllers/categories.controller.php
<?php
class categories extends controller {
public $models = array('category');
public function index() {
$data['categories'] = $this->category->find();
$this->set($data);
}
//Récupère un article
public function view($id) {
$data['category'] = $this->category->find(array(
'conditions' => 'categories.id = ' . $id
));
$data['category'] = $data['category'][0];
$this->set($data);
}
//Supprime un article
public function delete($id) {
$this->needLogin();
$this->category->delete($id);
$this->session->flash('La catégorie a bien été suprimmé');
router::redirect();
}
public function edit($id=null) {
$this->needLogin();
if(!empty($_POST['category'])){
$id = $this->category->save($_POST['category']);
if($id !== false){
$this->session->flash('La catégorie a été correctement créée.');
router::redirect(BASE_URL.'/categories');
} else{
$this->session->flash('Une erreur est survenue lors de la création de la catégorie.', 'error');
}
}
if(!empty($id)) {
$data['category'] = $this->category->find(array(
'conditions' => 'categories.id = ' . $id
));
# Puisque find renvoie des lignes de résultats, on assigne la premiere
$data['category'] = $data['category'][0];
} else {
$data['category']['name'] = '';
}
$this->set($data);
}
}
?>
| 20d44df8cf44b0a29569726ec9e044802575fd81 | [
"Markdown",
"SQL",
"PHP"
] | 35 | PHP | myagoo/Hello-PHP | 81adbf0eeb3e577f33bb74fa1147c551c15d51ea | e30a536d991263c0bf6c91c6f7bdb0dad77bf612 |
refs/heads/main | <file_sep>import socket
def Main():
port = 8000
client_binding = ('192.168.56.1', port)
s = socket.socket()
s.connect(client_binding)
filename = input("Please write the name of the file: ")
if filename != 'q':
s.send(filename.encode())
data = s.recv(1024)
if data[:6] == b'EXISTS':
filesize = int(data[6:])
message = input("This file exists, " + str(filesize) +
"Bytes, would you like to download it? (Y/N) ? ")
if message == 'Y':
s.send(b'OK')
f = open('new_' + filename, 'wb')
data = s.recv(1024)
TotalRecv = len(data)
f.write(data)
while TotalRecv < filesize:
data = s.recv(1024)
TotalRecv += len(data)
f.write(data)
print("{0:.2f}".format(
(TotalRecv/float(filesize))*100) + "% Done")
print("Your Download is complete")
else:
print("File does not exists")
s.close()
if __name__ == '__main__':
Main()
| 9b6ea846f9e1190ee0ef635def7490fec09b36e4 | [
"Python"
] | 1 | Python | fazeelhaider-ai/Personal-Transfer-Data-Protcol | e30e917a1b32a650f8fb04e5705c21759ffe27bb | 53648d9b9d5e37ca33f90c3b0f7e237653ebe5c5 |
refs/heads/master | <file_sep>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import VueLogger from 'vuejs-logger';
import 'bootstrap';
import 'font-awesome/css/font-awesome.css';
import App from './App';
import router from './router';
Vue.config.productionTip = false;
Vue.use(VueLogger, {
logLevel: 'debug',
// optional : defaults to false if not specified
stringifyArguments: false,
// optional : defaults to false if not specified
showLogLevel: false,
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
});
<file_sep># vuelendar
> Editable calendar/brochure with full features built with Vue.js 2
- Add any text content
- Add background image
- Add any asset, resize, drag, drop
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# check production build
npm install -g serve
serve dist
# run unit tests
npm run unit
# run e2e tests
npm run e2e
# run all tests
npm test
```
For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
## Credits
fabric.js
angular-editor-fabric-js
| e397192c520ddba2214bd10b272085b8a5f04569 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | CieDigitalLabs/vuelendar | 9be319e085b9352b1c83228f7bdb4a4aab6f9ff6 | e36df37d10c3c5f5b1091912b216ac0ef39d4112 |
refs/heads/master | <repo_name>chrisna2/vuelog<file_sep>/src/json/posts.js
export default [
{
title : '첫 째 프로젝트 : JavaScript 쇼핑몰',
content : '서버가 아닌 프론트엔드 환경에서 대부분의 기능을 만들어낼 수 있기 때문에 만들어보았습니다.',
date : 'September 24, 2019',
number : 0
},
{
title : '둘 째 프로젝트 : 뷰로만든 뷰동산',
content : '이제 앱보다는 PWA가 대세입니다. 뷰를 이용하면 매끈한 앱같은 웹을 만들 수 있습니다.',
date : 'October 20, 2019',
number : 1
},
{
title : '셋 째 프로젝트 : 현피 앱1',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 2
},
{
title : '셋 째 프로젝트 : 현피 앱2',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 3
},
{
title : '셋 째 프로젝트 : 현피 앱3',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 4
},
{
title : '셋 째 프로젝트 : 현피 앱4',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 5
},
{
title : '셋 째 프로젝트 : 현피 앱5',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 6
},
{
title : '셋 째 프로젝트 : 현피 앱6',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 7
},
{
title : '셋 째 프로젝트 : 현피 앱7',
content : '거리를 설정하면 가장 가까운 파이터를 소개해드려요! 서로 싸워보세요',
date : 'September 24, 2019',
number : 8
}
];
| 12f4f14c7c8bc77f6cb7c55581ab7b01eb9ef7f6 | [
"JavaScript"
] | 1 | JavaScript | chrisna2/vuelog | 76b9be6e08615b8460e34359a3b662534adb396b | 85f13579df91adf358b8c9217a3d2be54eef0ae5 |
refs/heads/master | <file_sep>/*I would have implemented more methods, such as "horizontalbar", but the lines for this
ascii art are so random creating new methods would actually increase the work
needed to write the code. Also, in case you are wondering, my two special string characters are the \n
new line as well as the \\ in order to print out a \
*/
public class ASCIIArt {
public static void main (String [] args) {
rasmussen();
is();
our();
god();
}
public static void rasmussen () {
System.out.print(" ___\n");
System.out.print(" | _ \\__ _ ____ __ _ _ ______ ___ _ _ \n");
System.out.print(" | / _` (_-< ' \\ || (_-<_-</ -_) ' \\ \n");
System.out.print(" |_|_\\__,_/__/_|_|_\\_,_/__/__/\\___|_||_|\n");
System.out.println();
}
public static void is () {
System.out.print(" _ _\n");
System.out.print(" |_ _|___\n");
System.out.print(" | |(_-< \n");
System.out.print(" |___/__/\n");
System.out.println();
}
public static void our () {
System.out.print(" ___ \n");
System.out.print(" / _ \\ _ _ _ _ \n");
System.out.print(" | (_) | || | '_|\n");
System.out.print(" \\___/ \\_,_|_| \n");
System.out.println();
}
public static void god () {
System.out.print(" _ _\n");
System.out.print(" / __|___ __| |\n");
System.out.print(" | (_ / _ \\/ _` |\n");
System.out.print(" \\___\\___/\\__,_|\n");
System.out.println();
}
}
| a7e7b14244938f077992b561b429fe72df24ee5c | [
"Java"
] | 1 | Java | NHS-2019-P5-AP-Comp-Sci/asciiart-dankboi69 | e0cef45a14e380618855bf3a1955399074e08072 | fbe59d83702c1a49a4c5f6399a041408600ba3c1 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day21
{
class Grid
{
private char[,] Elements;
public int Dimension => (int)Math.Sqrt(Elements.Length); // we know we are always a perfect square
public int Pixels { get { return this.ToString().Sum(character => (character == '#') ? 1 : 0); } }
protected Grid() { }
protected Grid(char[,] elements) { Elements = elements; }
public Grid(string set)
{
var rows = set.Split('/');
Elements = new char[rows.Length, rows.Length];
for (var rowIdx = 0; rowIdx < rows.Length; rowIdx++)
{
var elements = rows[rowIdx].ToCharArray();
for (var colIdx = 0; colIdx < elements.Length; colIdx++)
Elements[rowIdx, colIdx] = elements[colIdx];
}
}
public override string ToString()
{
var gridString = string.Empty;
for (var rowIdx = 0; rowIdx < Dimension; rowIdx++)
{
if (rowIdx != 0)
gridString += "/"; // add separator
for (var colIdx = 0; colIdx < Dimension; colIdx++)
gridString += Elements[rowIdx, colIdx];
}
return gridString;
}
internal static List<Grid> FromStrings(List<string> rows, int rowIdx, int gridSize)
{
var grids = new List<Grid>();
var colCount = rows.First().Length;
// add a grid for each colCount%gridSize jump
for (var i = 0; i < colCount; i += gridSize)
{
var gridSet = string.Empty;
// loop over the rows
for (var j = 0; j < gridSize; j++)
{
if (j != 0)
gridSet += "/";
// loop over the cols
for (var k = 0; k < gridSize; k++)
{
gridSet += rows[rowIdx * gridSize + j][i + k];
}
}
grids.Add(new Grid(gridSet));
}
return grids;
}
public Grid Expand(List<Rule> rules)
{
//foreach (var conformation in Conformations())
//{
// Console.WriteLine(conformation.ToString());
//}
// Console.ReadLine();
foreach (var conformation in Conformations())
{
foreach (var rule in rules)
{
if (conformation.ToString() == rule.Match)
return new Grid(rule.Conversion);
}
}
throw new Exception("No rules match any conformations for given Grid. Try mod 3 instead.");
}
private IEnumerable<Grid> Conformations()
{
yield return this;
yield return this.Rotate();
yield return this.Rotate().Rotate(); // cascading Rotate() calls is just me being lazy
yield return this.Rotate().Rotate().Rotate();
yield return this.Flip();
yield return this.Flip().Rotate();
yield return this.Flip().Rotate().Rotate();
yield return this.Flip().Rotate().Rotate().Rotate();
}
private Grid Rotate()
{
//return new Grid(Transpose(Elements));
var grid = new char[Dimension, Dimension];
if (Dimension == 2)
{
grid[0, 0] = Elements[1, 0]; grid[0, 1] = Elements[0, 0];
grid[1, 0] = Elements[1, 1]; grid[1, 1] = Elements[0, 1];
}
else
{
grid[0, 0] = Elements[2, 0]; grid[0, 1] = Elements[1, 0]; grid[0, 2] = Elements[0, 0];
grid[1, 0] = Elements[2, 1]; grid[1, 1] = Elements[1, 1]; grid[1, 2] = Elements[0, 1];
grid[2, 0] = Elements[2, 2]; grid[2, 1] = Elements[1, 2]; grid[2, 2] = Elements[0, 2];
}
return new Grid(grid);
}
// so#29483660
public char[,] Transpose(char[,] matrix)
{
var w = matrix.GetLength(0);
var h = matrix.GetLength(1);
var result = new char[h, w];
for (var i = 0; i < w; i++)
{
for (var j = 0; j < h; j++)
{
result[j, i] = matrix[i, j];
}
}
return result;
}
private Grid Flip()
{
var grid = new char[Dimension, Dimension];
if (Dimension == 2)
{
grid[0, 0] = Elements[0, 1];grid[0, 1] = Elements[0, 0];
grid[1, 0] = Elements[1, 1];grid[1, 1] = Elements[1, 0];
}
else
{
grid[0, 0] = Elements[0, 2];grid[0, 1] = Elements[0, 1];grid[0, 2] = Elements[0, 0];
grid[1, 0] = Elements[1, 2];grid[1, 1] = Elements[1, 1];grid[1, 2] = Elements[1, 0];
grid[2, 0] = Elements[2, 2];grid[2, 1] = Elements[2, 1];grid[2, 2] = Elements[2, 0];
}
return new Grid(grid);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day21
{
class Rule
{
public string Match { get; set; }
public string Conversion { get; set; }
internal static Rule Parse(string raw)
{
var regex = Regex.Match(raw, @"(?<match>.+) => (?<conversion>.+)$");
var match = regex.Groups["match"].ToString();
var conversion = regex.Groups["conversion"].ToString();
return new Rule { Match = match, Conversion = conversion };
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day11
{
class Grid
{
public enum Direction
{
N = 0,
NE,
SE,
S,
SW,
NW
}
//private HashSet<Hex> Hexes { get; set; }
private Hex Origin { get; set; }
private Hex Current { get; set; }
public int Furthest { get; set; }
public Grid()
{
// fill with the origin
Origin = new Hex() { Q = 0, R = 0 };
Current = new Hex() { Q = 0, R = 0 };
//Hexes = new HashSet<Hex> { Origin };
Furthest = 0;
}
public void Step(Direction direction)
{
var q = 0;
var r = 0;
switch (direction)
{
case Direction.N:
q = 0;
r = -1;
break;
case Direction.NE:
q = 1;
r = -1;
break;
case Direction.SE:
q = 1;
r = -0;
break;
case Direction.S:
q = 0;
r = 1;
break;
case Direction.SW:
q = -1;
r = 1;
break;
case Direction.NW:
q = -1;
r = 0;
break;
default:
throw new Exception("Unsupported step direction!");
}
/*Current = */Current.Step(q, r);
//Hexes.Add(Current);
var distance = DistanceToOrigin();
if (Furthest < distance)
Furthest = distance;
}
// returns the distance between the origin and the current hex
// axial hex distance is derived from the Manhattan distance on cubes
public int DistanceToOrigin()
{
var a = Origin;
var b = Current;
var distance = (Math.Abs(a.Q - b.Q)
+ Math.Abs(a.Q + a.R - b.Q - b.R)
+ Math.Abs(a.R - b.R)) / 2;
return distance;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day04
{
class Day_04_First
{
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var count1 = lines.Sum(line => IsValidPassphrase1(line) ? 1 : 0);
var count2 = lines.Sum(line => IsValidPassphrase2(line) ? 1 : 0);
Console.Write($"Day 04: Valid passphrases count1: {count1} count2: {count2}");
Console.ReadLine();
}
private static bool IsValidPassphrase1(string line)
{
var wordhash = new HashSet<string>();
var words = line.Split(null);
foreach (var word in words)
{
if (wordhash.Contains(word))
return false;
wordhash.Add(word);
}
return true;
}
private static bool IsValidPassphrase2(string line)
{
var wordhash = new HashSet<string>();
var words = line.Split(null);
foreach (var word in words)
{
var sortedword = SortWord(word);
if (wordhash.Contains(sortedword))
return false;
wordhash.Add(sortedword);
}
return true;
}
private static string SortWord(string word)
{
char[] chars = word.ToCharArray();
Array.Sort(chars);
var sortedWord = new string(chars);
return sortedWord;
}
}
}
<file_sep>using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace aoc_2017.Day16
{
public class Move
{
public enum DanceStyle
{
Spin = 0,
Xchange,
Partner
}
private string _step;
public DanceStyle Style { get; set; }
public object Index1 { get; set; }
public object Index2 { get; set; }
public Move(string step)
{
this._step = step;
Parse();
}
// i'm sure there's a more elegant and clever way of parsing the input but this is a race to get done
private void Parse()
{
// ex's: s1,x3/4,pe/b
// x11/4,pd/h,x10/5,s3,x0/7,pp/n,..
var moves = _step.Substring(1, _step.Length - 1);
switch (_step.First())
{
case 's':
Style = DanceStyle.Spin;
Index1 = int.Parse(moves);
Index2 = -1;
break;
case 'x':
Style = DanceStyle.Xchange;
var indices= moves.Split('/');
Index1 = int.Parse(indices[0]);
Index2 = int.Parse(indices[1]);
break;
case 'p':
// Index1/2 are "objects" but should be int's and do index conversion here?
Style = DanceStyle.Partner;
var partners= moves.Split('/');
Index1 = partners[0].ToCharArray()[0];
Index2 = partners[1].ToCharArray()[0];
break;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day06
{
public class Day_06
{
public static void Do(string srcFile)
{
// create the blocks
var input = System.IO.File.ReadAllLines(srcFile);
var blocks = new Blocks(input[0]);
var numCycles = 0;
do
{
numCycles++;
var idx = blocks.FindLargestBlockIndex();
blocks.RedistributeBlocks(idx);
} while (blocks.HasNotBeenSeenBefore(numCycles));
Console.Write($"Day 06: Starting Blocks: {blocks.Count} Cycles: {numCycles} Loop: {numCycles - blocks.CycleIdx}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day07
{
public class TreeNode
{
public string Name { get; set; }
public int Weight { get; set; }
public int Sum { get; set; }
public TreeNode Parent { get; set; }
public List<TreeNode> Children { get; set; }
private TreeNode()
{
}
public TreeNode(string line)
{
Children = new List<TreeNode>();
try
{
//string sample = @"navfz (187) -> jviwcde, wfwor, vpfabxa";
var match = Regex.Match(line, @"(?<name>.*) \((?<weight>.*)\) -> (?<children>.*$)");
if (match.Groups["children"].Length == 0)
match = Regex.Match(line, @"(?<name>.*) \((?<weight>.*)\)$");
else
IncludeChildren(match.Groups["children"].ToString());
Name = match.Groups["name"].ToString();
Weight = int.Parse(match.Groups["weight"].ToString());
Sum = 0;
}
catch (Exception /*ex*/)
{
//Add appropriate error handling here
throw;
}
}
private void IncludeChildren(string children)
{
var childNames = children.Split(',');
foreach (var childName in childNames)
Children.Add(new TreeNode { Name = childName.Trim() });
}
public void PopulateChildren(Dictionary<string, TreeNode> allNodes)
{
var numChildren = Children.Count;
for (var i = 0; i < numChildren; i++)
{
Children[i] = allNodes[Children[i].Name]; // yes, we are assuming the node always will be found
Children[i].Parent = this;
}
}
public TreeNode FindRoot()
{
while (Parent != null)
return Parent.FindRoot();
return this;
}
public TreeNode FindUnbalancedNode(Dictionary<string, TreeNode> allNodes)
{
foreach (var tvalue in allNodes)
{
var node = tvalue.Value;
if (node.Children.Count > 0)
{
var sum = node.Children.Sum(child => child.Sum);
if (sum/node.Children.Count != node.Children.First().Sum)
return node;
}
}
return null;
}
// note: this is a quick hack for this competition. not production quality.
public int DetermineCorrectedWeight(TreeNode badNode)
{
// we know there have to be at least 3 to cause an imbalance that is _locally_ correctable
TreeNode node0 = badNode.Children[0];
TreeNode node1 = null;
// find the two different values
for (var i = 2; i < badNode.Children.Count; i++)
{
if (badNode.Children[i].Sum != node0.Sum)
{
node1 = badNode.Children[i];
break;
}
}
// then count instances of each
var count1 = 0; var count2 = 0;
foreach (var child in badNode.Children)
{
if (child.Sum == node0.Sum)
count1++;
if (child.Sum == node1.Sum)
count2++;
}
// we're making lots of assumptions about the quality of the data here
if (count1 > count2)
return node1.Weight - Math.Abs(node0.Sum - node1.Sum);
else
return node0.Weight - Math.Abs(node0.Sum - node1.Sum);
}
internal int CalculateSum()
{
Sum = Weight;
foreach (var child in Children)
Sum += child.CalculateSum();
return Sum;
}
/*
// use Compare rather than overload ==, !=, and Equals operators and GetHashCode()
private bool Compares(TreeNode node)
{
return Name == node.Name;
}
internal void AddNode(TreeNode treeNode)
{
var node = FindDescendantNode(treeNode);
if (node == null)
{
// then the root node MUST be a child node of the treeNode
node = FindChildNode(treeNode);
}
}
// performs a depth-first search
private TreeNode FindDescendantNode(TreeNode treeNode)
{
foreach (var child in Children)
{
if (child.Compares(treeNode))
return child;
return FindDescendantNode(child);
}
return null;
}
private TreeNode FindChildNode(TreeNode treeNode)
{
return Children.FirstOrDefault(Compares);
}
*/
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day25
{
public class State
{
#region props, fields, consts, and ctors
public MoveWrite Zero { get; set; }
public MoveWrite One { get; set; }
private State(MoveWrite zeroVal, MoveWrite oneVal)
{
Zero = zeroVal;
One = oneVal;
}
public static State Parse(string[] blueprint)
{
if (blueprint[0].Trim() != "If the current value is 0:")
throw new Exception("Invalid definition for value 0.");
var regex = Regex.Match(blueprint[1].Trim(), @"- Write the value (?<zeroSet>.+).$");
var zeroSet = int.Parse(regex.Groups["zeroSet"].ToString());
regex = Regex.Match(blueprint[2].Trim(), @"- Move one slot to the (?<zeroDir>.+).$");
var zeroDir = (MoveWrite.TapeDirection)Enum.Parse(typeof(MoveWrite.TapeDirection), regex.Groups["zeroDir"].ToString());
regex = Regex.Match(blueprint[3].Trim(), @"- Continue with state (?<zeroNext>.+).$");
var zeroNext = regex.Groups["zeroNext"].ToString();
var zero = new MoveWrite(zeroSet, zeroDir, zeroNext);
if (blueprint[4].Trim() != "If the current value is 1:")
throw new Exception("Invalid definition for value 1.");
regex = Regex.Match(blueprint[5].Trim(), @"- Write the value (?<oneSet>.+).$");
var oneSet = int.Parse(regex.Groups["oneSet"].ToString());
regex = Regex.Match(blueprint[6].Trim(), @"- Move one slot to the (?<oneDir>.+).$");
var oneDir = (MoveWrite.TapeDirection)Enum.Parse(typeof(MoveWrite.TapeDirection), regex.Groups["oneDir"].ToString());
regex = Regex.Match(blueprint[7].Trim(), @"- Continue with state (?<oneNext>.+).$");
var oneNext = regex.Groups["oneNext"].ToString();
var one = new MoveWrite(oneSet, oneDir, oneNext);
return new State(zero, one);
}
#endregion props, fields, consts, and ctors
public class MoveWrite
{
public enum TapeDirection
{
left = 0,
right
}
public MoveWrite(int write, TapeDirection move, string next)
{
WriteValue = write;
MoveDirection = move;
NextState = next;
}
public int WriteValue { get; set; }
public TapeDirection MoveDirection { get; set; }
public string NextState { get; set; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day17
{
class SpinLock
{
private LinkedListNode<int> CurrentNode { get; set; }
public LinkedList<int> List { get; set; }
//int NumSteps = 3; // test
int NumSteps = 337; // actual
// returns the value immediately _after_ the current position
public int After => Next().Value;
public int AfterFirst => List.First.Next.Value;
public SpinLock()
{
List = new LinkedList<int>();
CurrentNode = List.AddFirst(0);
}
internal void Insert(int i)
{
CurrentNode = Advance().AddAfter(CurrentNode, i);
}
internal LinkedList<int> Advance()
{
for (var j = 0; j < NumSteps; j++)
CurrentNode = Next();
return List;
}
private LinkedListNode<int> Next()
{
return CurrentNode == List.Last ? List.First : CurrentNode.Next;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day19
{
class RoutingDiagram
{
#region fields, constants, properties, and ctors
public string[] Paths { get; set; } // each entry is another row/Y-coordinate
private int X { get; set; } // offset into the x direction
private int Y { get; set; } // offset into the y direction
private int Width { get; set; }
private const char DeadEnd = ' ';
private StringBuilder _letters;
public string Letters => _letters.ToString();
public int Steps { get; set; }
private Direction Compass { get; set; }
private enum Direction
{
Up = 0,
Right,
Down,
Left
}
private bool InBounds => (X >= 0) && (X < Width) && (Y >= 0) && (Y < Paths.Length);
public RoutingDiagram()
{
X = Y = 0;
}
#endregion fields, constants, properties, and ctors
public bool TracePath()
{
InitializeDiagramStart();
do
{
if (Next() == DeadEnd)
return false;
} while (InBounds);
return true;
}
private void InitializeDiagramStart()
{
var x = 0;
var firstRow = Paths[0];
for (x = 0; x < firstRow.Length; x++)
{
if (firstRow[x] == '|')
break;
}
X = x;
Y = 0;
Width = firstRow.Length;
Compass = Direction.Down;
_letters = new StringBuilder();
Steps = 0;
}
private char Next()
{
var next = DeadEnd;
// adjust your X & Y coordinates
switch (Compass)
{
case Direction.Up:
next = Paths[--Y][X];
break;
case Direction.Right:
next = Paths[Y][++X];
break;
case Direction.Down:
next = Paths[++Y][X];
break;
case Direction.Left:
next = Paths[Y][--X];
break;
}
switch (next)
{
case '|':
case '-':
break;
case '+':
if (Compass == Direction.Up || Compass == Direction.Down)
{
Compass = Paths[Y][X - 1] == DeadEnd ? Direction.Right : Direction.Left;
}
else if (Compass == Direction.Left || Compass == Direction.Right)
{
Compass = Paths[Y - 1][X] == DeadEnd ? Direction.Down : Direction.Up;
}
break;
case ' ': // do nothing. the handler will decide.
break;
default: // must be a letter
_letters.Append(next);
break;
}
Steps++;
return next;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day13
{
static class ExtensionMethods
{
// from SO#538729
// this method is faster because it only does one look-up
// rather than two like this method
// return (dictionary.ContainsKey(key)) ? dictionary[key] : default(TValue);
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue ret;
// Ignore return value
dictionary.TryGetValue(key, out ret);
return ret;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day07
{
public class Day_07
{
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var allNodes = lines.Select(line => new TreeNode(line)).ToDictionary(node => node.Name);
foreach (var node in allNodes)
node.Value.PopulateChildren(allNodes);
var treeRoot = allNodes.First().Value.FindRoot();
var rootSum = treeRoot.CalculateSum();
var badNode = treeRoot.FindUnbalancedNode(allNodes);
var correctedWeight = treeRoot.DetermineCorrectedWeight(badNode);
Console.Write($"Day 07: TreeRoot Name: {treeRoot.Name} Unbalanced Node: {badNode.Name} CorrectedWeight: {correctedWeight}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day10
{
public class Day_10_2
{
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var bytes = Encoding.ASCII.GetBytes(lines[0]).ToList();
var stdSuffix = new byte[] { 17, 31, 73, 47, 23 };
bytes.AddRange(stdSuffix);
var lengths = bytes.Select(bit => (int)bit).ToList();
var NumRounds = 64;
var knot = new Knot(256);
for (int i = 0; i < NumRounds; i++)
{
foreach (var length in lengths)
knot.Hash(length);
}
Console.Write($"Day 10.2: DenseHash: {knot.DenseHash()}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day22
{
class Day_22
{
public static void Do(string srcFile)
{
Do_1(srcFile);
Do_2(srcFile);
Console.ReadLine();
}
public static void Do_1(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var map = new Map(lines);
for (var i = 0; i < 10000; i++)
map.Burst();
Console.WriteLine($"Day 22.1: Number of infections from bursts: { map.Infections }");
}
public static void Do_2(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var map = new EvolvedMap(lines);
for (var i = 0; i < 10000000; i++)
map.Burst();
Console.WriteLine($"Day 22.2: Number of infections from evolved bursts: { map.Infections }");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day02
{
class Day_02_First
{
public static void Do(string srcFile)
{
StreamReader sr = null;
var vals = new List<int>();
var idx = 0;
try
{
sr = File.OpenText(srcFile);
string line = null;
while ((line = sr.ReadLine()) != null)
{
idx++;
vals.Add(GetEvenlyDivisibleRange(line));
//vals.Add(GetLargestRange(line));
}
}
catch (IOException ex)
{
var msg = ex.Message;
// handle please
}
finally
{
// clean up
sr?.Close();
}
Console.Write($"Day 02: Lines: {idx} Checksum: {vals.Aggregate((a, b) => b + a)}");
Console.ReadLine();
}
private static int GetEvenlyDivisibleRange(string line)
{
var nums = line.Split().Select(int.Parse).ToArray();
var numsCount = nums.Length;
for (int i = 0; i < numsCount; i++)
{
for (int j = i + 1; j < numsCount; j++)
{
var lower = (nums[i] < nums[j]) ? i : j;
var hiyer = (nums[i] > nums[j]) ? i : j;
var mod = nums[hiyer] % nums[lower];
if (mod == 0)
{
//Console.WriteLine($"{nums[hiyer]} % {nums[lower]} => {nums[hiyer] / nums[lower]}");
return nums[hiyer] / nums[lower];
}
}
}
return 0;
}
private static int GetLargestRange(string line)
{
var low = 9999;
var high = -1;
var nums = line.Split().Select(int.Parse);
foreach (var num in nums)
{
if (num < low) low = num;
if (num > high) high = num;
}
Console.WriteLine($"{high} - {low} = {high - low}");
return high - low;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day08
{
public class Instruction
{
public string RegisterName { get; set; }
public bool IncDec { get; set; }
public int Increment { get; set; }
public Condition Condition { get; set; }
public Instruction(string line)
{
//string sample = @"ytr dec -258 if xzn < 9";
var match = Regex.Match(line, @"(?<register>.*) (?<incdec>.*) (?<increment>.*) if (?<condition>.*$)");
RegisterName = match.Groups["register"].ToString();
IncDec = match.Groups["incdec"].ToString() == "inc";
Increment = int.Parse(match.Groups["increment"].ToString());
Condition = new Condition(match.Groups["condition"].ToString());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using aoc_2017.Day08;
namespace aoc_2017.Day12
{
class GraphNode
{
public int Index { get; set; }
public List<GraphNode> Nodes { get; set; }
public List<int> Paths { get; set; }
public bool Visited { get; set; }
public GraphNode()
{
Index = 0;
Nodes = new List<GraphNode>();
Paths = new List<int>();
Visited = false;
}
// use a little recursion to traverse the nodes...marking them as "visited"
public static int VisitConnectedNodes(GraphNode graphNode)
{
if (graphNode.Visited)
return 0;
graphNode.Visited = true;
return graphNode.Nodes.Sum(VisitConnectedNodes) + 1; // add 1 for this node
}
public static GraphNode Parse(string pipe)
{
// ex: "2 <-> 0, 3, 4"
var match = Regex.Match(pipe, @"(?<index>.*) <-> (?<paths>.*$)");
var index = int.Parse(match.Groups["index"].ToString());
var paths = match.Groups["paths"].ToString().Split(',').Select(int.Parse).ToList();
return new GraphNode() { Index = index, Paths = paths };
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day09
{
public class Day_09
{
public static void Do(string srcFile)
{
StreamReader sr = null;
var stack = new Stack<char>();
const int blockSize = 100;
var numGroups = 0;
var totalScore = 0;
var garbageCount = 0;
var skip1 = false;
var skip = false;
var nests = 0; // i could use the stack depth if i wasn't also putting the '<' on the stack
try
{
sr = File.OpenText(srcFile);
var blockCount = 0;
var buffer = new char[blockSize];
while (((blockCount = sr.ReadBlock(buffer, 0, blockSize)) > 0))
{
for (var i = 0; i < blockSize; i++)
{
if (buffer[i] == '\0')
break;
if (skip1)
{
skip1 = false;
continue;
}
if (buffer[i] == '!')
{
skip1 = true;
continue;
}
if (buffer[i] == '>')
{
if (stack.Peek() == '<')
{
stack.Pop();
skip = false;
continue;
}
}
if (skip)
{
garbageCount++;
continue;
}
if (buffer[i] == '<')
{
skip = true;
stack.Push(buffer[i]);
continue;
}
if (buffer[i] == '{')
{
nests++;
stack.Push(buffer[i]);
continue;
}
if (buffer[i] == '}')
{
if (stack.Peek() == '{')
{
stack.Pop();
numGroups++;
totalScore += nests;
nests--;
continue;
}
}
}
if (blockCount < blockSize) // this does not work when the file size is evenly divisible by the blockSize number but while-loop above should detect it and then exit
break;
Array.Clear(buffer, 0, blockSize);
}
}
catch (IOException ex)
{
var msg = ex.Message;
}
finally
{
sr?.Close();
}
Console.Write($"Day 09: numGroups: {numGroups} Total Score: {totalScore} Amount of Garbage: {garbageCount}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day10
{
public class Knot
{
public int Count { get; set; }
private int Index { get; set; }
private int SkipSize { get; set; }
public int Product => SparseHash[0] * SparseHash[1];
public List<int> SparseHash { get; set; }
public Knot(int count)
{
Count = count;
Index = 0;
SkipSize = 0;
SparseHash = Enumerable.Range(0, Count).ToList();
}
public void Hash(int length)
{
Reverse(length);
Index = (Index + length + SkipSize++) % Count;
}
private void Reverse(int length)
{
// we do for-loops that use modulus to handle the circular-ness of the list
// copy to a separate list..
var r = Enumerable.Range(0, length).ToList();
for (var i = 0; i < length; i++)
r[i] = SparseHash[(Index + i) % Count];
// ..so that we may leverage the built-in "Reverse()" method
r.Reverse();
// ..then copy the results back to mommy
for (var i = 0; i < length; i++)
SparseHash[(Index + i) % Count] = r[i];
}
public string DenseHash()
{
var loose = new byte[16];
var result = new byte[16];
var idense = new List<int>(16);
// run through all 16 blocks of 16 numbers and condense each block
for (var block = 0; block < 16; block++)
{
// grab the next chunk of 16 bytes
for (var i = 0; i < 16; i++)
loose[i] = Convert.ToByte((char)SparseHash[block * 16 + i]); // init "loose"
// condense those bytes down to one byte
byte bite = loose[0];
for (var j = 1; j < 16; j++)
bite ^= loose[j]; // xor
// add that byte to the final hash
result[block] = bite;
}
for (var j = 0; j < 16; j++)
idense.Add(Convert.ToInt32(result[j]));
var dense = new StringBuilder(32);
foreach (var d in idense)
dense.Append(d.ToString("x2"));
return dense.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day05
{
class Day_05_First
{
public static void Do(string srcFile)
{
var input = System.IO.File.ReadAllLines(srcFile);
var offsets = input.Select(int.Parse).ToList();
var steps = FindTheExit1(offsets);
//var steps = FindTheExit2(offsets);
Console.Write($"Day 05: Offsets: {offsets.Count} Steps to exit: {steps}");
Console.ReadLine();
}
private static int FindTheExit2(List<int> offsets)
{
var steps = 0;
var idx = 0;
var numOffsets = offsets.Count;
do
{
var tmp = idx;
idx += offsets[tmp];
offsets[tmp] += (offsets[tmp] >= 3) ? -1 : 1;
steps++;
} while (idx < numOffsets);
return steps;
}
private static int FindTheExit1(List<int> offsets)
{
var steps = 0;
var idx = 0;
var numOffsets = offsets.Count;
do
{
var tmp = idx;
idx += offsets[tmp]++;
steps++;
} while (idx < numOffsets);
return steps;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day22
{
class Cursor
{
public enum Direction
{
Up = 0,
Right,
Down,
Left
}
public enum Doble // spanish for "turn"
{
Left = 0,
Forward,
Right,
Reverse
}
public Direction Compass { get; set; }
public Tuple<int, int> Coordinates { get; set; }
protected Cursor()
{
Compass = Direction.Up;
}
public Cursor(int origin) : this()
{
Coordinates = new Tuple<int, int>(origin, origin);
}
public void Turn(Doble doble)
{
var numEnums = System.Enum.GetNames(typeof (Direction)).Length;
switch (doble)
{
case Doble.Left:
Compass = (Direction)(((int)Compass + numEnums - 1) % numEnums);
break;
case Doble.Forward:
break;
case Doble.Right:
Compass = (Direction)(((int)Compass + 1) % numEnums);
break;
case Doble.Reverse:
Compass = (Direction)(((int)Compass + numEnums/2) % numEnums); // assumes even number of enum elements
break;
default:
throw new Exception("A Turn for the worse!");
}
}
public void Move()
{
switch (Compass)
{
case Direction.Up:
Coordinates = new Tuple<int, int>(Coordinates.Item1, Coordinates.Item2 - 1);
break;
case Direction.Right:
Coordinates = new Tuple<int, int>(Coordinates.Item1 + 1, Coordinates.Item2);
break;
case Direction.Down:
Coordinates = new Tuple<int, int>(Coordinates.Item1, Coordinates.Item2 + 1);
break;
case Direction.Left:
Coordinates = new Tuple<int, int>(Coordinates.Item1 - 1, Coordinates.Item2);
break;
default:
throw new Exception("Bad move!");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace aoc_2017.Day16
{
internal class Dancers
{
private string OriginalLineUp = "abcdefghijklmnop";
private char[] ChorusLine = null;
public string CurrentLineUp
{
get
{
var line = new StringBuilder();
for (var i = 0; i < ChorusLine.Length; i++)
line.Append(ChorusLine[Idx(i)]);
return line.ToString();
}
}
private int FirstDancer { get; set; }
public Dancers()
{
// initialize the chorus line (a..p)
ChorusLine = OriginalLineUp.ToCharArray();
FirstDancer = 0;
}
internal void Step(Move movement)
{
switch (movement.Style)
{
case Move.DanceStyle.Spin:
Spin((int)movement.Index1);
break;
case Move.DanceStyle.Xchange:
Exchange((int)movement.Index1, (int)movement.Index2);
break;
case Move.DanceStyle.Partner:
movement.Index1 = ConvertPartnerToIndex((char)movement.Index1);
movement.Index2 = ConvertPartnerToIndex((char)movement.Index2);
Exchange((int)movement.Index1, (int)movement.Index2);
break;
}
}
private int ConvertPartnerToIndex(char partner)
{
var lineup = CurrentLineUp;
for (var i = 0; i < ChorusLine.Length; i++)
{
if (lineup[i] == partner)
return i;
}
return -1;
}
// what's the best way to do this?
// 1. use an index rather than actually move the characters?
private void Spin(int partner1)
{
FirstDancer = Idx(ChorusLine.Length - partner1);
}
private void Exchange(int index1, int index2)
{
char temp = ChorusLine[Idx(index1)];
ChorusLine[Idx(index1)] = ChorusLine[Idx(index2)];
ChorusLine[Idx(index2)] = temp;
}
// since the Chorus Line does not truly "spin" we need to offset the index
private int Idx(int partner)
{
return (FirstDancer + partner) % OriginalLineUp.Length;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day14
{
class Disk
{
public const int Size = 128;
public List<string> HexGridRows { get; set; }
public List<string> BitGridRows { get; set; }
public Disk()
{
HexGridRows = new List<string>(Size);
BitGridRows = new List<string>(Size);
}
public int UsedSquares()
{
var count = 0;
// convert strings to bytes then search the stream of 1s and 0s to count the number of 1s
foreach (var row in HexGridRows)
{
var bites = HexStringToByteArray(row);
count += bites.Sum(bite => SparseBitcount(int.Parse(bite.ToString())));
}
return count;
}
public int Groups()
{
var groups = 0;
// convert strings of hexes to strings of bits (why not int arrays?)
// TODO: move to ctor
foreach (var row in HexGridRows)
BitGridRows.Add(HexStringToByteStringArray(row));
// initialize the grid of visited sectors
var visited = new bool[Size, Size]; // TODO: use a HashSet of tuple strings instead!?
for (var i = 0; i < Size; i++)
{
for (var j = 0; j < Size; j++)
{
visited[i, j] = false;
}
}
// now traverse all the sectors looking for groups and marking them as visited
for (var i = 0; i < Size; i++)
{
for (var j = 0; j < Size; j++)
{
if (!visited[i, j])
{
if (Visit(i, j, visited))
groups++;
}
}
}
return groups;
}
// recursive call to visit all connected sectors, like a Flood Fill algorithm
private bool Visit(int i, int j, bool[,] visited)
{
if (visited[i, j] || IsZero(i, j))
return false;
visited[i, j] = true;
// continue marking any contiguous sectors
try
{
if (i > 0)
Visit(i - 1, j, visited);
if (i < Size - 1)
Visit(i + 1, j, visited);
if (j > 0)
Visit(i, j - 1, visited);
if (j < Size - 1)
Visit(i, j + 1, visited);
}
catch (Exception ex)
{
var msg = ex.Message;
throw;
}
return true;
}
private bool IsZero(int x, int y)
{
var row = BitGridRows[x];
return row[y] == '0';
}
// so#321370
private byte[] HexStringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
// https://www.dotnetperls.com/bitcount
int SparseBitcount(int n)
{
int count = 0;
while (n != 0)
{
count++;
n &= (n - 1);
}
return count;
}
public string HexStringToByteStringArray(string hex)
{
var hexes =
(from Match m in Regex.Matches(hex, "..")
select m.Value).ToArray();
var hexbites = hexes.Select(x => Convert.ToString(Convert.ToInt32(x, 16), 2).PadLeft(8, '0')); // convert base-16 to base-2
var bitestring = string.Join(string.Empty, hexbites);
return bitestring;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day13
{
class Layer
{
public int Depth { get; set; }
public int Range { get; set; }
public int Scanner { get; set; }
private bool Up { get; set; }
public Layer()
{
Up = false;
}
public void Advance()
{
if (!Up && (Scanner + 1) == Range)
Up = true;
else if (Up && (Scanner == 0))
Up = false;
if (Up) // decrement
Scanner--;
else // increment
Scanner++;
}
public bool Caught()
{
return Scanner == 0;
}
public void Reset()
{
Scanner = 0;
Up = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day08
{
public class Condition
{
public string Raw { get; set; }
public string Left { get; set; }
public string Operation { get; set; }
public string Right { get; set; }
public Condition(string raw)
{
Raw = raw;
Parse();
}
private void Parse()
{
//string sample = @"xzn < 9";
var match = Regex.Match(Raw, @"(?<left>.*) (?<operation>.*) (?<right>.*$)");
Left = match.Groups["left"].ToString();
Operation = match.Groups["operation"].ToString();
Right = match.Groups["right"].ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day18
{
class Day_18
{
public static void Do(string srcFile)
{
Do_1(srcFile);
//Do_2(srcFile);
Console.ReadLine();
}
public static void Do_1(string srcFile)
{
var instructions = System.IO.File.ReadAllLines(srcFile);
var vcard = new VirtualSoundCard();
var idx = 0L;
do
{
idx += vcard.Invoke(instructions[idx]);
} while (idx >= 0 && idx < instructions.Length);
Console.WriteLine($"Day 18.1: Value of the recovered frequency: { vcard.LastFrequency }");
}
public static void Do_2(string srcFile)
{
var instructions = System.IO.File.ReadAllLines(srcFile);
var duet1 = new Bubbler();
duet1.Registers["p"] = 0;
var duet2 = new Bubbler { Partner = duet1 };
duet2.Registers["p"] = 1;
duet1.Partner = duet2;
var task1 = new Task<long>(() => duet1.Process(instructions));
var task2 = new Task<long>(() => duet2.Process(instructions));
// start the race
task1.Start();
task2.Start();
Task.WaitAll(task1, task2);
Console.WriteLine($"Day 18.2: Number of times value sent to l: { duet2.SendCount }");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day15
{
class Day_15
{
const long f_a = 16807; // factor A
const long f_b = 48271; // factor B
const long MersennePrime = 2147483647; // modulus value - is a Mersenne Prime (2^31 - 1)
const long Mask = 0xffff;
public static void Do()
{
Do_1();
Do_2();
Console.ReadLine();
}
public static void Do_1()
{
const long Iterations = 40000000; // 40 million iterations
long g_a = 634; // generator A with starting value (65 test, 634 actual)
long g_b = 301; // generator B with starting value (8921 test, 301 actual)
var count = 0;
for (long i = 0; i < Iterations; i++)
{
g_a = (g_a * f_a) % MersennePrime;
g_b = (g_b * f_b) % MersennePrime;
if ((g_a & Mask) == (g_b & Mask))
count++;
}
Console.WriteLine($"Judges Final Count 1: { count }");
}
public static void Do_2()
{
const long Iterations = 5000000; // 5 million iterations
long g_a = 634; // generator A with starting value (65 test, 634 actual)
long g_b = 301; // generator B with starting value (8921 test, 301 actual)
Queue<long> q_a = new Queue<long>();
Queue<long> q_b = new Queue<long>();
// only add them to the queue's if they div evenly
do
{
g_a = (g_a*f_a)%MersennePrime;
if (g_a%4 == 0)
q_a.Enqueue(g_a);
} while (q_a.Count < Iterations);
do
{
g_b = (g_b*f_b)%MersennePrime;
if (g_b%8 == 0)
q_b.Enqueue(g_b);
} while (q_b.Count < Iterations);
var count = 0;
// now compare the values in the queues
do
{
if ((q_a.Dequeue() & Mask) == (q_b.Dequeue() & Mask))
count++;
} while (q_a.Any() && q_b.Any());
Console.WriteLine($"Judges Final Count 2: { count }");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day13
{
class Day_13
{
public static void Do(string srcFile)
{
// warning: doing this using my "simulation" implementation will take forever since the answer is 3946838
// the best answer is to follow the Chinese Remainder Theorem
var layers = System.IO.File.ReadAllLines(srcFile);
var firewall = new Firewall(layers);
Console.Write($"Day 13: Trip Severity on first step: 1728 Safest Pause: {firewall.FindSafestPause()}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day23
{
class Tablet
{
private const long DefaultReturnValue = 1;
public Dictionary<string, long> Registers { get; set; }
public long LastFrequency = -1;
public long MulCount { get; set; }
public Tablet()
{
Registers = new Dictionary<string, long>();
MulCount = 0;
}
public Tablet(string seedRegister, int seedValue): this()
{
Registers.Add(seedRegister, seedValue);
}
public long Invoke(string rawInstruction)
{
var match = Regex.Match(rawInstruction, @"(?<instruction>.*) (?<register1>.*) (?<register2>.*$)");
if (string.IsNullOrEmpty(match.Groups["register2"].ToString())) // quick hack to deal with cases where there is only one register
match = Regex.Match(rawInstruction, @"(?<instruction>.*) (?<register1>.*$)");
var instruction = match.Groups["instruction"].ToString();
var register1 = match.Groups["register1"].ToString();
var register2 = match.Groups["register2"].ToString();
switch (instruction)
{
case "set":
return doSet(register1, register2);
case "sub":
return doSub(register1, register2);
case "mul":
return doMul(register1, register2);
case "jnz":
return doJnz(register1, register2);
default:
throw new ArgumentNullException("Invalid instruction received!");
}
}
private long doSet(string register1, string register2)
{
var value = GetRegisterOrValue(register2);
Registers[register1] = value;
return DefaultReturnValue;
}
private long doSub(string register1, string register2)
{
Registers[register1] -= GetRegisterOrValue(register2);
return DefaultReturnValue;
}
private long doMul(string register1, string register2)
{
MulCount++;
if (!Registers.ContainsKey(register1))
Registers.Add(register1, 0L);
Registers[register1] *= GetRegisterOrValue(register2);
return DefaultReturnValue;
}
private long doJnz(string register1, string register2)
{
var value1 = GetRegisterOrValue(register1);
var value2 = GetRegisterOrValue(register2);
return value1 != 0 ? value2 : DefaultReturnValue;
}
private long GetRegisterOrValue(string register)
{
var value = 0L;
if (!long.TryParse(register, out value)) // test for number or register name
{
if (!Registers.ContainsKey(register))
Registers.Add(register, 0);
value = Registers[register];
}
return value;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day06
{
public class Blocks
{
private List<int> _blocks = new List<int>();
private HashSet<string> _seen = new HashSet<string>();
private Dictionary<int, string> _indices = new Dictionary<int, string>();
public int Count => _blocks.Count;
public int CycleIdx { get; set; }
public Blocks(string input)
{
_blocks = input.Split('\t').Select(int.Parse).ToList();
}
public void RedistributeBlocks(int idx)
{
var ctr = _blocks[idx];
_blocks[idx] = 0;
for (int i = 0; i < ctr; i++)
_blocks[(i + 1 + idx) % Count]++;
}
public int FindLargestBlockIndex()
{
var idx = 0;
var largest = 0;
for (int i = 0; i < Count; i++)
{
if (_blocks[i] > largest)
{
largest = _blocks[i];
idx = i;
}
}
return idx;
}
public bool HasNotBeenSeenBefore(int cycle)
{
var config = string.Join(" ", _blocks.Select(i => i.ToString()).ToArray());
var seen = _seen.Add(config);
if (seen)
_indices.Add(cycle, config);
else
CycleIdx = _indices.FirstOrDefault( x => x.Value == config).Key;
return seen;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day14
{
class Day_14
{
public static void Do()
{
//var input = "flqrgnkx"; // test input
var input = "wenycdww"; // puzzle input
var disk = new Disk();
for (int i = 0; i < Disk.Size; i++)
{
var knot = new Knot(256, $"{input}-{i}");
var dense = knot.Hash();
disk.HexGridRows.Add(dense); // TODO: move to Disk class ctor
}
var numUsedSquares = disk.UsedSquares();
var groups = disk.Groups();
Console.Write($"Day 14: Squares used: { numUsedSquares }, Number of groups: { groups }");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day25
{
// I know this is probably not the best use of IEnumerator
// but I am programming this for fun and it's Christmas Day.
// Besides, it does a great job of hiding implementation details!
class Turing : IEnumerator<int>
{
#region props, fields, consts, and ctors
private Dictionary<string, State> States;
private HashSet<int> Tape;
public int Checksum => Tape.Count;
private const int NumLinesPerState = 10;
public Turing(string startState, string[] raw)
{
InitializeStates(raw);
InitializeTape(startState); // must come after init-states
}
private void InitializeStates(string[] raw)
{
States = new Dictionary<string, State>(raw.Length);
for (var i = 2; i < raw.Length; i += NumLinesPerState) // a new state is defined every 10 lines starting at line 2
{
var regex = Regex.Match(raw[i + 1], @"In state (?<stateName>.+):$");
var stateName = regex.Groups["stateName"].ToString();
var rawBlueprint = raw.SubArray(i + 2, 8);
States.Add(stateName, State.Parse(rawBlueprint));
}
}
private void InitializeTape(string startState)
{
Tape = new HashSet<int>();
_index = 0;
CurrentState = States[startState];
}
#endregion props, fields, consts, and ctors
#region IEnumerator<int>
private int _index;
private State CurrentState { get; set; }
public int Current => Tape.Contains(_index) ? 1 : 0; // IEnumerator forces this to be an int instead of a bool
private bool CurrentTest => Current == 1;
object IEnumerator.Current
{
get
{
throw new NotImplementedException();
}
}
public bool MoveNext()
{
// I could have used linq to put this whole method into one line but that would have been unreadable
var mover = CurrentTest ? CurrentState.One : CurrentState.Zero;
if (mover.WriteValue == 1)
{
if (!CurrentTest)
Tape.Add(_index);
}
else
{
if (CurrentTest)
Tape.Remove(_index);
}
_index += mover.MoveDirection == State.MoveWrite.TapeDirection.left ? -1 : 1;
CurrentState = States[mover.NextState];
return true;
}
public void Reset()
{
_index = 0;
}
public void Dispose()
{
;
}
#endregion IEnumerator<int>
}
}
<file_sep># AdventOfCode_2017
http://adventofcode.com/2017/
These are my answers for the daily code challenge on the AdventOfCode web site for 2017.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day13
{
class Firewall
{
private Dictionary<int, Layer> Layers { get; set; }
public int TopLayer { get; set; }
public Firewall()
{
Layers = new Dictionary<int, Layer>();
TopLayer = 0;
}
public Firewall(string[] layers) : this()
{
var numLayers = layers.Length;
Layers = new Dictionary<int, Layer>(numLayers);
for (int i = 0; i < numLayers; i++)
{
// ex: "1: 2"
var match = Regex.Match(layers[i], @"(?<depth>.*): (?<range>.*$)");
var depth = int.Parse(match.Groups["depth"].ToString());
var range = int.Parse(match.Groups["range"].ToString());
Layers.Add(depth, new Layer() { Depth = depth, Range = range, Scanner = 0 });
TopLayer = TopLayer < depth ? depth : TopLayer;
}
}
// advance the scanners in all known layers by one picosecond
internal void TicToc()
{
foreach (var layer in Layers)
layer.Value.Advance();
}
public int Go()
{
var severity = 0;
var packet = new Packet();
var outerCaught = false;
// walk through each layer...one per picosecond
for (var i = 0; i <= TopLayer; i++)
{
var innerCaught = false;
severity += packet.Next(i, Layers.GetValueOrDefault(i), out innerCaught); // first the packet moves
outerCaught |= innerCaught;
TicToc(); // then the clock ticks and all layers advance
}
return severity + (outerCaught ? 1 : 0); // quick hack: add 1 if caught so we can guarantee getting caught at zero layer doesn't show a zero severity.
}
public int GoSoon(int pause)
{
// here's the delay
for (var tics = 0; tics < pause; tics++)
TicToc();
return Go();
}
public int FindSafestPause()
{
var pause = 0;
int severity;
do
{
ResetLayers();
severity = GoSoon(pause++);
} while (severity > 0);
return pause - 1;
}
private void ResetLayers()
{
foreach (var layer in Layers)
layer.Value.Reset();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day23
{
class OptimizedTablet
{
private int b = 106700;
private int c = 123700;
private int h = 0;
// counts the number of composite numbers between 106700 and 123700
public int Invoke()
{
for (; b <= c; b += 17)
{
if (IsComposite(b))
h++;
}
return h;
}
private bool IsComposite(int n)
{
return !IsPrime(n);
}
// https://en.wikipedia.org/wiki/Primality_test
private bool IsPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
var i = 5;
while (i * i <= n)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
i += 6;
}
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using aoc_2017.Day01;
using aoc_2017.Day02;
using aoc_2017.Day03;
using aoc_2017.Day04;
using aoc_2017.Day05;
using aoc_2017.Day06;
using aoc_2017.Day07;
using aoc_2017.Day08;
using aoc_2017.Day09;
using aoc_2017.Day10;
using aoc_2017.Day11;
using aoc_2017.Day12;
using aoc_2017.Day13;
using aoc_2017.Day14;
using aoc_2017.Day15;
using aoc_2017.Day16;
using aoc_2017.Day17;
using aoc_2017.Day18;
using aoc_2017.Day19;
using aoc_2017.Day20;
using aoc_2017.Day21;
using aoc_2017.Day22;
using aoc_2017.Day23;
using aoc_2017.Day24;
using aoc_2017.Day25;
namespace aoc_2017
{
class Program
{
static void Main(string[] args)
{
/*
*/
Day_01_First.Do();
Day_01_Second.Do();
Day_02_First.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day02\Day_02_First_test_1.aoc");
Day_03_First.Do(289326);
Day_04_First.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day04\Day_04_First_test_1.aoc");
Day_05_First.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day05\Day_05_input.aoc");
Day_06.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day06\Day_06_input.aoc");
Day_07.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day07\Day_07_input.aoc");
Day_08.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day08\Day_08_input.aoc");
Day_09.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day09\Day_09_input.aoc");
Day_10_1.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day10\Day_10_input.aoc");
Day_10_2.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day10\Day_10_input.aoc");
Day_11.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day11\Day_11_input.aoc");
Day_12.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day12\Day_12_input.aoc");
Day_13.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day13\Day_13_input.aoc");
Day_14.Do();
Day_15.Do();
Day_16.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day16\Day_16_input.aoc");
Day_17.Do();
Day_18.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day18\Day_18_input.aoc");
Day_19.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day19\Day_19_input.aoc");
Day_20.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day20\Day_20_input.aoc");
Day_21.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day21\Day_21_input.aoc");
Day_22.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day22\Day_22_input.aoc");
Day_23.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day23\Day_23_input.aoc");
Day_24.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day24\Day_24_input.aoc");
Day_25.Do(@"C:\github\AdventOfCode_2017\aoc_2017\Day25\blueprints_input.aoc");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day11
{
// flat-topped, hexagonal grid that uses axial coordinates
// thx to https://www.redblobgames.com/grids/hexagons/
class Hex
{
public int Q { get; set; } // axis x <--> column
public int R { get; set; } // axis z <--> row
/*
public override int GetHashCode()
{
return base.GetHashCode();
}
*/
internal /*Hex*/void Step(int q, int r)
{
Q += q;
R += r;
//return new Hex() {Q = this.Q + q, R = this.R + r};
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day22
{
class Map
{
private HashSet< Tuple<int, int> > Infected { get; set; }
public int Infections { get; set; }
private Direction Compass { get; set; }
private enum Direction
{
Up = 0,
Right,
Down,
Left
}
protected Tuple<int, int> Carrier { get; set; }
public Map(string[] lines)
{
Infected = new HashSet< Tuple<int, int> >();
Infections = 0;
Compass = Direction.Up;
Carrier = new Tuple<int, int> (lines.Length / 2, lines.Length / 2);
InitializeInfection(lines);
}
private void InitializeInfection(string[] lines)
{
for (var y = 0; y < lines.Length; y++)
{
var line = lines[y];
var chars = line.ToCharArray();
for (var x = 0; x < lines.Length; x++)
{
if (chars[x] == '#')
Infected.Add(new Tuple<int, int>(x, y));
}
}
}
public void Burst()
{
Turn();
Cleanfect();
Move();
}
private void Turn()
{
var infected = Infected.Contains(Carrier);
switch (Compass)
{
case Direction.Up:
Compass = infected ? Direction.Right : Direction.Left;
break;
case Direction.Right:
Compass = infected ? Direction.Down : Direction.Up;
break;
case Direction.Down:
Compass = infected ? Direction.Left : Direction.Right;
break;
case Direction.Left:
Compass = infected ? Direction.Up : Direction.Down;
break;
default:
throw new Exception("Bad directions!");
}
}
private void Cleanfect()
{
if (Infected.Contains(Carrier))
{
Infected.Remove(Carrier);
}
else
{
Infections++;
Infected.Add(Carrier);
}
}
private void Move()
{
switch (Compass)
{
case Direction.Up:
Carrier = new Tuple<int, int>(Carrier.Item1, Carrier.Item2 - 1);
break;
case Direction.Right:
Carrier = new Tuple<int, int>(Carrier.Item1 + 1, Carrier.Item2);
break;
case Direction.Down:
Carrier = new Tuple<int, int>(Carrier.Item1, Carrier.Item2 + 1);
break;
case Direction.Left:
Carrier = new Tuple<int, int>(Carrier.Item1 - 1, Carrier.Item2);
break;
default:
throw new Exception("Bad move!");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day24
{
class Component
{
public List<int> Ports { get; set; }
public bool InUse { get; set; }
public int Strength => Ports.Sum();
//public int Depth { get; set; } better to build in the depth as a return value rather than try to maintain the state at each node
public Component(List<int> ports)
{
Ports = ports;
InUse = false;
}
// recursive method for Part One
public int Strongest(List<Component> components, int port)
{
InUse = true;
var matchingPinComponents = components.Where(c => !c.InUse && c.Ports.Contains(port)); // collect all the unused components that have a matching port
if (!matchingPinComponents.Any())
{
InUse = false;
return this.Strength;
}
// recurse down each component with a matching pin to get a collection of their strengths
var descendantStrengths = new List<int>(matchingPinComponents.Count());
foreach (var matchingPinComponent in matchingPinComponents)
{
var openPort = (matchingPinComponent.Ports.Count(p => p != port) == 1) ? matchingPinComponent.Ports.First(p => p != port) : port;
descendantStrengths.Add(matchingPinComponent.Strongest(components, openPort));
}
InUse = false;
return this.Strength + descendantStrengths.Max();
}
// recursive method for Part Two
public Tuple<int, int> Longest(List<Component> components, int port)
{
InUse = true;
var matchingPinComponents = components.Where(c => !c.InUse && c.Ports.Contains(port)); // collect all the unused components that have a matching port
if (!matchingPinComponents.Any())
{
InUse = false;
return new Tuple<int, int>(1, Strength);
}
// recurse down each component with a matching pin to get a collection of their lengths
var descendantLengths = new List< Tuple<int, int> >(matchingPinComponents.Count());
foreach (var matchingPinComponent in matchingPinComponents)
{
var openPort = (matchingPinComponent.Ports.Count(p => p != port) == 1) ? matchingPinComponent.Ports.First(p => p != port) : port;
descendantLengths.Add(matchingPinComponent.Longest(components, openPort));
}
InUse = false;
var longest = descendantLengths.Where(l => l.Item1 == descendantLengths.Max(t => t.Item1));
var strongest = longest.First(l => l.Item2 == longest.Max(s => s.Item2));
return new Tuple<int, int>(strongest.Item1 + 1, strongest.Item2 + Strength);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day23
{
class Day_23
{
public static void Do(string srcFile)
{
Do_1(srcFile);
Do_2(srcFile);
Console.ReadLine();
}
public static void Do_1(string srcFile)
{
var instructions = System.IO.File.ReadAllLines(srcFile);
var tablet = new Tablet();
var idx = 0L;
do
{
idx += tablet.Invoke(instructions[idx]);
} while (idx >= 0 && idx < instructions.Length);
Console.WriteLine($"Day 23.1: Number of times 'mul' is invoked: { tablet.MulCount }");
}
public static void Do_2(string srcFile)
{
var otablet = new OptimizedTablet();
Console.WriteLine($"Day 23.2: Value left in register h: { otablet.Invoke() }");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day20
{
class Swarm
{
public List<Particle> Particles { get; set; }
private Dictionary<int, int> Closests { get; set; } // the set of closest particles after each round...with count for how many times that particle was closest
private Particle ClosestNow
{
get
{
var closest = Particle.Max;
foreach (var particle in Particles)
{
if (particle.ManhattanDistance < closest.ManhattanDistance)
closest = particle;
}
return closest;
}
}
public Particle ClosestLongTerm
{
get
{
var closestKey = Closests.OrderByDescending(c => c.Value).First().Key;
return Particles.First(p => p.Index == closestKey);
}
}
public Swarm()
{
Particles = new List<Particle>();
Closests = new Dictionary<int, int>();
}
public Swarm(string[] rawParticles)
: this()
{
for (int i = 0; i < rawParticles.Length; i++)
{
var rawParticle = rawParticles[i];
Particles.Add(Particle.Parse(rawParticle, i));
}
}
public void Next()
{
// advance all particles
foreach (var particle in Particles)
{
particle.Velocity = particle.UpdateVelocity;
particle.Position = particle.UpdatePosition;
}
// determine closest status
var closest = ClosestNow;
if (!Closests.ContainsKey(closest.Index))
{
Closests.Add(closest.Index, 1);
}
else
{
var closests = ++Closests[closest.Index];
Closests[closest.Index] = closests;
}
// eliminate any particles that collided (like anti-matter meets matter)
EliminateCollisions();
}
private void EliminateCollisions()
{
// collect all the particles by their distance
var distances = new Dictionary<long, List<Particle>>();
foreach (var particle in Particles)
{
var distance = particle.ManhattanDistance;
if (distances.ContainsKey(distance))
distances[distance].Add(particle);
else
distances.Add(distance, new List<Particle> { particle });
}
// only compare any distances that have more than one entry - this is much faster than doing an exhaustive O(n^2) search!
var confirmedDupes = new List<Particle>();
var distanceDupes = distances.Where(d => d.Value.Count > 1);
foreach (var distanceDupe in distanceDupes)
{
// now only exhaustively compare the dupes with the same distance
foreach (var dupe1 in distanceDupe.Value)
{
foreach (var dupe2 in distanceDupe.Value)
{
if (dupe1.Index == dupe2.Index) continue;
if (dupe1.Position == dupe2.Position)
{
if (!confirmedDupes.Contains(dupe1)) confirmedDupes.Add(dupe1);
if (!confirmedDupes.Contains(dupe2)) confirmedDupes.Add(dupe2);
}
}
}
}
foreach (var confirmedDupe in confirmedDupes)
Particles.Remove(confirmedDupe);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using aoc_2017.Day08;
namespace aoc_2017.Day20
{
class Particle
{
public Vector3D Position { get; set; }
public Vector3D Velocity { get; set; }
public Vector3D Acceleration { get; set; }
public int Index { get; set; }
public long ManhattanDistance => Math.Abs(Position.X) + Math.Abs(Position.Y) + Math.Abs(Position.Z);
public static Particle Max => new Particle() { Index = -1, Position = Vector3D.Max };
public static Particle Parse(string raw, int index)
{
var match = Regex.Match(raw, @"p=<(?<position>.*)>, v=<(?<vector>.*)>, a=<(?<acceleration>.*)>$");
var positions = match.Groups["position"].ToString().Split(',');
var vectors = match.Groups["vector"].ToString().Split(',');
var accelerations = match.Groups["acceleration"].ToString().Split(',');
return new Particle
{
Position = new Vector3D(positions),
Velocity = new Vector3D(vectors),
Acceleration = new Vector3D(accelerations),
Index = index
};
}
public Vector3D UpdateVelocity => Velocity + Acceleration;
public Vector3D UpdatePosition => Position + Velocity;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day22
{
class Node
{
public enum State
{
Clean,
Weakened,
Infected,
Flagged
}
public State Status { get; set; }
public Node()
{
Status = State.Clean;
}
public State UpdateStatus()
{
switch (Status)
{
case State.Clean:
Status = State.Weakened;
break;
case State.Weakened:
Status = State.Infected;
break;
case State.Infected:
Status = State.Flagged;
break;
case State.Flagged:
Status = State.Clean;
break;
default:
throw new Exception("Status Incognito!");
}
return Status;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day25
{
class Day_25
{
public static void Do(string srcFile)
{
var rawBlueprints = System.IO.File.ReadAllLines(srcFile);
var regex = Regex.Match(rawBlueprints[0], @"Begin in state (?<startState>.+).$");
var startState = regex.Groups["startState"].ToString();
regex = Regex.Match(rawBlueprints[1], @"Perform a diagnostic checksum after (?<numSteps>.+) steps.$");
var numSteps = int.Parse(regex.Groups["numSteps"].ToString());
var machine = new Turing(startState, rawBlueprints);
for (var i = 0; i < numSteps; i++)
machine.MoveNext();
Console.WriteLine($"Day 25.1: Diagnostic checksum: { machine.Checksum }");
Console.ReadLine();
}
public static void Do_2(string srcFile)
{
var pieces = System.IO.File.ReadAllLines(srcFile);
Console.WriteLine($"Day 25.2: Diagnostic checksum: { 0 }");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day18
{
class VirtualSoundCard
{
private const long DefaultReturnValue = 1;
public Dictionary<string, long> Registers { get; set; }
public long LastFrequency = -1;
public VirtualSoundCard()
{
Registers = new Dictionary<string, long>();
}
public long Invoke(string rawInstruction)
{
var match = Regex.Match(rawInstruction, @"(?<instruction>.*) (?<register1>.*) (?<register2>.*$)");
if (string.IsNullOrEmpty(match.Groups["register2"].ToString())) // quick hack to deal with cases where there is only one register
match = Regex.Match(rawInstruction, @"(?<instruction>.*) (?<register1>.*$)");
var instruction = match.Groups["instruction"].ToString();
var register1 = match.Groups["register1"].ToString();
var register2 = match.Groups["register2"].ToString();
switch (instruction)
{
case "snd":
return doSound(register1);
case "set":
return doSet(register1, register2);
case "add":
return doAdd(register1, register2);
case "mul":
return doMul(register1, register2);
case "mod":
return doMod(register1, register2);
case "rcv":
return doRcv(register1);
case "jgz":
return doJgz(register1, register2);
default:
throw new ArgumentNullException("Invalid instruction received!");
}
}
private long doSound(string register)
{
LastFrequency = Registers[register]; // always assumes register already exists
return DefaultReturnValue;
}
private long doSet(string register1, string register2)
{
long value = GetRegisterOrValue(register2);
Registers[register1] = value;
return DefaultReturnValue;
}
private long doAdd(string register1, string register2)
{
Registers[register1] += GetRegisterOrValue(register2);
return DefaultReturnValue;
}
private long doMul(string register1, string register2)
{
if (!Registers.ContainsKey(register1))
Registers.Add(register1, 0L);
Registers[register1] *= GetRegisterOrValue(register2);
return DefaultReturnValue;
}
private long doMod(string register1, string register2)
{
Registers[register1] %= GetRegisterOrValue(register2);
return DefaultReturnValue;
}
private long doRcv(string register)
{
if (GetRegisterOrValue(register) > 0L)
return -Registers.Count-1000; // signal recover
return DefaultReturnValue;
}
private long doJgz(string register1, string register2)
{
var value1 = GetRegisterOrValue(register1);
var value2 = GetRegisterOrValue(register2);
return value1 > 0 ? value2 : DefaultReturnValue;
}
private long GetRegisterOrValue(string register)
{
var value = 0L;
if (!long.TryParse(register, out value)) // test for number or register name
{
if (!Registers.ContainsKey(register))
Registers.Add(register, 0);
value = Registers[register];
}
return value;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day08
{
public class Day_08
{
public static void Do(string srcFile)
{
var registers = new Registers();
var lines = System.IO.File.ReadAllLines(srcFile);
var instructions = lines.Select(line => new Instruction(line)).ToList();
// first create the bank of registers
foreach (var instr1 in instructions)
{
if (!registers.Bank.ContainsKey(instr1.RegisterName))
registers.Bank.Add(instr1.RegisterName, new Register() {Name=instr1.RegisterName, Value = 0});
}
// then loop through and execute all of the instructions
var highest = 0;
foreach (var instruction2 in instructions)
{
var local = registers.ApplyInstruction(instruction2);
if (local > highest) highest = local;
}
var largest = registers.FindLargest();
Console.Write($"Day 08: Largest Final Value: {largest.Value} Highest Value: {highest}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day16
{
class Day_16
{
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var steps = lines[0].Split(',').ToList();
const int OneBillionTimes = 1000000000 % 48;
var troupe = new Dancers();
for (int i = 0; i < OneBillionTimes; i++)
{
foreach (var step in steps)
{
var movement = new Move(step);
troupe.Step(movement);
}
/* used the following to determine a cycle of 48
which we use to modulus the number of cycles to speed up.
the final number of loops is really only 16! bpcekomfgjdlinha
if (troupe.CurrentLineUp == "abcdefghijklmnop")
break;
*/
}
Console.WriteLine($"Day 16: Programs Standing Order: { troupe.CurrentLineUp }");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day20
{
// there is a Vector3 in XNA/DirectX.
// there is also a Point3D elsewhere in Windows-land.
// unfortunately there is too much cheese that comes with either pizzas.
// so i am spinning a quick one of my own here and blending the names.
class Vector3D
{
public long X { get; set; }
public long Y { get; set; }
public long Z { get; set; }
public static Vector3D Max => new Vector3D { X = long.MaxValue, Y = 0, Z = 0 };
public Vector3D() { }
public Vector3D(string[] axes)
{
X = long.Parse(axes[0]); // assumes valid long in string
Y = long.Parse(axes[1]);
Z = long.Parse(axes[2]);
}
public Vector3D(long x, long y, long z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3D operator +(Vector3D left, Vector3D right)
{
return new Vector3D(right.X + left.X, right.Y + left.Y, right.Z + left.Z);
}
public static bool operator ==(Vector3D left, Vector3D right)
{
return right.X == left.X && right.Y == left.Y && right.Z == left.Z;
}
public static bool operator !=(Vector3D left, Vector3D right)
{
return !(left == right);
}
public override bool Equals(object vec)
{
return this == (Vector3D) vec;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day24
{
class Port
{
public int Pins { get; set; }
public bool Connected { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day19
{
class Day_19
{
public static void Do(string srcFile)
{
var paths = System.IO.File.ReadAllLines(srcFile);
var diagram = new RoutingDiagram { Paths = paths };
var success = diagram.TracePath();
Console.WriteLine($"Day 19: Letters seen: { diagram.Letters } Steps taken: { diagram.Steps }");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day13
{
class Packet
{
public int CurrentDepth { get; set; }
public Layer CurrentLayer { get; set; }
public int Next(int depth, Layer nextLayer, out bool caught)
{
int severity = 0;
caught = false;
CurrentDepth = depth;
if (nextLayer != null)
{
// caught?
if (nextLayer.Caught())
{
severity = nextLayer.Depth * nextLayer.Range;
caught = true;
}
CurrentLayer = nextLayer;
}
return severity;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day03
{
class Manhattan
{
internal enum SENW
{
South = 0,
East,
North,
West
}
public SENW Direction { get; set; }
public int x { get; set; }
public int y { get; set; }
public int bottom { get; set; }
public int right { get; set; }
public int top { get; set; }
public int left { get; set; }
public bool turn { get; set; }
public Manhattan(int steps)
{
Direction = SENW.South;
x = y = bottom = right = top = left = 0;
turn = true;
}
public void Walk(int steps)
{
for (int i = 1; i < steps; i++)
{
SetDirection(i);
Move(i);
}
}
private void SetDirection(int idx)
{
// change direction if you can turn move
switch (Direction)
{
case SENW.South:
if (turn)
Direction = SENW.East;
break;
case SENW.East:
if (turn)
Direction = SENW.North;
break;
case SENW.North:
if (turn)
Direction = SENW.West;
break;
case SENW.West:
if (turn)
Direction = SENW.South;
break;
}
turn = false;
}
private void Move(int idx)
{
switch (Direction)
{
case SENW.South:
y -= 1;
if (y < bottom)
{
bottom = y;
turn = true;
}
break;
case SENW.East:
x += 1;
if (x > right)
{
right = x;
turn = true;
}
break;
case SENW.North:
y += 1;
if (y > top)
{
top = y;
turn = true;
}
break;
case SENW.West:
x -= 1;
if (x < left)
{
left = x;
turn = true;
}
break;
}
}
public int CalculateDistance()
{
return Math.Abs(x) + Math.Abs(y);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day11
{
class Day_11
{
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var steps = lines[0].Split(',').ToList();
var grid = new Grid();
foreach (var step in steps)
grid.Step((Grid.Direction)Enum.Parse(typeof(Grid.Direction), step.ToUpper()));
Console.Write($"Day 11: Fewest Steps: {grid.DistanceToOrigin()} Furthest Hex: {grid.Furthest}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day08
{
public class Registers
{
private Dictionary<string, Register> _bank = null;
public Dictionary<string, Register> Bank => _bank ?? (_bank = new Dictionary<string, Register>());
public int ApplyInstruction(Instruction inst)
{
// update the actee accordingly if the condition passes
if (TestCondition(inst))
return UpdateRegisterValue(inst);
return 0;
}
private bool TestCondition(Instruction inst)
{
// retrieve the register being tested
var testee = Bank[inst.Condition.Left];
var right = int.Parse(inst.Condition.Right);
switch (inst.Condition.Operation)
{
case "<": return testee.Value < right;
case ">": return testee.Value > right;
case "<=": return testee.Value <= right;
case ">=": return testee.Value >= right;
case "==": return testee.Value == right;
case "!=": return testee.Value != right;
}
return false;
}
private int UpdateRegisterValue(Instruction inst)
{
// retrieve the register being acted upon
var actee = Bank[inst.RegisterName];
if (inst.IncDec)
actee.Value += inst.Increment;
else
actee.Value -= inst.Increment;
return actee.Value;
}
public Register FindLargest()
{
Register largest = Bank.First().Value;
foreach (var register in Bank)
{
if (register.Value.Value > largest.Value)
largest = register.Value;
}
return largest;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day12
{
// connected component
// https://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29
class Day_12
{
public static void Do(string srcFile)
{
var pipes = System.IO.File.ReadAllLines(srcFile);
var nodes = pipes.Select(GraphNode.Parse).ToDictionary(node => node.Index);
foreach (var node in nodes)
{
foreach (var path in node.Value.Paths)
node.Value.Nodes.Add(nodes[path]);
}
const int programID = 0;
var connections = GraphNode.VisitConnectedNodes(nodes[programID]); // marks nodes as "visited"
// how many nodes have not been visited yet?
var groups = 1; // 1 group already visited
foreach (var node in nodes)
{
if (node.Value.Visited == false)
{
groups++;
GraphNode.VisitConnectedNodes(node.Value); // mark the nodes connected to this one
}
}
Console.Write($"Day 12: Node 0 connections: {connections} Number of Groups: {groups}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day24
{
class Day_24
{
public static void Do(string srcFile)
{
Do_1(srcFile);
Do_2(srcFile);
Console.ReadLine();
}
public static void Do_1(string srcFile)
{
var pieces = System.IO.File.ReadAllLines(srcFile);
var components = new List<Component>(pieces.Length);
components.AddRange(pieces.Select(piece => new Component(piece.Split('/').Select(int.Parse).ToList()) ));
const int StartingPin = 0;
var zeroPinComponents = components.Where(c => c.Ports.Contains(StartingPin));
var strengths = new List<int>(zeroPinComponents.Count());
foreach (var zeroPinComponent in zeroPinComponents)
{
var openPort = (zeroPinComponent.Ports.Count(p => p != StartingPin) == 1) ? zeroPinComponent.Ports.First(p => p != StartingPin) : StartingPin;
strengths.Add(zeroPinComponent.Strongest(components, openPort));
}
Console.WriteLine($"Day 24.1: Strength of strongest bridge: { strengths.Max() }");
}
public static void Do_2(string srcFile)
{
var pieces = System.IO.File.ReadAllLines(srcFile);
var components = new List<Component>(pieces.Length);
components.AddRange(pieces.Select(piece => new Component(piece.Split('/').Select(int.Parse).ToList())));
const int StartingPin = 0;
var zeroPinComponents = components.Where(c => c.Ports.Contains(StartingPin));
var lengths = new List<Tuple< int, int > >(zeroPinComponents.Count());
foreach (var zeroPinComponent in zeroPinComponents)
{
var openPort = (zeroPinComponent.Ports.Count(p => p != StartingPin) == 1) ? zeroPinComponent.Ports.First(p => p != StartingPin) : StartingPin;
lengths.Add(zeroPinComponent.Longest(components, openPort));
}
var longest = lengths.Where(c => c.Item1 == lengths.Max(t => t.Item1));
Console.WriteLine($"Day 24.2: Strength of longest bridge: { longest.Max().Item2 }");
}
}
}
<file_sep>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace aoc_2017.Day18
{
class Bubbler
{
private const long DefaultInstructionJump = 1;
public Dictionary<string, long> Registers { get; set; }
public Bubbler Partner { get; set; }
public long SendCount { get; set; }
private BlockingCollection<long> Queue { get; set; }
public Bubbler()
{
Registers = new Dictionary<string, long>();
Queue = new BlockingCollection<long>();
SendCount = 0L;
}
public long Process(string[] instructions)
{
var idx = 0L;
do
{
idx += Invoke(instructions[idx]);
} while (idx >= 0 && idx < instructions.Length);
return SendCount;
}
protected long Invoke(string rawInstruction)
{
var match = Regex.Match(rawInstruction, @"(?<instruction>.*) (?<register1>.*) (?<register2>.*$)");
if (string.IsNullOrEmpty(match.Groups["register2"].ToString())) // quick hack to deal with cases where there is only one register
match = Regex.Match(rawInstruction, @"(?<instruction>.*) (?<register1>.*$)");
var instruction = match.Groups["instruction"].ToString();
var register1 = match.Groups["register1"].ToString();
var register2 = match.Groups["register2"].ToString();
switch (instruction)
{
case "snd":
return doSend(register1);
case "set":
return doSet(register1, register2);
case "add":
return doAdd(register1, register2);
case "mul":
return doMul(register1, register2);
case "mod":
return doMod(register1, register2);
case "rcv":
return doReceive(register1);
case "jgz":
return doJgz(register1, register2);
default:
throw new ArgumentNullException("Invalid instruction received!");
}
}
private long doSend(string register)
{
Partner.Queue.Add(GetRegisterOrValue(register));
SendCount++;
return DefaultInstructionJump;
}
private long doSet(string register1, string register2)
{
long value = GetRegisterOrValue(register2);
Registers[register1] = value;
return DefaultInstructionJump;
}
private long doAdd(string register1, string register2)
{
Registers[register1] += GetRegisterOrValue(register2);
return DefaultInstructionJump;
}
private long doMul(string register1, string register2)
{
if (!Registers.ContainsKey(register1))
Registers.Add(register1, 0L);
Registers[register1] *= GetRegisterOrValue(register2);
return DefaultInstructionJump;
}
private long doMod(string register1, string register2)
{
Registers[register1] %= GetRegisterOrValue(register2);
return DefaultInstructionJump;
}
private long doReceive(string register)
{
var peek = 0L;
if (Queue.TryTake(out peek, 100))
Registers[register] = peek;
else
Partner.Queue.CompleteAdding();
return DefaultInstructionJump;
}
private long doJgz(string register1, string register2)
{
var value1 = GetRegisterOrValue(register1);
var value2 = GetRegisterOrValue(register2);
return value1 > 0 ? value2 : DefaultInstructionJump;
}
private long GetRegisterOrValue(string register)
{
var value = 0L;
if (!long.TryParse(register, out value)) // test for number or register name
{
if (!Registers.ContainsKey(register))
Registers.Add(register, 0);
value = Registers[register];
}
return value;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day22
{
class EvolvedMap
{
private Dictionary< Tuple<int, int>, Node > Infected { get; set; }
public int Infections { get; set; }
protected Cursor Carrier { get; set; }
public EvolvedMap(string[] lines)
{
Infected = new Dictionary< Tuple<int, int>, Node >();
Infections = 0;
Carrier = new Cursor(lines.Length / 2);
InitializeInfection(lines);
}
private void InitializeInfection(string[] lines)
{
for (var y = 0; y < lines.Length; y++)
{
var line = lines[y];
var chars = line.ToCharArray();
for (var x = 0; x < lines.Length; x++)
{
if (chars[x] == '#')
Infected.Add(new Tuple<int, int>(x, y), new Node { Status = Node.State.Infected });
}
}
}
public void Burst()
{
Turn();
Cleanfect();
Carrier.Move();
}
private void Turn()
{
var node = GetCurrentNode();//first after first turn&move this should be infected
var nodeStatus = node?.Status ?? Node.State.Clean;
switch (nodeStatus)
{
case Node.State.Clean:
Carrier.Turn(Cursor.Doble.Left);
break;
case Node.State.Weakened:
Carrier.Turn(Cursor.Doble.Forward); // redundant
break;
case Node.State.Infected:
Carrier.Turn(Cursor.Doble.Right);
break;
case Node.State.Flagged:
Carrier.Turn(Cursor.Doble.Reverse);
break;
default:
throw new Exception("Bad directions!");
}
}
private void Cleanfect()
{
var status = Node.State.Weakened;
var node = GetCurrentNode();
if (node != null)
status = node.UpdateStatus();
else
Infected.Add(Carrier.Coordinates, new Node { Status = status });
if (status == Node.State.Clean)
Infected.Remove(Carrier.Coordinates);
else if (status == Node.State.Infected)
Infections++;
}
private Node GetCurrentNode()
{
return Infected.ContainsKey(Carrier.Coordinates) ? Infected[Carrier.Coordinates] : null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day17
{
class Day_17
{
public static void Do()
{
Do_1();
Do_2();
Console.ReadLine();
}
public static void Do_1()
{
const int numInsertions = 2018;
var spinlock = new SpinLock();
for (var i = 1; i < numInsertions; i++) // 0 added in SpinLock ctor
spinlock.Insert(i);
Console.WriteLine($"Day 17.1: Value after { numInsertions } insertions: { spinlock.After }");
}
// is this the Josephus Problem?
// https://en.wikipedia.org/wiki/Josephus_problem
public static void Do_2()
{
const int numSteps = 337;
const int numInsertions = 50000000;
// no list needed! only need to keep track of the index and the second value
var idx = 0;
var second = 0;
for (var i = 1; i <= numInsertions; i++)
{
idx = (idx + numSteps + 1) % i;
if (idx == 0)
second = i;
}
Console.WriteLine($"Day 17.2: Second value { second }");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day20
{
class Day_20
{
public static void Do(string srcFile)
{
var rawParticles = System.IO.File.ReadAllLines(srcFile);
var swarm = new Swarm(rawParticles);
const int SampleSetSize = 1000;
for (var i = 0; i < SampleSetSize; i++)
swarm.Next();
//Console.WriteLine($"Day 20: Closest particle: { swarm.ClosestLongTerm.Index }"); // this will only work when you comment out the EliminateCollisions() call in Swarm. Don't have the time to care to fix it.
Console.WriteLine($"Day 20: Particles remaining: { swarm.Particles.Count }");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day10
{
public class Day_10_1
{
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var lengths = lines[0].Split(',').Select(int.Parse).ToList();
var knot = new Knot(256);
foreach (var length in lengths)
knot.Hash(length);
Console.Write($"Day 10.1: Product: {knot.Product}");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day21
{
class Day_21
{
// i implemented this with real grid objects down to the bottom. not very efficient.
// i saw someone else had done it through only strings and it was much simpler and probably faster.
public static void Do(string srcFile)
{
var lines = System.IO.File.ReadAllLines(srcFile);
var rules = lines.Select(Rule.Parse).ToList();
const int NumIterations = 5;
var image = Image.StartingImage;
for (var i = 0; i < NumIterations; i++)
image.Expand(rules);
Console.WriteLine($"Day 21: Pixels remaining: { image.Pixels }");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day21
{
// this is the container for the fractal image
class Image
{
// start with storing as one string per row. that should make it very flexible and easier to maintain size.
private List<List<Grid>> Grids { get; set; }
private int NumGrids => Grids[0].Count; // number of grids across/down
private int GridSize => Grids[0][0].Dimension; // number of rows/cols in each grid
public int Pixels { get { return Grids.Sum(gridRow => gridRow.Sum(grid => grid.Pixels)); } }
#region ctors
private const string StarterSet = ".#./..#/###";
//private const string StarterSet = "#..#/..../..../#..#";
public static Image StartingImage => new Image(StarterSet);
protected Image()
{
Grids = new List<List<Grid>>();
}
protected Image(string starterSet) : this()
{
Grids.Add(new List<Grid> { new Grid(starterSet) });
}
#endregion ctors
// I started so quickly with StartingImage that I found my rules being added in the Expand method. If I were to make this more professional I would change it to be in the ctor or similar.
internal void Expand(List<Rule> rules)
{
// convert grids in each row to a string
var rows = GetRows();
// break up into new "expanded" grids
Grids.Clear();
var gridSize = rows.Count % 2 == 0 ? 2 : 3;
try
{
for (var rowIdx = 0; rowIdx < rows.Count / gridSize; rowIdx++)
Grids.Add(Grid.FromStrings(rows, rowIdx, gridSize).Select(g => g.Expand(rules)).ToList());
}
catch (Exception)
{
// TODO: move out of exception handler
if (gridSize == 2 && rows.Count % 3 == 0)
{
gridSize = 3;
Grids.Clear();
for (var rowIdx = 0; rowIdx < rows.Count / gridSize; rowIdx++)
Grids.Add(Grid.FromStrings(rows, rowIdx, gridSize).Select(g => g.Expand(rules)).ToList());
}
//throw;
}
}
private List<string> GetRows()
{
// TODO: clean this up later...
var numRows = NumGrids * GridSize;
var rows = new List<string>(numRows);
for (var gridRowIdx = 0; gridRowIdx < NumGrids; gridRowIdx++)
{
var tempRows = new string[GridSize]; // allocate for number of real rows per grid row
for (var i = 0; i < GridSize; i++)
tempRows[i] = "";
for (var gridColIdx = 0; gridColIdx < NumGrids; gridColIdx++)
{
var splits = Grids[gridRowIdx][gridColIdx].ToString().Split('/');
for (var j = 0; j < GridSize; j++)
{
tempRows[j] = tempRows[j] + splits[j];
}
}
rows.AddRange(tempRows);
}
return rows;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aoc_2017.Day03
{
public class Day_03_First
{
public static void Do(int steps)
{
var square = new Day_03_First();
square.Dance(steps);
}
public void Dance(int steps)
{
var blocks = new Manhattan(steps);
blocks.Walk(steps);
Console.Write($"Day 03: Steps: {steps} Distance {blocks.CalculateDistance()}");
Console.ReadLine();
}
}
}
| 68094419f6510d2cb6ac32236afda3c8f8363572 | [
"Markdown",
"C#"
] | 64 | C# | jefflehmer/AdventOfCode_2017 | 582873944668681117d24dd72cabcbd23cd6bd91 | b55dbd9688f670252ea64d7aa617ed346fb1d344 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
namespace TwitterCollage.Models
{
public class TwitterUser
{
public string ScreenName { get; set; }
public Image Image { get; set; }
public string ImageUrl { get; set; }
public int RetweetsCount { get; set; }
public void LoadImage()
{
if (!String.IsNullOrEmpty(ImageUrl))
{
WebClient web = new WebClient();
byte[] imageBytes = web.DownloadData(ImageUrl);
MemoryStream ms = new MemoryStream(imageBytes);
Image = Image.FromStream(ms);
ms.Close();
}
else
{
throw new ArgumentException("ScreenName is null or empty");
}
}
}
}<file_sep># TwitterCollage
Asp.NET MVC application for creating collage from users that you retweeted
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using LinqToTwitter;
using TwitterCollage.Models;
namespace TwitterCollage.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult RetweetedUsers(string ScreenName)
{
var users = GetRetweetedUsers(ScreenName).Values.ToList();
var url = CreateCollage(users);
return View(url as object);
}
private string CreateCollage(List<TwitterUser> users)
{
var collageSize = 300;
Bitmap img = new Bitmap(collageSize,collageSize);
Graphics gr = Graphics.FromImage(img);
gr.FillRectangle(new SolidBrush(Color.White), new Rectangle(0,0,img.Width,img.Height));
int countInLine = (int)Math.Ceiling(Math.Sqrt(users.Count));
int size = (collageSize - countInLine + 1)/countInLine;
int[] freeSpaces = new int[countInLine];
for (int i = 0; i < countInLine; i++)
{
for (int column = countInLine; column > 0; column--)
{
if (column*countInLine + i+1 <= users.Count)
{
freeSpaces[i] = ((countInLine - column) - 1)*size/countInLine;
break;
}
}
}
for (int i=0;i< countInLine; i++) {
for (int j = 0; j < countInLine; j++)
{
if (i*countInLine + j >= users.Count) break;
users[i * countInLine + j].LoadImage();
users[i*countInLine + j].Image = CropAsSquare(users[i*countInLine + j].Image);
//var x = (j > 0) ? i*size + i + j*freeSpaces[j - 1] : i*size + i;
var x = i*size + i + (i + 1)*freeSpaces[j];
gr.DrawImage(users[i*countInLine+j].Image,new Rectangle(x,j*size+j*1,size,size));
}
}
gr.Flush();
var env = HostingEnvironment.ApplicationPhysicalPath + "Content\\collages\\collage.jpg";
img.Save(env, ImageFormat.Jpeg);
gr.Dispose();
img.Dispose();
return "../Content/collages/collage.jpg";
}
public Bitmap ResizeImage(Image image, int width, int height)
{
if (width == 0) width = 2;
if (height == 0) height = 2;
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
private Image CropAsSquare(Image img)
{
if (img.Width == img.Height) return img;
Bitmap tmpBitmap = new Bitmap(img);
Bitmap bMap = (Bitmap)tmpBitmap.Clone();
int size = (img.Width > img.Height) ? img.Height : img.Width;
int xPosition = 0, yPosition = 0;
if (img.Width > img.Height)
{
xPosition = (img.Width - size) / 2;
yPosition = 0;
}
else
{
yPosition = (img.Height - size) / 2;
xPosition = 0;
}
Rectangle rect = new Rectangle(xPosition, yPosition, size, size);
tmpBitmap = bMap.Clone(rect, bMap.PixelFormat);
MemoryStream stream = new MemoryStream();
tmpBitmap.Save(stream, ImageFormat.Jpeg);
return Image.FromStream(stream);
}
private Dictionary<string,TwitterUser> GetRetweetedUsers(string screenName)
{
Dictionary<string, TwitterUser> users = new Dictionary<string, TwitterUser>();
var config = new System.Configuration.AppSettingsReader();
var auth = new ApplicationOnlyAuthorizer()
{
CredentialStore =
new InMemoryCredentialStore()
{
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"]
}
};
var task = auth.AuthorizeAsync();
task.Wait();
var twx = new TwitterContext(auth);
var tweets = from tweet in twx.Status
where tweet.Type == StatusType.User &&
tweet.ScreenName == screenName &&
tweet.Count == 300 &&
tweet.TrimUser == false &&
tweet.ExcludeReplies == false
select tweet;
foreach (var tweet in tweets)
{
if (tweet.RetweetedStatus.User != null)
{
var screenNameRt = tweet.RetweetedStatus.User.ScreenNameResponse.Trim();
if (users.ContainsKey(screenNameRt))
{
users[screenNameRt].RetweetsCount++;
}
else
{
users.Add(screenNameRt, new TwitterUser()
{
ScreenName = screenNameRt,
ImageUrl = tweet.RetweetedStatus.User.ProfileImageUrl.Remove(tweet.RetweetedStatus.User.ProfileImageUrl.LastIndexOf("_normal",StringComparison.Ordinal),7),
RetweetsCount = 1
});
}
}
}
return users;
}
}
} | 6caf5038181ce4cb744f01a1429c51e0aaf406fb | [
"Markdown",
"C#"
] | 3 | C# | almarkua/TwitterCollage | 60744fa9ee4be976b80bb4e4a9a9bc8caf4d015e | 8a4d5c3c6c6a92c0a40fef5ffe6da95d65397827 |
refs/heads/master | <repo_name>divcoder/site-codes<file_sep>/README.md
# site-codes
Bu bölüm, divcoder.com sitesinin blog sayfasında paylaşılmış çözümler için açılmıştır
Çözümlerde eklenen kodlar burada yer almaktadır.
.php uzantılı dosyaları sitenize eklemeden önce konuyu okuduğunuzdan emin olun.
<file_sep>/login-screen-style.php
<?php //functions.php
/**
*Login CSS / URL
*/
function guvenligiris() {
echo '<link rel="stylesheet" type="text/css" href="' . get_bloginfo('stylesheet_directory') . '/giris/style.css" />';
}
add_action('login_head', 'guvenligiris');
function guvenligiris_url() {
return get_bloginfo( 'url' );
}
add_filter( 'login_headerurl', 'guvenligiris_url' );
//Shake.js Remover
function my_login_head() {
remove_action('login_head', 'wp_shake_js', 12);
}
add_action('login_head', 'my_login_head');
//Remember Checked
function login_checked_remember_me() {
add_filter( 'login_footer', 'rememberme_checked' );
}
add_action( 'init', 'login_checked_remember_me' );
function rememberme_checked() {
echo "<script>document.getElementById('rememberme').checked = true;</script>";
}
?>
<file_sep>/WP-Login-and-Register-Security.php
<?php //functions.php
// **
// Login Limit with Trasient
// **
if ( ! class_exists( 'Limit_Login_Attempts' ) ) {
class Limit_Login_Attempts {
var $failed_login_limit = 10; //Login Limit
var $lockout_duration = 60; //Lockout Duration > 60x10 = 10 min
var $transient_name = 'attempted_login'; //Transient Name
public function __construct() {
add_filter( 'authenticate', array( $this, 'check_attempted_login' ), 30, 3 );
add_action( 'wp_login_failed', array( $this, 'login_failed' ), 10, 1 );
}
/**
* Codes
*/
public function check_attempted_login( $user, $username, $password ) {
if ( get_transient( $this->transient_name ) ) {
$datas = get_transient( $this->transient_name );
if ( $datas['tried'] >= $this->failed_login_limit ) {
$until = get_option( '_transient_timeout_' . $this->transient_name );
$time = $this->when( $until );
//Error text
return new WP_Error( 'too_many_tried', sprintf( __( 'ERROR: Wrong password.' ) , $time ) );
}
}
return $user;
}
/**
* Add Trasient
*/
public function login_failed( $username ) {
if ( get_transient( $this->transient_name ) ) {
$datas = get_transient( $this->transient_name );
$datas['tried']++;
if ( $datas['tried'] <= $this->failed_login_limit )
set_transient( $this->transient_name, $datas , $this->lockout_duration );
} else {
$datas = array(
'tried' => 1
);
set_transient( $this->transient_name, $datas , $this->lockout_duration );
}
}
/**
*
* @param int $time
* @return string
*/
private function when( $time ) {
if ( ! $time )
return;
$right_now = time();
$diff = abs( $right_now - $time );
$second = 1;
$minute = $second * 60;
$hour = $minute * 60;
$day = $hour * 24;
if ( $diff < $minute )
return floor( $diff / $second ) . ' sec';
if ( $diff < $minute * 2 )
return "1 sec ago";
if ( $diff < $hour )
return floor( $diff / $minute ) . ' min';
if ( $diff < $hour * 2 )
return '1 min ago';
return floor( $diff / $hour ) . ' saat';
}
}
}
//Begin
new Limit_Login_Attempts();
// **
//Register Security Question
// **
add_action( 'register_form', 'add_register_field' );
function add_register_field() { ?>
<p>
<label><?php _e('<strong>QUESTION:</strong> Where was the first capital of the United States?') ?><br />
<input type="text" name="user_gsoru" id="user_gsoru" class="input" size="25" tabindex="20" /></label>
</p>
<?php }
add_action( 'register_post', 'add_register_field_validate', 10, 3 );
function add_register_field_validate( $sanitized_user_login, $user_email, $errors) {
if (!isset($_POST[ 'user_gsoru' ]) || empty($_POST[ 'user_gsoru' ])) {
return $errors->add( 'proofempty', '<strong>ERROR</strong>: This field is required.' );
} elseif ( strtolower( $_POST[ 'user_gsoru' ] ) != 'New York City' ) {
return $errors->add( 'prooffail', '<strong>ERROR</strong>: Wrong answer.' );
}
}
<file_sep>/wp-panel-korumasi.php
function panelengel() {
// Sadece adminlerin giriş yapabileceğini tanımlıyoruz
if ( ! current_user_can( 'manage_options' ) && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
// Eğer admin değil ise, WP-ADMIN panelinden anasayfaya yönlendirileceğini belirliyoruz
wp_redirect( home_url() );
}
}
add_action( 'admin_init', 'panelengel', 1 );
| 184f7f10dbd08d728a491e38764cd2294adf64da | [
"Markdown",
"PHP"
] | 4 | Markdown | divcoder/site-codes | fda94e56831ba8c463005c338a50abb953070ab5 | dc54f94a0c6643a98fceae389874c53e4989bb29 |
refs/heads/master | <repo_name>rchung95/urml<file_sep>/ca.queensu.cs.mase.urml.ui/src-gen/ca/queensu/cs/mase/ui/contentassist/antlr/internal/InternalUrmlParser.java
package ca.queensu.cs.mase.ui.contentassist.antlr.internal;
import java.io.InputStream;
import org.eclipse.xtext.*;
import org.eclipse.xtext.parser.*;
import org.eclipse.xtext.parser.impl.*;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.eclipse.xtext.parser.antlr.XtextTokenStream.HiddenTokens;
import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser;
import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.DFA;
import ca.queensu.cs.mase.services.UrmlGrammarAccess;
import org.antlr.runtime.*;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
@SuppressWarnings("all")
public class InternalUrmlParser extends AbstractInternalContentAssistParser {
public static final String[] tokenNames = new String[] {
"<invalid>", "<EOR>", "<DOWN>", "<UP>", "RULE_ID", "RULE_STRING", "RULE_INT", "RULE_BOOLEAN", "RULE_ML_COMMENT", "RULE_SL_COMMENT", "RULE_WS", "RULE_ANY_OTHER", "'model'", "'{'", "'}'", "'attribute'", "':='", "'protocol'", "'incoming'", "'outgoing'", "'('", "')'", "','", "'capsule'", "'external'", "'operation'", "'timerPort'", "'logPort'", "'port'", "':'", "'connector'", "'and'", "'.'", "'capsuleInstance'", "'stateMachine'", "'state'", "'entry'", "'exit'", "'sub'", "'transition'", "'->'", "'guard'", "'triggeredBy'", "'or'", "'timeout'", "'action'", "'while'", "'if'", "'else '", "'return'", "'var'", "'send'", "'inform'", "'in'", "'noop'", "'call'", "'log'", "'with'", "'choose'", "'flip'", "'^'", "'||'", "'&&'", "'<='", "'<'", "'>='", "'>'", "'=='", "'!='", "'+'", "'-'", "'*'", "'/'", "'%'", "'!'", "'bool'", "'int'", "'root'", "'void'", "'~'", "'final'", "'initial'"
};
public static final int T__50=50;
public static final int RULE_BOOLEAN=7;
public static final int T__19=19;
public static final int T__15=15;
public static final int T__59=59;
public static final int T__16=16;
public static final int T__17=17;
public static final int T__18=18;
public static final int T__55=55;
public static final int T__12=12;
public static final int T__56=56;
public static final int T__13=13;
public static final int T__57=57;
public static final int T__14=14;
public static final int T__58=58;
public static final int T__51=51;
public static final int T__52=52;
public static final int T__53=53;
public static final int T__54=54;
public static final int T__60=60;
public static final int T__61=61;
public static final int RULE_ID=4;
public static final int T__26=26;
public static final int T__27=27;
public static final int T__28=28;
public static final int RULE_INT=6;
public static final int T__29=29;
public static final int T__22=22;
public static final int T__66=66;
public static final int RULE_ML_COMMENT=8;
public static final int T__23=23;
public static final int T__67=67;
public static final int T__24=24;
public static final int T__68=68;
public static final int T__25=25;
public static final int T__69=69;
public static final int T__62=62;
public static final int T__63=63;
public static final int T__20=20;
public static final int T__64=64;
public static final int T__21=21;
public static final int T__65=65;
public static final int T__70=70;
public static final int T__71=71;
public static final int T__72=72;
public static final int RULE_STRING=5;
public static final int RULE_SL_COMMENT=9;
public static final int T__37=37;
public static final int T__38=38;
public static final int T__39=39;
public static final int T__33=33;
public static final int T__77=77;
public static final int T__34=34;
public static final int T__78=78;
public static final int T__35=35;
public static final int T__79=79;
public static final int T__36=36;
public static final int T__73=73;
public static final int EOF=-1;
public static final int T__30=30;
public static final int T__74=74;
public static final int T__31=31;
public static final int T__75=75;
public static final int T__32=32;
public static final int T__76=76;
public static final int T__80=80;
public static final int T__81=81;
public static final int RULE_WS=10;
public static final int RULE_ANY_OTHER=11;
public static final int T__48=48;
public static final int T__49=49;
public static final int T__44=44;
public static final int T__45=45;
public static final int T__46=46;
public static final int T__47=47;
public static final int T__40=40;
public static final int T__41=41;
public static final int T__42=42;
public static final int T__43=43;
// delegates
// delegators
public InternalUrmlParser(TokenStream input) {
this(input, new RecognizerSharedState());
}
public InternalUrmlParser(TokenStream input, RecognizerSharedState state) {
super(input, state);
}
public String[] getTokenNames() { return InternalUrmlParser.tokenNames; }
public String getGrammarFileName() { return "InternalUrml.g"; }
private UrmlGrammarAccess grammarAccess;
public void setGrammarAccess(UrmlGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
@Override
protected Grammar getGrammar() {
return grammarAccess.getGrammar();
}
@Override
protected String getValueForTokenName(String tokenName) {
return tokenName;
}
// $ANTLR start "entryRuleModel"
// InternalUrml.g:61:1: entryRuleModel : ruleModel EOF ;
public final void entryRuleModel() throws RecognitionException {
try {
// InternalUrml.g:62:1: ( ruleModel EOF )
// InternalUrml.g:63:1: ruleModel EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelRule());
}
pushFollow(FOLLOW_1);
ruleModel();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleModel"
// $ANTLR start "ruleModel"
// InternalUrml.g:70:1: ruleModel : ( ( rule__Model__Group__0 ) ) ;
public final void ruleModel() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:74:2: ( ( ( rule__Model__Group__0 ) ) )
// InternalUrml.g:75:1: ( ( rule__Model__Group__0 ) )
{
// InternalUrml.g:75:1: ( ( rule__Model__Group__0 ) )
// InternalUrml.g:76:1: ( rule__Model__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getGroup());
}
// InternalUrml.g:77:1: ( rule__Model__Group__0 )
// InternalUrml.g:77:2: rule__Model__Group__0
{
pushFollow(FOLLOW_2);
rule__Model__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleModel"
// $ANTLR start "entryRuleLocalVar"
// InternalUrml.g:89:1: entryRuleLocalVar : ruleLocalVar EOF ;
public final void entryRuleLocalVar() throws RecognitionException {
try {
// InternalUrml.g:90:1: ( ruleLocalVar EOF )
// InternalUrml.g:91:1: ruleLocalVar EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarRule());
}
pushFollow(FOLLOW_1);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleLocalVar"
// $ANTLR start "ruleLocalVar"
// InternalUrml.g:98:1: ruleLocalVar : ( ( rule__LocalVar__Group__0 ) ) ;
public final void ruleLocalVar() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:102:2: ( ( ( rule__LocalVar__Group__0 ) ) )
// InternalUrml.g:103:1: ( ( rule__LocalVar__Group__0 ) )
{
// InternalUrml.g:103:1: ( ( rule__LocalVar__Group__0 ) )
// InternalUrml.g:104:1: ( rule__LocalVar__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getGroup());
}
// InternalUrml.g:105:1: ( rule__LocalVar__Group__0 )
// InternalUrml.g:105:2: rule__LocalVar__Group__0
{
pushFollow(FOLLOW_2);
rule__LocalVar__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleLocalVar"
// $ANTLR start "entryRuleAttribute"
// InternalUrml.g:117:1: entryRuleAttribute : ruleAttribute EOF ;
public final void entryRuleAttribute() throws RecognitionException {
try {
// InternalUrml.g:118:1: ( ruleAttribute EOF )
// InternalUrml.g:119:1: ruleAttribute EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeRule());
}
pushFollow(FOLLOW_1);
ruleAttribute();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleAttribute"
// $ANTLR start "ruleAttribute"
// InternalUrml.g:126:1: ruleAttribute : ( ( rule__Attribute__Group__0 ) ) ;
public final void ruleAttribute() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:130:2: ( ( ( rule__Attribute__Group__0 ) ) )
// InternalUrml.g:131:1: ( ( rule__Attribute__Group__0 ) )
{
// InternalUrml.g:131:1: ( ( rule__Attribute__Group__0 ) )
// InternalUrml.g:132:1: ( rule__Attribute__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getGroup());
}
// InternalUrml.g:133:1: ( rule__Attribute__Group__0 )
// InternalUrml.g:133:2: rule__Attribute__Group__0
{
pushFollow(FOLLOW_2);
rule__Attribute__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleAttribute"
// $ANTLR start "entryRuleProtocol"
// InternalUrml.g:145:1: entryRuleProtocol : ruleProtocol EOF ;
public final void entryRuleProtocol() throws RecognitionException {
try {
// InternalUrml.g:146:1: ( ruleProtocol EOF )
// InternalUrml.g:147:1: ruleProtocol EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolRule());
}
pushFollow(FOLLOW_1);
ruleProtocol();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleProtocol"
// $ANTLR start "ruleProtocol"
// InternalUrml.g:154:1: ruleProtocol : ( ( rule__Protocol__Group__0 ) ) ;
public final void ruleProtocol() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:158:2: ( ( ( rule__Protocol__Group__0 ) ) )
// InternalUrml.g:159:1: ( ( rule__Protocol__Group__0 ) )
{
// InternalUrml.g:159:1: ( ( rule__Protocol__Group__0 ) )
// InternalUrml.g:160:1: ( rule__Protocol__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getGroup());
}
// InternalUrml.g:161:1: ( rule__Protocol__Group__0 )
// InternalUrml.g:161:2: rule__Protocol__Group__0
{
pushFollow(FOLLOW_2);
rule__Protocol__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleProtocol"
// $ANTLR start "entryRuleSignal"
// InternalUrml.g:173:1: entryRuleSignal : ruleSignal EOF ;
public final void entryRuleSignal() throws RecognitionException {
try {
// InternalUrml.g:174:1: ( ruleSignal EOF )
// InternalUrml.g:175:1: ruleSignal EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalRule());
}
pushFollow(FOLLOW_1);
ruleSignal();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleSignal"
// $ANTLR start "ruleSignal"
// InternalUrml.g:182:1: ruleSignal : ( ( rule__Signal__Group__0 ) ) ;
public final void ruleSignal() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:186:2: ( ( ( rule__Signal__Group__0 ) ) )
// InternalUrml.g:187:1: ( ( rule__Signal__Group__0 ) )
{
// InternalUrml.g:187:1: ( ( rule__Signal__Group__0 ) )
// InternalUrml.g:188:1: ( rule__Signal__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getGroup());
}
// InternalUrml.g:189:1: ( rule__Signal__Group__0 )
// InternalUrml.g:189:2: rule__Signal__Group__0
{
pushFollow(FOLLOW_2);
rule__Signal__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleSignal"
// $ANTLR start "entryRuleCapsule"
// InternalUrml.g:201:1: entryRuleCapsule : ruleCapsule EOF ;
public final void entryRuleCapsule() throws RecognitionException {
try {
// InternalUrml.g:202:1: ( ruleCapsule EOF )
// InternalUrml.g:203:1: ruleCapsule EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleRule());
}
pushFollow(FOLLOW_1);
ruleCapsule();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleCapsule"
// $ANTLR start "ruleCapsule"
// InternalUrml.g:210:1: ruleCapsule : ( ( rule__Capsule__Group__0 ) ) ;
public final void ruleCapsule() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:214:2: ( ( ( rule__Capsule__Group__0 ) ) )
// InternalUrml.g:215:1: ( ( rule__Capsule__Group__0 ) )
{
// InternalUrml.g:215:1: ( ( rule__Capsule__Group__0 ) )
// InternalUrml.g:216:1: ( rule__Capsule__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getGroup());
}
// InternalUrml.g:217:1: ( rule__Capsule__Group__0 )
// InternalUrml.g:217:2: rule__Capsule__Group__0
{
pushFollow(FOLLOW_2);
rule__Capsule__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleCapsule"
// $ANTLR start "entryRuleOperation"
// InternalUrml.g:229:1: entryRuleOperation : ruleOperation EOF ;
public final void entryRuleOperation() throws RecognitionException {
try {
// InternalUrml.g:230:1: ( ruleOperation EOF )
// InternalUrml.g:231:1: ruleOperation EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationRule());
}
pushFollow(FOLLOW_1);
ruleOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleOperation"
// $ANTLR start "ruleOperation"
// InternalUrml.g:238:1: ruleOperation : ( ( rule__Operation__Group__0 ) ) ;
public final void ruleOperation() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:242:2: ( ( ( rule__Operation__Group__0 ) ) )
// InternalUrml.g:243:1: ( ( rule__Operation__Group__0 ) )
{
// InternalUrml.g:243:1: ( ( rule__Operation__Group__0 ) )
// InternalUrml.g:244:1: ( rule__Operation__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getGroup());
}
// InternalUrml.g:245:1: ( rule__Operation__Group__0 )
// InternalUrml.g:245:2: rule__Operation__Group__0
{
pushFollow(FOLLOW_2);
rule__Operation__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleOperation"
// $ANTLR start "entryRuleTimerPort"
// InternalUrml.g:257:1: entryRuleTimerPort : ruleTimerPort EOF ;
public final void entryRuleTimerPort() throws RecognitionException {
try {
// InternalUrml.g:258:1: ( ruleTimerPort EOF )
// InternalUrml.g:259:1: ruleTimerPort EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTimerPortRule());
}
pushFollow(FOLLOW_1);
ruleTimerPort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTimerPortRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleTimerPort"
// $ANTLR start "ruleTimerPort"
// InternalUrml.g:266:1: ruleTimerPort : ( ( rule__TimerPort__Group__0 ) ) ;
public final void ruleTimerPort() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:270:2: ( ( ( rule__TimerPort__Group__0 ) ) )
// InternalUrml.g:271:1: ( ( rule__TimerPort__Group__0 ) )
{
// InternalUrml.g:271:1: ( ( rule__TimerPort__Group__0 ) )
// InternalUrml.g:272:1: ( rule__TimerPort__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTimerPortAccess().getGroup());
}
// InternalUrml.g:273:1: ( rule__TimerPort__Group__0 )
// InternalUrml.g:273:2: rule__TimerPort__Group__0
{
pushFollow(FOLLOW_2);
rule__TimerPort__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTimerPortAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleTimerPort"
// $ANTLR start "entryRuleLogPort"
// InternalUrml.g:285:1: entryRuleLogPort : ruleLogPort EOF ;
public final void entryRuleLogPort() throws RecognitionException {
try {
// InternalUrml.g:286:1: ( ruleLogPort EOF )
// InternalUrml.g:287:1: ruleLogPort EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogPortRule());
}
pushFollow(FOLLOW_1);
ruleLogPort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogPortRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleLogPort"
// $ANTLR start "ruleLogPort"
// InternalUrml.g:294:1: ruleLogPort : ( ( rule__LogPort__Group__0 ) ) ;
public final void ruleLogPort() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:298:2: ( ( ( rule__LogPort__Group__0 ) ) )
// InternalUrml.g:299:1: ( ( rule__LogPort__Group__0 ) )
{
// InternalUrml.g:299:1: ( ( rule__LogPort__Group__0 ) )
// InternalUrml.g:300:1: ( rule__LogPort__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogPortAccess().getGroup());
}
// InternalUrml.g:301:1: ( rule__LogPort__Group__0 )
// InternalUrml.g:301:2: rule__LogPort__Group__0
{
pushFollow(FOLLOW_2);
rule__LogPort__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLogPortAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleLogPort"
// $ANTLR start "entryRulePort"
// InternalUrml.g:313:1: entryRulePort : rulePort EOF ;
public final void entryRulePort() throws RecognitionException {
try {
// InternalUrml.g:314:1: ( rulePort EOF )
// InternalUrml.g:315:1: rulePort EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortRule());
}
pushFollow(FOLLOW_1);
rulePort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPortRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRulePort"
// $ANTLR start "rulePort"
// InternalUrml.g:322:1: rulePort : ( ( rule__Port__Group__0 ) ) ;
public final void rulePort() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:326:2: ( ( ( rule__Port__Group__0 ) ) )
// InternalUrml.g:327:1: ( ( rule__Port__Group__0 ) )
{
// InternalUrml.g:327:1: ( ( rule__Port__Group__0 ) )
// InternalUrml.g:328:1: ( rule__Port__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getGroup());
}
// InternalUrml.g:329:1: ( rule__Port__Group__0 )
// InternalUrml.g:329:2: rule__Port__Group__0
{
pushFollow(FOLLOW_2);
rule__Port__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rulePort"
// $ANTLR start "entryRuleConnector"
// InternalUrml.g:341:1: entryRuleConnector : ruleConnector EOF ;
public final void entryRuleConnector() throws RecognitionException {
try {
// InternalUrml.g:342:1: ( ruleConnector EOF )
// InternalUrml.g:343:1: ruleConnector EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorRule());
}
pushFollow(FOLLOW_1);
ruleConnector();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleConnector"
// $ANTLR start "ruleConnector"
// InternalUrml.g:350:1: ruleConnector : ( ( rule__Connector__Group__0 ) ) ;
public final void ruleConnector() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:354:2: ( ( ( rule__Connector__Group__0 ) ) )
// InternalUrml.g:355:1: ( ( rule__Connector__Group__0 ) )
{
// InternalUrml.g:355:1: ( ( rule__Connector__Group__0 ) )
// InternalUrml.g:356:1: ( rule__Connector__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getGroup());
}
// InternalUrml.g:357:1: ( rule__Connector__Group__0 )
// InternalUrml.g:357:2: rule__Connector__Group__0
{
pushFollow(FOLLOW_2);
rule__Connector__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleConnector"
// $ANTLR start "entryRuleCapsuleInst"
// InternalUrml.g:369:1: entryRuleCapsuleInst : ruleCapsuleInst EOF ;
public final void entryRuleCapsuleInst() throws RecognitionException {
try {
// InternalUrml.g:370:1: ( ruleCapsuleInst EOF )
// InternalUrml.g:371:1: ruleCapsuleInst EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstRule());
}
pushFollow(FOLLOW_1);
ruleCapsuleInst();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleCapsuleInst"
// $ANTLR start "ruleCapsuleInst"
// InternalUrml.g:378:1: ruleCapsuleInst : ( ( rule__CapsuleInst__Group__0 ) ) ;
public final void ruleCapsuleInst() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:382:2: ( ( ( rule__CapsuleInst__Group__0 ) ) )
// InternalUrml.g:383:1: ( ( rule__CapsuleInst__Group__0 ) )
{
// InternalUrml.g:383:1: ( ( rule__CapsuleInst__Group__0 ) )
// InternalUrml.g:384:1: ( rule__CapsuleInst__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getGroup());
}
// InternalUrml.g:385:1: ( rule__CapsuleInst__Group__0 )
// InternalUrml.g:385:2: rule__CapsuleInst__Group__0
{
pushFollow(FOLLOW_2);
rule__CapsuleInst__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleCapsuleInst"
// $ANTLR start "entryRuleStateMachine"
// InternalUrml.g:397:1: entryRuleStateMachine : ruleStateMachine EOF ;
public final void entryRuleStateMachine() throws RecognitionException {
try {
// InternalUrml.g:398:1: ( ruleStateMachine EOF )
// InternalUrml.g:399:1: ruleStateMachine EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineRule());
}
pushFollow(FOLLOW_1);
ruleStateMachine();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleStateMachine"
// $ANTLR start "ruleStateMachine"
// InternalUrml.g:406:1: ruleStateMachine : ( ( rule__StateMachine__Group__0 ) ) ;
public final void ruleStateMachine() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:410:2: ( ( ( rule__StateMachine__Group__0 ) ) )
// InternalUrml.g:411:1: ( ( rule__StateMachine__Group__0 ) )
{
// InternalUrml.g:411:1: ( ( rule__StateMachine__Group__0 ) )
// InternalUrml.g:412:1: ( rule__StateMachine__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getGroup());
}
// InternalUrml.g:413:1: ( rule__StateMachine__Group__0 )
// InternalUrml.g:413:2: rule__StateMachine__Group__0
{
pushFollow(FOLLOW_2);
rule__StateMachine__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleStateMachine"
// $ANTLR start "entryRuleState_"
// InternalUrml.g:425:1: entryRuleState_ : ruleState_ EOF ;
public final void entryRuleState_() throws RecognitionException {
try {
// InternalUrml.g:426:1: ( ruleState_ EOF )
// InternalUrml.g:427:1: ruleState_ EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Rule());
}
pushFollow(FOLLOW_1);
ruleState_();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Rule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleState_"
// $ANTLR start "ruleState_"
// InternalUrml.g:434:1: ruleState_ : ( ( rule__State___Group__0 ) ) ;
public final void ruleState_() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:438:2: ( ( ( rule__State___Group__0 ) ) )
// InternalUrml.g:439:1: ( ( rule__State___Group__0 ) )
{
// InternalUrml.g:439:1: ( ( rule__State___Group__0 ) )
// InternalUrml.g:440:1: ( rule__State___Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getGroup());
}
// InternalUrml.g:441:1: ( rule__State___Group__0 )
// InternalUrml.g:441:2: rule__State___Group__0
{
pushFollow(FOLLOW_2);
rule__State___Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleState_"
// $ANTLR start "entryRuleTransition"
// InternalUrml.g:453:1: entryRuleTransition : ruleTransition EOF ;
public final void entryRuleTransition() throws RecognitionException {
try {
// InternalUrml.g:454:1: ( ruleTransition EOF )
// InternalUrml.g:455:1: ruleTransition EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionRule());
}
pushFollow(FOLLOW_1);
ruleTransition();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleTransition"
// $ANTLR start "ruleTransition"
// InternalUrml.g:462:1: ruleTransition : ( ( rule__Transition__Group__0 ) ) ;
public final void ruleTransition() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:466:2: ( ( ( rule__Transition__Group__0 ) ) )
// InternalUrml.g:467:1: ( ( rule__Transition__Group__0 ) )
{
// InternalUrml.g:467:1: ( ( rule__Transition__Group__0 ) )
// InternalUrml.g:468:1: ( rule__Transition__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup());
}
// InternalUrml.g:469:1: ( rule__Transition__Group__0 )
// InternalUrml.g:469:2: rule__Transition__Group__0
{
pushFollow(FOLLOW_2);
rule__Transition__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleTransition"
// $ANTLR start "entryRuleTrigger_in"
// InternalUrml.g:481:1: entryRuleTrigger_in : ruleTrigger_in EOF ;
public final void entryRuleTrigger_in() throws RecognitionException {
try {
// InternalUrml.g:482:1: ( ruleTrigger_in EOF )
// InternalUrml.g:483:1: ruleTrigger_in EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inRule());
}
pushFollow(FOLLOW_1);
ruleTrigger_in();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleTrigger_in"
// $ANTLR start "ruleTrigger_in"
// InternalUrml.g:490:1: ruleTrigger_in : ( ( rule__Trigger_in__Group__0 ) ) ;
public final void ruleTrigger_in() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:494:2: ( ( ( rule__Trigger_in__Group__0 ) ) )
// InternalUrml.g:495:1: ( ( rule__Trigger_in__Group__0 ) )
{
// InternalUrml.g:495:1: ( ( rule__Trigger_in__Group__0 ) )
// InternalUrml.g:496:1: ( rule__Trigger_in__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getGroup());
}
// InternalUrml.g:497:1: ( rule__Trigger_in__Group__0 )
// InternalUrml.g:497:2: rule__Trigger_in__Group__0
{
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleTrigger_in"
// $ANTLR start "entryRuleIncomingVariable"
// InternalUrml.g:509:1: entryRuleIncomingVariable : ruleIncomingVariable EOF ;
public final void entryRuleIncomingVariable() throws RecognitionException {
try {
// InternalUrml.g:510:1: ( ruleIncomingVariable EOF )
// InternalUrml.g:511:1: ruleIncomingVariable EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableRule());
}
pushFollow(FOLLOW_1);
ruleIncomingVariable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIncomingVariable"
// $ANTLR start "ruleIncomingVariable"
// InternalUrml.g:518:1: ruleIncomingVariable : ( ( rule__IncomingVariable__Group__0 ) ) ;
public final void ruleIncomingVariable() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:522:2: ( ( ( rule__IncomingVariable__Group__0 ) ) )
// InternalUrml.g:523:1: ( ( rule__IncomingVariable__Group__0 ) )
{
// InternalUrml.g:523:1: ( ( rule__IncomingVariable__Group__0 ) )
// InternalUrml.g:524:1: ( rule__IncomingVariable__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getGroup());
}
// InternalUrml.g:525:1: ( rule__IncomingVariable__Group__0 )
// InternalUrml.g:525:2: rule__IncomingVariable__Group__0
{
pushFollow(FOLLOW_2);
rule__IncomingVariable__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIncomingVariable"
// $ANTLR start "entryRuleTrigger_out"
// InternalUrml.g:537:1: entryRuleTrigger_out : ruleTrigger_out EOF ;
public final void entryRuleTrigger_out() throws RecognitionException {
try {
// InternalUrml.g:538:1: ( ruleTrigger_out EOF )
// InternalUrml.g:539:1: ruleTrigger_out EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outRule());
}
pushFollow(FOLLOW_1);
ruleTrigger_out();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleTrigger_out"
// $ANTLR start "ruleTrigger_out"
// InternalUrml.g:546:1: ruleTrigger_out : ( ( rule__Trigger_out__Group__0 ) ) ;
public final void ruleTrigger_out() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:550:2: ( ( ( rule__Trigger_out__Group__0 ) ) )
// InternalUrml.g:551:1: ( ( rule__Trigger_out__Group__0 ) )
{
// InternalUrml.g:551:1: ( ( rule__Trigger_out__Group__0 ) )
// InternalUrml.g:552:1: ( rule__Trigger_out__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getGroup());
}
// InternalUrml.g:553:1: ( rule__Trigger_out__Group__0 )
// InternalUrml.g:553:2: rule__Trigger_out__Group__0
{
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleTrigger_out"
// $ANTLR start "entryRuleOperationCode"
// InternalUrml.g:565:1: entryRuleOperationCode : ruleOperationCode EOF ;
public final void entryRuleOperationCode() throws RecognitionException {
try {
// InternalUrml.g:566:1: ( ruleOperationCode EOF )
// InternalUrml.g:567:1: ruleOperationCode EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationCodeRule());
}
pushFollow(FOLLOW_1);
ruleOperationCode();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationCodeRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleOperationCode"
// $ANTLR start "ruleOperationCode"
// InternalUrml.g:574:1: ruleOperationCode : ( ( ( rule__OperationCode__StatementsAssignment ) ) ( ( rule__OperationCode__StatementsAssignment )* ) ) ;
public final void ruleOperationCode() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:578:2: ( ( ( ( rule__OperationCode__StatementsAssignment ) ) ( ( rule__OperationCode__StatementsAssignment )* ) ) )
// InternalUrml.g:579:1: ( ( ( rule__OperationCode__StatementsAssignment ) ) ( ( rule__OperationCode__StatementsAssignment )* ) )
{
// InternalUrml.g:579:1: ( ( ( rule__OperationCode__StatementsAssignment ) ) ( ( rule__OperationCode__StatementsAssignment )* ) )
// InternalUrml.g:580:1: ( ( rule__OperationCode__StatementsAssignment ) ) ( ( rule__OperationCode__StatementsAssignment )* )
{
// InternalUrml.g:580:1: ( ( rule__OperationCode__StatementsAssignment ) )
// InternalUrml.g:581:1: ( rule__OperationCode__StatementsAssignment )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationCodeAccess().getStatementsAssignment());
}
// InternalUrml.g:582:1: ( rule__OperationCode__StatementsAssignment )
// InternalUrml.g:582:2: rule__OperationCode__StatementsAssignment
{
pushFollow(FOLLOW_3);
rule__OperationCode__StatementsAssignment();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationCodeAccess().getStatementsAssignment());
}
}
// InternalUrml.g:585:1: ( ( rule__OperationCode__StatementsAssignment )* )
// InternalUrml.g:586:1: ( rule__OperationCode__StatementsAssignment )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationCodeAccess().getStatementsAssignment());
}
// InternalUrml.g:587:1: ( rule__OperationCode__StatementsAssignment )*
loop1:
do {
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==RULE_ID||(LA1_0>=46 && LA1_0<=47)||(LA1_0>=49 && LA1_0<=52)||(LA1_0>=54 && LA1_0<=56)||(LA1_0>=58 && LA1_0<=59)) ) {
alt1=1;
}
switch (alt1) {
case 1 :
// InternalUrml.g:587:2: rule__OperationCode__StatementsAssignment
{
pushFollow(FOLLOW_3);
rule__OperationCode__StatementsAssignment();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop1;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationCodeAccess().getStatementsAssignment());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleOperationCode"
// $ANTLR start "entryRuleStatementOperation"
// InternalUrml.g:600:1: entryRuleStatementOperation : ruleStatementOperation EOF ;
public final void entryRuleStatementOperation() throws RecognitionException {
try {
// InternalUrml.g:601:1: ( ruleStatementOperation EOF )
// InternalUrml.g:602:1: ruleStatementOperation EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationRule());
}
pushFollow(FOLLOW_1);
ruleStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleStatementOperation"
// $ANTLR start "ruleStatementOperation"
// InternalUrml.g:609:1: ruleStatementOperation : ( ( rule__StatementOperation__Alternatives ) ) ;
public final void ruleStatementOperation() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:613:2: ( ( ( rule__StatementOperation__Alternatives ) ) )
// InternalUrml.g:614:1: ( ( rule__StatementOperation__Alternatives ) )
{
// InternalUrml.g:614:1: ( ( rule__StatementOperation__Alternatives ) )
// InternalUrml.g:615:1: ( rule__StatementOperation__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getAlternatives());
}
// InternalUrml.g:616:1: ( rule__StatementOperation__Alternatives )
// InternalUrml.g:616:2: rule__StatementOperation__Alternatives
{
pushFollow(FOLLOW_2);
rule__StatementOperation__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleStatementOperation"
// $ANTLR start "entryRuleWhileLoopOperation"
// InternalUrml.g:628:1: entryRuleWhileLoopOperation : ruleWhileLoopOperation EOF ;
public final void entryRuleWhileLoopOperation() throws RecognitionException {
try {
// InternalUrml.g:629:1: ( ruleWhileLoopOperation EOF )
// InternalUrml.g:630:1: ruleWhileLoopOperation EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationRule());
}
pushFollow(FOLLOW_1);
ruleWhileLoopOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleWhileLoopOperation"
// $ANTLR start "ruleWhileLoopOperation"
// InternalUrml.g:637:1: ruleWhileLoopOperation : ( ( rule__WhileLoopOperation__Group__0 ) ) ;
public final void ruleWhileLoopOperation() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:641:2: ( ( ( rule__WhileLoopOperation__Group__0 ) ) )
// InternalUrml.g:642:1: ( ( rule__WhileLoopOperation__Group__0 ) )
{
// InternalUrml.g:642:1: ( ( rule__WhileLoopOperation__Group__0 ) )
// InternalUrml.g:643:1: ( rule__WhileLoopOperation__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getGroup());
}
// InternalUrml.g:644:1: ( rule__WhileLoopOperation__Group__0 )
// InternalUrml.g:644:2: rule__WhileLoopOperation__Group__0
{
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleWhileLoopOperation"
// $ANTLR start "entryRuleIfStatementOperation"
// InternalUrml.g:656:1: entryRuleIfStatementOperation : ruleIfStatementOperation EOF ;
public final void entryRuleIfStatementOperation() throws RecognitionException {
try {
// InternalUrml.g:657:1: ( ruleIfStatementOperation EOF )
// InternalUrml.g:658:1: ruleIfStatementOperation EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationRule());
}
pushFollow(FOLLOW_1);
ruleIfStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIfStatementOperation"
// $ANTLR start "ruleIfStatementOperation"
// InternalUrml.g:665:1: ruleIfStatementOperation : ( ( rule__IfStatementOperation__Group__0 ) ) ;
public final void ruleIfStatementOperation() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:669:2: ( ( ( rule__IfStatementOperation__Group__0 ) ) )
// InternalUrml.g:670:1: ( ( rule__IfStatementOperation__Group__0 ) )
{
// InternalUrml.g:670:1: ( ( rule__IfStatementOperation__Group__0 ) )
// InternalUrml.g:671:1: ( rule__IfStatementOperation__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getGroup());
}
// InternalUrml.g:672:1: ( rule__IfStatementOperation__Group__0 )
// InternalUrml.g:672:2: rule__IfStatementOperation__Group__0
{
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIfStatementOperation"
// $ANTLR start "entryRuleReturnStatement"
// InternalUrml.g:684:1: entryRuleReturnStatement : ruleReturnStatement EOF ;
public final void entryRuleReturnStatement() throws RecognitionException {
try {
// InternalUrml.g:685:1: ( ruleReturnStatement EOF )
// InternalUrml.g:686:1: ruleReturnStatement EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getReturnStatementRule());
}
pushFollow(FOLLOW_1);
ruleReturnStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getReturnStatementRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleReturnStatement"
// $ANTLR start "ruleReturnStatement"
// InternalUrml.g:693:1: ruleReturnStatement : ( ( rule__ReturnStatement__Group__0 ) ) ;
public final void ruleReturnStatement() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:697:2: ( ( ( rule__ReturnStatement__Group__0 ) ) )
// InternalUrml.g:698:1: ( ( rule__ReturnStatement__Group__0 ) )
{
// InternalUrml.g:698:1: ( ( rule__ReturnStatement__Group__0 ) )
// InternalUrml.g:699:1: ( rule__ReturnStatement__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getReturnStatementAccess().getGroup());
}
// InternalUrml.g:700:1: ( rule__ReturnStatement__Group__0 )
// InternalUrml.g:700:2: rule__ReturnStatement__Group__0
{
pushFollow(FOLLOW_2);
rule__ReturnStatement__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getReturnStatementAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleReturnStatement"
// $ANTLR start "entryRuleActionCode"
// InternalUrml.g:712:1: entryRuleActionCode : ruleActionCode EOF ;
public final void entryRuleActionCode() throws RecognitionException {
try {
// InternalUrml.g:713:1: ( ruleActionCode EOF )
// InternalUrml.g:714:1: ruleActionCode EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getActionCodeRule());
}
pushFollow(FOLLOW_1);
ruleActionCode();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getActionCodeRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleActionCode"
// $ANTLR start "ruleActionCode"
// InternalUrml.g:721:1: ruleActionCode : ( ( ( rule__ActionCode__StatementsAssignment ) ) ( ( rule__ActionCode__StatementsAssignment )* ) ) ;
public final void ruleActionCode() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:725:2: ( ( ( ( rule__ActionCode__StatementsAssignment ) ) ( ( rule__ActionCode__StatementsAssignment )* ) ) )
// InternalUrml.g:726:1: ( ( ( rule__ActionCode__StatementsAssignment ) ) ( ( rule__ActionCode__StatementsAssignment )* ) )
{
// InternalUrml.g:726:1: ( ( ( rule__ActionCode__StatementsAssignment ) ) ( ( rule__ActionCode__StatementsAssignment )* ) )
// InternalUrml.g:727:1: ( ( rule__ActionCode__StatementsAssignment ) ) ( ( rule__ActionCode__StatementsAssignment )* )
{
// InternalUrml.g:727:1: ( ( rule__ActionCode__StatementsAssignment ) )
// InternalUrml.g:728:1: ( rule__ActionCode__StatementsAssignment )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getActionCodeAccess().getStatementsAssignment());
}
// InternalUrml.g:729:1: ( rule__ActionCode__StatementsAssignment )
// InternalUrml.g:729:2: rule__ActionCode__StatementsAssignment
{
pushFollow(FOLLOW_3);
rule__ActionCode__StatementsAssignment();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getActionCodeAccess().getStatementsAssignment());
}
}
// InternalUrml.g:732:1: ( ( rule__ActionCode__StatementsAssignment )* )
// InternalUrml.g:733:1: ( rule__ActionCode__StatementsAssignment )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getActionCodeAccess().getStatementsAssignment());
}
// InternalUrml.g:734:1: ( rule__ActionCode__StatementsAssignment )*
loop2:
do {
int alt2=2;
int LA2_0 = input.LA(1);
if ( (LA2_0==RULE_ID||(LA2_0>=46 && LA2_0<=47)||(LA2_0>=50 && LA2_0<=52)||(LA2_0>=54 && LA2_0<=56)||(LA2_0>=58 && LA2_0<=59)) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// InternalUrml.g:734:2: rule__ActionCode__StatementsAssignment
{
pushFollow(FOLLOW_3);
rule__ActionCode__StatementsAssignment();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop2;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getActionCodeAccess().getStatementsAssignment());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleActionCode"
// $ANTLR start "entryRuleStatement"
// InternalUrml.g:747:1: entryRuleStatement : ruleStatement EOF ;
public final void entryRuleStatement() throws RecognitionException {
try {
// InternalUrml.g:748:1: ( ruleStatement EOF )
// InternalUrml.g:749:1: ruleStatement EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementRule());
}
pushFollow(FOLLOW_1);
ruleStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleStatement"
// $ANTLR start "ruleStatement"
// InternalUrml.g:756:1: ruleStatement : ( ( rule__Statement__Alternatives ) ) ;
public final void ruleStatement() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:760:2: ( ( ( rule__Statement__Alternatives ) ) )
// InternalUrml.g:761:1: ( ( rule__Statement__Alternatives ) )
{
// InternalUrml.g:761:1: ( ( rule__Statement__Alternatives ) )
// InternalUrml.g:762:1: ( rule__Statement__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getAlternatives());
}
// InternalUrml.g:763:1: ( rule__Statement__Alternatives )
// InternalUrml.g:763:2: rule__Statement__Alternatives
{
pushFollow(FOLLOW_2);
rule__Statement__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleStatement"
// $ANTLR start "entryRuleVariable"
// InternalUrml.g:775:1: entryRuleVariable : ruleVariable EOF ;
public final void entryRuleVariable() throws RecognitionException {
try {
// InternalUrml.g:776:1: ( ruleVariable EOF )
// InternalUrml.g:777:1: ruleVariable EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableRule());
}
pushFollow(FOLLOW_1);
ruleVariable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleVariable"
// $ANTLR start "ruleVariable"
// InternalUrml.g:784:1: ruleVariable : ( ( rule__Variable__Group__0 ) ) ;
public final void ruleVariable() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:788:2: ( ( ( rule__Variable__Group__0 ) ) )
// InternalUrml.g:789:1: ( ( rule__Variable__Group__0 ) )
{
// InternalUrml.g:789:1: ( ( rule__Variable__Group__0 ) )
// InternalUrml.g:790:1: ( rule__Variable__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getGroup());
}
// InternalUrml.g:791:1: ( rule__Variable__Group__0 )
// InternalUrml.g:791:2: rule__Variable__Group__0
{
pushFollow(FOLLOW_2);
rule__Variable__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleVariable"
// $ANTLR start "entryRuleSendTrigger"
// InternalUrml.g:803:1: entryRuleSendTrigger : ruleSendTrigger EOF ;
public final void entryRuleSendTrigger() throws RecognitionException {
try {
// InternalUrml.g:804:1: ( ruleSendTrigger EOF )
// InternalUrml.g:805:1: ruleSendTrigger EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerRule());
}
pushFollow(FOLLOW_1);
ruleSendTrigger();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleSendTrigger"
// $ANTLR start "ruleSendTrigger"
// InternalUrml.g:812:1: ruleSendTrigger : ( ( rule__SendTrigger__Group__0 ) ) ;
public final void ruleSendTrigger() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:816:2: ( ( ( rule__SendTrigger__Group__0 ) ) )
// InternalUrml.g:817:1: ( ( rule__SendTrigger__Group__0 ) )
{
// InternalUrml.g:817:1: ( ( rule__SendTrigger__Group__0 ) )
// InternalUrml.g:818:1: ( rule__SendTrigger__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getGroup());
}
// InternalUrml.g:819:1: ( rule__SendTrigger__Group__0 )
// InternalUrml.g:819:2: rule__SendTrigger__Group__0
{
pushFollow(FOLLOW_2);
rule__SendTrigger__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleSendTrigger"
// $ANTLR start "entryRuleInformTimer"
// InternalUrml.g:831:1: entryRuleInformTimer : ruleInformTimer EOF ;
public final void entryRuleInformTimer() throws RecognitionException {
try {
// InternalUrml.g:832:1: ( ruleInformTimer EOF )
// InternalUrml.g:833:1: ruleInformTimer EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerRule());
}
pushFollow(FOLLOW_1);
ruleInformTimer();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleInformTimer"
// $ANTLR start "ruleInformTimer"
// InternalUrml.g:840:1: ruleInformTimer : ( ( rule__InformTimer__Group__0 ) ) ;
public final void ruleInformTimer() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:844:2: ( ( ( rule__InformTimer__Group__0 ) ) )
// InternalUrml.g:845:1: ( ( rule__InformTimer__Group__0 ) )
{
// InternalUrml.g:845:1: ( ( rule__InformTimer__Group__0 ) )
// InternalUrml.g:846:1: ( rule__InformTimer__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getGroup());
}
// InternalUrml.g:847:1: ( rule__InformTimer__Group__0 )
// InternalUrml.g:847:2: rule__InformTimer__Group__0
{
pushFollow(FOLLOW_2);
rule__InformTimer__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleInformTimer"
// $ANTLR start "entryRuleNoOp"
// InternalUrml.g:859:1: entryRuleNoOp : ruleNoOp EOF ;
public final void entryRuleNoOp() throws RecognitionException {
try {
// InternalUrml.g:860:1: ( ruleNoOp EOF )
// InternalUrml.g:861:1: ruleNoOp EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNoOpRule());
}
pushFollow(FOLLOW_1);
ruleNoOp();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getNoOpRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleNoOp"
// $ANTLR start "ruleNoOp"
// InternalUrml.g:868:1: ruleNoOp : ( ( rule__NoOp__Group__0 ) ) ;
public final void ruleNoOp() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:872:2: ( ( ( rule__NoOp__Group__0 ) ) )
// InternalUrml.g:873:1: ( ( rule__NoOp__Group__0 ) )
{
// InternalUrml.g:873:1: ( ( rule__NoOp__Group__0 ) )
// InternalUrml.g:874:1: ( rule__NoOp__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNoOpAccess().getGroup());
}
// InternalUrml.g:875:1: ( rule__NoOp__Group__0 )
// InternalUrml.g:875:2: rule__NoOp__Group__0
{
pushFollow(FOLLOW_2);
rule__NoOp__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getNoOpAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleNoOp"
// $ANTLR start "entryRuleInvoke"
// InternalUrml.g:887:1: entryRuleInvoke : ruleInvoke EOF ;
public final void entryRuleInvoke() throws RecognitionException {
try {
// InternalUrml.g:888:1: ( ruleInvoke EOF )
// InternalUrml.g:889:1: ruleInvoke EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeRule());
}
pushFollow(FOLLOW_1);
ruleInvoke();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleInvoke"
// $ANTLR start "ruleInvoke"
// InternalUrml.g:896:1: ruleInvoke : ( ( rule__Invoke__Group__0 ) ) ;
public final void ruleInvoke() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:900:2: ( ( ( rule__Invoke__Group__0 ) ) )
// InternalUrml.g:901:1: ( ( rule__Invoke__Group__0 ) )
{
// InternalUrml.g:901:1: ( ( rule__Invoke__Group__0 ) )
// InternalUrml.g:902:1: ( rule__Invoke__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getGroup());
}
// InternalUrml.g:903:1: ( rule__Invoke__Group__0 )
// InternalUrml.g:903:2: rule__Invoke__Group__0
{
pushFollow(FOLLOW_2);
rule__Invoke__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleInvoke"
// $ANTLR start "entryRuleAssignment"
// InternalUrml.g:915:1: entryRuleAssignment : ruleAssignment EOF ;
public final void entryRuleAssignment() throws RecognitionException {
try {
// InternalUrml.g:916:1: ( ruleAssignment EOF )
// InternalUrml.g:917:1: ruleAssignment EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentRule());
}
pushFollow(FOLLOW_1);
ruleAssignment();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleAssignment"
// $ANTLR start "ruleAssignment"
// InternalUrml.g:924:1: ruleAssignment : ( ( rule__Assignment__Group__0 ) ) ;
public final void ruleAssignment() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:928:2: ( ( ( rule__Assignment__Group__0 ) ) )
// InternalUrml.g:929:1: ( ( rule__Assignment__Group__0 ) )
{
// InternalUrml.g:929:1: ( ( rule__Assignment__Group__0 ) )
// InternalUrml.g:930:1: ( rule__Assignment__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getGroup());
}
// InternalUrml.g:931:1: ( rule__Assignment__Group__0 )
// InternalUrml.g:931:2: rule__Assignment__Group__0
{
pushFollow(FOLLOW_2);
rule__Assignment__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleAssignment"
// $ANTLR start "entryRuleAssignable"
// InternalUrml.g:943:1: entryRuleAssignable : ruleAssignable EOF ;
public final void entryRuleAssignable() throws RecognitionException {
try {
// InternalUrml.g:944:1: ( ruleAssignable EOF )
// InternalUrml.g:945:1: ruleAssignable EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignableRule());
}
pushFollow(FOLLOW_1);
ruleAssignable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignableRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleAssignable"
// $ANTLR start "ruleAssignable"
// InternalUrml.g:952:1: ruleAssignable : ( ( rule__Assignable__Alternatives ) ) ;
public final void ruleAssignable() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:956:2: ( ( ( rule__Assignable__Alternatives ) ) )
// InternalUrml.g:957:1: ( ( rule__Assignable__Alternatives ) )
{
// InternalUrml.g:957:1: ( ( rule__Assignable__Alternatives ) )
// InternalUrml.g:958:1: ( rule__Assignable__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignableAccess().getAlternatives());
}
// InternalUrml.g:959:1: ( rule__Assignable__Alternatives )
// InternalUrml.g:959:2: rule__Assignable__Alternatives
{
pushFollow(FOLLOW_2);
rule__Assignable__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignableAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleAssignable"
// $ANTLR start "entryRuleWhileLoop"
// InternalUrml.g:971:1: entryRuleWhileLoop : ruleWhileLoop EOF ;
public final void entryRuleWhileLoop() throws RecognitionException {
try {
// InternalUrml.g:972:1: ( ruleWhileLoop EOF )
// InternalUrml.g:973:1: ruleWhileLoop EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopRule());
}
pushFollow(FOLLOW_1);
ruleWhileLoop();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleWhileLoop"
// $ANTLR start "ruleWhileLoop"
// InternalUrml.g:980:1: ruleWhileLoop : ( ( rule__WhileLoop__Group__0 ) ) ;
public final void ruleWhileLoop() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:984:2: ( ( ( rule__WhileLoop__Group__0 ) ) )
// InternalUrml.g:985:1: ( ( rule__WhileLoop__Group__0 ) )
{
// InternalUrml.g:985:1: ( ( rule__WhileLoop__Group__0 ) )
// InternalUrml.g:986:1: ( rule__WhileLoop__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getGroup());
}
// InternalUrml.g:987:1: ( rule__WhileLoop__Group__0 )
// InternalUrml.g:987:2: rule__WhileLoop__Group__0
{
pushFollow(FOLLOW_2);
rule__WhileLoop__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleWhileLoop"
// $ANTLR start "entryRuleIfStatement"
// InternalUrml.g:999:1: entryRuleIfStatement : ruleIfStatement EOF ;
public final void entryRuleIfStatement() throws RecognitionException {
try {
// InternalUrml.g:1000:1: ( ruleIfStatement EOF )
// InternalUrml.g:1001:1: ruleIfStatement EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementRule());
}
pushFollow(FOLLOW_1);
ruleIfStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIfStatement"
// $ANTLR start "ruleIfStatement"
// InternalUrml.g:1008:1: ruleIfStatement : ( ( rule__IfStatement__Group__0 ) ) ;
public final void ruleIfStatement() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1012:2: ( ( ( rule__IfStatement__Group__0 ) ) )
// InternalUrml.g:1013:1: ( ( rule__IfStatement__Group__0 ) )
{
// InternalUrml.g:1013:1: ( ( rule__IfStatement__Group__0 ) )
// InternalUrml.g:1014:1: ( rule__IfStatement__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getGroup());
}
// InternalUrml.g:1015:1: ( rule__IfStatement__Group__0 )
// InternalUrml.g:1015:2: rule__IfStatement__Group__0
{
pushFollow(FOLLOW_2);
rule__IfStatement__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIfStatement"
// $ANTLR start "entryRuleLogStatement"
// InternalUrml.g:1027:1: entryRuleLogStatement : ruleLogStatement EOF ;
public final void entryRuleLogStatement() throws RecognitionException {
try {
// InternalUrml.g:1028:1: ( ruleLogStatement EOF )
// InternalUrml.g:1029:1: ruleLogStatement EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementRule());
}
pushFollow(FOLLOW_1);
ruleLogStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleLogStatement"
// $ANTLR start "ruleLogStatement"
// InternalUrml.g:1036:1: ruleLogStatement : ( ( rule__LogStatement__Group__0 ) ) ;
public final void ruleLogStatement() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1040:2: ( ( ( rule__LogStatement__Group__0 ) ) )
// InternalUrml.g:1041:1: ( ( rule__LogStatement__Group__0 ) )
{
// InternalUrml.g:1041:1: ( ( rule__LogStatement__Group__0 ) )
// InternalUrml.g:1042:1: ( rule__LogStatement__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getGroup());
}
// InternalUrml.g:1043:1: ( rule__LogStatement__Group__0 )
// InternalUrml.g:1043:2: rule__LogStatement__Group__0
{
pushFollow(FOLLOW_2);
rule__LogStatement__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleLogStatement"
// $ANTLR start "entryRuleChooseStatement"
// InternalUrml.g:1055:1: entryRuleChooseStatement : ruleChooseStatement EOF ;
public final void entryRuleChooseStatement() throws RecognitionException {
try {
// InternalUrml.g:1056:1: ( ruleChooseStatement EOF )
// InternalUrml.g:1057:1: ruleChooseStatement EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementRule());
}
pushFollow(FOLLOW_1);
ruleChooseStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleChooseStatement"
// $ANTLR start "ruleChooseStatement"
// InternalUrml.g:1064:1: ruleChooseStatement : ( ( rule__ChooseStatement__Group__0 ) ) ;
public final void ruleChooseStatement() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1068:2: ( ( ( rule__ChooseStatement__Group__0 ) ) )
// InternalUrml.g:1069:1: ( ( rule__ChooseStatement__Group__0 ) )
{
// InternalUrml.g:1069:1: ( ( rule__ChooseStatement__Group__0 ) )
// InternalUrml.g:1070:1: ( rule__ChooseStatement__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getGroup());
}
// InternalUrml.g:1071:1: ( rule__ChooseStatement__Group__0 )
// InternalUrml.g:1071:2: rule__ChooseStatement__Group__0
{
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleChooseStatement"
// $ANTLR start "entryRuleFlipStatement"
// InternalUrml.g:1083:1: entryRuleFlipStatement : ruleFlipStatement EOF ;
public final void entryRuleFlipStatement() throws RecognitionException {
try {
// InternalUrml.g:1084:1: ( ruleFlipStatement EOF )
// InternalUrml.g:1085:1: ruleFlipStatement EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementRule());
}
pushFollow(FOLLOW_1);
ruleFlipStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleFlipStatement"
// $ANTLR start "ruleFlipStatement"
// InternalUrml.g:1092:1: ruleFlipStatement : ( ( rule__FlipStatement__Group__0 ) ) ;
public final void ruleFlipStatement() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1096:2: ( ( ( rule__FlipStatement__Group__0 ) ) )
// InternalUrml.g:1097:1: ( ( rule__FlipStatement__Group__0 ) )
{
// InternalUrml.g:1097:1: ( ( rule__FlipStatement__Group__0 ) )
// InternalUrml.g:1098:1: ( rule__FlipStatement__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getGroup());
}
// InternalUrml.g:1099:1: ( rule__FlipStatement__Group__0 )
// InternalUrml.g:1099:2: rule__FlipStatement__Group__0
{
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleFlipStatement"
// $ANTLR start "entryRuleIntegerExpression"
// InternalUrml.g:1111:1: entryRuleIntegerExpression : ruleIntegerExpression EOF ;
public final void entryRuleIntegerExpression() throws RecognitionException {
try {
// InternalUrml.g:1112:1: ( ruleIntegerExpression EOF )
// InternalUrml.g:1113:1: ruleIntegerExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntegerExpressionRule());
}
pushFollow(FOLLOW_1);
ruleIntegerExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIntegerExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIntegerExpression"
// $ANTLR start "ruleIntegerExpression"
// InternalUrml.g:1120:1: ruleIntegerExpression : ( ( rule__IntegerExpression__ExprAssignment ) ) ;
public final void ruleIntegerExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1124:2: ( ( ( rule__IntegerExpression__ExprAssignment ) ) )
// InternalUrml.g:1125:1: ( ( rule__IntegerExpression__ExprAssignment ) )
{
// InternalUrml.g:1125:1: ( ( rule__IntegerExpression__ExprAssignment ) )
// InternalUrml.g:1126:1: ( rule__IntegerExpression__ExprAssignment )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntegerExpressionAccess().getExprAssignment());
}
// InternalUrml.g:1127:1: ( rule__IntegerExpression__ExprAssignment )
// InternalUrml.g:1127:2: rule__IntegerExpression__ExprAssignment
{
pushFollow(FOLLOW_2);
rule__IntegerExpression__ExprAssignment();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIntegerExpressionAccess().getExprAssignment());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIntegerExpression"
// $ANTLR start "entryRuleStringExpression"
// InternalUrml.g:1139:1: entryRuleStringExpression : ruleStringExpression EOF ;
public final void entryRuleStringExpression() throws RecognitionException {
try {
// InternalUrml.g:1140:1: ( ruleStringExpression EOF )
// InternalUrml.g:1141:1: ruleStringExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionRule());
}
pushFollow(FOLLOW_1);
ruleStringExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleStringExpression"
// $ANTLR start "ruleStringExpression"
// InternalUrml.g:1148:1: ruleStringExpression : ( ( rule__StringExpression__Group__0 ) ) ;
public final void ruleStringExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1152:2: ( ( ( rule__StringExpression__Group__0 ) ) )
// InternalUrml.g:1153:1: ( ( rule__StringExpression__Group__0 ) )
{
// InternalUrml.g:1153:1: ( ( rule__StringExpression__Group__0 ) )
// InternalUrml.g:1154:1: ( rule__StringExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getGroup());
}
// InternalUrml.g:1155:1: ( rule__StringExpression__Group__0 )
// InternalUrml.g:1155:2: rule__StringExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__StringExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleStringExpression"
// $ANTLR start "entryRuleIndividualExpression"
// InternalUrml.g:1167:1: entryRuleIndividualExpression : ruleIndividualExpression EOF ;
public final void entryRuleIndividualExpression() throws RecognitionException {
try {
// InternalUrml.g:1168:1: ( ruleIndividualExpression EOF )
// InternalUrml.g:1169:1: ruleIndividualExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIndividualExpressionRule());
}
pushFollow(FOLLOW_1);
ruleIndividualExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIndividualExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIndividualExpression"
// $ANTLR start "ruleIndividualExpression"
// InternalUrml.g:1176:1: ruleIndividualExpression : ( ( rule__IndividualExpression__Alternatives ) ) ;
public final void ruleIndividualExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1180:2: ( ( ( rule__IndividualExpression__Alternatives ) ) )
// InternalUrml.g:1181:1: ( ( rule__IndividualExpression__Alternatives ) )
{
// InternalUrml.g:1181:1: ( ( rule__IndividualExpression__Alternatives ) )
// InternalUrml.g:1182:1: ( rule__IndividualExpression__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIndividualExpressionAccess().getAlternatives());
}
// InternalUrml.g:1183:1: ( rule__IndividualExpression__Alternatives )
// InternalUrml.g:1183:2: rule__IndividualExpression__Alternatives
{
pushFollow(FOLLOW_2);
rule__IndividualExpression__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIndividualExpressionAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIndividualExpression"
// $ANTLR start "entryRuleExpression"
// InternalUrml.g:1195:1: entryRuleExpression : ruleExpression EOF ;
public final void entryRuleExpression() throws RecognitionException {
try {
// InternalUrml.g:1196:1: ( ruleExpression EOF )
// InternalUrml.g:1197:1: ruleExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getExpressionRule());
}
pushFollow(FOLLOW_1);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleExpression"
// $ANTLR start "ruleExpression"
// InternalUrml.g:1204:1: ruleExpression : ( ruleConditionalOrExpression ) ;
public final void ruleExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1208:2: ( ( ruleConditionalOrExpression ) )
// InternalUrml.g:1209:1: ( ruleConditionalOrExpression )
{
// InternalUrml.g:1209:1: ( ruleConditionalOrExpression )
// InternalUrml.g:1210:1: ruleConditionalOrExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getExpressionAccess().getConditionalOrExpressionParserRuleCall());
}
pushFollow(FOLLOW_2);
ruleConditionalOrExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getExpressionAccess().getConditionalOrExpressionParserRuleCall());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleExpression"
// $ANTLR start "entryRuleConditionalOrExpression"
// InternalUrml.g:1223:1: entryRuleConditionalOrExpression : ruleConditionalOrExpression EOF ;
public final void entryRuleConditionalOrExpression() throws RecognitionException {
try {
// InternalUrml.g:1224:1: ( ruleConditionalOrExpression EOF )
// InternalUrml.g:1225:1: ruleConditionalOrExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionRule());
}
pushFollow(FOLLOW_1);
ruleConditionalOrExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleConditionalOrExpression"
// $ANTLR start "ruleConditionalOrExpression"
// InternalUrml.g:1232:1: ruleConditionalOrExpression : ( ( rule__ConditionalOrExpression__Group__0 ) ) ;
public final void ruleConditionalOrExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1236:2: ( ( ( rule__ConditionalOrExpression__Group__0 ) ) )
// InternalUrml.g:1237:1: ( ( rule__ConditionalOrExpression__Group__0 ) )
{
// InternalUrml.g:1237:1: ( ( rule__ConditionalOrExpression__Group__0 ) )
// InternalUrml.g:1238:1: ( rule__ConditionalOrExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getGroup());
}
// InternalUrml.g:1239:1: ( rule__ConditionalOrExpression__Group__0 )
// InternalUrml.g:1239:2: rule__ConditionalOrExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleConditionalOrExpression"
// $ANTLR start "entryRuleConditionalAndExpression"
// InternalUrml.g:1251:1: entryRuleConditionalAndExpression : ruleConditionalAndExpression EOF ;
public final void entryRuleConditionalAndExpression() throws RecognitionException {
try {
// InternalUrml.g:1252:1: ( ruleConditionalAndExpression EOF )
// InternalUrml.g:1253:1: ruleConditionalAndExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionRule());
}
pushFollow(FOLLOW_1);
ruleConditionalAndExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleConditionalAndExpression"
// $ANTLR start "ruleConditionalAndExpression"
// InternalUrml.g:1260:1: ruleConditionalAndExpression : ( ( rule__ConditionalAndExpression__Group__0 ) ) ;
public final void ruleConditionalAndExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1264:2: ( ( ( rule__ConditionalAndExpression__Group__0 ) ) )
// InternalUrml.g:1265:1: ( ( rule__ConditionalAndExpression__Group__0 ) )
{
// InternalUrml.g:1265:1: ( ( rule__ConditionalAndExpression__Group__0 ) )
// InternalUrml.g:1266:1: ( rule__ConditionalAndExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getGroup());
}
// InternalUrml.g:1267:1: ( rule__ConditionalAndExpression__Group__0 )
// InternalUrml.g:1267:2: rule__ConditionalAndExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleConditionalAndExpression"
// $ANTLR start "entryRuleRelationalOpExpression"
// InternalUrml.g:1279:1: entryRuleRelationalOpExpression : ruleRelationalOpExpression EOF ;
public final void entryRuleRelationalOpExpression() throws RecognitionException {
try {
// InternalUrml.g:1280:1: ( ruleRelationalOpExpression EOF )
// InternalUrml.g:1281:1: ruleRelationalOpExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionRule());
}
pushFollow(FOLLOW_1);
ruleRelationalOpExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleRelationalOpExpression"
// $ANTLR start "ruleRelationalOpExpression"
// InternalUrml.g:1288:1: ruleRelationalOpExpression : ( ( rule__RelationalOpExpression__Group__0 ) ) ;
public final void ruleRelationalOpExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1292:2: ( ( ( rule__RelationalOpExpression__Group__0 ) ) )
// InternalUrml.g:1293:1: ( ( rule__RelationalOpExpression__Group__0 ) )
{
// InternalUrml.g:1293:1: ( ( rule__RelationalOpExpression__Group__0 ) )
// InternalUrml.g:1294:1: ( rule__RelationalOpExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup());
}
// InternalUrml.g:1295:1: ( rule__RelationalOpExpression__Group__0 )
// InternalUrml.g:1295:2: rule__RelationalOpExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleRelationalOpExpression"
// $ANTLR start "entryRuleAdditiveExpression"
// InternalUrml.g:1307:1: entryRuleAdditiveExpression : ruleAdditiveExpression EOF ;
public final void entryRuleAdditiveExpression() throws RecognitionException {
try {
// InternalUrml.g:1308:1: ( ruleAdditiveExpression EOF )
// InternalUrml.g:1309:1: ruleAdditiveExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionRule());
}
pushFollow(FOLLOW_1);
ruleAdditiveExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleAdditiveExpression"
// $ANTLR start "ruleAdditiveExpression"
// InternalUrml.g:1316:1: ruleAdditiveExpression : ( ( rule__AdditiveExpression__Group__0 ) ) ;
public final void ruleAdditiveExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1320:2: ( ( ( rule__AdditiveExpression__Group__0 ) ) )
// InternalUrml.g:1321:1: ( ( rule__AdditiveExpression__Group__0 ) )
{
// InternalUrml.g:1321:1: ( ( rule__AdditiveExpression__Group__0 ) )
// InternalUrml.g:1322:1: ( rule__AdditiveExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getGroup());
}
// InternalUrml.g:1323:1: ( rule__AdditiveExpression__Group__0 )
// InternalUrml.g:1323:2: rule__AdditiveExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleAdditiveExpression"
// $ANTLR start "entryRuleMultiplicativeExpression"
// InternalUrml.g:1335:1: entryRuleMultiplicativeExpression : ruleMultiplicativeExpression EOF ;
public final void entryRuleMultiplicativeExpression() throws RecognitionException {
try {
// InternalUrml.g:1336:1: ( ruleMultiplicativeExpression EOF )
// InternalUrml.g:1337:1: ruleMultiplicativeExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionRule());
}
pushFollow(FOLLOW_1);
ruleMultiplicativeExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleMultiplicativeExpression"
// $ANTLR start "ruleMultiplicativeExpression"
// InternalUrml.g:1344:1: ruleMultiplicativeExpression : ( ( rule__MultiplicativeExpression__Group__0 ) ) ;
public final void ruleMultiplicativeExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1348:2: ( ( ( rule__MultiplicativeExpression__Group__0 ) ) )
// InternalUrml.g:1349:1: ( ( rule__MultiplicativeExpression__Group__0 ) )
{
// InternalUrml.g:1349:1: ( ( rule__MultiplicativeExpression__Group__0 ) )
// InternalUrml.g:1350:1: ( rule__MultiplicativeExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getGroup());
}
// InternalUrml.g:1351:1: ( rule__MultiplicativeExpression__Group__0 )
// InternalUrml.g:1351:2: rule__MultiplicativeExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleMultiplicativeExpression"
// $ANTLR start "entryRuleUnaryExpression"
// InternalUrml.g:1363:1: entryRuleUnaryExpression : ruleUnaryExpression EOF ;
public final void entryRuleUnaryExpression() throws RecognitionException {
try {
// InternalUrml.g:1364:1: ( ruleUnaryExpression EOF )
// InternalUrml.g:1365:1: ruleUnaryExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionRule());
}
pushFollow(FOLLOW_1);
ruleUnaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleUnaryExpression"
// $ANTLR start "ruleUnaryExpression"
// InternalUrml.g:1372:1: ruleUnaryExpression : ( ( rule__UnaryExpression__Alternatives ) ) ;
public final void ruleUnaryExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1376:2: ( ( ( rule__UnaryExpression__Alternatives ) ) )
// InternalUrml.g:1377:1: ( ( rule__UnaryExpression__Alternatives ) )
{
// InternalUrml.g:1377:1: ( ( rule__UnaryExpression__Alternatives ) )
// InternalUrml.g:1378:1: ( rule__UnaryExpression__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getAlternatives());
}
// InternalUrml.g:1379:1: ( rule__UnaryExpression__Alternatives )
// InternalUrml.g:1379:2: rule__UnaryExpression__Alternatives
{
pushFollow(FOLLOW_2);
rule__UnaryExpression__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleUnaryExpression"
// $ANTLR start "entryRuleUnaryExpressionNotPlusMinus"
// InternalUrml.g:1391:1: entryRuleUnaryExpressionNotPlusMinus : ruleUnaryExpressionNotPlusMinus EOF ;
public final void entryRuleUnaryExpressionNotPlusMinus() throws RecognitionException {
try {
// InternalUrml.g:1392:1: ( ruleUnaryExpressionNotPlusMinus EOF )
// InternalUrml.g:1393:1: ruleUnaryExpressionNotPlusMinus EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionNotPlusMinusRule());
}
pushFollow(FOLLOW_1);
ruleUnaryExpressionNotPlusMinus();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionNotPlusMinusRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleUnaryExpressionNotPlusMinus"
// $ANTLR start "ruleUnaryExpressionNotPlusMinus"
// InternalUrml.g:1400:1: ruleUnaryExpressionNotPlusMinus : ( ( rule__UnaryExpressionNotPlusMinus__Alternatives ) ) ;
public final void ruleUnaryExpressionNotPlusMinus() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1404:2: ( ( ( rule__UnaryExpressionNotPlusMinus__Alternatives ) ) )
// InternalUrml.g:1405:1: ( ( rule__UnaryExpressionNotPlusMinus__Alternatives ) )
{
// InternalUrml.g:1405:1: ( ( rule__UnaryExpressionNotPlusMinus__Alternatives ) )
// InternalUrml.g:1406:1: ( rule__UnaryExpressionNotPlusMinus__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionNotPlusMinusAccess().getAlternatives());
}
// InternalUrml.g:1407:1: ( rule__UnaryExpressionNotPlusMinus__Alternatives )
// InternalUrml.g:1407:2: rule__UnaryExpressionNotPlusMinus__Alternatives
{
pushFollow(FOLLOW_2);
rule__UnaryExpressionNotPlusMinus__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionNotPlusMinusAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleUnaryExpressionNotPlusMinus"
// $ANTLR start "entryRuleNotBooleanExpression"
// InternalUrml.g:1419:1: entryRuleNotBooleanExpression : ruleNotBooleanExpression EOF ;
public final void entryRuleNotBooleanExpression() throws RecognitionException {
try {
// InternalUrml.g:1420:1: ( ruleNotBooleanExpression EOF )
// InternalUrml.g:1421:1: ruleNotBooleanExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNotBooleanExpressionRule());
}
pushFollow(FOLLOW_1);
ruleNotBooleanExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getNotBooleanExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleNotBooleanExpression"
// $ANTLR start "ruleNotBooleanExpression"
// InternalUrml.g:1428:1: ruleNotBooleanExpression : ( ( rule__NotBooleanExpression__Group__0 ) ) ;
public final void ruleNotBooleanExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1432:2: ( ( ( rule__NotBooleanExpression__Group__0 ) ) )
// InternalUrml.g:1433:1: ( ( rule__NotBooleanExpression__Group__0 ) )
{
// InternalUrml.g:1433:1: ( ( rule__NotBooleanExpression__Group__0 ) )
// InternalUrml.g:1434:1: ( rule__NotBooleanExpression__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNotBooleanExpressionAccess().getGroup());
}
// InternalUrml.g:1435:1: ( rule__NotBooleanExpression__Group__0 )
// InternalUrml.g:1435:2: rule__NotBooleanExpression__Group__0
{
pushFollow(FOLLOW_2);
rule__NotBooleanExpression__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getNotBooleanExpressionAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleNotBooleanExpression"
// $ANTLR start "entryRulePrimaryExpression"
// InternalUrml.g:1447:1: entryRulePrimaryExpression : rulePrimaryExpression EOF ;
public final void entryRulePrimaryExpression() throws RecognitionException {
try {
// InternalUrml.g:1448:1: ( rulePrimaryExpression EOF )
// InternalUrml.g:1449:1: rulePrimaryExpression EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionRule());
}
pushFollow(FOLLOW_1);
rulePrimaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRulePrimaryExpression"
// $ANTLR start "rulePrimaryExpression"
// InternalUrml.g:1456:1: rulePrimaryExpression : ( ( rule__PrimaryExpression__Alternatives ) ) ;
public final void rulePrimaryExpression() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1460:2: ( ( ( rule__PrimaryExpression__Alternatives ) ) )
// InternalUrml.g:1461:1: ( ( rule__PrimaryExpression__Alternatives ) )
{
// InternalUrml.g:1461:1: ( ( rule__PrimaryExpression__Alternatives ) )
// InternalUrml.g:1462:1: ( rule__PrimaryExpression__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionAccess().getAlternatives());
}
// InternalUrml.g:1463:1: ( rule__PrimaryExpression__Alternatives )
// InternalUrml.g:1463:2: rule__PrimaryExpression__Alternatives
{
pushFollow(FOLLOW_2);
rule__PrimaryExpression__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rulePrimaryExpression"
// $ANTLR start "entryRuleLiteralOrIdentifier"
// InternalUrml.g:1475:1: entryRuleLiteralOrIdentifier : ruleLiteralOrIdentifier EOF ;
public final void entryRuleLiteralOrIdentifier() throws RecognitionException {
try {
// InternalUrml.g:1476:1: ( ruleLiteralOrIdentifier EOF )
// InternalUrml.g:1477:1: ruleLiteralOrIdentifier EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralOrIdentifierRule());
}
pushFollow(FOLLOW_1);
ruleLiteralOrIdentifier();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralOrIdentifierRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleLiteralOrIdentifier"
// $ANTLR start "ruleLiteralOrIdentifier"
// InternalUrml.g:1484:1: ruleLiteralOrIdentifier : ( ( rule__LiteralOrIdentifier__Alternatives ) ) ;
public final void ruleLiteralOrIdentifier() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1488:2: ( ( ( rule__LiteralOrIdentifier__Alternatives ) ) )
// InternalUrml.g:1489:1: ( ( rule__LiteralOrIdentifier__Alternatives ) )
{
// InternalUrml.g:1489:1: ( ( rule__LiteralOrIdentifier__Alternatives ) )
// InternalUrml.g:1490:1: ( rule__LiteralOrIdentifier__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralOrIdentifierAccess().getAlternatives());
}
// InternalUrml.g:1491:1: ( rule__LiteralOrIdentifier__Alternatives )
// InternalUrml.g:1491:2: rule__LiteralOrIdentifier__Alternatives
{
pushFollow(FOLLOW_2);
rule__LiteralOrIdentifier__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralOrIdentifierAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleLiteralOrIdentifier"
// $ANTLR start "entryRuleLiteral"
// InternalUrml.g:1503:1: entryRuleLiteral : ruleLiteral EOF ;
public final void entryRuleLiteral() throws RecognitionException {
try {
// InternalUrml.g:1504:1: ( ruleLiteral EOF )
// InternalUrml.g:1505:1: ruleLiteral EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralRule());
}
pushFollow(FOLLOW_1);
ruleLiteral();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleLiteral"
// $ANTLR start "ruleLiteral"
// InternalUrml.g:1512:1: ruleLiteral : ( ( rule__Literal__Alternatives ) ) ;
public final void ruleLiteral() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1516:2: ( ( ( rule__Literal__Alternatives ) ) )
// InternalUrml.g:1517:1: ( ( rule__Literal__Alternatives ) )
{
// InternalUrml.g:1517:1: ( ( rule__Literal__Alternatives ) )
// InternalUrml.g:1518:1: ( rule__Literal__Alternatives )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralAccess().getAlternatives());
}
// InternalUrml.g:1519:1: ( rule__Literal__Alternatives )
// InternalUrml.g:1519:2: rule__Literal__Alternatives
{
pushFollow(FOLLOW_2);
rule__Literal__Alternatives();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralAccess().getAlternatives());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleLiteral"
// $ANTLR start "entryRuleIntLiteral"
// InternalUrml.g:1531:1: entryRuleIntLiteral : ruleIntLiteral EOF ;
public final void entryRuleIntLiteral() throws RecognitionException {
try {
// InternalUrml.g:1532:1: ( ruleIntLiteral EOF )
// InternalUrml.g:1533:1: ruleIntLiteral EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntLiteralRule());
}
pushFollow(FOLLOW_1);
ruleIntLiteral();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIntLiteralRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIntLiteral"
// $ANTLR start "ruleIntLiteral"
// InternalUrml.g:1540:1: ruleIntLiteral : ( ( rule__IntLiteral__Group__0 ) ) ;
public final void ruleIntLiteral() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1544:2: ( ( ( rule__IntLiteral__Group__0 ) ) )
// InternalUrml.g:1545:1: ( ( rule__IntLiteral__Group__0 ) )
{
// InternalUrml.g:1545:1: ( ( rule__IntLiteral__Group__0 ) )
// InternalUrml.g:1546:1: ( rule__IntLiteral__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntLiteralAccess().getGroup());
}
// InternalUrml.g:1547:1: ( rule__IntLiteral__Group__0 )
// InternalUrml.g:1547:2: rule__IntLiteral__Group__0
{
pushFollow(FOLLOW_2);
rule__IntLiteral__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIntLiteralAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIntLiteral"
// $ANTLR start "entryRuleIdentifier"
// InternalUrml.g:1559:1: entryRuleIdentifier : ruleIdentifier EOF ;
public final void entryRuleIdentifier() throws RecognitionException {
try {
// InternalUrml.g:1560:1: ( ruleIdentifier EOF )
// InternalUrml.g:1561:1: ruleIdentifier EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIdentifierRule());
}
pushFollow(FOLLOW_1);
ruleIdentifier();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIdentifierRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleIdentifier"
// $ANTLR start "ruleIdentifier"
// InternalUrml.g:1568:1: ruleIdentifier : ( ( rule__Identifier__IdAssignment ) ) ;
public final void ruleIdentifier() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1572:2: ( ( ( rule__Identifier__IdAssignment ) ) )
// InternalUrml.g:1573:1: ( ( rule__Identifier__IdAssignment ) )
{
// InternalUrml.g:1573:1: ( ( rule__Identifier__IdAssignment ) )
// InternalUrml.g:1574:1: ( rule__Identifier__IdAssignment )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIdentifierAccess().getIdAssignment());
}
// InternalUrml.g:1575:1: ( rule__Identifier__IdAssignment )
// InternalUrml.g:1575:2: rule__Identifier__IdAssignment
{
pushFollow(FOLLOW_2);
rule__Identifier__IdAssignment();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIdentifierAccess().getIdAssignment());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleIdentifier"
// $ANTLR start "entryRuleFunctionCall"
// InternalUrml.g:1589:1: entryRuleFunctionCall : ruleFunctionCall EOF ;
public final void entryRuleFunctionCall() throws RecognitionException {
try {
// InternalUrml.g:1590:1: ( ruleFunctionCall EOF )
// InternalUrml.g:1591:1: ruleFunctionCall EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallRule());
}
pushFollow(FOLLOW_1);
ruleFunctionCall();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleFunctionCall"
// $ANTLR start "ruleFunctionCall"
// InternalUrml.g:1598:1: ruleFunctionCall : ( ( rule__FunctionCall__Group__0 ) ) ;
public final void ruleFunctionCall() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1602:2: ( ( ( rule__FunctionCall__Group__0 ) ) )
// InternalUrml.g:1603:1: ( ( rule__FunctionCall__Group__0 ) )
{
// InternalUrml.g:1603:1: ( ( rule__FunctionCall__Group__0 ) )
// InternalUrml.g:1604:1: ( rule__FunctionCall__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getGroup());
}
// InternalUrml.g:1605:1: ( rule__FunctionCall__Group__0 )
// InternalUrml.g:1605:2: rule__FunctionCall__Group__0
{
pushFollow(FOLLOW_2);
rule__FunctionCall__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleFunctionCall"
// $ANTLR start "entryRuleBoolLiteral"
// InternalUrml.g:1617:1: entryRuleBoolLiteral : ruleBoolLiteral EOF ;
public final void entryRuleBoolLiteral() throws RecognitionException {
try {
// InternalUrml.g:1618:1: ( ruleBoolLiteral EOF )
// InternalUrml.g:1619:1: ruleBoolLiteral EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.getBoolLiteralRule());
}
pushFollow(FOLLOW_1);
ruleBoolLiteral();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getBoolLiteralRule());
}
match(input,EOF,FOLLOW_2); if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
}
return ;
}
// $ANTLR end "entryRuleBoolLiteral"
// $ANTLR start "ruleBoolLiteral"
// InternalUrml.g:1626:1: ruleBoolLiteral : ( ( rule__BoolLiteral__Group__0 ) ) ;
public final void ruleBoolLiteral() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1630:2: ( ( ( rule__BoolLiteral__Group__0 ) ) )
// InternalUrml.g:1631:1: ( ( rule__BoolLiteral__Group__0 ) )
{
// InternalUrml.g:1631:1: ( ( rule__BoolLiteral__Group__0 ) )
// InternalUrml.g:1632:1: ( rule__BoolLiteral__Group__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getBoolLiteralAccess().getGroup());
}
// InternalUrml.g:1633:1: ( rule__BoolLiteral__Group__0 )
// InternalUrml.g:1633:2: rule__BoolLiteral__Group__0
{
pushFollow(FOLLOW_2);
rule__BoolLiteral__Group__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getBoolLiteralAccess().getGroup());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "ruleBoolLiteral"
// $ANTLR start "rule__Model__Alternatives_3"
// InternalUrml.g:1645:1: rule__Model__Alternatives_3 : ( ( ( rule__Model__CapsulesAssignment_3_0 ) ) | ( ( rule__Model__ProtocolsAssignment_3_1 ) ) );
public final void rule__Model__Alternatives_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1649:1: ( ( ( rule__Model__CapsulesAssignment_3_0 ) ) | ( ( rule__Model__ProtocolsAssignment_3_1 ) ) )
int alt3=2;
int LA3_0 = input.LA(1);
if ( (LA3_0==23||LA3_0==77) ) {
alt3=1;
}
else if ( (LA3_0==17) ) {
alt3=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 3, 0, input);
throw nvae;
}
switch (alt3) {
case 1 :
// InternalUrml.g:1650:1: ( ( rule__Model__CapsulesAssignment_3_0 ) )
{
// InternalUrml.g:1650:1: ( ( rule__Model__CapsulesAssignment_3_0 ) )
// InternalUrml.g:1651:1: ( rule__Model__CapsulesAssignment_3_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getCapsulesAssignment_3_0());
}
// InternalUrml.g:1652:1: ( rule__Model__CapsulesAssignment_3_0 )
// InternalUrml.g:1652:2: rule__Model__CapsulesAssignment_3_0
{
pushFollow(FOLLOW_2);
rule__Model__CapsulesAssignment_3_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getCapsulesAssignment_3_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1656:6: ( ( rule__Model__ProtocolsAssignment_3_1 ) )
{
// InternalUrml.g:1656:6: ( ( rule__Model__ProtocolsAssignment_3_1 ) )
// InternalUrml.g:1657:1: ( rule__Model__ProtocolsAssignment_3_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getProtocolsAssignment_3_1());
}
// InternalUrml.g:1658:1: ( rule__Model__ProtocolsAssignment_3_1 )
// InternalUrml.g:1658:2: rule__Model__ProtocolsAssignment_3_1
{
pushFollow(FOLLOW_2);
rule__Model__ProtocolsAssignment_3_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getProtocolsAssignment_3_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Alternatives_3"
// $ANTLR start "rule__LocalVar__Alternatives_0"
// InternalUrml.g:1667:1: rule__LocalVar__Alternatives_0 : ( ( ( rule__LocalVar__IsBoolAssignment_0_0 ) ) | ( ( rule__LocalVar__IsIntAssignment_0_1 ) ) );
public final void rule__LocalVar__Alternatives_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1671:1: ( ( ( rule__LocalVar__IsBoolAssignment_0_0 ) ) | ( ( rule__LocalVar__IsIntAssignment_0_1 ) ) )
int alt4=2;
int LA4_0 = input.LA(1);
if ( (LA4_0==75) ) {
alt4=1;
}
else if ( (LA4_0==76) ) {
alt4=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 4, 0, input);
throw nvae;
}
switch (alt4) {
case 1 :
// InternalUrml.g:1672:1: ( ( rule__LocalVar__IsBoolAssignment_0_0 ) )
{
// InternalUrml.g:1672:1: ( ( rule__LocalVar__IsBoolAssignment_0_0 ) )
// InternalUrml.g:1673:1: ( rule__LocalVar__IsBoolAssignment_0_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getIsBoolAssignment_0_0());
}
// InternalUrml.g:1674:1: ( rule__LocalVar__IsBoolAssignment_0_0 )
// InternalUrml.g:1674:2: rule__LocalVar__IsBoolAssignment_0_0
{
pushFollow(FOLLOW_2);
rule__LocalVar__IsBoolAssignment_0_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getIsBoolAssignment_0_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1678:6: ( ( rule__LocalVar__IsIntAssignment_0_1 ) )
{
// InternalUrml.g:1678:6: ( ( rule__LocalVar__IsIntAssignment_0_1 ) )
// InternalUrml.g:1679:1: ( rule__LocalVar__IsIntAssignment_0_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getIsIntAssignment_0_1());
}
// InternalUrml.g:1680:1: ( rule__LocalVar__IsIntAssignment_0_1 )
// InternalUrml.g:1680:2: rule__LocalVar__IsIntAssignment_0_1
{
pushFollow(FOLLOW_2);
rule__LocalVar__IsIntAssignment_0_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getIsIntAssignment_0_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__Alternatives_0"
// $ANTLR start "rule__Attribute__Alternatives_1"
// InternalUrml.g:1689:1: rule__Attribute__Alternatives_1 : ( ( ( rule__Attribute__IsBoolAssignment_1_0 ) ) | ( ( rule__Attribute__IsIntAssignment_1_1 ) ) );
public final void rule__Attribute__Alternatives_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1693:1: ( ( ( rule__Attribute__IsBoolAssignment_1_0 ) ) | ( ( rule__Attribute__IsIntAssignment_1_1 ) ) )
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0==75) ) {
alt5=1;
}
else if ( (LA5_0==76) ) {
alt5=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 5, 0, input);
throw nvae;
}
switch (alt5) {
case 1 :
// InternalUrml.g:1694:1: ( ( rule__Attribute__IsBoolAssignment_1_0 ) )
{
// InternalUrml.g:1694:1: ( ( rule__Attribute__IsBoolAssignment_1_0 ) )
// InternalUrml.g:1695:1: ( rule__Attribute__IsBoolAssignment_1_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getIsBoolAssignment_1_0());
}
// InternalUrml.g:1696:1: ( rule__Attribute__IsBoolAssignment_1_0 )
// InternalUrml.g:1696:2: rule__Attribute__IsBoolAssignment_1_0
{
pushFollow(FOLLOW_2);
rule__Attribute__IsBoolAssignment_1_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getIsBoolAssignment_1_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1700:6: ( ( rule__Attribute__IsIntAssignment_1_1 ) )
{
// InternalUrml.g:1700:6: ( ( rule__Attribute__IsIntAssignment_1_1 ) )
// InternalUrml.g:1701:1: ( rule__Attribute__IsIntAssignment_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getIsIntAssignment_1_1());
}
// InternalUrml.g:1702:1: ( rule__Attribute__IsIntAssignment_1_1 )
// InternalUrml.g:1702:2: rule__Attribute__IsIntAssignment_1_1
{
pushFollow(FOLLOW_2);
rule__Attribute__IsIntAssignment_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getIsIntAssignment_1_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Alternatives_1"
// $ANTLR start "rule__Protocol__Alternatives_3"
// InternalUrml.g:1711:1: rule__Protocol__Alternatives_3 : ( ( ( rule__Protocol__Group_3_0__0 ) ) | ( ( rule__Protocol__Group_3_1__0 ) ) );
public final void rule__Protocol__Alternatives_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1715:1: ( ( ( rule__Protocol__Group_3_0__0 ) ) | ( ( rule__Protocol__Group_3_1__0 ) ) )
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0==18) ) {
alt6=1;
}
else if ( (LA6_0==19) ) {
alt6=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1 :
// InternalUrml.g:1716:1: ( ( rule__Protocol__Group_3_0__0 ) )
{
// InternalUrml.g:1716:1: ( ( rule__Protocol__Group_3_0__0 ) )
// InternalUrml.g:1717:1: ( rule__Protocol__Group_3_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getGroup_3_0());
}
// InternalUrml.g:1718:1: ( rule__Protocol__Group_3_0__0 )
// InternalUrml.g:1718:2: rule__Protocol__Group_3_0__0
{
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getGroup_3_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1722:6: ( ( rule__Protocol__Group_3_1__0 ) )
{
// InternalUrml.g:1722:6: ( ( rule__Protocol__Group_3_1__0 ) )
// InternalUrml.g:1723:1: ( rule__Protocol__Group_3_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getGroup_3_1());
}
// InternalUrml.g:1724:1: ( rule__Protocol__Group_3_1__0 )
// InternalUrml.g:1724:2: rule__Protocol__Group_3_1__0
{
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getGroup_3_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Alternatives_3"
// $ANTLR start "rule__Capsule__Alternatives_4"
// InternalUrml.g:1733:1: rule__Capsule__Alternatives_4 : ( ( ( rule__Capsule__Group_4_0__0 ) ) | ( ( rule__Capsule__InternalPortsAssignment_4_1 ) ) | ( ( rule__Capsule__TimerPortsAssignment_4_2 ) ) | ( ( rule__Capsule__LogPortsAssignment_4_3 ) ) | ( ( rule__Capsule__AttributesAssignment_4_4 ) ) | ( ( rule__Capsule__CapsuleInstsAssignment_4_5 ) ) | ( ( rule__Capsule__ConnectorsAssignment_4_6 ) ) | ( ( rule__Capsule__OperationsAssignment_4_7 ) ) | ( ( rule__Capsule__StatemachinesAssignment_4_8 ) ) );
public final void rule__Capsule__Alternatives_4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1737:1: ( ( ( rule__Capsule__Group_4_0__0 ) ) | ( ( rule__Capsule__InternalPortsAssignment_4_1 ) ) | ( ( rule__Capsule__TimerPortsAssignment_4_2 ) ) | ( ( rule__Capsule__LogPortsAssignment_4_3 ) ) | ( ( rule__Capsule__AttributesAssignment_4_4 ) ) | ( ( rule__Capsule__CapsuleInstsAssignment_4_5 ) ) | ( ( rule__Capsule__ConnectorsAssignment_4_6 ) ) | ( ( rule__Capsule__OperationsAssignment_4_7 ) ) | ( ( rule__Capsule__StatemachinesAssignment_4_8 ) ) )
int alt7=9;
switch ( input.LA(1) ) {
case 24:
{
alt7=1;
}
break;
case 28:
{
alt7=2;
}
break;
case 26:
{
alt7=3;
}
break;
case 27:
{
alt7=4;
}
break;
case 15:
{
alt7=5;
}
break;
case 33:
{
alt7=6;
}
break;
case 30:
{
alt7=7;
}
break;
case 25:
{
alt7=8;
}
break;
case 34:
{
alt7=9;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 7, 0, input);
throw nvae;
}
switch (alt7) {
case 1 :
// InternalUrml.g:1738:1: ( ( rule__Capsule__Group_4_0__0 ) )
{
// InternalUrml.g:1738:1: ( ( rule__Capsule__Group_4_0__0 ) )
// InternalUrml.g:1739:1: ( rule__Capsule__Group_4_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getGroup_4_0());
}
// InternalUrml.g:1740:1: ( rule__Capsule__Group_4_0__0 )
// InternalUrml.g:1740:2: rule__Capsule__Group_4_0__0
{
pushFollow(FOLLOW_2);
rule__Capsule__Group_4_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getGroup_4_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1744:6: ( ( rule__Capsule__InternalPortsAssignment_4_1 ) )
{
// InternalUrml.g:1744:6: ( ( rule__Capsule__InternalPortsAssignment_4_1 ) )
// InternalUrml.g:1745:1: ( rule__Capsule__InternalPortsAssignment_4_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getInternalPortsAssignment_4_1());
}
// InternalUrml.g:1746:1: ( rule__Capsule__InternalPortsAssignment_4_1 )
// InternalUrml.g:1746:2: rule__Capsule__InternalPortsAssignment_4_1
{
pushFollow(FOLLOW_2);
rule__Capsule__InternalPortsAssignment_4_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getInternalPortsAssignment_4_1());
}
}
}
break;
case 3 :
// InternalUrml.g:1750:6: ( ( rule__Capsule__TimerPortsAssignment_4_2 ) )
{
// InternalUrml.g:1750:6: ( ( rule__Capsule__TimerPortsAssignment_4_2 ) )
// InternalUrml.g:1751:1: ( rule__Capsule__TimerPortsAssignment_4_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getTimerPortsAssignment_4_2());
}
// InternalUrml.g:1752:1: ( rule__Capsule__TimerPortsAssignment_4_2 )
// InternalUrml.g:1752:2: rule__Capsule__TimerPortsAssignment_4_2
{
pushFollow(FOLLOW_2);
rule__Capsule__TimerPortsAssignment_4_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getTimerPortsAssignment_4_2());
}
}
}
break;
case 4 :
// InternalUrml.g:1756:6: ( ( rule__Capsule__LogPortsAssignment_4_3 ) )
{
// InternalUrml.g:1756:6: ( ( rule__Capsule__LogPortsAssignment_4_3 ) )
// InternalUrml.g:1757:1: ( rule__Capsule__LogPortsAssignment_4_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getLogPortsAssignment_4_3());
}
// InternalUrml.g:1758:1: ( rule__Capsule__LogPortsAssignment_4_3 )
// InternalUrml.g:1758:2: rule__Capsule__LogPortsAssignment_4_3
{
pushFollow(FOLLOW_2);
rule__Capsule__LogPortsAssignment_4_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getLogPortsAssignment_4_3());
}
}
}
break;
case 5 :
// InternalUrml.g:1762:6: ( ( rule__Capsule__AttributesAssignment_4_4 ) )
{
// InternalUrml.g:1762:6: ( ( rule__Capsule__AttributesAssignment_4_4 ) )
// InternalUrml.g:1763:1: ( rule__Capsule__AttributesAssignment_4_4 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getAttributesAssignment_4_4());
}
// InternalUrml.g:1764:1: ( rule__Capsule__AttributesAssignment_4_4 )
// InternalUrml.g:1764:2: rule__Capsule__AttributesAssignment_4_4
{
pushFollow(FOLLOW_2);
rule__Capsule__AttributesAssignment_4_4();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getAttributesAssignment_4_4());
}
}
}
break;
case 6 :
// InternalUrml.g:1768:6: ( ( rule__Capsule__CapsuleInstsAssignment_4_5 ) )
{
// InternalUrml.g:1768:6: ( ( rule__Capsule__CapsuleInstsAssignment_4_5 ) )
// InternalUrml.g:1769:1: ( rule__Capsule__CapsuleInstsAssignment_4_5 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getCapsuleInstsAssignment_4_5());
}
// InternalUrml.g:1770:1: ( rule__Capsule__CapsuleInstsAssignment_4_5 )
// InternalUrml.g:1770:2: rule__Capsule__CapsuleInstsAssignment_4_5
{
pushFollow(FOLLOW_2);
rule__Capsule__CapsuleInstsAssignment_4_5();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getCapsuleInstsAssignment_4_5());
}
}
}
break;
case 7 :
// InternalUrml.g:1774:6: ( ( rule__Capsule__ConnectorsAssignment_4_6 ) )
{
// InternalUrml.g:1774:6: ( ( rule__Capsule__ConnectorsAssignment_4_6 ) )
// InternalUrml.g:1775:1: ( rule__Capsule__ConnectorsAssignment_4_6 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getConnectorsAssignment_4_6());
}
// InternalUrml.g:1776:1: ( rule__Capsule__ConnectorsAssignment_4_6 )
// InternalUrml.g:1776:2: rule__Capsule__ConnectorsAssignment_4_6
{
pushFollow(FOLLOW_2);
rule__Capsule__ConnectorsAssignment_4_6();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getConnectorsAssignment_4_6());
}
}
}
break;
case 8 :
// InternalUrml.g:1780:6: ( ( rule__Capsule__OperationsAssignment_4_7 ) )
{
// InternalUrml.g:1780:6: ( ( rule__Capsule__OperationsAssignment_4_7 ) )
// InternalUrml.g:1781:1: ( rule__Capsule__OperationsAssignment_4_7 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getOperationsAssignment_4_7());
}
// InternalUrml.g:1782:1: ( rule__Capsule__OperationsAssignment_4_7 )
// InternalUrml.g:1782:2: rule__Capsule__OperationsAssignment_4_7
{
pushFollow(FOLLOW_2);
rule__Capsule__OperationsAssignment_4_7();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getOperationsAssignment_4_7());
}
}
}
break;
case 9 :
// InternalUrml.g:1786:6: ( ( rule__Capsule__StatemachinesAssignment_4_8 ) )
{
// InternalUrml.g:1786:6: ( ( rule__Capsule__StatemachinesAssignment_4_8 ) )
// InternalUrml.g:1787:1: ( rule__Capsule__StatemachinesAssignment_4_8 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getStatemachinesAssignment_4_8());
}
// InternalUrml.g:1788:1: ( rule__Capsule__StatemachinesAssignment_4_8 )
// InternalUrml.g:1788:2: rule__Capsule__StatemachinesAssignment_4_8
{
pushFollow(FOLLOW_2);
rule__Capsule__StatemachinesAssignment_4_8();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getStatemachinesAssignment_4_8());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Alternatives_4"
// $ANTLR start "rule__Operation__Alternatives_1"
// InternalUrml.g:1797:1: rule__Operation__Alternatives_1 : ( ( ( rule__Operation__IsBoolAssignment_1_0 ) ) | ( ( rule__Operation__IsIntAssignment_1_1 ) ) | ( ( rule__Operation__IsVoidAssignment_1_2 ) ) );
public final void rule__Operation__Alternatives_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1801:1: ( ( ( rule__Operation__IsBoolAssignment_1_0 ) ) | ( ( rule__Operation__IsIntAssignment_1_1 ) ) | ( ( rule__Operation__IsVoidAssignment_1_2 ) ) )
int alt8=3;
switch ( input.LA(1) ) {
case 75:
{
alt8=1;
}
break;
case 76:
{
alt8=2;
}
break;
case 78:
{
alt8=3;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 8, 0, input);
throw nvae;
}
switch (alt8) {
case 1 :
// InternalUrml.g:1802:1: ( ( rule__Operation__IsBoolAssignment_1_0 ) )
{
// InternalUrml.g:1802:1: ( ( rule__Operation__IsBoolAssignment_1_0 ) )
// InternalUrml.g:1803:1: ( rule__Operation__IsBoolAssignment_1_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsBoolAssignment_1_0());
}
// InternalUrml.g:1804:1: ( rule__Operation__IsBoolAssignment_1_0 )
// InternalUrml.g:1804:2: rule__Operation__IsBoolAssignment_1_0
{
pushFollow(FOLLOW_2);
rule__Operation__IsBoolAssignment_1_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsBoolAssignment_1_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1808:6: ( ( rule__Operation__IsIntAssignment_1_1 ) )
{
// InternalUrml.g:1808:6: ( ( rule__Operation__IsIntAssignment_1_1 ) )
// InternalUrml.g:1809:1: ( rule__Operation__IsIntAssignment_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsIntAssignment_1_1());
}
// InternalUrml.g:1810:1: ( rule__Operation__IsIntAssignment_1_1 )
// InternalUrml.g:1810:2: rule__Operation__IsIntAssignment_1_1
{
pushFollow(FOLLOW_2);
rule__Operation__IsIntAssignment_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsIntAssignment_1_1());
}
}
}
break;
case 3 :
// InternalUrml.g:1814:6: ( ( rule__Operation__IsVoidAssignment_1_2 ) )
{
// InternalUrml.g:1814:6: ( ( rule__Operation__IsVoidAssignment_1_2 ) )
// InternalUrml.g:1815:1: ( rule__Operation__IsVoidAssignment_1_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsVoidAssignment_1_2());
}
// InternalUrml.g:1816:1: ( rule__Operation__IsVoidAssignment_1_2 )
// InternalUrml.g:1816:2: rule__Operation__IsVoidAssignment_1_2
{
pushFollow(FOLLOW_2);
rule__Operation__IsVoidAssignment_1_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsVoidAssignment_1_2());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Alternatives_1"
// $ANTLR start "rule__StateMachine__Alternatives_3"
// InternalUrml.g:1825:1: rule__StateMachine__Alternatives_3 : ( ( ( rule__StateMachine__StatesAssignment_3_0 ) ) | ( ( rule__StateMachine__TransitionsAssignment_3_1 ) ) );
public final void rule__StateMachine__Alternatives_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1829:1: ( ( ( rule__StateMachine__StatesAssignment_3_0 ) ) | ( ( rule__StateMachine__TransitionsAssignment_3_1 ) ) )
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0==35||LA9_0==80) ) {
alt9=1;
}
else if ( (LA9_0==39) ) {
alt9=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 9, 0, input);
throw nvae;
}
switch (alt9) {
case 1 :
// InternalUrml.g:1830:1: ( ( rule__StateMachine__StatesAssignment_3_0 ) )
{
// InternalUrml.g:1830:1: ( ( rule__StateMachine__StatesAssignment_3_0 ) )
// InternalUrml.g:1831:1: ( rule__StateMachine__StatesAssignment_3_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getStatesAssignment_3_0());
}
// InternalUrml.g:1832:1: ( rule__StateMachine__StatesAssignment_3_0 )
// InternalUrml.g:1832:2: rule__StateMachine__StatesAssignment_3_0
{
pushFollow(FOLLOW_2);
rule__StateMachine__StatesAssignment_3_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getStatesAssignment_3_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1836:6: ( ( rule__StateMachine__TransitionsAssignment_3_1 ) )
{
// InternalUrml.g:1836:6: ( ( rule__StateMachine__TransitionsAssignment_3_1 ) )
// InternalUrml.g:1837:1: ( rule__StateMachine__TransitionsAssignment_3_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getTransitionsAssignment_3_1());
}
// InternalUrml.g:1838:1: ( rule__StateMachine__TransitionsAssignment_3_1 )
// InternalUrml.g:1838:2: rule__StateMachine__TransitionsAssignment_3_1
{
pushFollow(FOLLOW_2);
rule__StateMachine__TransitionsAssignment_3_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getTransitionsAssignment_3_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Alternatives_3"
// $ANTLR start "rule__Transition__Alternatives_3"
// InternalUrml.g:1847:1: rule__Transition__Alternatives_3 : ( ( ( rule__Transition__InitAssignment_3_0 ) ) | ( ( rule__Transition__FromAssignment_3_1 ) ) );
public final void rule__Transition__Alternatives_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1851:1: ( ( ( rule__Transition__InitAssignment_3_0 ) ) | ( ( rule__Transition__FromAssignment_3_1 ) ) )
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==81) ) {
alt10=1;
}
else if ( (LA10_0==RULE_ID) ) {
alt10=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 10, 0, input);
throw nvae;
}
switch (alt10) {
case 1 :
// InternalUrml.g:1852:1: ( ( rule__Transition__InitAssignment_3_0 ) )
{
// InternalUrml.g:1852:1: ( ( rule__Transition__InitAssignment_3_0 ) )
// InternalUrml.g:1853:1: ( rule__Transition__InitAssignment_3_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getInitAssignment_3_0());
}
// InternalUrml.g:1854:1: ( rule__Transition__InitAssignment_3_0 )
// InternalUrml.g:1854:2: rule__Transition__InitAssignment_3_0
{
pushFollow(FOLLOW_2);
rule__Transition__InitAssignment_3_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getInitAssignment_3_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1858:6: ( ( rule__Transition__FromAssignment_3_1 ) )
{
// InternalUrml.g:1858:6: ( ( rule__Transition__FromAssignment_3_1 ) )
// InternalUrml.g:1859:1: ( rule__Transition__FromAssignment_3_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getFromAssignment_3_1());
}
// InternalUrml.g:1860:1: ( rule__Transition__FromAssignment_3_1 )
// InternalUrml.g:1860:2: rule__Transition__FromAssignment_3_1
{
pushFollow(FOLLOW_2);
rule__Transition__FromAssignment_3_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getFromAssignment_3_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Alternatives_3"
// $ANTLR start "rule__Transition__Alternatives_8_1"
// InternalUrml.g:1869:1: rule__Transition__Alternatives_8_1 : ( ( ( rule__Transition__Group_8_1_0__0 ) ) | ( ( rule__Transition__Group_8_1_1__0 ) ) | ( ( rule__Transition__UniversalAssignment_8_1_2 ) ) );
public final void rule__Transition__Alternatives_8_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1873:1: ( ( ( rule__Transition__Group_8_1_0__0 ) ) | ( ( rule__Transition__Group_8_1_1__0 ) ) | ( ( rule__Transition__UniversalAssignment_8_1_2 ) ) )
int alt11=3;
switch ( input.LA(1) ) {
case RULE_ID:
{
alt11=1;
}
break;
case 44:
{
alt11=2;
}
break;
case 71:
{
alt11=3;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 11, 0, input);
throw nvae;
}
switch (alt11) {
case 1 :
// InternalUrml.g:1874:1: ( ( rule__Transition__Group_8_1_0__0 ) )
{
// InternalUrml.g:1874:1: ( ( rule__Transition__Group_8_1_0__0 ) )
// InternalUrml.g:1875:1: ( rule__Transition__Group_8_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup_8_1_0());
}
// InternalUrml.g:1876:1: ( rule__Transition__Group_8_1_0__0 )
// InternalUrml.g:1876:2: rule__Transition__Group_8_1_0__0
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup_8_1_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1880:6: ( ( rule__Transition__Group_8_1_1__0 ) )
{
// InternalUrml.g:1880:6: ( ( rule__Transition__Group_8_1_1__0 ) )
// InternalUrml.g:1881:1: ( rule__Transition__Group_8_1_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup_8_1_1());
}
// InternalUrml.g:1882:1: ( rule__Transition__Group_8_1_1__0 )
// InternalUrml.g:1882:2: rule__Transition__Group_8_1_1__0
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup_8_1_1());
}
}
}
break;
case 3 :
// InternalUrml.g:1886:6: ( ( rule__Transition__UniversalAssignment_8_1_2 ) )
{
// InternalUrml.g:1886:6: ( ( rule__Transition__UniversalAssignment_8_1_2 ) )
// InternalUrml.g:1887:1: ( rule__Transition__UniversalAssignment_8_1_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getUniversalAssignment_8_1_2());
}
// InternalUrml.g:1888:1: ( rule__Transition__UniversalAssignment_8_1_2 )
// InternalUrml.g:1888:2: rule__Transition__UniversalAssignment_8_1_2
{
pushFollow(FOLLOW_2);
rule__Transition__UniversalAssignment_8_1_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getUniversalAssignment_8_1_2());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Alternatives_8_1"
// $ANTLR start "rule__IncomingVariable__Alternatives_0"
// InternalUrml.g:1897:1: rule__IncomingVariable__Alternatives_0 : ( ( ( rule__IncomingVariable__IsBoolAssignment_0_0 ) ) | ( ( rule__IncomingVariable__IsIntAssignment_0_1 ) ) );
public final void rule__IncomingVariable__Alternatives_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1901:1: ( ( ( rule__IncomingVariable__IsBoolAssignment_0_0 ) ) | ( ( rule__IncomingVariable__IsIntAssignment_0_1 ) ) )
int alt12=2;
int LA12_0 = input.LA(1);
if ( (LA12_0==75) ) {
alt12=1;
}
else if ( (LA12_0==76) ) {
alt12=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 12, 0, input);
throw nvae;
}
switch (alt12) {
case 1 :
// InternalUrml.g:1902:1: ( ( rule__IncomingVariable__IsBoolAssignment_0_0 ) )
{
// InternalUrml.g:1902:1: ( ( rule__IncomingVariable__IsBoolAssignment_0_0 ) )
// InternalUrml.g:1903:1: ( rule__IncomingVariable__IsBoolAssignment_0_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getIsBoolAssignment_0_0());
}
// InternalUrml.g:1904:1: ( rule__IncomingVariable__IsBoolAssignment_0_0 )
// InternalUrml.g:1904:2: rule__IncomingVariable__IsBoolAssignment_0_0
{
pushFollow(FOLLOW_2);
rule__IncomingVariable__IsBoolAssignment_0_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getIsBoolAssignment_0_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1908:6: ( ( rule__IncomingVariable__IsIntAssignment_0_1 ) )
{
// InternalUrml.g:1908:6: ( ( rule__IncomingVariable__IsIntAssignment_0_1 ) )
// InternalUrml.g:1909:1: ( rule__IncomingVariable__IsIntAssignment_0_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getIsIntAssignment_0_1());
}
// InternalUrml.g:1910:1: ( rule__IncomingVariable__IsIntAssignment_0_1 )
// InternalUrml.g:1910:2: rule__IncomingVariable__IsIntAssignment_0_1
{
pushFollow(FOLLOW_2);
rule__IncomingVariable__IsIntAssignment_0_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getIsIntAssignment_0_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__Alternatives_0"
// $ANTLR start "rule__StatementOperation__Alternatives"
// InternalUrml.g:1919:1: rule__StatementOperation__Alternatives : ( ( ruleNoOp ) | ( ruleVariable ) | ( ruleInvoke ) | ( ruleAssignment ) | ( ruleSendTrigger ) | ( ruleInformTimer ) | ( ruleWhileLoopOperation ) | ( ruleIfStatementOperation ) | ( ruleLogStatement ) | ( ruleReturnStatement ) | ( ruleChooseStatement ) | ( ruleFlipStatement ) );
public final void rule__StatementOperation__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:1923:1: ( ( ruleNoOp ) | ( ruleVariable ) | ( ruleInvoke ) | ( ruleAssignment ) | ( ruleSendTrigger ) | ( ruleInformTimer ) | ( ruleWhileLoopOperation ) | ( ruleIfStatementOperation ) | ( ruleLogStatement ) | ( ruleReturnStatement ) | ( ruleChooseStatement ) | ( ruleFlipStatement ) )
int alt13=12;
switch ( input.LA(1) ) {
case 54:
{
alt13=1;
}
break;
case 50:
{
alt13=2;
}
break;
case 55:
{
alt13=3;
}
break;
case RULE_ID:
{
alt13=4;
}
break;
case 51:
{
alt13=5;
}
break;
case 52:
{
alt13=6;
}
break;
case 46:
{
alt13=7;
}
break;
case 47:
{
alt13=8;
}
break;
case 56:
{
alt13=9;
}
break;
case 49:
{
alt13=10;
}
break;
case 58:
{
alt13=11;
}
break;
case 59:
{
alt13=12;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 13, 0, input);
throw nvae;
}
switch (alt13) {
case 1 :
// InternalUrml.g:1924:1: ( ruleNoOp )
{
// InternalUrml.g:1924:1: ( ruleNoOp )
// InternalUrml.g:1925:1: ruleNoOp
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getNoOpParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleNoOp();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getNoOpParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:1930:6: ( ruleVariable )
{
// InternalUrml.g:1930:6: ( ruleVariable )
// InternalUrml.g:1931:1: ruleVariable
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getVariableParserRuleCall_1());
}
pushFollow(FOLLOW_2);
ruleVariable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getVariableParserRuleCall_1());
}
}
}
break;
case 3 :
// InternalUrml.g:1936:6: ( ruleInvoke )
{
// InternalUrml.g:1936:6: ( ruleInvoke )
// InternalUrml.g:1937:1: ruleInvoke
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getInvokeParserRuleCall_2());
}
pushFollow(FOLLOW_2);
ruleInvoke();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getInvokeParserRuleCall_2());
}
}
}
break;
case 4 :
// InternalUrml.g:1942:6: ( ruleAssignment )
{
// InternalUrml.g:1942:6: ( ruleAssignment )
// InternalUrml.g:1943:1: ruleAssignment
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getAssignmentParserRuleCall_3());
}
pushFollow(FOLLOW_2);
ruleAssignment();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getAssignmentParserRuleCall_3());
}
}
}
break;
case 5 :
// InternalUrml.g:1948:6: ( ruleSendTrigger )
{
// InternalUrml.g:1948:6: ( ruleSendTrigger )
// InternalUrml.g:1949:1: ruleSendTrigger
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getSendTriggerParserRuleCall_4());
}
pushFollow(FOLLOW_2);
ruleSendTrigger();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getSendTriggerParserRuleCall_4());
}
}
}
break;
case 6 :
// InternalUrml.g:1954:6: ( ruleInformTimer )
{
// InternalUrml.g:1954:6: ( ruleInformTimer )
// InternalUrml.g:1955:1: ruleInformTimer
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getInformTimerParserRuleCall_5());
}
pushFollow(FOLLOW_2);
ruleInformTimer();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getInformTimerParserRuleCall_5());
}
}
}
break;
case 7 :
// InternalUrml.g:1960:6: ( ruleWhileLoopOperation )
{
// InternalUrml.g:1960:6: ( ruleWhileLoopOperation )
// InternalUrml.g:1961:1: ruleWhileLoopOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getWhileLoopOperationParserRuleCall_6());
}
pushFollow(FOLLOW_2);
ruleWhileLoopOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getWhileLoopOperationParserRuleCall_6());
}
}
}
break;
case 8 :
// InternalUrml.g:1966:6: ( ruleIfStatementOperation )
{
// InternalUrml.g:1966:6: ( ruleIfStatementOperation )
// InternalUrml.g:1967:1: ruleIfStatementOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getIfStatementOperationParserRuleCall_7());
}
pushFollow(FOLLOW_2);
ruleIfStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getIfStatementOperationParserRuleCall_7());
}
}
}
break;
case 9 :
// InternalUrml.g:1972:6: ( ruleLogStatement )
{
// InternalUrml.g:1972:6: ( ruleLogStatement )
// InternalUrml.g:1973:1: ruleLogStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getLogStatementParserRuleCall_8());
}
pushFollow(FOLLOW_2);
ruleLogStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getLogStatementParserRuleCall_8());
}
}
}
break;
case 10 :
// InternalUrml.g:1978:6: ( ruleReturnStatement )
{
// InternalUrml.g:1978:6: ( ruleReturnStatement )
// InternalUrml.g:1979:1: ruleReturnStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getReturnStatementParserRuleCall_9());
}
pushFollow(FOLLOW_2);
ruleReturnStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getReturnStatementParserRuleCall_9());
}
}
}
break;
case 11 :
// InternalUrml.g:1984:6: ( ruleChooseStatement )
{
// InternalUrml.g:1984:6: ( ruleChooseStatement )
// InternalUrml.g:1985:1: ruleChooseStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getChooseStatementParserRuleCall_10());
}
pushFollow(FOLLOW_2);
ruleChooseStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getChooseStatementParserRuleCall_10());
}
}
}
break;
case 12 :
// InternalUrml.g:1990:6: ( ruleFlipStatement )
{
// InternalUrml.g:1990:6: ( ruleFlipStatement )
// InternalUrml.g:1991:1: ruleFlipStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementOperationAccess().getFlipStatementParserRuleCall_11());
}
pushFollow(FOLLOW_2);
ruleFlipStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementOperationAccess().getFlipStatementParserRuleCall_11());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StatementOperation__Alternatives"
// $ANTLR start "rule__Statement__Alternatives"
// InternalUrml.g:2001:1: rule__Statement__Alternatives : ( ( ruleSendTrigger ) | ( ruleVariable ) | ( ruleInformTimer ) | ( ruleNoOp ) | ( ruleInvoke ) | ( ruleAssignment ) | ( ruleWhileLoop ) | ( ruleIfStatement ) | ( ruleLogStatement ) | ( ruleChooseStatement ) | ( ruleFlipStatement ) );
public final void rule__Statement__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2005:1: ( ( ruleSendTrigger ) | ( ruleVariable ) | ( ruleInformTimer ) | ( ruleNoOp ) | ( ruleInvoke ) | ( ruleAssignment ) | ( ruleWhileLoop ) | ( ruleIfStatement ) | ( ruleLogStatement ) | ( ruleChooseStatement ) | ( ruleFlipStatement ) )
int alt14=11;
switch ( input.LA(1) ) {
case 51:
{
alt14=1;
}
break;
case 50:
{
alt14=2;
}
break;
case 52:
{
alt14=3;
}
break;
case 54:
{
alt14=4;
}
break;
case 55:
{
alt14=5;
}
break;
case RULE_ID:
{
alt14=6;
}
break;
case 46:
{
alt14=7;
}
break;
case 47:
{
alt14=8;
}
break;
case 56:
{
alt14=9;
}
break;
case 58:
{
alt14=10;
}
break;
case 59:
{
alt14=11;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 14, 0, input);
throw nvae;
}
switch (alt14) {
case 1 :
// InternalUrml.g:2006:1: ( ruleSendTrigger )
{
// InternalUrml.g:2006:1: ( ruleSendTrigger )
// InternalUrml.g:2007:1: ruleSendTrigger
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getSendTriggerParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleSendTrigger();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getSendTriggerParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2012:6: ( ruleVariable )
{
// InternalUrml.g:2012:6: ( ruleVariable )
// InternalUrml.g:2013:1: ruleVariable
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getVariableParserRuleCall_1());
}
pushFollow(FOLLOW_2);
ruleVariable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getVariableParserRuleCall_1());
}
}
}
break;
case 3 :
// InternalUrml.g:2018:6: ( ruleInformTimer )
{
// InternalUrml.g:2018:6: ( ruleInformTimer )
// InternalUrml.g:2019:1: ruleInformTimer
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getInformTimerParserRuleCall_2());
}
pushFollow(FOLLOW_2);
ruleInformTimer();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getInformTimerParserRuleCall_2());
}
}
}
break;
case 4 :
// InternalUrml.g:2024:6: ( ruleNoOp )
{
// InternalUrml.g:2024:6: ( ruleNoOp )
// InternalUrml.g:2025:1: ruleNoOp
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getNoOpParserRuleCall_3());
}
pushFollow(FOLLOW_2);
ruleNoOp();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getNoOpParserRuleCall_3());
}
}
}
break;
case 5 :
// InternalUrml.g:2030:6: ( ruleInvoke )
{
// InternalUrml.g:2030:6: ( ruleInvoke )
// InternalUrml.g:2031:1: ruleInvoke
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getInvokeParserRuleCall_4());
}
pushFollow(FOLLOW_2);
ruleInvoke();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getInvokeParserRuleCall_4());
}
}
}
break;
case 6 :
// InternalUrml.g:2036:6: ( ruleAssignment )
{
// InternalUrml.g:2036:6: ( ruleAssignment )
// InternalUrml.g:2037:1: ruleAssignment
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getAssignmentParserRuleCall_5());
}
pushFollow(FOLLOW_2);
ruleAssignment();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getAssignmentParserRuleCall_5());
}
}
}
break;
case 7 :
// InternalUrml.g:2042:6: ( ruleWhileLoop )
{
// InternalUrml.g:2042:6: ( ruleWhileLoop )
// InternalUrml.g:2043:1: ruleWhileLoop
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getWhileLoopParserRuleCall_6());
}
pushFollow(FOLLOW_2);
ruleWhileLoop();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getWhileLoopParserRuleCall_6());
}
}
}
break;
case 8 :
// InternalUrml.g:2048:6: ( ruleIfStatement )
{
// InternalUrml.g:2048:6: ( ruleIfStatement )
// InternalUrml.g:2049:1: ruleIfStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getIfStatementParserRuleCall_7());
}
pushFollow(FOLLOW_2);
ruleIfStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getIfStatementParserRuleCall_7());
}
}
}
break;
case 9 :
// InternalUrml.g:2054:6: ( ruleLogStatement )
{
// InternalUrml.g:2054:6: ( ruleLogStatement )
// InternalUrml.g:2055:1: ruleLogStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getLogStatementParserRuleCall_8());
}
pushFollow(FOLLOW_2);
ruleLogStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getLogStatementParserRuleCall_8());
}
}
}
break;
case 10 :
// InternalUrml.g:2060:6: ( ruleChooseStatement )
{
// InternalUrml.g:2060:6: ( ruleChooseStatement )
// InternalUrml.g:2061:1: ruleChooseStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getChooseStatementParserRuleCall_9());
}
pushFollow(FOLLOW_2);
ruleChooseStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getChooseStatementParserRuleCall_9());
}
}
}
break;
case 11 :
// InternalUrml.g:2066:6: ( ruleFlipStatement )
{
// InternalUrml.g:2066:6: ( ruleFlipStatement )
// InternalUrml.g:2067:1: ruleFlipStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStatementAccess().getFlipStatementParserRuleCall_10());
}
pushFollow(FOLLOW_2);
ruleFlipStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStatementAccess().getFlipStatementParserRuleCall_10());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Statement__Alternatives"
// $ANTLR start "rule__Assignable__Alternatives"
// InternalUrml.g:2077:1: rule__Assignable__Alternatives : ( ( ruleLocalVar ) | ( ruleAttribute ) );
public final void rule__Assignable__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2081:1: ( ( ruleLocalVar ) | ( ruleAttribute ) )
int alt15=2;
int LA15_0 = input.LA(1);
if ( ((LA15_0>=75 && LA15_0<=76)) ) {
alt15=1;
}
else if ( (LA15_0==15) ) {
alt15=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 15, 0, input);
throw nvae;
}
switch (alt15) {
case 1 :
// InternalUrml.g:2082:1: ( ruleLocalVar )
{
// InternalUrml.g:2082:1: ( ruleLocalVar )
// InternalUrml.g:2083:1: ruleLocalVar
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignableAccess().getLocalVarParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignableAccess().getLocalVarParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2088:6: ( ruleAttribute )
{
// InternalUrml.g:2088:6: ( ruleAttribute )
// InternalUrml.g:2089:1: ruleAttribute
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignableAccess().getAttributeParserRuleCall_1());
}
pushFollow(FOLLOW_2);
ruleAttribute();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignableAccess().getAttributeParserRuleCall_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignable__Alternatives"
// $ANTLR start "rule__IndividualExpression__Alternatives"
// InternalUrml.g:2099:1: rule__IndividualExpression__Alternatives : ( ( ( rule__IndividualExpression__ExprAssignment_0 ) ) | ( ( rule__IndividualExpression__StrAssignment_1 ) ) );
public final void rule__IndividualExpression__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2103:1: ( ( ( rule__IndividualExpression__ExprAssignment_0 ) ) | ( ( rule__IndividualExpression__StrAssignment_1 ) ) )
int alt16=2;
int LA16_0 = input.LA(1);
if ( (LA16_0==RULE_ID||(LA16_0>=RULE_INT && LA16_0<=RULE_BOOLEAN)||LA16_0==20||LA16_0==70||LA16_0==74) ) {
alt16=1;
}
else if ( (LA16_0==RULE_STRING) ) {
alt16=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 16, 0, input);
throw nvae;
}
switch (alt16) {
case 1 :
// InternalUrml.g:2104:1: ( ( rule__IndividualExpression__ExprAssignment_0 ) )
{
// InternalUrml.g:2104:1: ( ( rule__IndividualExpression__ExprAssignment_0 ) )
// InternalUrml.g:2105:1: ( rule__IndividualExpression__ExprAssignment_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIndividualExpressionAccess().getExprAssignment_0());
}
// InternalUrml.g:2106:1: ( rule__IndividualExpression__ExprAssignment_0 )
// InternalUrml.g:2106:2: rule__IndividualExpression__ExprAssignment_0
{
pushFollow(FOLLOW_2);
rule__IndividualExpression__ExprAssignment_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIndividualExpressionAccess().getExprAssignment_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2110:6: ( ( rule__IndividualExpression__StrAssignment_1 ) )
{
// InternalUrml.g:2110:6: ( ( rule__IndividualExpression__StrAssignment_1 ) )
// InternalUrml.g:2111:1: ( rule__IndividualExpression__StrAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIndividualExpressionAccess().getStrAssignment_1());
}
// InternalUrml.g:2112:1: ( rule__IndividualExpression__StrAssignment_1 )
// InternalUrml.g:2112:2: rule__IndividualExpression__StrAssignment_1
{
pushFollow(FOLLOW_2);
rule__IndividualExpression__StrAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIndividualExpressionAccess().getStrAssignment_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IndividualExpression__Alternatives"
// $ANTLR start "rule__RelationalOpExpression__Alternatives_1_0_0"
// InternalUrml.g:2121:1: rule__RelationalOpExpression__Alternatives_1_0_0 : ( ( ( rule__RelationalOpExpression__Group_1_0_0_0__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_1__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_2__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_3__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_4__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_5__0 ) ) );
public final void rule__RelationalOpExpression__Alternatives_1_0_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2125:1: ( ( ( rule__RelationalOpExpression__Group_1_0_0_0__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_1__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_2__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_3__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_4__0 ) ) | ( ( rule__RelationalOpExpression__Group_1_0_0_5__0 ) ) )
int alt17=6;
switch ( input.LA(1) ) {
case 63:
{
alt17=1;
}
break;
case 64:
{
alt17=2;
}
break;
case 65:
{
alt17=3;
}
break;
case 66:
{
alt17=4;
}
break;
case 67:
{
alt17=5;
}
break;
case 68:
{
alt17=6;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 17, 0, input);
throw nvae;
}
switch (alt17) {
case 1 :
// InternalUrml.g:2126:1: ( ( rule__RelationalOpExpression__Group_1_0_0_0__0 ) )
{
// InternalUrml.g:2126:1: ( ( rule__RelationalOpExpression__Group_1_0_0_0__0 ) )
// InternalUrml.g:2127:1: ( rule__RelationalOpExpression__Group_1_0_0_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_0());
}
// InternalUrml.g:2128:1: ( rule__RelationalOpExpression__Group_1_0_0_0__0 )
// InternalUrml.g:2128:2: rule__RelationalOpExpression__Group_1_0_0_0__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2132:6: ( ( rule__RelationalOpExpression__Group_1_0_0_1__0 ) )
{
// InternalUrml.g:2132:6: ( ( rule__RelationalOpExpression__Group_1_0_0_1__0 ) )
// InternalUrml.g:2133:1: ( rule__RelationalOpExpression__Group_1_0_0_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_1());
}
// InternalUrml.g:2134:1: ( rule__RelationalOpExpression__Group_1_0_0_1__0 )
// InternalUrml.g:2134:2: rule__RelationalOpExpression__Group_1_0_0_1__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_1());
}
}
}
break;
case 3 :
// InternalUrml.g:2138:6: ( ( rule__RelationalOpExpression__Group_1_0_0_2__0 ) )
{
// InternalUrml.g:2138:6: ( ( rule__RelationalOpExpression__Group_1_0_0_2__0 ) )
// InternalUrml.g:2139:1: ( rule__RelationalOpExpression__Group_1_0_0_2__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_2());
}
// InternalUrml.g:2140:1: ( rule__RelationalOpExpression__Group_1_0_0_2__0 )
// InternalUrml.g:2140:2: rule__RelationalOpExpression__Group_1_0_0_2__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_2__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_2());
}
}
}
break;
case 4 :
// InternalUrml.g:2144:6: ( ( rule__RelationalOpExpression__Group_1_0_0_3__0 ) )
{
// InternalUrml.g:2144:6: ( ( rule__RelationalOpExpression__Group_1_0_0_3__0 ) )
// InternalUrml.g:2145:1: ( rule__RelationalOpExpression__Group_1_0_0_3__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_3());
}
// InternalUrml.g:2146:1: ( rule__RelationalOpExpression__Group_1_0_0_3__0 )
// InternalUrml.g:2146:2: rule__RelationalOpExpression__Group_1_0_0_3__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_3__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_3());
}
}
}
break;
case 5 :
// InternalUrml.g:2150:6: ( ( rule__RelationalOpExpression__Group_1_0_0_4__0 ) )
{
// InternalUrml.g:2150:6: ( ( rule__RelationalOpExpression__Group_1_0_0_4__0 ) )
// InternalUrml.g:2151:1: ( rule__RelationalOpExpression__Group_1_0_0_4__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_4());
}
// InternalUrml.g:2152:1: ( rule__RelationalOpExpression__Group_1_0_0_4__0 )
// InternalUrml.g:2152:2: rule__RelationalOpExpression__Group_1_0_0_4__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_4__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_4());
}
}
}
break;
case 6 :
// InternalUrml.g:2156:6: ( ( rule__RelationalOpExpression__Group_1_0_0_5__0 ) )
{
// InternalUrml.g:2156:6: ( ( rule__RelationalOpExpression__Group_1_0_0_5__0 ) )
// InternalUrml.g:2157:1: ( rule__RelationalOpExpression__Group_1_0_0_5__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_5());
}
// InternalUrml.g:2158:1: ( rule__RelationalOpExpression__Group_1_0_0_5__0 )
// InternalUrml.g:2158:2: rule__RelationalOpExpression__Group_1_0_0_5__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_5__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0_0_5());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Alternatives_1_0_0"
// $ANTLR start "rule__AdditiveExpression__Alternatives_1_0_0"
// InternalUrml.g:2167:1: rule__AdditiveExpression__Alternatives_1_0_0 : ( ( ( rule__AdditiveExpression__Group_1_0_0_0__0 ) ) | ( ( rule__AdditiveExpression__Group_1_0_0_1__0 ) ) );
public final void rule__AdditiveExpression__Alternatives_1_0_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2171:1: ( ( ( rule__AdditiveExpression__Group_1_0_0_0__0 ) ) | ( ( rule__AdditiveExpression__Group_1_0_0_1__0 ) ) )
int alt18=2;
int LA18_0 = input.LA(1);
if ( (LA18_0==69) ) {
alt18=1;
}
else if ( (LA18_0==70) ) {
alt18=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 18, 0, input);
throw nvae;
}
switch (alt18) {
case 1 :
// InternalUrml.g:2172:1: ( ( rule__AdditiveExpression__Group_1_0_0_0__0 ) )
{
// InternalUrml.g:2172:1: ( ( rule__AdditiveExpression__Group_1_0_0_0__0 ) )
// InternalUrml.g:2173:1: ( rule__AdditiveExpression__Group_1_0_0_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getGroup_1_0_0_0());
}
// InternalUrml.g:2174:1: ( rule__AdditiveExpression__Group_1_0_0_0__0 )
// InternalUrml.g:2174:2: rule__AdditiveExpression__Group_1_0_0_0__0
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0_0_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getGroup_1_0_0_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2178:6: ( ( rule__AdditiveExpression__Group_1_0_0_1__0 ) )
{
// InternalUrml.g:2178:6: ( ( rule__AdditiveExpression__Group_1_0_0_1__0 ) )
// InternalUrml.g:2179:1: ( rule__AdditiveExpression__Group_1_0_0_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getGroup_1_0_0_1());
}
// InternalUrml.g:2180:1: ( rule__AdditiveExpression__Group_1_0_0_1__0 )
// InternalUrml.g:2180:2: rule__AdditiveExpression__Group_1_0_0_1__0
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0_0_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getGroup_1_0_0_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Alternatives_1_0_0"
// $ANTLR start "rule__MultiplicativeExpression__Alternatives_1_0_0"
// InternalUrml.g:2189:1: rule__MultiplicativeExpression__Alternatives_1_0_0 : ( ( ( rule__MultiplicativeExpression__Group_1_0_0_0__0 ) ) | ( ( rule__MultiplicativeExpression__Group_1_0_0_1__0 ) ) | ( ( rule__MultiplicativeExpression__Group_1_0_0_2__0 ) ) );
public final void rule__MultiplicativeExpression__Alternatives_1_0_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2193:1: ( ( ( rule__MultiplicativeExpression__Group_1_0_0_0__0 ) ) | ( ( rule__MultiplicativeExpression__Group_1_0_0_1__0 ) ) | ( ( rule__MultiplicativeExpression__Group_1_0_0_2__0 ) ) )
int alt19=3;
switch ( input.LA(1) ) {
case 71:
{
alt19=1;
}
break;
case 72:
{
alt19=2;
}
break;
case 73:
{
alt19=3;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 19, 0, input);
throw nvae;
}
switch (alt19) {
case 1 :
// InternalUrml.g:2194:1: ( ( rule__MultiplicativeExpression__Group_1_0_0_0__0 ) )
{
// InternalUrml.g:2194:1: ( ( rule__MultiplicativeExpression__Group_1_0_0_0__0 ) )
// InternalUrml.g:2195:1: ( rule__MultiplicativeExpression__Group_1_0_0_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0_0_0());
}
// InternalUrml.g:2196:1: ( rule__MultiplicativeExpression__Group_1_0_0_0__0 )
// InternalUrml.g:2196:2: rule__MultiplicativeExpression__Group_1_0_0_0__0
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0_0_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2200:6: ( ( rule__MultiplicativeExpression__Group_1_0_0_1__0 ) )
{
// InternalUrml.g:2200:6: ( ( rule__MultiplicativeExpression__Group_1_0_0_1__0 ) )
// InternalUrml.g:2201:1: ( rule__MultiplicativeExpression__Group_1_0_0_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0_0_1());
}
// InternalUrml.g:2202:1: ( rule__MultiplicativeExpression__Group_1_0_0_1__0 )
// InternalUrml.g:2202:2: rule__MultiplicativeExpression__Group_1_0_0_1__0
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0_0_1());
}
}
}
break;
case 3 :
// InternalUrml.g:2206:6: ( ( rule__MultiplicativeExpression__Group_1_0_0_2__0 ) )
{
// InternalUrml.g:2206:6: ( ( rule__MultiplicativeExpression__Group_1_0_0_2__0 ) )
// InternalUrml.g:2207:1: ( rule__MultiplicativeExpression__Group_1_0_0_2__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0_0_2());
}
// InternalUrml.g:2208:1: ( rule__MultiplicativeExpression__Group_1_0_0_2__0 )
// InternalUrml.g:2208:2: rule__MultiplicativeExpression__Group_1_0_0_2__0
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_2__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0_0_2());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Alternatives_1_0_0"
// $ANTLR start "rule__UnaryExpression__Alternatives"
// InternalUrml.g:2217:1: rule__UnaryExpression__Alternatives : ( ( ruleUnaryExpressionNotPlusMinus ) | ( ( rule__UnaryExpression__Group_1__0 ) ) );
public final void rule__UnaryExpression__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2221:1: ( ( ruleUnaryExpressionNotPlusMinus ) | ( ( rule__UnaryExpression__Group_1__0 ) ) )
int alt20=2;
int LA20_0 = input.LA(1);
if ( (LA20_0==RULE_ID||(LA20_0>=RULE_INT && LA20_0<=RULE_BOOLEAN)||LA20_0==20||LA20_0==74) ) {
alt20=1;
}
else if ( (LA20_0==70) ) {
alt20=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 20, 0, input);
throw nvae;
}
switch (alt20) {
case 1 :
// InternalUrml.g:2222:1: ( ruleUnaryExpressionNotPlusMinus )
{
// InternalUrml.g:2222:1: ( ruleUnaryExpressionNotPlusMinus )
// InternalUrml.g:2223:1: ruleUnaryExpressionNotPlusMinus
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getUnaryExpressionNotPlusMinusParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleUnaryExpressionNotPlusMinus();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getUnaryExpressionNotPlusMinusParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2228:6: ( ( rule__UnaryExpression__Group_1__0 ) )
{
// InternalUrml.g:2228:6: ( ( rule__UnaryExpression__Group_1__0 ) )
// InternalUrml.g:2229:1: ( rule__UnaryExpression__Group_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getGroup_1());
}
// InternalUrml.g:2230:1: ( rule__UnaryExpression__Group_1__0 )
// InternalUrml.g:2230:2: rule__UnaryExpression__Group_1__0
{
pushFollow(FOLLOW_2);
rule__UnaryExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getGroup_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Alternatives"
// $ANTLR start "rule__UnaryExpressionNotPlusMinus__Alternatives"
// InternalUrml.g:2239:1: rule__UnaryExpressionNotPlusMinus__Alternatives : ( ( ruleNotBooleanExpression ) | ( rulePrimaryExpression ) );
public final void rule__UnaryExpressionNotPlusMinus__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2243:1: ( ( ruleNotBooleanExpression ) | ( rulePrimaryExpression ) )
int alt21=2;
int LA21_0 = input.LA(1);
if ( (LA21_0==74) ) {
alt21=1;
}
else if ( (LA21_0==RULE_ID||(LA21_0>=RULE_INT && LA21_0<=RULE_BOOLEAN)||LA21_0==20) ) {
alt21=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 21, 0, input);
throw nvae;
}
switch (alt21) {
case 1 :
// InternalUrml.g:2244:1: ( ruleNotBooleanExpression )
{
// InternalUrml.g:2244:1: ( ruleNotBooleanExpression )
// InternalUrml.g:2245:1: ruleNotBooleanExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionNotPlusMinusAccess().getNotBooleanExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleNotBooleanExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionNotPlusMinusAccess().getNotBooleanExpressionParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2250:6: ( rulePrimaryExpression )
{
// InternalUrml.g:2250:6: ( rulePrimaryExpression )
// InternalUrml.g:2251:1: rulePrimaryExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionNotPlusMinusAccess().getPrimaryExpressionParserRuleCall_1());
}
pushFollow(FOLLOW_2);
rulePrimaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionNotPlusMinusAccess().getPrimaryExpressionParserRuleCall_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpressionNotPlusMinus__Alternatives"
// $ANTLR start "rule__PrimaryExpression__Alternatives"
// InternalUrml.g:2261:1: rule__PrimaryExpression__Alternatives : ( ( ruleLiteralOrIdentifier ) | ( ( rule__PrimaryExpression__Group_1__0 ) ) );
public final void rule__PrimaryExpression__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2265:1: ( ( ruleLiteralOrIdentifier ) | ( ( rule__PrimaryExpression__Group_1__0 ) ) )
int alt22=2;
int LA22_0 = input.LA(1);
if ( (LA22_0==RULE_ID||(LA22_0>=RULE_INT && LA22_0<=RULE_BOOLEAN)) ) {
alt22=1;
}
else if ( (LA22_0==20) ) {
alt22=2;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 22, 0, input);
throw nvae;
}
switch (alt22) {
case 1 :
// InternalUrml.g:2266:1: ( ruleLiteralOrIdentifier )
{
// InternalUrml.g:2266:1: ( ruleLiteralOrIdentifier )
// InternalUrml.g:2267:1: ruleLiteralOrIdentifier
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionAccess().getLiteralOrIdentifierParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleLiteralOrIdentifier();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionAccess().getLiteralOrIdentifierParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2272:6: ( ( rule__PrimaryExpression__Group_1__0 ) )
{
// InternalUrml.g:2272:6: ( ( rule__PrimaryExpression__Group_1__0 ) )
// InternalUrml.g:2273:1: ( rule__PrimaryExpression__Group_1__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionAccess().getGroup_1());
}
// InternalUrml.g:2274:1: ( rule__PrimaryExpression__Group_1__0 )
// InternalUrml.g:2274:2: rule__PrimaryExpression__Group_1__0
{
pushFollow(FOLLOW_2);
rule__PrimaryExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionAccess().getGroup_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Alternatives"
// $ANTLR start "rule__LiteralOrIdentifier__Alternatives"
// InternalUrml.g:2283:1: rule__LiteralOrIdentifier__Alternatives : ( ( ruleLiteral ) | ( ruleIdentifier ) );
public final void rule__LiteralOrIdentifier__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2287:1: ( ( ruleLiteral ) | ( ruleIdentifier ) )
int alt23=2;
int LA23_0 = input.LA(1);
if ( ((LA23_0>=RULE_INT && LA23_0<=RULE_BOOLEAN)) ) {
alt23=1;
}
else if ( (LA23_0==RULE_ID) ) {
int LA23_2 = input.LA(2);
if ( (LA23_2==EOF||LA23_2==RULE_ID||(LA23_2>=13 && LA23_2<=15)||(LA23_2>=21 && LA23_2<=22)||(LA23_2>=24 && LA23_2<=28)||LA23_2==30||(LA23_2>=33 && LA23_2<=34)||(LA23_2>=46 && LA23_2<=47)||(LA23_2>=49 && LA23_2<=52)||(LA23_2>=54 && LA23_2<=56)||(LA23_2>=58 && LA23_2<=73)) ) {
alt23=2;
}
else if ( (LA23_2==20) ) {
alt23=1;
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 23, 2, input);
throw nvae;
}
}
else {
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 23, 0, input);
throw nvae;
}
switch (alt23) {
case 1 :
// InternalUrml.g:2288:1: ( ruleLiteral )
{
// InternalUrml.g:2288:1: ( ruleLiteral )
// InternalUrml.g:2289:1: ruleLiteral
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralOrIdentifierAccess().getLiteralParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleLiteral();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralOrIdentifierAccess().getLiteralParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2294:6: ( ruleIdentifier )
{
// InternalUrml.g:2294:6: ( ruleIdentifier )
// InternalUrml.g:2295:1: ruleIdentifier
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralOrIdentifierAccess().getIdentifierParserRuleCall_1());
}
pushFollow(FOLLOW_2);
ruleIdentifier();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralOrIdentifierAccess().getIdentifierParserRuleCall_1());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LiteralOrIdentifier__Alternatives"
// $ANTLR start "rule__Literal__Alternatives"
// InternalUrml.g:2305:1: rule__Literal__Alternatives : ( ( ruleIntLiteral ) | ( ruleBoolLiteral ) | ( ruleFunctionCall ) );
public final void rule__Literal__Alternatives() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2309:1: ( ( ruleIntLiteral ) | ( ruleBoolLiteral ) | ( ruleFunctionCall ) )
int alt24=3;
switch ( input.LA(1) ) {
case RULE_INT:
{
alt24=1;
}
break;
case RULE_BOOLEAN:
{
alt24=2;
}
break;
case RULE_ID:
{
alt24=3;
}
break;
default:
if (state.backtracking>0) {state.failed=true; return ;}
NoViableAltException nvae =
new NoViableAltException("", 24, 0, input);
throw nvae;
}
switch (alt24) {
case 1 :
// InternalUrml.g:2310:1: ( ruleIntLiteral )
{
// InternalUrml.g:2310:1: ( ruleIntLiteral )
// InternalUrml.g:2311:1: ruleIntLiteral
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralAccess().getIntLiteralParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleIntLiteral();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralAccess().getIntLiteralParserRuleCall_0());
}
}
}
break;
case 2 :
// InternalUrml.g:2316:6: ( ruleBoolLiteral )
{
// InternalUrml.g:2316:6: ( ruleBoolLiteral )
// InternalUrml.g:2317:1: ruleBoolLiteral
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralAccess().getBoolLiteralParserRuleCall_1());
}
pushFollow(FOLLOW_2);
ruleBoolLiteral();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralAccess().getBoolLiteralParserRuleCall_1());
}
}
}
break;
case 3 :
// InternalUrml.g:2322:6: ( ruleFunctionCall )
{
// InternalUrml.g:2322:6: ( ruleFunctionCall )
// InternalUrml.g:2323:1: ruleFunctionCall
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLiteralAccess().getFunctionCallParserRuleCall_2());
}
pushFollow(FOLLOW_2);
ruleFunctionCall();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLiteralAccess().getFunctionCallParserRuleCall_2());
}
}
}
break;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Literal__Alternatives"
// $ANTLR start "rule__Model__Group__0"
// InternalUrml.g:2336:1: rule__Model__Group__0 : rule__Model__Group__0__Impl rule__Model__Group__1 ;
public final void rule__Model__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2340:1: ( rule__Model__Group__0__Impl rule__Model__Group__1 )
// InternalUrml.g:2341:2: rule__Model__Group__0__Impl rule__Model__Group__1
{
pushFollow(FOLLOW_4);
rule__Model__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Model__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__0"
// $ANTLR start "rule__Model__Group__0__Impl"
// InternalUrml.g:2348:1: rule__Model__Group__0__Impl : ( 'model' ) ;
public final void rule__Model__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2352:1: ( ( 'model' ) )
// InternalUrml.g:2353:1: ( 'model' )
{
// InternalUrml.g:2353:1: ( 'model' )
// InternalUrml.g:2354:1: 'model'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getModelKeyword_0());
}
match(input,12,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getModelKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__0__Impl"
// $ANTLR start "rule__Model__Group__1"
// InternalUrml.g:2367:1: rule__Model__Group__1 : rule__Model__Group__1__Impl rule__Model__Group__2 ;
public final void rule__Model__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2371:1: ( rule__Model__Group__1__Impl rule__Model__Group__2 )
// InternalUrml.g:2372:2: rule__Model__Group__1__Impl rule__Model__Group__2
{
pushFollow(FOLLOW_5);
rule__Model__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Model__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__1"
// $ANTLR start "rule__Model__Group__1__Impl"
// InternalUrml.g:2379:1: rule__Model__Group__1__Impl : ( ( rule__Model__NameAssignment_1 ) ) ;
public final void rule__Model__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2383:1: ( ( ( rule__Model__NameAssignment_1 ) ) )
// InternalUrml.g:2384:1: ( ( rule__Model__NameAssignment_1 ) )
{
// InternalUrml.g:2384:1: ( ( rule__Model__NameAssignment_1 ) )
// InternalUrml.g:2385:1: ( rule__Model__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getNameAssignment_1());
}
// InternalUrml.g:2386:1: ( rule__Model__NameAssignment_1 )
// InternalUrml.g:2386:2: rule__Model__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__Model__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__1__Impl"
// $ANTLR start "rule__Model__Group__2"
// InternalUrml.g:2396:1: rule__Model__Group__2 : rule__Model__Group__2__Impl rule__Model__Group__3 ;
public final void rule__Model__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2400:1: ( rule__Model__Group__2__Impl rule__Model__Group__3 )
// InternalUrml.g:2401:2: rule__Model__Group__2__Impl rule__Model__Group__3
{
pushFollow(FOLLOW_6);
rule__Model__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Model__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__2"
// $ANTLR start "rule__Model__Group__2__Impl"
// InternalUrml.g:2408:1: rule__Model__Group__2__Impl : ( '{' ) ;
public final void rule__Model__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2412:1: ( ( '{' ) )
// InternalUrml.g:2413:1: ( '{' )
{
// InternalUrml.g:2413:1: ( '{' )
// InternalUrml.g:2414:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__2__Impl"
// $ANTLR start "rule__Model__Group__3"
// InternalUrml.g:2427:1: rule__Model__Group__3 : rule__Model__Group__3__Impl rule__Model__Group__4 ;
public final void rule__Model__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2431:1: ( rule__Model__Group__3__Impl rule__Model__Group__4 )
// InternalUrml.g:2432:2: rule__Model__Group__3__Impl rule__Model__Group__4
{
pushFollow(FOLLOW_6);
rule__Model__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Model__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__3"
// $ANTLR start "rule__Model__Group__3__Impl"
// InternalUrml.g:2439:1: rule__Model__Group__3__Impl : ( ( rule__Model__Alternatives_3 )* ) ;
public final void rule__Model__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2443:1: ( ( ( rule__Model__Alternatives_3 )* ) )
// InternalUrml.g:2444:1: ( ( rule__Model__Alternatives_3 )* )
{
// InternalUrml.g:2444:1: ( ( rule__Model__Alternatives_3 )* )
// InternalUrml.g:2445:1: ( rule__Model__Alternatives_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getAlternatives_3());
}
// InternalUrml.g:2446:1: ( rule__Model__Alternatives_3 )*
loop25:
do {
int alt25=2;
int LA25_0 = input.LA(1);
if ( (LA25_0==17||LA25_0==23||LA25_0==77) ) {
alt25=1;
}
switch (alt25) {
case 1 :
// InternalUrml.g:2446:2: rule__Model__Alternatives_3
{
pushFollow(FOLLOW_7);
rule__Model__Alternatives_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop25;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getAlternatives_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__3__Impl"
// $ANTLR start "rule__Model__Group__4"
// InternalUrml.g:2456:1: rule__Model__Group__4 : rule__Model__Group__4__Impl ;
public final void rule__Model__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2460:1: ( rule__Model__Group__4__Impl )
// InternalUrml.g:2461:2: rule__Model__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__Model__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__4"
// $ANTLR start "rule__Model__Group__4__Impl"
// InternalUrml.g:2467:1: rule__Model__Group__4__Impl : ( '}' ) ;
public final void rule__Model__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2471:1: ( ( '}' ) )
// InternalUrml.g:2472:1: ( '}' )
{
// InternalUrml.g:2472:1: ( '}' )
// InternalUrml.g:2473:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__Group__4__Impl"
// $ANTLR start "rule__LocalVar__Group__0"
// InternalUrml.g:2496:1: rule__LocalVar__Group__0 : rule__LocalVar__Group__0__Impl rule__LocalVar__Group__1 ;
public final void rule__LocalVar__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2500:1: ( rule__LocalVar__Group__0__Impl rule__LocalVar__Group__1 )
// InternalUrml.g:2501:2: rule__LocalVar__Group__0__Impl rule__LocalVar__Group__1
{
pushFollow(FOLLOW_4);
rule__LocalVar__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__LocalVar__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__Group__0"
// $ANTLR start "rule__LocalVar__Group__0__Impl"
// InternalUrml.g:2508:1: rule__LocalVar__Group__0__Impl : ( ( rule__LocalVar__Alternatives_0 ) ) ;
public final void rule__LocalVar__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2512:1: ( ( ( rule__LocalVar__Alternatives_0 ) ) )
// InternalUrml.g:2513:1: ( ( rule__LocalVar__Alternatives_0 ) )
{
// InternalUrml.g:2513:1: ( ( rule__LocalVar__Alternatives_0 ) )
// InternalUrml.g:2514:1: ( rule__LocalVar__Alternatives_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getAlternatives_0());
}
// InternalUrml.g:2515:1: ( rule__LocalVar__Alternatives_0 )
// InternalUrml.g:2515:2: rule__LocalVar__Alternatives_0
{
pushFollow(FOLLOW_2);
rule__LocalVar__Alternatives_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getAlternatives_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__Group__0__Impl"
// $ANTLR start "rule__LocalVar__Group__1"
// InternalUrml.g:2525:1: rule__LocalVar__Group__1 : rule__LocalVar__Group__1__Impl ;
public final void rule__LocalVar__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2529:1: ( rule__LocalVar__Group__1__Impl )
// InternalUrml.g:2530:2: rule__LocalVar__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__LocalVar__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__Group__1"
// $ANTLR start "rule__LocalVar__Group__1__Impl"
// InternalUrml.g:2536:1: rule__LocalVar__Group__1__Impl : ( ( rule__LocalVar__NameAssignment_1 ) ) ;
public final void rule__LocalVar__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2540:1: ( ( ( rule__LocalVar__NameAssignment_1 ) ) )
// InternalUrml.g:2541:1: ( ( rule__LocalVar__NameAssignment_1 ) )
{
// InternalUrml.g:2541:1: ( ( rule__LocalVar__NameAssignment_1 ) )
// InternalUrml.g:2542:1: ( rule__LocalVar__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getNameAssignment_1());
}
// InternalUrml.g:2543:1: ( rule__LocalVar__NameAssignment_1 )
// InternalUrml.g:2543:2: rule__LocalVar__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__LocalVar__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__Group__1__Impl"
// $ANTLR start "rule__Attribute__Group__0"
// InternalUrml.g:2557:1: rule__Attribute__Group__0 : rule__Attribute__Group__0__Impl rule__Attribute__Group__1 ;
public final void rule__Attribute__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2561:1: ( rule__Attribute__Group__0__Impl rule__Attribute__Group__1 )
// InternalUrml.g:2562:2: rule__Attribute__Group__0__Impl rule__Attribute__Group__1
{
pushFollow(FOLLOW_8);
rule__Attribute__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Attribute__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__0"
// $ANTLR start "rule__Attribute__Group__0__Impl"
// InternalUrml.g:2569:1: rule__Attribute__Group__0__Impl : ( 'attribute' ) ;
public final void rule__Attribute__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2573:1: ( ( 'attribute' ) )
// InternalUrml.g:2574:1: ( 'attribute' )
{
// InternalUrml.g:2574:1: ( 'attribute' )
// InternalUrml.g:2575:1: 'attribute'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getAttributeKeyword_0());
}
match(input,15,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getAttributeKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__0__Impl"
// $ANTLR start "rule__Attribute__Group__1"
// InternalUrml.g:2588:1: rule__Attribute__Group__1 : rule__Attribute__Group__1__Impl rule__Attribute__Group__2 ;
public final void rule__Attribute__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2592:1: ( rule__Attribute__Group__1__Impl rule__Attribute__Group__2 )
// InternalUrml.g:2593:2: rule__Attribute__Group__1__Impl rule__Attribute__Group__2
{
pushFollow(FOLLOW_4);
rule__Attribute__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Attribute__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__1"
// $ANTLR start "rule__Attribute__Group__1__Impl"
// InternalUrml.g:2600:1: rule__Attribute__Group__1__Impl : ( ( rule__Attribute__Alternatives_1 ) ) ;
public final void rule__Attribute__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2604:1: ( ( ( rule__Attribute__Alternatives_1 ) ) )
// InternalUrml.g:2605:1: ( ( rule__Attribute__Alternatives_1 ) )
{
// InternalUrml.g:2605:1: ( ( rule__Attribute__Alternatives_1 ) )
// InternalUrml.g:2606:1: ( rule__Attribute__Alternatives_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getAlternatives_1());
}
// InternalUrml.g:2607:1: ( rule__Attribute__Alternatives_1 )
// InternalUrml.g:2607:2: rule__Attribute__Alternatives_1
{
pushFollow(FOLLOW_2);
rule__Attribute__Alternatives_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getAlternatives_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__1__Impl"
// $ANTLR start "rule__Attribute__Group__2"
// InternalUrml.g:2617:1: rule__Attribute__Group__2 : rule__Attribute__Group__2__Impl rule__Attribute__Group__3 ;
public final void rule__Attribute__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2621:1: ( rule__Attribute__Group__2__Impl rule__Attribute__Group__3 )
// InternalUrml.g:2622:2: rule__Attribute__Group__2__Impl rule__Attribute__Group__3
{
pushFollow(FOLLOW_9);
rule__Attribute__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Attribute__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__2"
// $ANTLR start "rule__Attribute__Group__2__Impl"
// InternalUrml.g:2629:1: rule__Attribute__Group__2__Impl : ( ( rule__Attribute__NameAssignment_2 ) ) ;
public final void rule__Attribute__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2633:1: ( ( ( rule__Attribute__NameAssignment_2 ) ) )
// InternalUrml.g:2634:1: ( ( rule__Attribute__NameAssignment_2 ) )
{
// InternalUrml.g:2634:1: ( ( rule__Attribute__NameAssignment_2 ) )
// InternalUrml.g:2635:1: ( rule__Attribute__NameAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getNameAssignment_2());
}
// InternalUrml.g:2636:1: ( rule__Attribute__NameAssignment_2 )
// InternalUrml.g:2636:2: rule__Attribute__NameAssignment_2
{
pushFollow(FOLLOW_2);
rule__Attribute__NameAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getNameAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__2__Impl"
// $ANTLR start "rule__Attribute__Group__3"
// InternalUrml.g:2646:1: rule__Attribute__Group__3 : rule__Attribute__Group__3__Impl ;
public final void rule__Attribute__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2650:1: ( rule__Attribute__Group__3__Impl )
// InternalUrml.g:2651:2: rule__Attribute__Group__3__Impl
{
pushFollow(FOLLOW_2);
rule__Attribute__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__3"
// $ANTLR start "rule__Attribute__Group__3__Impl"
// InternalUrml.g:2657:1: rule__Attribute__Group__3__Impl : ( ( rule__Attribute__Group_3__0 )? ) ;
public final void rule__Attribute__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2661:1: ( ( ( rule__Attribute__Group_3__0 )? ) )
// InternalUrml.g:2662:1: ( ( rule__Attribute__Group_3__0 )? )
{
// InternalUrml.g:2662:1: ( ( rule__Attribute__Group_3__0 )? )
// InternalUrml.g:2663:1: ( rule__Attribute__Group_3__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getGroup_3());
}
// InternalUrml.g:2664:1: ( rule__Attribute__Group_3__0 )?
int alt26=2;
int LA26_0 = input.LA(1);
if ( (LA26_0==16) ) {
alt26=1;
}
switch (alt26) {
case 1 :
// InternalUrml.g:2664:2: rule__Attribute__Group_3__0
{
pushFollow(FOLLOW_2);
rule__Attribute__Group_3__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getGroup_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group__3__Impl"
// $ANTLR start "rule__Attribute__Group_3__0"
// InternalUrml.g:2682:1: rule__Attribute__Group_3__0 : rule__Attribute__Group_3__0__Impl rule__Attribute__Group_3__1 ;
public final void rule__Attribute__Group_3__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2686:1: ( rule__Attribute__Group_3__0__Impl rule__Attribute__Group_3__1 )
// InternalUrml.g:2687:2: rule__Attribute__Group_3__0__Impl rule__Attribute__Group_3__1
{
pushFollow(FOLLOW_10);
rule__Attribute__Group_3__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Attribute__Group_3__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group_3__0"
// $ANTLR start "rule__Attribute__Group_3__0__Impl"
// InternalUrml.g:2694:1: rule__Attribute__Group_3__0__Impl : ( ':=' ) ;
public final void rule__Attribute__Group_3__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2698:1: ( ( ':=' ) )
// InternalUrml.g:2699:1: ( ':=' )
{
// InternalUrml.g:2699:1: ( ':=' )
// InternalUrml.g:2700:1: ':='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getColonEqualsSignKeyword_3_0());
}
match(input,16,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getColonEqualsSignKeyword_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group_3__0__Impl"
// $ANTLR start "rule__Attribute__Group_3__1"
// InternalUrml.g:2713:1: rule__Attribute__Group_3__1 : rule__Attribute__Group_3__1__Impl ;
public final void rule__Attribute__Group_3__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2717:1: ( rule__Attribute__Group_3__1__Impl )
// InternalUrml.g:2718:2: rule__Attribute__Group_3__1__Impl
{
pushFollow(FOLLOW_2);
rule__Attribute__Group_3__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group_3__1"
// $ANTLR start "rule__Attribute__Group_3__1__Impl"
// InternalUrml.g:2724:1: rule__Attribute__Group_3__1__Impl : ( ( rule__Attribute__DefaultValueAssignment_3_1 ) ) ;
public final void rule__Attribute__Group_3__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2728:1: ( ( ( rule__Attribute__DefaultValueAssignment_3_1 ) ) )
// InternalUrml.g:2729:1: ( ( rule__Attribute__DefaultValueAssignment_3_1 ) )
{
// InternalUrml.g:2729:1: ( ( rule__Attribute__DefaultValueAssignment_3_1 ) )
// InternalUrml.g:2730:1: ( rule__Attribute__DefaultValueAssignment_3_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getDefaultValueAssignment_3_1());
}
// InternalUrml.g:2731:1: ( rule__Attribute__DefaultValueAssignment_3_1 )
// InternalUrml.g:2731:2: rule__Attribute__DefaultValueAssignment_3_1
{
pushFollow(FOLLOW_2);
rule__Attribute__DefaultValueAssignment_3_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getDefaultValueAssignment_3_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__Group_3__1__Impl"
// $ANTLR start "rule__Protocol__Group__0"
// InternalUrml.g:2745:1: rule__Protocol__Group__0 : rule__Protocol__Group__0__Impl rule__Protocol__Group__1 ;
public final void rule__Protocol__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2749:1: ( rule__Protocol__Group__0__Impl rule__Protocol__Group__1 )
// InternalUrml.g:2750:2: rule__Protocol__Group__0__Impl rule__Protocol__Group__1
{
pushFollow(FOLLOW_4);
rule__Protocol__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__0"
// $ANTLR start "rule__Protocol__Group__0__Impl"
// InternalUrml.g:2757:1: rule__Protocol__Group__0__Impl : ( 'protocol' ) ;
public final void rule__Protocol__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2761:1: ( ( 'protocol' ) )
// InternalUrml.g:2762:1: ( 'protocol' )
{
// InternalUrml.g:2762:1: ( 'protocol' )
// InternalUrml.g:2763:1: 'protocol'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getProtocolKeyword_0());
}
match(input,17,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getProtocolKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__0__Impl"
// $ANTLR start "rule__Protocol__Group__1"
// InternalUrml.g:2776:1: rule__Protocol__Group__1 : rule__Protocol__Group__1__Impl rule__Protocol__Group__2 ;
public final void rule__Protocol__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2780:1: ( rule__Protocol__Group__1__Impl rule__Protocol__Group__2 )
// InternalUrml.g:2781:2: rule__Protocol__Group__1__Impl rule__Protocol__Group__2
{
pushFollow(FOLLOW_5);
rule__Protocol__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__1"
// $ANTLR start "rule__Protocol__Group__1__Impl"
// InternalUrml.g:2788:1: rule__Protocol__Group__1__Impl : ( ( rule__Protocol__NameAssignment_1 ) ) ;
public final void rule__Protocol__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2792:1: ( ( ( rule__Protocol__NameAssignment_1 ) ) )
// InternalUrml.g:2793:1: ( ( rule__Protocol__NameAssignment_1 ) )
{
// InternalUrml.g:2793:1: ( ( rule__Protocol__NameAssignment_1 ) )
// InternalUrml.g:2794:1: ( rule__Protocol__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getNameAssignment_1());
}
// InternalUrml.g:2795:1: ( rule__Protocol__NameAssignment_1 )
// InternalUrml.g:2795:2: rule__Protocol__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__Protocol__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__1__Impl"
// $ANTLR start "rule__Protocol__Group__2"
// InternalUrml.g:2805:1: rule__Protocol__Group__2 : rule__Protocol__Group__2__Impl rule__Protocol__Group__3 ;
public final void rule__Protocol__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2809:1: ( rule__Protocol__Group__2__Impl rule__Protocol__Group__3 )
// InternalUrml.g:2810:2: rule__Protocol__Group__2__Impl rule__Protocol__Group__3
{
pushFollow(FOLLOW_11);
rule__Protocol__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__2"
// $ANTLR start "rule__Protocol__Group__2__Impl"
// InternalUrml.g:2817:1: rule__Protocol__Group__2__Impl : ( '{' ) ;
public final void rule__Protocol__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2821:1: ( ( '{' ) )
// InternalUrml.g:2822:1: ( '{' )
{
// InternalUrml.g:2822:1: ( '{' )
// InternalUrml.g:2823:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__2__Impl"
// $ANTLR start "rule__Protocol__Group__3"
// InternalUrml.g:2836:1: rule__Protocol__Group__3 : rule__Protocol__Group__3__Impl rule__Protocol__Group__4 ;
public final void rule__Protocol__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2840:1: ( rule__Protocol__Group__3__Impl rule__Protocol__Group__4 )
// InternalUrml.g:2841:2: rule__Protocol__Group__3__Impl rule__Protocol__Group__4
{
pushFollow(FOLLOW_11);
rule__Protocol__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__3"
// $ANTLR start "rule__Protocol__Group__3__Impl"
// InternalUrml.g:2848:1: rule__Protocol__Group__3__Impl : ( ( rule__Protocol__Alternatives_3 )* ) ;
public final void rule__Protocol__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2852:1: ( ( ( rule__Protocol__Alternatives_3 )* ) )
// InternalUrml.g:2853:1: ( ( rule__Protocol__Alternatives_3 )* )
{
// InternalUrml.g:2853:1: ( ( rule__Protocol__Alternatives_3 )* )
// InternalUrml.g:2854:1: ( rule__Protocol__Alternatives_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getAlternatives_3());
}
// InternalUrml.g:2855:1: ( rule__Protocol__Alternatives_3 )*
loop27:
do {
int alt27=2;
int LA27_0 = input.LA(1);
if ( ((LA27_0>=18 && LA27_0<=19)) ) {
alt27=1;
}
switch (alt27) {
case 1 :
// InternalUrml.g:2855:2: rule__Protocol__Alternatives_3
{
pushFollow(FOLLOW_12);
rule__Protocol__Alternatives_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop27;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getAlternatives_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__3__Impl"
// $ANTLR start "rule__Protocol__Group__4"
// InternalUrml.g:2865:1: rule__Protocol__Group__4 : rule__Protocol__Group__4__Impl ;
public final void rule__Protocol__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2869:1: ( rule__Protocol__Group__4__Impl )
// InternalUrml.g:2870:2: rule__Protocol__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__Protocol__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__4"
// $ANTLR start "rule__Protocol__Group__4__Impl"
// InternalUrml.g:2876:1: rule__Protocol__Group__4__Impl : ( '}' ) ;
public final void rule__Protocol__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2880:1: ( ( '}' ) )
// InternalUrml.g:2881:1: ( '}' )
{
// InternalUrml.g:2881:1: ( '}' )
// InternalUrml.g:2882:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group__4__Impl"
// $ANTLR start "rule__Protocol__Group_3_0__0"
// InternalUrml.g:2905:1: rule__Protocol__Group_3_0__0 : rule__Protocol__Group_3_0__0__Impl rule__Protocol__Group_3_0__1 ;
public final void rule__Protocol__Group_3_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2909:1: ( rule__Protocol__Group_3_0__0__Impl rule__Protocol__Group_3_0__1 )
// InternalUrml.g:2910:2: rule__Protocol__Group_3_0__0__Impl rule__Protocol__Group_3_0__1
{
pushFollow(FOLLOW_5);
rule__Protocol__Group_3_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__0"
// $ANTLR start "rule__Protocol__Group_3_0__0__Impl"
// InternalUrml.g:2917:1: rule__Protocol__Group_3_0__0__Impl : ( 'incoming' ) ;
public final void rule__Protocol__Group_3_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2921:1: ( ( 'incoming' ) )
// InternalUrml.g:2922:1: ( 'incoming' )
{
// InternalUrml.g:2922:1: ( 'incoming' )
// InternalUrml.g:2923:1: 'incoming'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getIncomingKeyword_3_0_0());
}
match(input,18,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getIncomingKeyword_3_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__0__Impl"
// $ANTLR start "rule__Protocol__Group_3_0__1"
// InternalUrml.g:2936:1: rule__Protocol__Group_3_0__1 : rule__Protocol__Group_3_0__1__Impl rule__Protocol__Group_3_0__2 ;
public final void rule__Protocol__Group_3_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2940:1: ( rule__Protocol__Group_3_0__1__Impl rule__Protocol__Group_3_0__2 )
// InternalUrml.g:2941:2: rule__Protocol__Group_3_0__1__Impl rule__Protocol__Group_3_0__2
{
pushFollow(FOLLOW_13);
rule__Protocol__Group_3_0__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_0__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__1"
// $ANTLR start "rule__Protocol__Group_3_0__1__Impl"
// InternalUrml.g:2948:1: rule__Protocol__Group_3_0__1__Impl : ( '{' ) ;
public final void rule__Protocol__Group_3_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2952:1: ( ( '{' ) )
// InternalUrml.g:2953:1: ( '{' )
{
// InternalUrml.g:2953:1: ( '{' )
// InternalUrml.g:2954:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getLeftCurlyBracketKeyword_3_0_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getLeftCurlyBracketKeyword_3_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__1__Impl"
// $ANTLR start "rule__Protocol__Group_3_0__2"
// InternalUrml.g:2967:1: rule__Protocol__Group_3_0__2 : rule__Protocol__Group_3_0__2__Impl rule__Protocol__Group_3_0__3 ;
public final void rule__Protocol__Group_3_0__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2971:1: ( rule__Protocol__Group_3_0__2__Impl rule__Protocol__Group_3_0__3 )
// InternalUrml.g:2972:2: rule__Protocol__Group_3_0__2__Impl rule__Protocol__Group_3_0__3
{
pushFollow(FOLLOW_13);
rule__Protocol__Group_3_0__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_0__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__2"
// $ANTLR start "rule__Protocol__Group_3_0__2__Impl"
// InternalUrml.g:2979:1: rule__Protocol__Group_3_0__2__Impl : ( ( rule__Protocol__IncomingMessagesAssignment_3_0_2 )* ) ;
public final void rule__Protocol__Group_3_0__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:2983:1: ( ( ( rule__Protocol__IncomingMessagesAssignment_3_0_2 )* ) )
// InternalUrml.g:2984:1: ( ( rule__Protocol__IncomingMessagesAssignment_3_0_2 )* )
{
// InternalUrml.g:2984:1: ( ( rule__Protocol__IncomingMessagesAssignment_3_0_2 )* )
// InternalUrml.g:2985:1: ( rule__Protocol__IncomingMessagesAssignment_3_0_2 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getIncomingMessagesAssignment_3_0_2());
}
// InternalUrml.g:2986:1: ( rule__Protocol__IncomingMessagesAssignment_3_0_2 )*
loop28:
do {
int alt28=2;
int LA28_0 = input.LA(1);
if ( (LA28_0==RULE_ID) ) {
alt28=1;
}
switch (alt28) {
case 1 :
// InternalUrml.g:2986:2: rule__Protocol__IncomingMessagesAssignment_3_0_2
{
pushFollow(FOLLOW_14);
rule__Protocol__IncomingMessagesAssignment_3_0_2();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop28;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getIncomingMessagesAssignment_3_0_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__2__Impl"
// $ANTLR start "rule__Protocol__Group_3_0__3"
// InternalUrml.g:2996:1: rule__Protocol__Group_3_0__3 : rule__Protocol__Group_3_0__3__Impl ;
public final void rule__Protocol__Group_3_0__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3000:1: ( rule__Protocol__Group_3_0__3__Impl )
// InternalUrml.g:3001:2: rule__Protocol__Group_3_0__3__Impl
{
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_0__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__3"
// $ANTLR start "rule__Protocol__Group_3_0__3__Impl"
// InternalUrml.g:3007:1: rule__Protocol__Group_3_0__3__Impl : ( '}' ) ;
public final void rule__Protocol__Group_3_0__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3011:1: ( ( '}' ) )
// InternalUrml.g:3012:1: ( '}' )
{
// InternalUrml.g:3012:1: ( '}' )
// InternalUrml.g:3013:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getRightCurlyBracketKeyword_3_0_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getRightCurlyBracketKeyword_3_0_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_0__3__Impl"
// $ANTLR start "rule__Protocol__Group_3_1__0"
// InternalUrml.g:3034:1: rule__Protocol__Group_3_1__0 : rule__Protocol__Group_3_1__0__Impl rule__Protocol__Group_3_1__1 ;
public final void rule__Protocol__Group_3_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3038:1: ( rule__Protocol__Group_3_1__0__Impl rule__Protocol__Group_3_1__1 )
// InternalUrml.g:3039:2: rule__Protocol__Group_3_1__0__Impl rule__Protocol__Group_3_1__1
{
pushFollow(FOLLOW_5);
rule__Protocol__Group_3_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__0"
// $ANTLR start "rule__Protocol__Group_3_1__0__Impl"
// InternalUrml.g:3046:1: rule__Protocol__Group_3_1__0__Impl : ( 'outgoing' ) ;
public final void rule__Protocol__Group_3_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3050:1: ( ( 'outgoing' ) )
// InternalUrml.g:3051:1: ( 'outgoing' )
{
// InternalUrml.g:3051:1: ( 'outgoing' )
// InternalUrml.g:3052:1: 'outgoing'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getOutgoingKeyword_3_1_0());
}
match(input,19,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getOutgoingKeyword_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__0__Impl"
// $ANTLR start "rule__Protocol__Group_3_1__1"
// InternalUrml.g:3065:1: rule__Protocol__Group_3_1__1 : rule__Protocol__Group_3_1__1__Impl rule__Protocol__Group_3_1__2 ;
public final void rule__Protocol__Group_3_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3069:1: ( rule__Protocol__Group_3_1__1__Impl rule__Protocol__Group_3_1__2 )
// InternalUrml.g:3070:2: rule__Protocol__Group_3_1__1__Impl rule__Protocol__Group_3_1__2
{
pushFollow(FOLLOW_13);
rule__Protocol__Group_3_1__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_1__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__1"
// $ANTLR start "rule__Protocol__Group_3_1__1__Impl"
// InternalUrml.g:3077:1: rule__Protocol__Group_3_1__1__Impl : ( '{' ) ;
public final void rule__Protocol__Group_3_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3081:1: ( ( '{' ) )
// InternalUrml.g:3082:1: ( '{' )
{
// InternalUrml.g:3082:1: ( '{' )
// InternalUrml.g:3083:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getLeftCurlyBracketKeyword_3_1_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getLeftCurlyBracketKeyword_3_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__1__Impl"
// $ANTLR start "rule__Protocol__Group_3_1__2"
// InternalUrml.g:3096:1: rule__Protocol__Group_3_1__2 : rule__Protocol__Group_3_1__2__Impl rule__Protocol__Group_3_1__3 ;
public final void rule__Protocol__Group_3_1__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3100:1: ( rule__Protocol__Group_3_1__2__Impl rule__Protocol__Group_3_1__3 )
// InternalUrml.g:3101:2: rule__Protocol__Group_3_1__2__Impl rule__Protocol__Group_3_1__3
{
pushFollow(FOLLOW_13);
rule__Protocol__Group_3_1__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_1__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__2"
// $ANTLR start "rule__Protocol__Group_3_1__2__Impl"
// InternalUrml.g:3108:1: rule__Protocol__Group_3_1__2__Impl : ( ( rule__Protocol__OutgoingMessagesAssignment_3_1_2 )* ) ;
public final void rule__Protocol__Group_3_1__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3112:1: ( ( ( rule__Protocol__OutgoingMessagesAssignment_3_1_2 )* ) )
// InternalUrml.g:3113:1: ( ( rule__Protocol__OutgoingMessagesAssignment_3_1_2 )* )
{
// InternalUrml.g:3113:1: ( ( rule__Protocol__OutgoingMessagesAssignment_3_1_2 )* )
// InternalUrml.g:3114:1: ( rule__Protocol__OutgoingMessagesAssignment_3_1_2 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getOutgoingMessagesAssignment_3_1_2());
}
// InternalUrml.g:3115:1: ( rule__Protocol__OutgoingMessagesAssignment_3_1_2 )*
loop29:
do {
int alt29=2;
int LA29_0 = input.LA(1);
if ( (LA29_0==RULE_ID) ) {
alt29=1;
}
switch (alt29) {
case 1 :
// InternalUrml.g:3115:2: rule__Protocol__OutgoingMessagesAssignment_3_1_2
{
pushFollow(FOLLOW_14);
rule__Protocol__OutgoingMessagesAssignment_3_1_2();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop29;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getOutgoingMessagesAssignment_3_1_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__2__Impl"
// $ANTLR start "rule__Protocol__Group_3_1__3"
// InternalUrml.g:3125:1: rule__Protocol__Group_3_1__3 : rule__Protocol__Group_3_1__3__Impl ;
public final void rule__Protocol__Group_3_1__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3129:1: ( rule__Protocol__Group_3_1__3__Impl )
// InternalUrml.g:3130:2: rule__Protocol__Group_3_1__3__Impl
{
pushFollow(FOLLOW_2);
rule__Protocol__Group_3_1__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__3"
// $ANTLR start "rule__Protocol__Group_3_1__3__Impl"
// InternalUrml.g:3136:1: rule__Protocol__Group_3_1__3__Impl : ( '}' ) ;
public final void rule__Protocol__Group_3_1__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3140:1: ( ( '}' ) )
// InternalUrml.g:3141:1: ( '}' )
{
// InternalUrml.g:3141:1: ( '}' )
// InternalUrml.g:3142:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getRightCurlyBracketKeyword_3_1_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getRightCurlyBracketKeyword_3_1_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__Group_3_1__3__Impl"
// $ANTLR start "rule__Signal__Group__0"
// InternalUrml.g:3163:1: rule__Signal__Group__0 : rule__Signal__Group__0__Impl rule__Signal__Group__1 ;
public final void rule__Signal__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3167:1: ( rule__Signal__Group__0__Impl rule__Signal__Group__1 )
// InternalUrml.g:3168:2: rule__Signal__Group__0__Impl rule__Signal__Group__1
{
pushFollow(FOLLOW_15);
rule__Signal__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Signal__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__0"
// $ANTLR start "rule__Signal__Group__0__Impl"
// InternalUrml.g:3175:1: rule__Signal__Group__0__Impl : ( ( rule__Signal__NameAssignment_0 ) ) ;
public final void rule__Signal__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3179:1: ( ( ( rule__Signal__NameAssignment_0 ) ) )
// InternalUrml.g:3180:1: ( ( rule__Signal__NameAssignment_0 ) )
{
// InternalUrml.g:3180:1: ( ( rule__Signal__NameAssignment_0 ) )
// InternalUrml.g:3181:1: ( rule__Signal__NameAssignment_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getNameAssignment_0());
}
// InternalUrml.g:3182:1: ( rule__Signal__NameAssignment_0 )
// InternalUrml.g:3182:2: rule__Signal__NameAssignment_0
{
pushFollow(FOLLOW_2);
rule__Signal__NameAssignment_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getNameAssignment_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__0__Impl"
// $ANTLR start "rule__Signal__Group__1"
// InternalUrml.g:3192:1: rule__Signal__Group__1 : rule__Signal__Group__1__Impl rule__Signal__Group__2 ;
public final void rule__Signal__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3196:1: ( rule__Signal__Group__1__Impl rule__Signal__Group__2 )
// InternalUrml.g:3197:2: rule__Signal__Group__1__Impl rule__Signal__Group__2
{
pushFollow(FOLLOW_16);
rule__Signal__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Signal__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__1"
// $ANTLR start "rule__Signal__Group__1__Impl"
// InternalUrml.g:3204:1: rule__Signal__Group__1__Impl : ( '(' ) ;
public final void rule__Signal__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3208:1: ( ( '(' ) )
// InternalUrml.g:3209:1: ( '(' )
{
// InternalUrml.g:3209:1: ( '(' )
// InternalUrml.g:3210:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getLeftParenthesisKeyword_1());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getLeftParenthesisKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__1__Impl"
// $ANTLR start "rule__Signal__Group__2"
// InternalUrml.g:3223:1: rule__Signal__Group__2 : rule__Signal__Group__2__Impl rule__Signal__Group__3 ;
public final void rule__Signal__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3227:1: ( rule__Signal__Group__2__Impl rule__Signal__Group__3 )
// InternalUrml.g:3228:2: rule__Signal__Group__2__Impl rule__Signal__Group__3
{
pushFollow(FOLLOW_16);
rule__Signal__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Signal__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__2"
// $ANTLR start "rule__Signal__Group__2__Impl"
// InternalUrml.g:3235:1: rule__Signal__Group__2__Impl : ( ( rule__Signal__Group_2__0 )? ) ;
public final void rule__Signal__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3239:1: ( ( ( rule__Signal__Group_2__0 )? ) )
// InternalUrml.g:3240:1: ( ( rule__Signal__Group_2__0 )? )
{
// InternalUrml.g:3240:1: ( ( rule__Signal__Group_2__0 )? )
// InternalUrml.g:3241:1: ( rule__Signal__Group_2__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getGroup_2());
}
// InternalUrml.g:3242:1: ( rule__Signal__Group_2__0 )?
int alt30=2;
int LA30_0 = input.LA(1);
if ( ((LA30_0>=75 && LA30_0<=76)) ) {
alt30=1;
}
switch (alt30) {
case 1 :
// InternalUrml.g:3242:2: rule__Signal__Group_2__0
{
pushFollow(FOLLOW_2);
rule__Signal__Group_2__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getGroup_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__2__Impl"
// $ANTLR start "rule__Signal__Group__3"
// InternalUrml.g:3252:1: rule__Signal__Group__3 : rule__Signal__Group__3__Impl ;
public final void rule__Signal__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3256:1: ( rule__Signal__Group__3__Impl )
// InternalUrml.g:3257:2: rule__Signal__Group__3__Impl
{
pushFollow(FOLLOW_2);
rule__Signal__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__3"
// $ANTLR start "rule__Signal__Group__3__Impl"
// InternalUrml.g:3263:1: rule__Signal__Group__3__Impl : ( ')' ) ;
public final void rule__Signal__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3267:1: ( ( ')' ) )
// InternalUrml.g:3268:1: ( ')' )
{
// InternalUrml.g:3268:1: ( ')' )
// InternalUrml.g:3269:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getRightParenthesisKeyword_3());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getRightParenthesisKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group__3__Impl"
// $ANTLR start "rule__Signal__Group_2__0"
// InternalUrml.g:3290:1: rule__Signal__Group_2__0 : rule__Signal__Group_2__0__Impl rule__Signal__Group_2__1 ;
public final void rule__Signal__Group_2__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3294:1: ( rule__Signal__Group_2__0__Impl rule__Signal__Group_2__1 )
// InternalUrml.g:3295:2: rule__Signal__Group_2__0__Impl rule__Signal__Group_2__1
{
pushFollow(FOLLOW_17);
rule__Signal__Group_2__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Signal__Group_2__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2__0"
// $ANTLR start "rule__Signal__Group_2__0__Impl"
// InternalUrml.g:3302:1: rule__Signal__Group_2__0__Impl : ( ( rule__Signal__LocalVarsAssignment_2_0 ) ) ;
public final void rule__Signal__Group_2__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3306:1: ( ( ( rule__Signal__LocalVarsAssignment_2_0 ) ) )
// InternalUrml.g:3307:1: ( ( rule__Signal__LocalVarsAssignment_2_0 ) )
{
// InternalUrml.g:3307:1: ( ( rule__Signal__LocalVarsAssignment_2_0 ) )
// InternalUrml.g:3308:1: ( rule__Signal__LocalVarsAssignment_2_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getLocalVarsAssignment_2_0());
}
// InternalUrml.g:3309:1: ( rule__Signal__LocalVarsAssignment_2_0 )
// InternalUrml.g:3309:2: rule__Signal__LocalVarsAssignment_2_0
{
pushFollow(FOLLOW_2);
rule__Signal__LocalVarsAssignment_2_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getLocalVarsAssignment_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2__0__Impl"
// $ANTLR start "rule__Signal__Group_2__1"
// InternalUrml.g:3319:1: rule__Signal__Group_2__1 : rule__Signal__Group_2__1__Impl ;
public final void rule__Signal__Group_2__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3323:1: ( rule__Signal__Group_2__1__Impl )
// InternalUrml.g:3324:2: rule__Signal__Group_2__1__Impl
{
pushFollow(FOLLOW_2);
rule__Signal__Group_2__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2__1"
// $ANTLR start "rule__Signal__Group_2__1__Impl"
// InternalUrml.g:3330:1: rule__Signal__Group_2__1__Impl : ( ( rule__Signal__Group_2_1__0 )* ) ;
public final void rule__Signal__Group_2__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3334:1: ( ( ( rule__Signal__Group_2_1__0 )* ) )
// InternalUrml.g:3335:1: ( ( rule__Signal__Group_2_1__0 )* )
{
// InternalUrml.g:3335:1: ( ( rule__Signal__Group_2_1__0 )* )
// InternalUrml.g:3336:1: ( rule__Signal__Group_2_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getGroup_2_1());
}
// InternalUrml.g:3337:1: ( rule__Signal__Group_2_1__0 )*
loop31:
do {
int alt31=2;
int LA31_0 = input.LA(1);
if ( (LA31_0==22) ) {
alt31=1;
}
switch (alt31) {
case 1 :
// InternalUrml.g:3337:2: rule__Signal__Group_2_1__0
{
pushFollow(FOLLOW_18);
rule__Signal__Group_2_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop31;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getGroup_2_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2__1__Impl"
// $ANTLR start "rule__Signal__Group_2_1__0"
// InternalUrml.g:3351:1: rule__Signal__Group_2_1__0 : rule__Signal__Group_2_1__0__Impl rule__Signal__Group_2_1__1 ;
public final void rule__Signal__Group_2_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3355:1: ( rule__Signal__Group_2_1__0__Impl rule__Signal__Group_2_1__1 )
// InternalUrml.g:3356:2: rule__Signal__Group_2_1__0__Impl rule__Signal__Group_2_1__1
{
pushFollow(FOLLOW_8);
rule__Signal__Group_2_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Signal__Group_2_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2_1__0"
// $ANTLR start "rule__Signal__Group_2_1__0__Impl"
// InternalUrml.g:3363:1: rule__Signal__Group_2_1__0__Impl : ( ',' ) ;
public final void rule__Signal__Group_2_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3367:1: ( ( ',' ) )
// InternalUrml.g:3368:1: ( ',' )
{
// InternalUrml.g:3368:1: ( ',' )
// InternalUrml.g:3369:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getCommaKeyword_2_1_0());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getCommaKeyword_2_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2_1__0__Impl"
// $ANTLR start "rule__Signal__Group_2_1__1"
// InternalUrml.g:3382:1: rule__Signal__Group_2_1__1 : rule__Signal__Group_2_1__1__Impl ;
public final void rule__Signal__Group_2_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3386:1: ( rule__Signal__Group_2_1__1__Impl )
// InternalUrml.g:3387:2: rule__Signal__Group_2_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Signal__Group_2_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2_1__1"
// $ANTLR start "rule__Signal__Group_2_1__1__Impl"
// InternalUrml.g:3393:1: rule__Signal__Group_2_1__1__Impl : ( ( rule__Signal__LocalVarsAssignment_2_1_1 ) ) ;
public final void rule__Signal__Group_2_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3397:1: ( ( ( rule__Signal__LocalVarsAssignment_2_1_1 ) ) )
// InternalUrml.g:3398:1: ( ( rule__Signal__LocalVarsAssignment_2_1_1 ) )
{
// InternalUrml.g:3398:1: ( ( rule__Signal__LocalVarsAssignment_2_1_1 ) )
// InternalUrml.g:3399:1: ( rule__Signal__LocalVarsAssignment_2_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getLocalVarsAssignment_2_1_1());
}
// InternalUrml.g:3400:1: ( rule__Signal__LocalVarsAssignment_2_1_1 )
// InternalUrml.g:3400:2: rule__Signal__LocalVarsAssignment_2_1_1
{
pushFollow(FOLLOW_2);
rule__Signal__LocalVarsAssignment_2_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getLocalVarsAssignment_2_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__Group_2_1__1__Impl"
// $ANTLR start "rule__Capsule__Group__0"
// InternalUrml.g:3414:1: rule__Capsule__Group__0 : rule__Capsule__Group__0__Impl rule__Capsule__Group__1 ;
public final void rule__Capsule__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3418:1: ( rule__Capsule__Group__0__Impl rule__Capsule__Group__1 )
// InternalUrml.g:3419:2: rule__Capsule__Group__0__Impl rule__Capsule__Group__1
{
pushFollow(FOLLOW_19);
rule__Capsule__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Capsule__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__0"
// $ANTLR start "rule__Capsule__Group__0__Impl"
// InternalUrml.g:3426:1: rule__Capsule__Group__0__Impl : ( ( rule__Capsule__RootAssignment_0 )? ) ;
public final void rule__Capsule__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3430:1: ( ( ( rule__Capsule__RootAssignment_0 )? ) )
// InternalUrml.g:3431:1: ( ( rule__Capsule__RootAssignment_0 )? )
{
// InternalUrml.g:3431:1: ( ( rule__Capsule__RootAssignment_0 )? )
// InternalUrml.g:3432:1: ( rule__Capsule__RootAssignment_0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getRootAssignment_0());
}
// InternalUrml.g:3433:1: ( rule__Capsule__RootAssignment_0 )?
int alt32=2;
int LA32_0 = input.LA(1);
if ( (LA32_0==77) ) {
alt32=1;
}
switch (alt32) {
case 1 :
// InternalUrml.g:3433:2: rule__Capsule__RootAssignment_0
{
pushFollow(FOLLOW_2);
rule__Capsule__RootAssignment_0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getRootAssignment_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__0__Impl"
// $ANTLR start "rule__Capsule__Group__1"
// InternalUrml.g:3443:1: rule__Capsule__Group__1 : rule__Capsule__Group__1__Impl rule__Capsule__Group__2 ;
public final void rule__Capsule__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3447:1: ( rule__Capsule__Group__1__Impl rule__Capsule__Group__2 )
// InternalUrml.g:3448:2: rule__Capsule__Group__1__Impl rule__Capsule__Group__2
{
pushFollow(FOLLOW_4);
rule__Capsule__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Capsule__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__1"
// $ANTLR start "rule__Capsule__Group__1__Impl"
// InternalUrml.g:3455:1: rule__Capsule__Group__1__Impl : ( 'capsule' ) ;
public final void rule__Capsule__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3459:1: ( ( 'capsule' ) )
// InternalUrml.g:3460:1: ( 'capsule' )
{
// InternalUrml.g:3460:1: ( 'capsule' )
// InternalUrml.g:3461:1: 'capsule'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getCapsuleKeyword_1());
}
match(input,23,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getCapsuleKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__1__Impl"
// $ANTLR start "rule__Capsule__Group__2"
// InternalUrml.g:3474:1: rule__Capsule__Group__2 : rule__Capsule__Group__2__Impl rule__Capsule__Group__3 ;
public final void rule__Capsule__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3478:1: ( rule__Capsule__Group__2__Impl rule__Capsule__Group__3 )
// InternalUrml.g:3479:2: rule__Capsule__Group__2__Impl rule__Capsule__Group__3
{
pushFollow(FOLLOW_5);
rule__Capsule__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Capsule__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__2"
// $ANTLR start "rule__Capsule__Group__2__Impl"
// InternalUrml.g:3486:1: rule__Capsule__Group__2__Impl : ( ( rule__Capsule__NameAssignment_2 ) ) ;
public final void rule__Capsule__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3490:1: ( ( ( rule__Capsule__NameAssignment_2 ) ) )
// InternalUrml.g:3491:1: ( ( rule__Capsule__NameAssignment_2 ) )
{
// InternalUrml.g:3491:1: ( ( rule__Capsule__NameAssignment_2 ) )
// InternalUrml.g:3492:1: ( rule__Capsule__NameAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getNameAssignment_2());
}
// InternalUrml.g:3493:1: ( rule__Capsule__NameAssignment_2 )
// InternalUrml.g:3493:2: rule__Capsule__NameAssignment_2
{
pushFollow(FOLLOW_2);
rule__Capsule__NameAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getNameAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__2__Impl"
// $ANTLR start "rule__Capsule__Group__3"
// InternalUrml.g:3503:1: rule__Capsule__Group__3 : rule__Capsule__Group__3__Impl rule__Capsule__Group__4 ;
public final void rule__Capsule__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3507:1: ( rule__Capsule__Group__3__Impl rule__Capsule__Group__4 )
// InternalUrml.g:3508:2: rule__Capsule__Group__3__Impl rule__Capsule__Group__4
{
pushFollow(FOLLOW_20);
rule__Capsule__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Capsule__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__3"
// $ANTLR start "rule__Capsule__Group__3__Impl"
// InternalUrml.g:3515:1: rule__Capsule__Group__3__Impl : ( '{' ) ;
public final void rule__Capsule__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3519:1: ( ( '{' ) )
// InternalUrml.g:3520:1: ( '{' )
{
// InternalUrml.g:3520:1: ( '{' )
// InternalUrml.g:3521:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getLeftCurlyBracketKeyword_3());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getLeftCurlyBracketKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__3__Impl"
// $ANTLR start "rule__Capsule__Group__4"
// InternalUrml.g:3534:1: rule__Capsule__Group__4 : rule__Capsule__Group__4__Impl rule__Capsule__Group__5 ;
public final void rule__Capsule__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3538:1: ( rule__Capsule__Group__4__Impl rule__Capsule__Group__5 )
// InternalUrml.g:3539:2: rule__Capsule__Group__4__Impl rule__Capsule__Group__5
{
pushFollow(FOLLOW_20);
rule__Capsule__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Capsule__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__4"
// $ANTLR start "rule__Capsule__Group__4__Impl"
// InternalUrml.g:3546:1: rule__Capsule__Group__4__Impl : ( ( rule__Capsule__Alternatives_4 )* ) ;
public final void rule__Capsule__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3550:1: ( ( ( rule__Capsule__Alternatives_4 )* ) )
// InternalUrml.g:3551:1: ( ( rule__Capsule__Alternatives_4 )* )
{
// InternalUrml.g:3551:1: ( ( rule__Capsule__Alternatives_4 )* )
// InternalUrml.g:3552:1: ( rule__Capsule__Alternatives_4 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getAlternatives_4());
}
// InternalUrml.g:3553:1: ( rule__Capsule__Alternatives_4 )*
loop33:
do {
int alt33=2;
int LA33_0 = input.LA(1);
if ( (LA33_0==15||(LA33_0>=24 && LA33_0<=28)||LA33_0==30||(LA33_0>=33 && LA33_0<=34)) ) {
alt33=1;
}
switch (alt33) {
case 1 :
// InternalUrml.g:3553:2: rule__Capsule__Alternatives_4
{
pushFollow(FOLLOW_21);
rule__Capsule__Alternatives_4();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop33;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getAlternatives_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__4__Impl"
// $ANTLR start "rule__Capsule__Group__5"
// InternalUrml.g:3563:1: rule__Capsule__Group__5 : rule__Capsule__Group__5__Impl ;
public final void rule__Capsule__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3567:1: ( rule__Capsule__Group__5__Impl )
// InternalUrml.g:3568:2: rule__Capsule__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__Capsule__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__5"
// $ANTLR start "rule__Capsule__Group__5__Impl"
// InternalUrml.g:3574:1: rule__Capsule__Group__5__Impl : ( '}' ) ;
public final void rule__Capsule__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3578:1: ( ( '}' ) )
// InternalUrml.g:3579:1: ( '}' )
{
// InternalUrml.g:3579:1: ( '}' )
// InternalUrml.g:3580:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getRightCurlyBracketKeyword_5());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getRightCurlyBracketKeyword_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group__5__Impl"
// $ANTLR start "rule__Capsule__Group_4_0__0"
// InternalUrml.g:3605:1: rule__Capsule__Group_4_0__0 : rule__Capsule__Group_4_0__0__Impl rule__Capsule__Group_4_0__1 ;
public final void rule__Capsule__Group_4_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3609:1: ( rule__Capsule__Group_4_0__0__Impl rule__Capsule__Group_4_0__1 )
// InternalUrml.g:3610:2: rule__Capsule__Group_4_0__0__Impl rule__Capsule__Group_4_0__1
{
pushFollow(FOLLOW_22);
rule__Capsule__Group_4_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Capsule__Group_4_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group_4_0__0"
// $ANTLR start "rule__Capsule__Group_4_0__0__Impl"
// InternalUrml.g:3617:1: rule__Capsule__Group_4_0__0__Impl : ( 'external' ) ;
public final void rule__Capsule__Group_4_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3621:1: ( ( 'external' ) )
// InternalUrml.g:3622:1: ( 'external' )
{
// InternalUrml.g:3622:1: ( 'external' )
// InternalUrml.g:3623:1: 'external'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getExternalKeyword_4_0_0());
}
match(input,24,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getExternalKeyword_4_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group_4_0__0__Impl"
// $ANTLR start "rule__Capsule__Group_4_0__1"
// InternalUrml.g:3636:1: rule__Capsule__Group_4_0__1 : rule__Capsule__Group_4_0__1__Impl ;
public final void rule__Capsule__Group_4_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3640:1: ( rule__Capsule__Group_4_0__1__Impl )
// InternalUrml.g:3641:2: rule__Capsule__Group_4_0__1__Impl
{
pushFollow(FOLLOW_2);
rule__Capsule__Group_4_0__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group_4_0__1"
// $ANTLR start "rule__Capsule__Group_4_0__1__Impl"
// InternalUrml.g:3647:1: rule__Capsule__Group_4_0__1__Impl : ( ( rule__Capsule__InterfacePortsAssignment_4_0_1 ) ) ;
public final void rule__Capsule__Group_4_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3651:1: ( ( ( rule__Capsule__InterfacePortsAssignment_4_0_1 ) ) )
// InternalUrml.g:3652:1: ( ( rule__Capsule__InterfacePortsAssignment_4_0_1 ) )
{
// InternalUrml.g:3652:1: ( ( rule__Capsule__InterfacePortsAssignment_4_0_1 ) )
// InternalUrml.g:3653:1: ( rule__Capsule__InterfacePortsAssignment_4_0_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getInterfacePortsAssignment_4_0_1());
}
// InternalUrml.g:3654:1: ( rule__Capsule__InterfacePortsAssignment_4_0_1 )
// InternalUrml.g:3654:2: rule__Capsule__InterfacePortsAssignment_4_0_1
{
pushFollow(FOLLOW_2);
rule__Capsule__InterfacePortsAssignment_4_0_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getInterfacePortsAssignment_4_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__Group_4_0__1__Impl"
// $ANTLR start "rule__Operation__Group__0"
// InternalUrml.g:3668:1: rule__Operation__Group__0 : rule__Operation__Group__0__Impl rule__Operation__Group__1 ;
public final void rule__Operation__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3672:1: ( rule__Operation__Group__0__Impl rule__Operation__Group__1 )
// InternalUrml.g:3673:2: rule__Operation__Group__0__Impl rule__Operation__Group__1
{
pushFollow(FOLLOW_23);
rule__Operation__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__0"
// $ANTLR start "rule__Operation__Group__0__Impl"
// InternalUrml.g:3680:1: rule__Operation__Group__0__Impl : ( 'operation' ) ;
public final void rule__Operation__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3684:1: ( ( 'operation' ) )
// InternalUrml.g:3685:1: ( 'operation' )
{
// InternalUrml.g:3685:1: ( 'operation' )
// InternalUrml.g:3686:1: 'operation'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getOperationKeyword_0());
}
match(input,25,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getOperationKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__0__Impl"
// $ANTLR start "rule__Operation__Group__1"
// InternalUrml.g:3699:1: rule__Operation__Group__1 : rule__Operation__Group__1__Impl rule__Operation__Group__2 ;
public final void rule__Operation__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3703:1: ( rule__Operation__Group__1__Impl rule__Operation__Group__2 )
// InternalUrml.g:3704:2: rule__Operation__Group__1__Impl rule__Operation__Group__2
{
pushFollow(FOLLOW_4);
rule__Operation__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__1"
// $ANTLR start "rule__Operation__Group__1__Impl"
// InternalUrml.g:3711:1: rule__Operation__Group__1__Impl : ( ( rule__Operation__Alternatives_1 ) ) ;
public final void rule__Operation__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3715:1: ( ( ( rule__Operation__Alternatives_1 ) ) )
// InternalUrml.g:3716:1: ( ( rule__Operation__Alternatives_1 ) )
{
// InternalUrml.g:3716:1: ( ( rule__Operation__Alternatives_1 ) )
// InternalUrml.g:3717:1: ( rule__Operation__Alternatives_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getAlternatives_1());
}
// InternalUrml.g:3718:1: ( rule__Operation__Alternatives_1 )
// InternalUrml.g:3718:2: rule__Operation__Alternatives_1
{
pushFollow(FOLLOW_2);
rule__Operation__Alternatives_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getAlternatives_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__1__Impl"
// $ANTLR start "rule__Operation__Group__2"
// InternalUrml.g:3728:1: rule__Operation__Group__2 : rule__Operation__Group__2__Impl rule__Operation__Group__3 ;
public final void rule__Operation__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3732:1: ( rule__Operation__Group__2__Impl rule__Operation__Group__3 )
// InternalUrml.g:3733:2: rule__Operation__Group__2__Impl rule__Operation__Group__3
{
pushFollow(FOLLOW_15);
rule__Operation__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__2"
// $ANTLR start "rule__Operation__Group__2__Impl"
// InternalUrml.g:3740:1: rule__Operation__Group__2__Impl : ( ( rule__Operation__NameAssignment_2 ) ) ;
public final void rule__Operation__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3744:1: ( ( ( rule__Operation__NameAssignment_2 ) ) )
// InternalUrml.g:3745:1: ( ( rule__Operation__NameAssignment_2 ) )
{
// InternalUrml.g:3745:1: ( ( rule__Operation__NameAssignment_2 ) )
// InternalUrml.g:3746:1: ( rule__Operation__NameAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getNameAssignment_2());
}
// InternalUrml.g:3747:1: ( rule__Operation__NameAssignment_2 )
// InternalUrml.g:3747:2: rule__Operation__NameAssignment_2
{
pushFollow(FOLLOW_2);
rule__Operation__NameAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getNameAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__2__Impl"
// $ANTLR start "rule__Operation__Group__3"
// InternalUrml.g:3757:1: rule__Operation__Group__3 : rule__Operation__Group__3__Impl rule__Operation__Group__4 ;
public final void rule__Operation__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3761:1: ( rule__Operation__Group__3__Impl rule__Operation__Group__4 )
// InternalUrml.g:3762:2: rule__Operation__Group__3__Impl rule__Operation__Group__4
{
pushFollow(FOLLOW_16);
rule__Operation__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__3"
// $ANTLR start "rule__Operation__Group__3__Impl"
// InternalUrml.g:3769:1: rule__Operation__Group__3__Impl : ( '(' ) ;
public final void rule__Operation__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3773:1: ( ( '(' ) )
// InternalUrml.g:3774:1: ( '(' )
{
// InternalUrml.g:3774:1: ( '(' )
// InternalUrml.g:3775:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getLeftParenthesisKeyword_3());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getLeftParenthesisKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__3__Impl"
// $ANTLR start "rule__Operation__Group__4"
// InternalUrml.g:3788:1: rule__Operation__Group__4 : rule__Operation__Group__4__Impl rule__Operation__Group__5 ;
public final void rule__Operation__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3792:1: ( rule__Operation__Group__4__Impl rule__Operation__Group__5 )
// InternalUrml.g:3793:2: rule__Operation__Group__4__Impl rule__Operation__Group__5
{
pushFollow(FOLLOW_16);
rule__Operation__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__4"
// $ANTLR start "rule__Operation__Group__4__Impl"
// InternalUrml.g:3800:1: rule__Operation__Group__4__Impl : ( ( rule__Operation__Group_4__0 )? ) ;
public final void rule__Operation__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3804:1: ( ( ( rule__Operation__Group_4__0 )? ) )
// InternalUrml.g:3805:1: ( ( rule__Operation__Group_4__0 )? )
{
// InternalUrml.g:3805:1: ( ( rule__Operation__Group_4__0 )? )
// InternalUrml.g:3806:1: ( rule__Operation__Group_4__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getGroup_4());
}
// InternalUrml.g:3807:1: ( rule__Operation__Group_4__0 )?
int alt34=2;
int LA34_0 = input.LA(1);
if ( ((LA34_0>=75 && LA34_0<=76)) ) {
alt34=1;
}
switch (alt34) {
case 1 :
// InternalUrml.g:3807:2: rule__Operation__Group_4__0
{
pushFollow(FOLLOW_2);
rule__Operation__Group_4__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getGroup_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__4__Impl"
// $ANTLR start "rule__Operation__Group__5"
// InternalUrml.g:3817:1: rule__Operation__Group__5 : rule__Operation__Group__5__Impl rule__Operation__Group__6 ;
public final void rule__Operation__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3821:1: ( rule__Operation__Group__5__Impl rule__Operation__Group__6 )
// InternalUrml.g:3822:2: rule__Operation__Group__5__Impl rule__Operation__Group__6
{
pushFollow(FOLLOW_5);
rule__Operation__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__6();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__5"
// $ANTLR start "rule__Operation__Group__5__Impl"
// InternalUrml.g:3829:1: rule__Operation__Group__5__Impl : ( ')' ) ;
public final void rule__Operation__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3833:1: ( ( ')' ) )
// InternalUrml.g:3834:1: ( ')' )
{
// InternalUrml.g:3834:1: ( ')' )
// InternalUrml.g:3835:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getRightParenthesisKeyword_5());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getRightParenthesisKeyword_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__5__Impl"
// $ANTLR start "rule__Operation__Group__6"
// InternalUrml.g:3848:1: rule__Operation__Group__6 : rule__Operation__Group__6__Impl rule__Operation__Group__7 ;
public final void rule__Operation__Group__6() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3852:1: ( rule__Operation__Group__6__Impl rule__Operation__Group__7 )
// InternalUrml.g:3853:2: rule__Operation__Group__6__Impl rule__Operation__Group__7
{
pushFollow(FOLLOW_24);
rule__Operation__Group__6__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__7();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__6"
// $ANTLR start "rule__Operation__Group__6__Impl"
// InternalUrml.g:3860:1: rule__Operation__Group__6__Impl : ( '{' ) ;
public final void rule__Operation__Group__6__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3864:1: ( ( '{' ) )
// InternalUrml.g:3865:1: ( '{' )
{
// InternalUrml.g:3865:1: ( '{' )
// InternalUrml.g:3866:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getLeftCurlyBracketKeyword_6());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getLeftCurlyBracketKeyword_6());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__6__Impl"
// $ANTLR start "rule__Operation__Group__7"
// InternalUrml.g:3879:1: rule__Operation__Group__7 : rule__Operation__Group__7__Impl rule__Operation__Group__8 ;
public final void rule__Operation__Group__7() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3883:1: ( rule__Operation__Group__7__Impl rule__Operation__Group__8 )
// InternalUrml.g:3884:2: rule__Operation__Group__7__Impl rule__Operation__Group__8
{
pushFollow(FOLLOW_25);
rule__Operation__Group__7__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group__8();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__7"
// $ANTLR start "rule__Operation__Group__7__Impl"
// InternalUrml.g:3891:1: rule__Operation__Group__7__Impl : ( ( rule__Operation__OperationCodeAssignment_7 ) ) ;
public final void rule__Operation__Group__7__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3895:1: ( ( ( rule__Operation__OperationCodeAssignment_7 ) ) )
// InternalUrml.g:3896:1: ( ( rule__Operation__OperationCodeAssignment_7 ) )
{
// InternalUrml.g:3896:1: ( ( rule__Operation__OperationCodeAssignment_7 ) )
// InternalUrml.g:3897:1: ( rule__Operation__OperationCodeAssignment_7 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getOperationCodeAssignment_7());
}
// InternalUrml.g:3898:1: ( rule__Operation__OperationCodeAssignment_7 )
// InternalUrml.g:3898:2: rule__Operation__OperationCodeAssignment_7
{
pushFollow(FOLLOW_2);
rule__Operation__OperationCodeAssignment_7();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getOperationCodeAssignment_7());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__7__Impl"
// $ANTLR start "rule__Operation__Group__8"
// InternalUrml.g:3908:1: rule__Operation__Group__8 : rule__Operation__Group__8__Impl ;
public final void rule__Operation__Group__8() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3912:1: ( rule__Operation__Group__8__Impl )
// InternalUrml.g:3913:2: rule__Operation__Group__8__Impl
{
pushFollow(FOLLOW_2);
rule__Operation__Group__8__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__8"
// $ANTLR start "rule__Operation__Group__8__Impl"
// InternalUrml.g:3919:1: rule__Operation__Group__8__Impl : ( '}' ) ;
public final void rule__Operation__Group__8__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3923:1: ( ( '}' ) )
// InternalUrml.g:3924:1: ( '}' )
{
// InternalUrml.g:3924:1: ( '}' )
// InternalUrml.g:3925:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getRightCurlyBracketKeyword_8());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getRightCurlyBracketKeyword_8());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group__8__Impl"
// $ANTLR start "rule__Operation__Group_4__0"
// InternalUrml.g:3956:1: rule__Operation__Group_4__0 : rule__Operation__Group_4__0__Impl rule__Operation__Group_4__1 ;
public final void rule__Operation__Group_4__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3960:1: ( rule__Operation__Group_4__0__Impl rule__Operation__Group_4__1 )
// InternalUrml.g:3961:2: rule__Operation__Group_4__0__Impl rule__Operation__Group_4__1
{
pushFollow(FOLLOW_17);
rule__Operation__Group_4__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group_4__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4__0"
// $ANTLR start "rule__Operation__Group_4__0__Impl"
// InternalUrml.g:3968:1: rule__Operation__Group_4__0__Impl : ( ( rule__Operation__LocalVarsAssignment_4_0 ) ) ;
public final void rule__Operation__Group_4__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3972:1: ( ( ( rule__Operation__LocalVarsAssignment_4_0 ) ) )
// InternalUrml.g:3973:1: ( ( rule__Operation__LocalVarsAssignment_4_0 ) )
{
// InternalUrml.g:3973:1: ( ( rule__Operation__LocalVarsAssignment_4_0 ) )
// InternalUrml.g:3974:1: ( rule__Operation__LocalVarsAssignment_4_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getLocalVarsAssignment_4_0());
}
// InternalUrml.g:3975:1: ( rule__Operation__LocalVarsAssignment_4_0 )
// InternalUrml.g:3975:2: rule__Operation__LocalVarsAssignment_4_0
{
pushFollow(FOLLOW_2);
rule__Operation__LocalVarsAssignment_4_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getLocalVarsAssignment_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4__0__Impl"
// $ANTLR start "rule__Operation__Group_4__1"
// InternalUrml.g:3985:1: rule__Operation__Group_4__1 : rule__Operation__Group_4__1__Impl ;
public final void rule__Operation__Group_4__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:3989:1: ( rule__Operation__Group_4__1__Impl )
// InternalUrml.g:3990:2: rule__Operation__Group_4__1__Impl
{
pushFollow(FOLLOW_2);
rule__Operation__Group_4__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4__1"
// $ANTLR start "rule__Operation__Group_4__1__Impl"
// InternalUrml.g:3996:1: rule__Operation__Group_4__1__Impl : ( ( rule__Operation__Group_4_1__0 )* ) ;
public final void rule__Operation__Group_4__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4000:1: ( ( ( rule__Operation__Group_4_1__0 )* ) )
// InternalUrml.g:4001:1: ( ( rule__Operation__Group_4_1__0 )* )
{
// InternalUrml.g:4001:1: ( ( rule__Operation__Group_4_1__0 )* )
// InternalUrml.g:4002:1: ( rule__Operation__Group_4_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getGroup_4_1());
}
// InternalUrml.g:4003:1: ( rule__Operation__Group_4_1__0 )*
loop35:
do {
int alt35=2;
int LA35_0 = input.LA(1);
if ( (LA35_0==22) ) {
alt35=1;
}
switch (alt35) {
case 1 :
// InternalUrml.g:4003:2: rule__Operation__Group_4_1__0
{
pushFollow(FOLLOW_18);
rule__Operation__Group_4_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop35;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getGroup_4_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4__1__Impl"
// $ANTLR start "rule__Operation__Group_4_1__0"
// InternalUrml.g:4017:1: rule__Operation__Group_4_1__0 : rule__Operation__Group_4_1__0__Impl rule__Operation__Group_4_1__1 ;
public final void rule__Operation__Group_4_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4021:1: ( rule__Operation__Group_4_1__0__Impl rule__Operation__Group_4_1__1 )
// InternalUrml.g:4022:2: rule__Operation__Group_4_1__0__Impl rule__Operation__Group_4_1__1
{
pushFollow(FOLLOW_8);
rule__Operation__Group_4_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Operation__Group_4_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4_1__0"
// $ANTLR start "rule__Operation__Group_4_1__0__Impl"
// InternalUrml.g:4029:1: rule__Operation__Group_4_1__0__Impl : ( ',' ) ;
public final void rule__Operation__Group_4_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4033:1: ( ( ',' ) )
// InternalUrml.g:4034:1: ( ',' )
{
// InternalUrml.g:4034:1: ( ',' )
// InternalUrml.g:4035:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getCommaKeyword_4_1_0());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getCommaKeyword_4_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4_1__0__Impl"
// $ANTLR start "rule__Operation__Group_4_1__1"
// InternalUrml.g:4048:1: rule__Operation__Group_4_1__1 : rule__Operation__Group_4_1__1__Impl ;
public final void rule__Operation__Group_4_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4052:1: ( rule__Operation__Group_4_1__1__Impl )
// InternalUrml.g:4053:2: rule__Operation__Group_4_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Operation__Group_4_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4_1__1"
// $ANTLR start "rule__Operation__Group_4_1__1__Impl"
// InternalUrml.g:4059:1: rule__Operation__Group_4_1__1__Impl : ( ( rule__Operation__LocalVarsAssignment_4_1_1 ) ) ;
public final void rule__Operation__Group_4_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4063:1: ( ( ( rule__Operation__LocalVarsAssignment_4_1_1 ) ) )
// InternalUrml.g:4064:1: ( ( rule__Operation__LocalVarsAssignment_4_1_1 ) )
{
// InternalUrml.g:4064:1: ( ( rule__Operation__LocalVarsAssignment_4_1_1 ) )
// InternalUrml.g:4065:1: ( rule__Operation__LocalVarsAssignment_4_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getLocalVarsAssignment_4_1_1());
}
// InternalUrml.g:4066:1: ( rule__Operation__LocalVarsAssignment_4_1_1 )
// InternalUrml.g:4066:2: rule__Operation__LocalVarsAssignment_4_1_1
{
pushFollow(FOLLOW_2);
rule__Operation__LocalVarsAssignment_4_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getLocalVarsAssignment_4_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__Group_4_1__1__Impl"
// $ANTLR start "rule__TimerPort__Group__0"
// InternalUrml.g:4080:1: rule__TimerPort__Group__0 : rule__TimerPort__Group__0__Impl rule__TimerPort__Group__1 ;
public final void rule__TimerPort__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4084:1: ( rule__TimerPort__Group__0__Impl rule__TimerPort__Group__1 )
// InternalUrml.g:4085:2: rule__TimerPort__Group__0__Impl rule__TimerPort__Group__1
{
pushFollow(FOLLOW_4);
rule__TimerPort__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__TimerPort__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__TimerPort__Group__0"
// $ANTLR start "rule__TimerPort__Group__0__Impl"
// InternalUrml.g:4092:1: rule__TimerPort__Group__0__Impl : ( 'timerPort' ) ;
public final void rule__TimerPort__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4096:1: ( ( 'timerPort' ) )
// InternalUrml.g:4097:1: ( 'timerPort' )
{
// InternalUrml.g:4097:1: ( 'timerPort' )
// InternalUrml.g:4098:1: 'timerPort'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTimerPortAccess().getTimerPortKeyword_0());
}
match(input,26,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTimerPortAccess().getTimerPortKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__TimerPort__Group__0__Impl"
// $ANTLR start "rule__TimerPort__Group__1"
// InternalUrml.g:4111:1: rule__TimerPort__Group__1 : rule__TimerPort__Group__1__Impl ;
public final void rule__TimerPort__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4115:1: ( rule__TimerPort__Group__1__Impl )
// InternalUrml.g:4116:2: rule__TimerPort__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__TimerPort__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__TimerPort__Group__1"
// $ANTLR start "rule__TimerPort__Group__1__Impl"
// InternalUrml.g:4122:1: rule__TimerPort__Group__1__Impl : ( ( rule__TimerPort__NameAssignment_1 ) ) ;
public final void rule__TimerPort__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4126:1: ( ( ( rule__TimerPort__NameAssignment_1 ) ) )
// InternalUrml.g:4127:1: ( ( rule__TimerPort__NameAssignment_1 ) )
{
// InternalUrml.g:4127:1: ( ( rule__TimerPort__NameAssignment_1 ) )
// InternalUrml.g:4128:1: ( rule__TimerPort__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTimerPortAccess().getNameAssignment_1());
}
// InternalUrml.g:4129:1: ( rule__TimerPort__NameAssignment_1 )
// InternalUrml.g:4129:2: rule__TimerPort__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__TimerPort__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTimerPortAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__TimerPort__Group__1__Impl"
// $ANTLR start "rule__LogPort__Group__0"
// InternalUrml.g:4143:1: rule__LogPort__Group__0 : rule__LogPort__Group__0__Impl rule__LogPort__Group__1 ;
public final void rule__LogPort__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4147:1: ( rule__LogPort__Group__0__Impl rule__LogPort__Group__1 )
// InternalUrml.g:4148:2: rule__LogPort__Group__0__Impl rule__LogPort__Group__1
{
pushFollow(FOLLOW_4);
rule__LogPort__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__LogPort__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogPort__Group__0"
// $ANTLR start "rule__LogPort__Group__0__Impl"
// InternalUrml.g:4155:1: rule__LogPort__Group__0__Impl : ( 'logPort' ) ;
public final void rule__LogPort__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4159:1: ( ( 'logPort' ) )
// InternalUrml.g:4160:1: ( 'logPort' )
{
// InternalUrml.g:4160:1: ( 'logPort' )
// InternalUrml.g:4161:1: 'logPort'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogPortAccess().getLogPortKeyword_0());
}
match(input,27,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogPortAccess().getLogPortKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogPort__Group__0__Impl"
// $ANTLR start "rule__LogPort__Group__1"
// InternalUrml.g:4174:1: rule__LogPort__Group__1 : rule__LogPort__Group__1__Impl ;
public final void rule__LogPort__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4178:1: ( rule__LogPort__Group__1__Impl )
// InternalUrml.g:4179:2: rule__LogPort__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__LogPort__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogPort__Group__1"
// $ANTLR start "rule__LogPort__Group__1__Impl"
// InternalUrml.g:4185:1: rule__LogPort__Group__1__Impl : ( ( rule__LogPort__NameAssignment_1 ) ) ;
public final void rule__LogPort__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4189:1: ( ( ( rule__LogPort__NameAssignment_1 ) ) )
// InternalUrml.g:4190:1: ( ( rule__LogPort__NameAssignment_1 ) )
{
// InternalUrml.g:4190:1: ( ( rule__LogPort__NameAssignment_1 ) )
// InternalUrml.g:4191:1: ( rule__LogPort__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogPortAccess().getNameAssignment_1());
}
// InternalUrml.g:4192:1: ( rule__LogPort__NameAssignment_1 )
// InternalUrml.g:4192:2: rule__LogPort__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__LogPort__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLogPortAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogPort__Group__1__Impl"
// $ANTLR start "rule__Port__Group__0"
// InternalUrml.g:4206:1: rule__Port__Group__0 : rule__Port__Group__0__Impl rule__Port__Group__1 ;
public final void rule__Port__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4210:1: ( rule__Port__Group__0__Impl rule__Port__Group__1 )
// InternalUrml.g:4211:2: rule__Port__Group__0__Impl rule__Port__Group__1
{
pushFollow(FOLLOW_26);
rule__Port__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Port__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__0"
// $ANTLR start "rule__Port__Group__0__Impl"
// InternalUrml.g:4218:1: rule__Port__Group__0__Impl : ( 'port' ) ;
public final void rule__Port__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4222:1: ( ( 'port' ) )
// InternalUrml.g:4223:1: ( 'port' )
{
// InternalUrml.g:4223:1: ( 'port' )
// InternalUrml.g:4224:1: 'port'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getPortKeyword_0());
}
match(input,28,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getPortKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__0__Impl"
// $ANTLR start "rule__Port__Group__1"
// InternalUrml.g:4237:1: rule__Port__Group__1 : rule__Port__Group__1__Impl rule__Port__Group__2 ;
public final void rule__Port__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4241:1: ( rule__Port__Group__1__Impl rule__Port__Group__2 )
// InternalUrml.g:4242:2: rule__Port__Group__1__Impl rule__Port__Group__2
{
pushFollow(FOLLOW_26);
rule__Port__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Port__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__1"
// $ANTLR start "rule__Port__Group__1__Impl"
// InternalUrml.g:4249:1: rule__Port__Group__1__Impl : ( ( rule__Port__ConjugatedAssignment_1 )? ) ;
public final void rule__Port__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4253:1: ( ( ( rule__Port__ConjugatedAssignment_1 )? ) )
// InternalUrml.g:4254:1: ( ( rule__Port__ConjugatedAssignment_1 )? )
{
// InternalUrml.g:4254:1: ( ( rule__Port__ConjugatedAssignment_1 )? )
// InternalUrml.g:4255:1: ( rule__Port__ConjugatedAssignment_1 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getConjugatedAssignment_1());
}
// InternalUrml.g:4256:1: ( rule__Port__ConjugatedAssignment_1 )?
int alt36=2;
int LA36_0 = input.LA(1);
if ( (LA36_0==79) ) {
alt36=1;
}
switch (alt36) {
case 1 :
// InternalUrml.g:4256:2: rule__Port__ConjugatedAssignment_1
{
pushFollow(FOLLOW_2);
rule__Port__ConjugatedAssignment_1();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getConjugatedAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__1__Impl"
// $ANTLR start "rule__Port__Group__2"
// InternalUrml.g:4266:1: rule__Port__Group__2 : rule__Port__Group__2__Impl rule__Port__Group__3 ;
public final void rule__Port__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4270:1: ( rule__Port__Group__2__Impl rule__Port__Group__3 )
// InternalUrml.g:4271:2: rule__Port__Group__2__Impl rule__Port__Group__3
{
pushFollow(FOLLOW_27);
rule__Port__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Port__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__2"
// $ANTLR start "rule__Port__Group__2__Impl"
// InternalUrml.g:4278:1: rule__Port__Group__2__Impl : ( ( rule__Port__NameAssignment_2 ) ) ;
public final void rule__Port__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4282:1: ( ( ( rule__Port__NameAssignment_2 ) ) )
// InternalUrml.g:4283:1: ( ( rule__Port__NameAssignment_2 ) )
{
// InternalUrml.g:4283:1: ( ( rule__Port__NameAssignment_2 ) )
// InternalUrml.g:4284:1: ( rule__Port__NameAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getNameAssignment_2());
}
// InternalUrml.g:4285:1: ( rule__Port__NameAssignment_2 )
// InternalUrml.g:4285:2: rule__Port__NameAssignment_2
{
pushFollow(FOLLOW_2);
rule__Port__NameAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getNameAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__2__Impl"
// $ANTLR start "rule__Port__Group__3"
// InternalUrml.g:4295:1: rule__Port__Group__3 : rule__Port__Group__3__Impl rule__Port__Group__4 ;
public final void rule__Port__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4299:1: ( rule__Port__Group__3__Impl rule__Port__Group__4 )
// InternalUrml.g:4300:2: rule__Port__Group__3__Impl rule__Port__Group__4
{
pushFollow(FOLLOW_4);
rule__Port__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Port__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__3"
// $ANTLR start "rule__Port__Group__3__Impl"
// InternalUrml.g:4307:1: rule__Port__Group__3__Impl : ( ':' ) ;
public final void rule__Port__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4311:1: ( ( ':' ) )
// InternalUrml.g:4312:1: ( ':' )
{
// InternalUrml.g:4312:1: ( ':' )
// InternalUrml.g:4313:1: ':'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getColonKeyword_3());
}
match(input,29,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getColonKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__3__Impl"
// $ANTLR start "rule__Port__Group__4"
// InternalUrml.g:4326:1: rule__Port__Group__4 : rule__Port__Group__4__Impl ;
public final void rule__Port__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4330:1: ( rule__Port__Group__4__Impl )
// InternalUrml.g:4331:2: rule__Port__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__Port__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__4"
// $ANTLR start "rule__Port__Group__4__Impl"
// InternalUrml.g:4337:1: rule__Port__Group__4__Impl : ( ( rule__Port__ProtocolAssignment_4 ) ) ;
public final void rule__Port__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4341:1: ( ( ( rule__Port__ProtocolAssignment_4 ) ) )
// InternalUrml.g:4342:1: ( ( rule__Port__ProtocolAssignment_4 ) )
{
// InternalUrml.g:4342:1: ( ( rule__Port__ProtocolAssignment_4 ) )
// InternalUrml.g:4343:1: ( rule__Port__ProtocolAssignment_4 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getProtocolAssignment_4());
}
// InternalUrml.g:4344:1: ( rule__Port__ProtocolAssignment_4 )
// InternalUrml.g:4344:2: rule__Port__ProtocolAssignment_4
{
pushFollow(FOLLOW_2);
rule__Port__ProtocolAssignment_4();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getProtocolAssignment_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__Group__4__Impl"
// $ANTLR start "rule__Connector__Group__0"
// InternalUrml.g:4364:1: rule__Connector__Group__0 : rule__Connector__Group__0__Impl rule__Connector__Group__1 ;
public final void rule__Connector__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4368:1: ( rule__Connector__Group__0__Impl rule__Connector__Group__1 )
// InternalUrml.g:4369:2: rule__Connector__Group__0__Impl rule__Connector__Group__1
{
pushFollow(FOLLOW_4);
rule__Connector__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__0"
// $ANTLR start "rule__Connector__Group__0__Impl"
// InternalUrml.g:4376:1: rule__Connector__Group__0__Impl : ( 'connector' ) ;
public final void rule__Connector__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4380:1: ( ( 'connector' ) )
// InternalUrml.g:4381:1: ( 'connector' )
{
// InternalUrml.g:4381:1: ( 'connector' )
// InternalUrml.g:4382:1: 'connector'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getConnectorKeyword_0());
}
match(input,30,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getConnectorKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__0__Impl"
// $ANTLR start "rule__Connector__Group__1"
// InternalUrml.g:4395:1: rule__Connector__Group__1 : rule__Connector__Group__1__Impl rule__Connector__Group__2 ;
public final void rule__Connector__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4399:1: ( rule__Connector__Group__1__Impl rule__Connector__Group__2 )
// InternalUrml.g:4400:2: rule__Connector__Group__1__Impl rule__Connector__Group__2
{
pushFollow(FOLLOW_4);
rule__Connector__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__1"
// $ANTLR start "rule__Connector__Group__1__Impl"
// InternalUrml.g:4407:1: rule__Connector__Group__1__Impl : ( ( rule__Connector__Group_1__0 )? ) ;
public final void rule__Connector__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4411:1: ( ( ( rule__Connector__Group_1__0 )? ) )
// InternalUrml.g:4412:1: ( ( rule__Connector__Group_1__0 )? )
{
// InternalUrml.g:4412:1: ( ( rule__Connector__Group_1__0 )? )
// InternalUrml.g:4413:1: ( rule__Connector__Group_1__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getGroup_1());
}
// InternalUrml.g:4414:1: ( rule__Connector__Group_1__0 )?
int alt37=2;
int LA37_0 = input.LA(1);
if ( (LA37_0==RULE_ID) ) {
int LA37_1 = input.LA(2);
if ( (LA37_1==32) ) {
alt37=1;
}
}
switch (alt37) {
case 1 :
// InternalUrml.g:4414:2: rule__Connector__Group_1__0
{
pushFollow(FOLLOW_2);
rule__Connector__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__1__Impl"
// $ANTLR start "rule__Connector__Group__2"
// InternalUrml.g:4424:1: rule__Connector__Group__2 : rule__Connector__Group__2__Impl rule__Connector__Group__3 ;
public final void rule__Connector__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4428:1: ( rule__Connector__Group__2__Impl rule__Connector__Group__3 )
// InternalUrml.g:4429:2: rule__Connector__Group__2__Impl rule__Connector__Group__3
{
pushFollow(FOLLOW_28);
rule__Connector__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__2"
// $ANTLR start "rule__Connector__Group__2__Impl"
// InternalUrml.g:4436:1: rule__Connector__Group__2__Impl : ( ( rule__Connector__Port1Assignment_2 ) ) ;
public final void rule__Connector__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4440:1: ( ( ( rule__Connector__Port1Assignment_2 ) ) )
// InternalUrml.g:4441:1: ( ( rule__Connector__Port1Assignment_2 ) )
{
// InternalUrml.g:4441:1: ( ( rule__Connector__Port1Assignment_2 ) )
// InternalUrml.g:4442:1: ( rule__Connector__Port1Assignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getPort1Assignment_2());
}
// InternalUrml.g:4443:1: ( rule__Connector__Port1Assignment_2 )
// InternalUrml.g:4443:2: rule__Connector__Port1Assignment_2
{
pushFollow(FOLLOW_2);
rule__Connector__Port1Assignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getPort1Assignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__2__Impl"
// $ANTLR start "rule__Connector__Group__3"
// InternalUrml.g:4453:1: rule__Connector__Group__3 : rule__Connector__Group__3__Impl rule__Connector__Group__4 ;
public final void rule__Connector__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4457:1: ( rule__Connector__Group__3__Impl rule__Connector__Group__4 )
// InternalUrml.g:4458:2: rule__Connector__Group__3__Impl rule__Connector__Group__4
{
pushFollow(FOLLOW_4);
rule__Connector__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__3"
// $ANTLR start "rule__Connector__Group__3__Impl"
// InternalUrml.g:4465:1: rule__Connector__Group__3__Impl : ( 'and' ) ;
public final void rule__Connector__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4469:1: ( ( 'and' ) )
// InternalUrml.g:4470:1: ( 'and' )
{
// InternalUrml.g:4470:1: ( 'and' )
// InternalUrml.g:4471:1: 'and'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getAndKeyword_3());
}
match(input,31,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getAndKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__3__Impl"
// $ANTLR start "rule__Connector__Group__4"
// InternalUrml.g:4484:1: rule__Connector__Group__4 : rule__Connector__Group__4__Impl rule__Connector__Group__5 ;
public final void rule__Connector__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4488:1: ( rule__Connector__Group__4__Impl rule__Connector__Group__5 )
// InternalUrml.g:4489:2: rule__Connector__Group__4__Impl rule__Connector__Group__5
{
pushFollow(FOLLOW_4);
rule__Connector__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__4"
// $ANTLR start "rule__Connector__Group__4__Impl"
// InternalUrml.g:4496:1: rule__Connector__Group__4__Impl : ( ( rule__Connector__Group_4__0 )? ) ;
public final void rule__Connector__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4500:1: ( ( ( rule__Connector__Group_4__0 )? ) )
// InternalUrml.g:4501:1: ( ( rule__Connector__Group_4__0 )? )
{
// InternalUrml.g:4501:1: ( ( rule__Connector__Group_4__0 )? )
// InternalUrml.g:4502:1: ( rule__Connector__Group_4__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getGroup_4());
}
// InternalUrml.g:4503:1: ( rule__Connector__Group_4__0 )?
int alt38=2;
int LA38_0 = input.LA(1);
if ( (LA38_0==RULE_ID) ) {
int LA38_1 = input.LA(2);
if ( (LA38_1==32) ) {
alt38=1;
}
}
switch (alt38) {
case 1 :
// InternalUrml.g:4503:2: rule__Connector__Group_4__0
{
pushFollow(FOLLOW_2);
rule__Connector__Group_4__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getGroup_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__4__Impl"
// $ANTLR start "rule__Connector__Group__5"
// InternalUrml.g:4513:1: rule__Connector__Group__5 : rule__Connector__Group__5__Impl ;
public final void rule__Connector__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4517:1: ( rule__Connector__Group__5__Impl )
// InternalUrml.g:4518:2: rule__Connector__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__Connector__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__5"
// $ANTLR start "rule__Connector__Group__5__Impl"
// InternalUrml.g:4524:1: rule__Connector__Group__5__Impl : ( ( rule__Connector__Port2Assignment_5 ) ) ;
public final void rule__Connector__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4528:1: ( ( ( rule__Connector__Port2Assignment_5 ) ) )
// InternalUrml.g:4529:1: ( ( rule__Connector__Port2Assignment_5 ) )
{
// InternalUrml.g:4529:1: ( ( rule__Connector__Port2Assignment_5 ) )
// InternalUrml.g:4530:1: ( rule__Connector__Port2Assignment_5 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getPort2Assignment_5());
}
// InternalUrml.g:4531:1: ( rule__Connector__Port2Assignment_5 )
// InternalUrml.g:4531:2: rule__Connector__Port2Assignment_5
{
pushFollow(FOLLOW_2);
rule__Connector__Port2Assignment_5();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getPort2Assignment_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group__5__Impl"
// $ANTLR start "rule__Connector__Group_1__0"
// InternalUrml.g:4553:1: rule__Connector__Group_1__0 : rule__Connector__Group_1__0__Impl rule__Connector__Group_1__1 ;
public final void rule__Connector__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4557:1: ( rule__Connector__Group_1__0__Impl rule__Connector__Group_1__1 )
// InternalUrml.g:4558:2: rule__Connector__Group_1__0__Impl rule__Connector__Group_1__1
{
pushFollow(FOLLOW_29);
rule__Connector__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_1__0"
// $ANTLR start "rule__Connector__Group_1__0__Impl"
// InternalUrml.g:4565:1: rule__Connector__Group_1__0__Impl : ( ( rule__Connector__CapsuleInst1Assignment_1_0 ) ) ;
public final void rule__Connector__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4569:1: ( ( ( rule__Connector__CapsuleInst1Assignment_1_0 ) ) )
// InternalUrml.g:4570:1: ( ( rule__Connector__CapsuleInst1Assignment_1_0 ) )
{
// InternalUrml.g:4570:1: ( ( rule__Connector__CapsuleInst1Assignment_1_0 ) )
// InternalUrml.g:4571:1: ( rule__Connector__CapsuleInst1Assignment_1_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getCapsuleInst1Assignment_1_0());
}
// InternalUrml.g:4572:1: ( rule__Connector__CapsuleInst1Assignment_1_0 )
// InternalUrml.g:4572:2: rule__Connector__CapsuleInst1Assignment_1_0
{
pushFollow(FOLLOW_2);
rule__Connector__CapsuleInst1Assignment_1_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getCapsuleInst1Assignment_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_1__0__Impl"
// $ANTLR start "rule__Connector__Group_1__1"
// InternalUrml.g:4582:1: rule__Connector__Group_1__1 : rule__Connector__Group_1__1__Impl ;
public final void rule__Connector__Group_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4586:1: ( rule__Connector__Group_1__1__Impl )
// InternalUrml.g:4587:2: rule__Connector__Group_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Connector__Group_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_1__1"
// $ANTLR start "rule__Connector__Group_1__1__Impl"
// InternalUrml.g:4593:1: rule__Connector__Group_1__1__Impl : ( '.' ) ;
public final void rule__Connector__Group_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4597:1: ( ( '.' ) )
// InternalUrml.g:4598:1: ( '.' )
{
// InternalUrml.g:4598:1: ( '.' )
// InternalUrml.g:4599:1: '.'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getFullStopKeyword_1_1());
}
match(input,32,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getFullStopKeyword_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_1__1__Impl"
// $ANTLR start "rule__Connector__Group_4__0"
// InternalUrml.g:4616:1: rule__Connector__Group_4__0 : rule__Connector__Group_4__0__Impl rule__Connector__Group_4__1 ;
public final void rule__Connector__Group_4__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4620:1: ( rule__Connector__Group_4__0__Impl rule__Connector__Group_4__1 )
// InternalUrml.g:4621:2: rule__Connector__Group_4__0__Impl rule__Connector__Group_4__1
{
pushFollow(FOLLOW_29);
rule__Connector__Group_4__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Connector__Group_4__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_4__0"
// $ANTLR start "rule__Connector__Group_4__0__Impl"
// InternalUrml.g:4628:1: rule__Connector__Group_4__0__Impl : ( ( rule__Connector__CapsuleInst2Assignment_4_0 ) ) ;
public final void rule__Connector__Group_4__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4632:1: ( ( ( rule__Connector__CapsuleInst2Assignment_4_0 ) ) )
// InternalUrml.g:4633:1: ( ( rule__Connector__CapsuleInst2Assignment_4_0 ) )
{
// InternalUrml.g:4633:1: ( ( rule__Connector__CapsuleInst2Assignment_4_0 ) )
// InternalUrml.g:4634:1: ( rule__Connector__CapsuleInst2Assignment_4_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getCapsuleInst2Assignment_4_0());
}
// InternalUrml.g:4635:1: ( rule__Connector__CapsuleInst2Assignment_4_0 )
// InternalUrml.g:4635:2: rule__Connector__CapsuleInst2Assignment_4_0
{
pushFollow(FOLLOW_2);
rule__Connector__CapsuleInst2Assignment_4_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getCapsuleInst2Assignment_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_4__0__Impl"
// $ANTLR start "rule__Connector__Group_4__1"
// InternalUrml.g:4645:1: rule__Connector__Group_4__1 : rule__Connector__Group_4__1__Impl ;
public final void rule__Connector__Group_4__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4649:1: ( rule__Connector__Group_4__1__Impl )
// InternalUrml.g:4650:2: rule__Connector__Group_4__1__Impl
{
pushFollow(FOLLOW_2);
rule__Connector__Group_4__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_4__1"
// $ANTLR start "rule__Connector__Group_4__1__Impl"
// InternalUrml.g:4656:1: rule__Connector__Group_4__1__Impl : ( '.' ) ;
public final void rule__Connector__Group_4__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4660:1: ( ( '.' ) )
// InternalUrml.g:4661:1: ( '.' )
{
// InternalUrml.g:4661:1: ( '.' )
// InternalUrml.g:4662:1: '.'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getFullStopKeyword_4_1());
}
match(input,32,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getFullStopKeyword_4_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Group_4__1__Impl"
// $ANTLR start "rule__CapsuleInst__Group__0"
// InternalUrml.g:4679:1: rule__CapsuleInst__Group__0 : rule__CapsuleInst__Group__0__Impl rule__CapsuleInst__Group__1 ;
public final void rule__CapsuleInst__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4683:1: ( rule__CapsuleInst__Group__0__Impl rule__CapsuleInst__Group__1 )
// InternalUrml.g:4684:2: rule__CapsuleInst__Group__0__Impl rule__CapsuleInst__Group__1
{
pushFollow(FOLLOW_4);
rule__CapsuleInst__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__CapsuleInst__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__0"
// $ANTLR start "rule__CapsuleInst__Group__0__Impl"
// InternalUrml.g:4691:1: rule__CapsuleInst__Group__0__Impl : ( 'capsuleInstance' ) ;
public final void rule__CapsuleInst__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4695:1: ( ( 'capsuleInstance' ) )
// InternalUrml.g:4696:1: ( 'capsuleInstance' )
{
// InternalUrml.g:4696:1: ( 'capsuleInstance' )
// InternalUrml.g:4697:1: 'capsuleInstance'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getCapsuleInstanceKeyword_0());
}
match(input,33,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getCapsuleInstanceKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__0__Impl"
// $ANTLR start "rule__CapsuleInst__Group__1"
// InternalUrml.g:4710:1: rule__CapsuleInst__Group__1 : rule__CapsuleInst__Group__1__Impl rule__CapsuleInst__Group__2 ;
public final void rule__CapsuleInst__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4714:1: ( rule__CapsuleInst__Group__1__Impl rule__CapsuleInst__Group__2 )
// InternalUrml.g:4715:2: rule__CapsuleInst__Group__1__Impl rule__CapsuleInst__Group__2
{
pushFollow(FOLLOW_27);
rule__CapsuleInst__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__CapsuleInst__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__1"
// $ANTLR start "rule__CapsuleInst__Group__1__Impl"
// InternalUrml.g:4722:1: rule__CapsuleInst__Group__1__Impl : ( ( rule__CapsuleInst__NameAssignment_1 ) ) ;
public final void rule__CapsuleInst__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4726:1: ( ( ( rule__CapsuleInst__NameAssignment_1 ) ) )
// InternalUrml.g:4727:1: ( ( rule__CapsuleInst__NameAssignment_1 ) )
{
// InternalUrml.g:4727:1: ( ( rule__CapsuleInst__NameAssignment_1 ) )
// InternalUrml.g:4728:1: ( rule__CapsuleInst__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getNameAssignment_1());
}
// InternalUrml.g:4729:1: ( rule__CapsuleInst__NameAssignment_1 )
// InternalUrml.g:4729:2: rule__CapsuleInst__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__CapsuleInst__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__1__Impl"
// $ANTLR start "rule__CapsuleInst__Group__2"
// InternalUrml.g:4739:1: rule__CapsuleInst__Group__2 : rule__CapsuleInst__Group__2__Impl rule__CapsuleInst__Group__3 ;
public final void rule__CapsuleInst__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4743:1: ( rule__CapsuleInst__Group__2__Impl rule__CapsuleInst__Group__3 )
// InternalUrml.g:4744:2: rule__CapsuleInst__Group__2__Impl rule__CapsuleInst__Group__3
{
pushFollow(FOLLOW_4);
rule__CapsuleInst__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__CapsuleInst__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__2"
// $ANTLR start "rule__CapsuleInst__Group__2__Impl"
// InternalUrml.g:4751:1: rule__CapsuleInst__Group__2__Impl : ( ':' ) ;
public final void rule__CapsuleInst__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4755:1: ( ( ':' ) )
// InternalUrml.g:4756:1: ( ':' )
{
// InternalUrml.g:4756:1: ( ':' )
// InternalUrml.g:4757:1: ':'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getColonKeyword_2());
}
match(input,29,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getColonKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__2__Impl"
// $ANTLR start "rule__CapsuleInst__Group__3"
// InternalUrml.g:4770:1: rule__CapsuleInst__Group__3 : rule__CapsuleInst__Group__3__Impl ;
public final void rule__CapsuleInst__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4774:1: ( rule__CapsuleInst__Group__3__Impl )
// InternalUrml.g:4775:2: rule__CapsuleInst__Group__3__Impl
{
pushFollow(FOLLOW_2);
rule__CapsuleInst__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__3"
// $ANTLR start "rule__CapsuleInst__Group__3__Impl"
// InternalUrml.g:4781:1: rule__CapsuleInst__Group__3__Impl : ( ( rule__CapsuleInst__TypeAssignment_3 ) ) ;
public final void rule__CapsuleInst__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4785:1: ( ( ( rule__CapsuleInst__TypeAssignment_3 ) ) )
// InternalUrml.g:4786:1: ( ( rule__CapsuleInst__TypeAssignment_3 ) )
{
// InternalUrml.g:4786:1: ( ( rule__CapsuleInst__TypeAssignment_3 ) )
// InternalUrml.g:4787:1: ( rule__CapsuleInst__TypeAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getTypeAssignment_3());
}
// InternalUrml.g:4788:1: ( rule__CapsuleInst__TypeAssignment_3 )
// InternalUrml.g:4788:2: rule__CapsuleInst__TypeAssignment_3
{
pushFollow(FOLLOW_2);
rule__CapsuleInst__TypeAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getTypeAssignment_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__Group__3__Impl"
// $ANTLR start "rule__StateMachine__Group__0"
// InternalUrml.g:4806:1: rule__StateMachine__Group__0 : rule__StateMachine__Group__0__Impl rule__StateMachine__Group__1 ;
public final void rule__StateMachine__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4810:1: ( rule__StateMachine__Group__0__Impl rule__StateMachine__Group__1 )
// InternalUrml.g:4811:2: rule__StateMachine__Group__0__Impl rule__StateMachine__Group__1
{
pushFollow(FOLLOW_30);
rule__StateMachine__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StateMachine__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__0"
// $ANTLR start "rule__StateMachine__Group__0__Impl"
// InternalUrml.g:4818:1: rule__StateMachine__Group__0__Impl : ( () ) ;
public final void rule__StateMachine__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4822:1: ( ( () ) )
// InternalUrml.g:4823:1: ( () )
{
// InternalUrml.g:4823:1: ( () )
// InternalUrml.g:4824:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getStateMachineAction_0());
}
// InternalUrml.g:4825:1: ()
// InternalUrml.g:4827:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getStateMachineAction_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__0__Impl"
// $ANTLR start "rule__StateMachine__Group__1"
// InternalUrml.g:4837:1: rule__StateMachine__Group__1 : rule__StateMachine__Group__1__Impl rule__StateMachine__Group__2 ;
public final void rule__StateMachine__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4841:1: ( rule__StateMachine__Group__1__Impl rule__StateMachine__Group__2 )
// InternalUrml.g:4842:2: rule__StateMachine__Group__1__Impl rule__StateMachine__Group__2
{
pushFollow(FOLLOW_5);
rule__StateMachine__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StateMachine__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__1"
// $ANTLR start "rule__StateMachine__Group__1__Impl"
// InternalUrml.g:4849:1: rule__StateMachine__Group__1__Impl : ( 'stateMachine' ) ;
public final void rule__StateMachine__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4853:1: ( ( 'stateMachine' ) )
// InternalUrml.g:4854:1: ( 'stateMachine' )
{
// InternalUrml.g:4854:1: ( 'stateMachine' )
// InternalUrml.g:4855:1: 'stateMachine'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getStateMachineKeyword_1());
}
match(input,34,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getStateMachineKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__1__Impl"
// $ANTLR start "rule__StateMachine__Group__2"
// InternalUrml.g:4868:1: rule__StateMachine__Group__2 : rule__StateMachine__Group__2__Impl rule__StateMachine__Group__3 ;
public final void rule__StateMachine__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4872:1: ( rule__StateMachine__Group__2__Impl rule__StateMachine__Group__3 )
// InternalUrml.g:4873:2: rule__StateMachine__Group__2__Impl rule__StateMachine__Group__3
{
pushFollow(FOLLOW_31);
rule__StateMachine__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StateMachine__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__2"
// $ANTLR start "rule__StateMachine__Group__2__Impl"
// InternalUrml.g:4880:1: rule__StateMachine__Group__2__Impl : ( '{' ) ;
public final void rule__StateMachine__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4884:1: ( ( '{' ) )
// InternalUrml.g:4885:1: ( '{' )
{
// InternalUrml.g:4885:1: ( '{' )
// InternalUrml.g:4886:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__2__Impl"
// $ANTLR start "rule__StateMachine__Group__3"
// InternalUrml.g:4899:1: rule__StateMachine__Group__3 : rule__StateMachine__Group__3__Impl rule__StateMachine__Group__4 ;
public final void rule__StateMachine__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4903:1: ( rule__StateMachine__Group__3__Impl rule__StateMachine__Group__4 )
// InternalUrml.g:4904:2: rule__StateMachine__Group__3__Impl rule__StateMachine__Group__4
{
pushFollow(FOLLOW_31);
rule__StateMachine__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StateMachine__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__3"
// $ANTLR start "rule__StateMachine__Group__3__Impl"
// InternalUrml.g:4911:1: rule__StateMachine__Group__3__Impl : ( ( rule__StateMachine__Alternatives_3 )* ) ;
public final void rule__StateMachine__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4915:1: ( ( ( rule__StateMachine__Alternatives_3 )* ) )
// InternalUrml.g:4916:1: ( ( rule__StateMachine__Alternatives_3 )* )
{
// InternalUrml.g:4916:1: ( ( rule__StateMachine__Alternatives_3 )* )
// InternalUrml.g:4917:1: ( rule__StateMachine__Alternatives_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getAlternatives_3());
}
// InternalUrml.g:4918:1: ( rule__StateMachine__Alternatives_3 )*
loop39:
do {
int alt39=2;
int LA39_0 = input.LA(1);
if ( (LA39_0==35||LA39_0==39||LA39_0==80) ) {
alt39=1;
}
switch (alt39) {
case 1 :
// InternalUrml.g:4918:2: rule__StateMachine__Alternatives_3
{
pushFollow(FOLLOW_32);
rule__StateMachine__Alternatives_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop39;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getAlternatives_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__3__Impl"
// $ANTLR start "rule__StateMachine__Group__4"
// InternalUrml.g:4928:1: rule__StateMachine__Group__4 : rule__StateMachine__Group__4__Impl ;
public final void rule__StateMachine__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4932:1: ( rule__StateMachine__Group__4__Impl )
// InternalUrml.g:4933:2: rule__StateMachine__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__StateMachine__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__4"
// $ANTLR start "rule__StateMachine__Group__4__Impl"
// InternalUrml.g:4939:1: rule__StateMachine__Group__4__Impl : ( '}' ) ;
public final void rule__StateMachine__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4943:1: ( ( '}' ) )
// InternalUrml.g:4944:1: ( '}' )
{
// InternalUrml.g:4944:1: ( '}' )
// InternalUrml.g:4945:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__Group__4__Impl"
// $ANTLR start "rule__State___Group__0"
// InternalUrml.g:4968:1: rule__State___Group__0 : rule__State___Group__0__Impl rule__State___Group__1 ;
public final void rule__State___Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4972:1: ( rule__State___Group__0__Impl rule__State___Group__1 )
// InternalUrml.g:4973:2: rule__State___Group__0__Impl rule__State___Group__1
{
pushFollow(FOLLOW_33);
rule__State___Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__0"
// $ANTLR start "rule__State___Group__0__Impl"
// InternalUrml.g:4980:1: rule__State___Group__0__Impl : ( ( rule__State___FinalAssignment_0 )? ) ;
public final void rule__State___Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:4984:1: ( ( ( rule__State___FinalAssignment_0 )? ) )
// InternalUrml.g:4985:1: ( ( rule__State___FinalAssignment_0 )? )
{
// InternalUrml.g:4985:1: ( ( rule__State___FinalAssignment_0 )? )
// InternalUrml.g:4986:1: ( rule__State___FinalAssignment_0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getFinalAssignment_0());
}
// InternalUrml.g:4987:1: ( rule__State___FinalAssignment_0 )?
int alt40=2;
int LA40_0 = input.LA(1);
if ( (LA40_0==80) ) {
alt40=1;
}
switch (alt40) {
case 1 :
// InternalUrml.g:4987:2: rule__State___FinalAssignment_0
{
pushFollow(FOLLOW_2);
rule__State___FinalAssignment_0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getFinalAssignment_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__0__Impl"
// $ANTLR start "rule__State___Group__1"
// InternalUrml.g:4997:1: rule__State___Group__1 : rule__State___Group__1__Impl rule__State___Group__2 ;
public final void rule__State___Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5001:1: ( rule__State___Group__1__Impl rule__State___Group__2 )
// InternalUrml.g:5002:2: rule__State___Group__1__Impl rule__State___Group__2
{
pushFollow(FOLLOW_4);
rule__State___Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__1"
// $ANTLR start "rule__State___Group__1__Impl"
// InternalUrml.g:5009:1: rule__State___Group__1__Impl : ( 'state' ) ;
public final void rule__State___Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5013:1: ( ( 'state' ) )
// InternalUrml.g:5014:1: ( 'state' )
{
// InternalUrml.g:5014:1: ( 'state' )
// InternalUrml.g:5015:1: 'state'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getStateKeyword_1());
}
match(input,35,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getStateKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__1__Impl"
// $ANTLR start "rule__State___Group__2"
// InternalUrml.g:5028:1: rule__State___Group__2 : rule__State___Group__2__Impl rule__State___Group__3 ;
public final void rule__State___Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5032:1: ( rule__State___Group__2__Impl rule__State___Group__3 )
// InternalUrml.g:5033:2: rule__State___Group__2__Impl rule__State___Group__3
{
pushFollow(FOLLOW_5);
rule__State___Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__2"
// $ANTLR start "rule__State___Group__2__Impl"
// InternalUrml.g:5040:1: rule__State___Group__2__Impl : ( ( rule__State___NameAssignment_2 ) ) ;
public final void rule__State___Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5044:1: ( ( ( rule__State___NameAssignment_2 ) ) )
// InternalUrml.g:5045:1: ( ( rule__State___NameAssignment_2 ) )
{
// InternalUrml.g:5045:1: ( ( rule__State___NameAssignment_2 ) )
// InternalUrml.g:5046:1: ( rule__State___NameAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getNameAssignment_2());
}
// InternalUrml.g:5047:1: ( rule__State___NameAssignment_2 )
// InternalUrml.g:5047:2: rule__State___NameAssignment_2
{
pushFollow(FOLLOW_2);
rule__State___NameAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getNameAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__2__Impl"
// $ANTLR start "rule__State___Group__3"
// InternalUrml.g:5057:1: rule__State___Group__3 : rule__State___Group__3__Impl ;
public final void rule__State___Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5061:1: ( rule__State___Group__3__Impl )
// InternalUrml.g:5062:2: rule__State___Group__3__Impl
{
pushFollow(FOLLOW_2);
rule__State___Group__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__3"
// $ANTLR start "rule__State___Group__3__Impl"
// InternalUrml.g:5068:1: rule__State___Group__3__Impl : ( ( rule__State___Group_3__0 )? ) ;
public final void rule__State___Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5072:1: ( ( ( rule__State___Group_3__0 )? ) )
// InternalUrml.g:5073:1: ( ( rule__State___Group_3__0 )? )
{
// InternalUrml.g:5073:1: ( ( rule__State___Group_3__0 )? )
// InternalUrml.g:5074:1: ( rule__State___Group_3__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getGroup_3());
}
// InternalUrml.g:5075:1: ( rule__State___Group_3__0 )?
int alt41=2;
int LA41_0 = input.LA(1);
if ( (LA41_0==13) ) {
alt41=1;
}
switch (alt41) {
case 1 :
// InternalUrml.g:5075:2: rule__State___Group_3__0
{
pushFollow(FOLLOW_2);
rule__State___Group_3__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getGroup_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group__3__Impl"
// $ANTLR start "rule__State___Group_3__0"
// InternalUrml.g:5093:1: rule__State___Group_3__0 : rule__State___Group_3__0__Impl rule__State___Group_3__1 ;
public final void rule__State___Group_3__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5097:1: ( rule__State___Group_3__0__Impl rule__State___Group_3__1 )
// InternalUrml.g:5098:2: rule__State___Group_3__0__Impl rule__State___Group_3__1
{
pushFollow(FOLLOW_34);
rule__State___Group_3__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__0"
// $ANTLR start "rule__State___Group_3__0__Impl"
// InternalUrml.g:5105:1: rule__State___Group_3__0__Impl : ( '{' ) ;
public final void rule__State___Group_3__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5109:1: ( ( '{' ) )
// InternalUrml.g:5110:1: ( '{' )
{
// InternalUrml.g:5110:1: ( '{' )
// InternalUrml.g:5111:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getLeftCurlyBracketKeyword_3_0());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getLeftCurlyBracketKeyword_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__0__Impl"
// $ANTLR start "rule__State___Group_3__1"
// InternalUrml.g:5124:1: rule__State___Group_3__1 : rule__State___Group_3__1__Impl rule__State___Group_3__2 ;
public final void rule__State___Group_3__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5128:1: ( rule__State___Group_3__1__Impl rule__State___Group_3__2 )
// InternalUrml.g:5129:2: rule__State___Group_3__1__Impl rule__State___Group_3__2
{
pushFollow(FOLLOW_34);
rule__State___Group_3__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__1"
// $ANTLR start "rule__State___Group_3__1__Impl"
// InternalUrml.g:5136:1: rule__State___Group_3__1__Impl : ( ( rule__State___Group_3_1__0 )? ) ;
public final void rule__State___Group_3__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5140:1: ( ( ( rule__State___Group_3_1__0 )? ) )
// InternalUrml.g:5141:1: ( ( rule__State___Group_3_1__0 )? )
{
// InternalUrml.g:5141:1: ( ( rule__State___Group_3_1__0 )? )
// InternalUrml.g:5142:1: ( rule__State___Group_3_1__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getGroup_3_1());
}
// InternalUrml.g:5143:1: ( rule__State___Group_3_1__0 )?
int alt42=2;
int LA42_0 = input.LA(1);
if ( (LA42_0==36) ) {
alt42=1;
}
switch (alt42) {
case 1 :
// InternalUrml.g:5143:2: rule__State___Group_3_1__0
{
pushFollow(FOLLOW_2);
rule__State___Group_3_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getGroup_3_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__1__Impl"
// $ANTLR start "rule__State___Group_3__2"
// InternalUrml.g:5153:1: rule__State___Group_3__2 : rule__State___Group_3__2__Impl rule__State___Group_3__3 ;
public final void rule__State___Group_3__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5157:1: ( rule__State___Group_3__2__Impl rule__State___Group_3__3 )
// InternalUrml.g:5158:2: rule__State___Group_3__2__Impl rule__State___Group_3__3
{
pushFollow(FOLLOW_34);
rule__State___Group_3__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__2"
// $ANTLR start "rule__State___Group_3__2__Impl"
// InternalUrml.g:5165:1: rule__State___Group_3__2__Impl : ( ( rule__State___Group_3_2__0 )? ) ;
public final void rule__State___Group_3__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5169:1: ( ( ( rule__State___Group_3_2__0 )? ) )
// InternalUrml.g:5170:1: ( ( rule__State___Group_3_2__0 )? )
{
// InternalUrml.g:5170:1: ( ( rule__State___Group_3_2__0 )? )
// InternalUrml.g:5171:1: ( rule__State___Group_3_2__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getGroup_3_2());
}
// InternalUrml.g:5172:1: ( rule__State___Group_3_2__0 )?
int alt43=2;
int LA43_0 = input.LA(1);
if ( (LA43_0==37) ) {
alt43=1;
}
switch (alt43) {
case 1 :
// InternalUrml.g:5172:2: rule__State___Group_3_2__0
{
pushFollow(FOLLOW_2);
rule__State___Group_3_2__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getGroup_3_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__2__Impl"
// $ANTLR start "rule__State___Group_3__3"
// InternalUrml.g:5182:1: rule__State___Group_3__3 : rule__State___Group_3__3__Impl rule__State___Group_3__4 ;
public final void rule__State___Group_3__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5186:1: ( rule__State___Group_3__3__Impl rule__State___Group_3__4 )
// InternalUrml.g:5187:2: rule__State___Group_3__3__Impl rule__State___Group_3__4
{
pushFollow(FOLLOW_34);
rule__State___Group_3__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__3"
// $ANTLR start "rule__State___Group_3__3__Impl"
// InternalUrml.g:5194:1: rule__State___Group_3__3__Impl : ( ( rule__State___Group_3_3__0 )? ) ;
public final void rule__State___Group_3__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5198:1: ( ( ( rule__State___Group_3_3__0 )? ) )
// InternalUrml.g:5199:1: ( ( rule__State___Group_3_3__0 )? )
{
// InternalUrml.g:5199:1: ( ( rule__State___Group_3_3__0 )? )
// InternalUrml.g:5200:1: ( rule__State___Group_3_3__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getGroup_3_3());
}
// InternalUrml.g:5201:1: ( rule__State___Group_3_3__0 )?
int alt44=2;
int LA44_0 = input.LA(1);
if ( (LA44_0==38) ) {
alt44=1;
}
switch (alt44) {
case 1 :
// InternalUrml.g:5201:2: rule__State___Group_3_3__0
{
pushFollow(FOLLOW_2);
rule__State___Group_3_3__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getGroup_3_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__3__Impl"
// $ANTLR start "rule__State___Group_3__4"
// InternalUrml.g:5211:1: rule__State___Group_3__4 : rule__State___Group_3__4__Impl ;
public final void rule__State___Group_3__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5215:1: ( rule__State___Group_3__4__Impl )
// InternalUrml.g:5216:2: rule__State___Group_3__4__Impl
{
pushFollow(FOLLOW_2);
rule__State___Group_3__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__4"
// $ANTLR start "rule__State___Group_3__4__Impl"
// InternalUrml.g:5222:1: rule__State___Group_3__4__Impl : ( '}' ) ;
public final void rule__State___Group_3__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5226:1: ( ( '}' ) )
// InternalUrml.g:5227:1: ( '}' )
{
// InternalUrml.g:5227:1: ( '}' )
// InternalUrml.g:5228:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getRightCurlyBracketKeyword_3_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getRightCurlyBracketKeyword_3_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3__4__Impl"
// $ANTLR start "rule__State___Group_3_1__0"
// InternalUrml.g:5251:1: rule__State___Group_3_1__0 : rule__State___Group_3_1__0__Impl rule__State___Group_3_1__1 ;
public final void rule__State___Group_3_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5255:1: ( rule__State___Group_3_1__0__Impl rule__State___Group_3_1__1 )
// InternalUrml.g:5256:2: rule__State___Group_3_1__0__Impl rule__State___Group_3_1__1
{
pushFollow(FOLLOW_5);
rule__State___Group_3_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__0"
// $ANTLR start "rule__State___Group_3_1__0__Impl"
// InternalUrml.g:5263:1: rule__State___Group_3_1__0__Impl : ( 'entry' ) ;
public final void rule__State___Group_3_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5267:1: ( ( 'entry' ) )
// InternalUrml.g:5268:1: ( 'entry' )
{
// InternalUrml.g:5268:1: ( 'entry' )
// InternalUrml.g:5269:1: 'entry'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getEntryKeyword_3_1_0());
}
match(input,36,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getEntryKeyword_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__0__Impl"
// $ANTLR start "rule__State___Group_3_1__1"
// InternalUrml.g:5282:1: rule__State___Group_3_1__1 : rule__State___Group_3_1__1__Impl rule__State___Group_3_1__2 ;
public final void rule__State___Group_3_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5286:1: ( rule__State___Group_3_1__1__Impl rule__State___Group_3_1__2 )
// InternalUrml.g:5287:2: rule__State___Group_3_1__1__Impl rule__State___Group_3_1__2
{
pushFollow(FOLLOW_24);
rule__State___Group_3_1__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_1__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__1"
// $ANTLR start "rule__State___Group_3_1__1__Impl"
// InternalUrml.g:5294:1: rule__State___Group_3_1__1__Impl : ( '{' ) ;
public final void rule__State___Group_3_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5298:1: ( ( '{' ) )
// InternalUrml.g:5299:1: ( '{' )
{
// InternalUrml.g:5299:1: ( '{' )
// InternalUrml.g:5300:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getLeftCurlyBracketKeyword_3_1_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getLeftCurlyBracketKeyword_3_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__1__Impl"
// $ANTLR start "rule__State___Group_3_1__2"
// InternalUrml.g:5313:1: rule__State___Group_3_1__2 : rule__State___Group_3_1__2__Impl rule__State___Group_3_1__3 ;
public final void rule__State___Group_3_1__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5317:1: ( rule__State___Group_3_1__2__Impl rule__State___Group_3_1__3 )
// InternalUrml.g:5318:2: rule__State___Group_3_1__2__Impl rule__State___Group_3_1__3
{
pushFollow(FOLLOW_25);
rule__State___Group_3_1__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_1__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__2"
// $ANTLR start "rule__State___Group_3_1__2__Impl"
// InternalUrml.g:5325:1: rule__State___Group_3_1__2__Impl : ( ( rule__State___EntryCodeAssignment_3_1_2 ) ) ;
public final void rule__State___Group_3_1__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5329:1: ( ( ( rule__State___EntryCodeAssignment_3_1_2 ) ) )
// InternalUrml.g:5330:1: ( ( rule__State___EntryCodeAssignment_3_1_2 ) )
{
// InternalUrml.g:5330:1: ( ( rule__State___EntryCodeAssignment_3_1_2 ) )
// InternalUrml.g:5331:1: ( rule__State___EntryCodeAssignment_3_1_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getEntryCodeAssignment_3_1_2());
}
// InternalUrml.g:5332:1: ( rule__State___EntryCodeAssignment_3_1_2 )
// InternalUrml.g:5332:2: rule__State___EntryCodeAssignment_3_1_2
{
pushFollow(FOLLOW_2);
rule__State___EntryCodeAssignment_3_1_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getEntryCodeAssignment_3_1_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__2__Impl"
// $ANTLR start "rule__State___Group_3_1__3"
// InternalUrml.g:5342:1: rule__State___Group_3_1__3 : rule__State___Group_3_1__3__Impl ;
public final void rule__State___Group_3_1__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5346:1: ( rule__State___Group_3_1__3__Impl )
// InternalUrml.g:5347:2: rule__State___Group_3_1__3__Impl
{
pushFollow(FOLLOW_2);
rule__State___Group_3_1__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__3"
// $ANTLR start "rule__State___Group_3_1__3__Impl"
// InternalUrml.g:5353:1: rule__State___Group_3_1__3__Impl : ( '}' ) ;
public final void rule__State___Group_3_1__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5357:1: ( ( '}' ) )
// InternalUrml.g:5358:1: ( '}' )
{
// InternalUrml.g:5358:1: ( '}' )
// InternalUrml.g:5359:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getRightCurlyBracketKeyword_3_1_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getRightCurlyBracketKeyword_3_1_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_1__3__Impl"
// $ANTLR start "rule__State___Group_3_2__0"
// InternalUrml.g:5380:1: rule__State___Group_3_2__0 : rule__State___Group_3_2__0__Impl rule__State___Group_3_2__1 ;
public final void rule__State___Group_3_2__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5384:1: ( rule__State___Group_3_2__0__Impl rule__State___Group_3_2__1 )
// InternalUrml.g:5385:2: rule__State___Group_3_2__0__Impl rule__State___Group_3_2__1
{
pushFollow(FOLLOW_5);
rule__State___Group_3_2__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_2__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__0"
// $ANTLR start "rule__State___Group_3_2__0__Impl"
// InternalUrml.g:5392:1: rule__State___Group_3_2__0__Impl : ( 'exit' ) ;
public final void rule__State___Group_3_2__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5396:1: ( ( 'exit' ) )
// InternalUrml.g:5397:1: ( 'exit' )
{
// InternalUrml.g:5397:1: ( 'exit' )
// InternalUrml.g:5398:1: 'exit'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getExitKeyword_3_2_0());
}
match(input,37,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getExitKeyword_3_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__0__Impl"
// $ANTLR start "rule__State___Group_3_2__1"
// InternalUrml.g:5411:1: rule__State___Group_3_2__1 : rule__State___Group_3_2__1__Impl rule__State___Group_3_2__2 ;
public final void rule__State___Group_3_2__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5415:1: ( rule__State___Group_3_2__1__Impl rule__State___Group_3_2__2 )
// InternalUrml.g:5416:2: rule__State___Group_3_2__1__Impl rule__State___Group_3_2__2
{
pushFollow(FOLLOW_24);
rule__State___Group_3_2__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_2__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__1"
// $ANTLR start "rule__State___Group_3_2__1__Impl"
// InternalUrml.g:5423:1: rule__State___Group_3_2__1__Impl : ( '{' ) ;
public final void rule__State___Group_3_2__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5427:1: ( ( '{' ) )
// InternalUrml.g:5428:1: ( '{' )
{
// InternalUrml.g:5428:1: ( '{' )
// InternalUrml.g:5429:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getLeftCurlyBracketKeyword_3_2_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getLeftCurlyBracketKeyword_3_2_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__1__Impl"
// $ANTLR start "rule__State___Group_3_2__2"
// InternalUrml.g:5442:1: rule__State___Group_3_2__2 : rule__State___Group_3_2__2__Impl rule__State___Group_3_2__3 ;
public final void rule__State___Group_3_2__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5446:1: ( rule__State___Group_3_2__2__Impl rule__State___Group_3_2__3 )
// InternalUrml.g:5447:2: rule__State___Group_3_2__2__Impl rule__State___Group_3_2__3
{
pushFollow(FOLLOW_25);
rule__State___Group_3_2__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_2__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__2"
// $ANTLR start "rule__State___Group_3_2__2__Impl"
// InternalUrml.g:5454:1: rule__State___Group_3_2__2__Impl : ( ( rule__State___ExitCodeAssignment_3_2_2 ) ) ;
public final void rule__State___Group_3_2__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5458:1: ( ( ( rule__State___ExitCodeAssignment_3_2_2 ) ) )
// InternalUrml.g:5459:1: ( ( rule__State___ExitCodeAssignment_3_2_2 ) )
{
// InternalUrml.g:5459:1: ( ( rule__State___ExitCodeAssignment_3_2_2 ) )
// InternalUrml.g:5460:1: ( rule__State___ExitCodeAssignment_3_2_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getExitCodeAssignment_3_2_2());
}
// InternalUrml.g:5461:1: ( rule__State___ExitCodeAssignment_3_2_2 )
// InternalUrml.g:5461:2: rule__State___ExitCodeAssignment_3_2_2
{
pushFollow(FOLLOW_2);
rule__State___ExitCodeAssignment_3_2_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getExitCodeAssignment_3_2_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__2__Impl"
// $ANTLR start "rule__State___Group_3_2__3"
// InternalUrml.g:5471:1: rule__State___Group_3_2__3 : rule__State___Group_3_2__3__Impl ;
public final void rule__State___Group_3_2__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5475:1: ( rule__State___Group_3_2__3__Impl )
// InternalUrml.g:5476:2: rule__State___Group_3_2__3__Impl
{
pushFollow(FOLLOW_2);
rule__State___Group_3_2__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__3"
// $ANTLR start "rule__State___Group_3_2__3__Impl"
// InternalUrml.g:5482:1: rule__State___Group_3_2__3__Impl : ( '}' ) ;
public final void rule__State___Group_3_2__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5486:1: ( ( '}' ) )
// InternalUrml.g:5487:1: ( '}' )
{
// InternalUrml.g:5487:1: ( '}' )
// InternalUrml.g:5488:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getRightCurlyBracketKeyword_3_2_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getRightCurlyBracketKeyword_3_2_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_2__3__Impl"
// $ANTLR start "rule__State___Group_3_3__0"
// InternalUrml.g:5509:1: rule__State___Group_3_3__0 : rule__State___Group_3_3__0__Impl rule__State___Group_3_3__1 ;
public final void rule__State___Group_3_3__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5513:1: ( rule__State___Group_3_3__0__Impl rule__State___Group_3_3__1 )
// InternalUrml.g:5514:2: rule__State___Group_3_3__0__Impl rule__State___Group_3_3__1
{
pushFollow(FOLLOW_30);
rule__State___Group_3_3__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__State___Group_3_3__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_3__0"
// $ANTLR start "rule__State___Group_3_3__0__Impl"
// InternalUrml.g:5521:1: rule__State___Group_3_3__0__Impl : ( 'sub' ) ;
public final void rule__State___Group_3_3__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5525:1: ( ( 'sub' ) )
// InternalUrml.g:5526:1: ( 'sub' )
{
// InternalUrml.g:5526:1: ( 'sub' )
// InternalUrml.g:5527:1: 'sub'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getSubKeyword_3_3_0());
}
match(input,38,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getSubKeyword_3_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_3__0__Impl"
// $ANTLR start "rule__State___Group_3_3__1"
// InternalUrml.g:5540:1: rule__State___Group_3_3__1 : rule__State___Group_3_3__1__Impl ;
public final void rule__State___Group_3_3__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5544:1: ( rule__State___Group_3_3__1__Impl )
// InternalUrml.g:5545:2: rule__State___Group_3_3__1__Impl
{
pushFollow(FOLLOW_2);
rule__State___Group_3_3__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_3__1"
// $ANTLR start "rule__State___Group_3_3__1__Impl"
// InternalUrml.g:5551:1: rule__State___Group_3_3__1__Impl : ( ( rule__State___SubstatemachineAssignment_3_3_1 ) ) ;
public final void rule__State___Group_3_3__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5555:1: ( ( ( rule__State___SubstatemachineAssignment_3_3_1 ) ) )
// InternalUrml.g:5556:1: ( ( rule__State___SubstatemachineAssignment_3_3_1 ) )
{
// InternalUrml.g:5556:1: ( ( rule__State___SubstatemachineAssignment_3_3_1 ) )
// InternalUrml.g:5557:1: ( rule__State___SubstatemachineAssignment_3_3_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getSubstatemachineAssignment_3_3_1());
}
// InternalUrml.g:5558:1: ( rule__State___SubstatemachineAssignment_3_3_1 )
// InternalUrml.g:5558:2: rule__State___SubstatemachineAssignment_3_3_1
{
pushFollow(FOLLOW_2);
rule__State___SubstatemachineAssignment_3_3_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getSubstatemachineAssignment_3_3_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___Group_3_3__1__Impl"
// $ANTLR start "rule__Transition__Group__0"
// InternalUrml.g:5572:1: rule__Transition__Group__0 : rule__Transition__Group__0__Impl rule__Transition__Group__1 ;
public final void rule__Transition__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5576:1: ( rule__Transition__Group__0__Impl rule__Transition__Group__1 )
// InternalUrml.g:5577:2: rule__Transition__Group__0__Impl rule__Transition__Group__1
{
pushFollow(FOLLOW_35);
rule__Transition__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__0"
// $ANTLR start "rule__Transition__Group__0__Impl"
// InternalUrml.g:5584:1: rule__Transition__Group__0__Impl : ( 'transition' ) ;
public final void rule__Transition__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5588:1: ( ( 'transition' ) )
// InternalUrml.g:5589:1: ( 'transition' )
{
// InternalUrml.g:5589:1: ( 'transition' )
// InternalUrml.g:5590:1: 'transition'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTransitionKeyword_0());
}
match(input,39,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTransitionKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__0__Impl"
// $ANTLR start "rule__Transition__Group__1"
// InternalUrml.g:5603:1: rule__Transition__Group__1 : rule__Transition__Group__1__Impl rule__Transition__Group__2 ;
public final void rule__Transition__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5607:1: ( rule__Transition__Group__1__Impl rule__Transition__Group__2 )
// InternalUrml.g:5608:2: rule__Transition__Group__1__Impl rule__Transition__Group__2
{
pushFollow(FOLLOW_35);
rule__Transition__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__1"
// $ANTLR start "rule__Transition__Group__1__Impl"
// InternalUrml.g:5615:1: rule__Transition__Group__1__Impl : ( ( rule__Transition__NameAssignment_1 )? ) ;
public final void rule__Transition__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5619:1: ( ( ( rule__Transition__NameAssignment_1 )? ) )
// InternalUrml.g:5620:1: ( ( rule__Transition__NameAssignment_1 )? )
{
// InternalUrml.g:5620:1: ( ( rule__Transition__NameAssignment_1 )? )
// InternalUrml.g:5621:1: ( rule__Transition__NameAssignment_1 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getNameAssignment_1());
}
// InternalUrml.g:5622:1: ( rule__Transition__NameAssignment_1 )?
int alt45=2;
int LA45_0 = input.LA(1);
if ( (LA45_0==RULE_ID) ) {
alt45=1;
}
switch (alt45) {
case 1 :
// InternalUrml.g:5622:2: rule__Transition__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__Transition__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__1__Impl"
// $ANTLR start "rule__Transition__Group__2"
// InternalUrml.g:5632:1: rule__Transition__Group__2 : rule__Transition__Group__2__Impl rule__Transition__Group__3 ;
public final void rule__Transition__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5636:1: ( rule__Transition__Group__2__Impl rule__Transition__Group__3 )
// InternalUrml.g:5637:2: rule__Transition__Group__2__Impl rule__Transition__Group__3
{
pushFollow(FOLLOW_36);
rule__Transition__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__2"
// $ANTLR start "rule__Transition__Group__2__Impl"
// InternalUrml.g:5644:1: rule__Transition__Group__2__Impl : ( ':' ) ;
public final void rule__Transition__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5648:1: ( ( ':' ) )
// InternalUrml.g:5649:1: ( ':' )
{
// InternalUrml.g:5649:1: ( ':' )
// InternalUrml.g:5650:1: ':'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getColonKeyword_2());
}
match(input,29,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getColonKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__2__Impl"
// $ANTLR start "rule__Transition__Group__3"
// InternalUrml.g:5663:1: rule__Transition__Group__3 : rule__Transition__Group__3__Impl rule__Transition__Group__4 ;
public final void rule__Transition__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5667:1: ( rule__Transition__Group__3__Impl rule__Transition__Group__4 )
// InternalUrml.g:5668:2: rule__Transition__Group__3__Impl rule__Transition__Group__4
{
pushFollow(FOLLOW_37);
rule__Transition__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__3"
// $ANTLR start "rule__Transition__Group__3__Impl"
// InternalUrml.g:5675:1: rule__Transition__Group__3__Impl : ( ( rule__Transition__Alternatives_3 ) ) ;
public final void rule__Transition__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5679:1: ( ( ( rule__Transition__Alternatives_3 ) ) )
// InternalUrml.g:5680:1: ( ( rule__Transition__Alternatives_3 ) )
{
// InternalUrml.g:5680:1: ( ( rule__Transition__Alternatives_3 ) )
// InternalUrml.g:5681:1: ( rule__Transition__Alternatives_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getAlternatives_3());
}
// InternalUrml.g:5682:1: ( rule__Transition__Alternatives_3 )
// InternalUrml.g:5682:2: rule__Transition__Alternatives_3
{
pushFollow(FOLLOW_2);
rule__Transition__Alternatives_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getAlternatives_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__3__Impl"
// $ANTLR start "rule__Transition__Group__4"
// InternalUrml.g:5692:1: rule__Transition__Group__4 : rule__Transition__Group__4__Impl rule__Transition__Group__5 ;
public final void rule__Transition__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5696:1: ( rule__Transition__Group__4__Impl rule__Transition__Group__5 )
// InternalUrml.g:5697:2: rule__Transition__Group__4__Impl rule__Transition__Group__5
{
pushFollow(FOLLOW_4);
rule__Transition__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__4"
// $ANTLR start "rule__Transition__Group__4__Impl"
// InternalUrml.g:5704:1: rule__Transition__Group__4__Impl : ( '->' ) ;
public final void rule__Transition__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5708:1: ( ( '->' ) )
// InternalUrml.g:5709:1: ( '->' )
{
// InternalUrml.g:5709:1: ( '->' )
// InternalUrml.g:5710:1: '->'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getHyphenMinusGreaterThanSignKeyword_4());
}
match(input,40,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getHyphenMinusGreaterThanSignKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__4__Impl"
// $ANTLR start "rule__Transition__Group__5"
// InternalUrml.g:5723:1: rule__Transition__Group__5 : rule__Transition__Group__5__Impl rule__Transition__Group__6 ;
public final void rule__Transition__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5727:1: ( rule__Transition__Group__5__Impl rule__Transition__Group__6 )
// InternalUrml.g:5728:2: rule__Transition__Group__5__Impl rule__Transition__Group__6
{
pushFollow(FOLLOW_5);
rule__Transition__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__6();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__5"
// $ANTLR start "rule__Transition__Group__5__Impl"
// InternalUrml.g:5735:1: rule__Transition__Group__5__Impl : ( ( rule__Transition__ToAssignment_5 ) ) ;
public final void rule__Transition__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5739:1: ( ( ( rule__Transition__ToAssignment_5 ) ) )
// InternalUrml.g:5740:1: ( ( rule__Transition__ToAssignment_5 ) )
{
// InternalUrml.g:5740:1: ( ( rule__Transition__ToAssignment_5 ) )
// InternalUrml.g:5741:1: ( rule__Transition__ToAssignment_5 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getToAssignment_5());
}
// InternalUrml.g:5742:1: ( rule__Transition__ToAssignment_5 )
// InternalUrml.g:5742:2: rule__Transition__ToAssignment_5
{
pushFollow(FOLLOW_2);
rule__Transition__ToAssignment_5();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getToAssignment_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__5__Impl"
// $ANTLR start "rule__Transition__Group__6"
// InternalUrml.g:5752:1: rule__Transition__Group__6 : rule__Transition__Group__6__Impl rule__Transition__Group__7 ;
public final void rule__Transition__Group__6() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5756:1: ( rule__Transition__Group__6__Impl rule__Transition__Group__7 )
// InternalUrml.g:5757:2: rule__Transition__Group__6__Impl rule__Transition__Group__7
{
pushFollow(FOLLOW_38);
rule__Transition__Group__6__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__7();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__6"
// $ANTLR start "rule__Transition__Group__6__Impl"
// InternalUrml.g:5764:1: rule__Transition__Group__6__Impl : ( '{' ) ;
public final void rule__Transition__Group__6__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5768:1: ( ( '{' ) )
// InternalUrml.g:5769:1: ( '{' )
{
// InternalUrml.g:5769:1: ( '{' )
// InternalUrml.g:5770:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getLeftCurlyBracketKeyword_6());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getLeftCurlyBracketKeyword_6());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__6__Impl"
// $ANTLR start "rule__Transition__Group__7"
// InternalUrml.g:5783:1: rule__Transition__Group__7 : rule__Transition__Group__7__Impl rule__Transition__Group__8 ;
public final void rule__Transition__Group__7() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5787:1: ( rule__Transition__Group__7__Impl rule__Transition__Group__8 )
// InternalUrml.g:5788:2: rule__Transition__Group__7__Impl rule__Transition__Group__8
{
pushFollow(FOLLOW_38);
rule__Transition__Group__7__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__8();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__7"
// $ANTLR start "rule__Transition__Group__7__Impl"
// InternalUrml.g:5795:1: rule__Transition__Group__7__Impl : ( ( rule__Transition__Group_7__0 )? ) ;
public final void rule__Transition__Group__7__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5799:1: ( ( ( rule__Transition__Group_7__0 )? ) )
// InternalUrml.g:5800:1: ( ( rule__Transition__Group_7__0 )? )
{
// InternalUrml.g:5800:1: ( ( rule__Transition__Group_7__0 )? )
// InternalUrml.g:5801:1: ( rule__Transition__Group_7__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup_7());
}
// InternalUrml.g:5802:1: ( rule__Transition__Group_7__0 )?
int alt46=2;
int LA46_0 = input.LA(1);
if ( (LA46_0==41) ) {
alt46=1;
}
switch (alt46) {
case 1 :
// InternalUrml.g:5802:2: rule__Transition__Group_7__0
{
pushFollow(FOLLOW_2);
rule__Transition__Group_7__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup_7());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__7__Impl"
// $ANTLR start "rule__Transition__Group__8"
// InternalUrml.g:5812:1: rule__Transition__Group__8 : rule__Transition__Group__8__Impl rule__Transition__Group__9 ;
public final void rule__Transition__Group__8() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5816:1: ( rule__Transition__Group__8__Impl rule__Transition__Group__9 )
// InternalUrml.g:5817:2: rule__Transition__Group__8__Impl rule__Transition__Group__9
{
pushFollow(FOLLOW_38);
rule__Transition__Group__8__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__9();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__8"
// $ANTLR start "rule__Transition__Group__8__Impl"
// InternalUrml.g:5824:1: rule__Transition__Group__8__Impl : ( ( rule__Transition__Group_8__0 )? ) ;
public final void rule__Transition__Group__8__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5828:1: ( ( ( rule__Transition__Group_8__0 )? ) )
// InternalUrml.g:5829:1: ( ( rule__Transition__Group_8__0 )? )
{
// InternalUrml.g:5829:1: ( ( rule__Transition__Group_8__0 )? )
// InternalUrml.g:5830:1: ( rule__Transition__Group_8__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup_8());
}
// InternalUrml.g:5831:1: ( rule__Transition__Group_8__0 )?
int alt47=2;
int LA47_0 = input.LA(1);
if ( (LA47_0==42) ) {
alt47=1;
}
switch (alt47) {
case 1 :
// InternalUrml.g:5831:2: rule__Transition__Group_8__0
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup_8());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__8__Impl"
// $ANTLR start "rule__Transition__Group__9"
// InternalUrml.g:5841:1: rule__Transition__Group__9 : rule__Transition__Group__9__Impl rule__Transition__Group__10 ;
public final void rule__Transition__Group__9() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5845:1: ( rule__Transition__Group__9__Impl rule__Transition__Group__10 )
// InternalUrml.g:5846:2: rule__Transition__Group__9__Impl rule__Transition__Group__10
{
pushFollow(FOLLOW_38);
rule__Transition__Group__9__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group__10();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__9"
// $ANTLR start "rule__Transition__Group__9__Impl"
// InternalUrml.g:5853:1: rule__Transition__Group__9__Impl : ( ( rule__Transition__Group_9__0 )? ) ;
public final void rule__Transition__Group__9__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5857:1: ( ( ( rule__Transition__Group_9__0 )? ) )
// InternalUrml.g:5858:1: ( ( rule__Transition__Group_9__0 )? )
{
// InternalUrml.g:5858:1: ( ( rule__Transition__Group_9__0 )? )
// InternalUrml.g:5859:1: ( rule__Transition__Group_9__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup_9());
}
// InternalUrml.g:5860:1: ( rule__Transition__Group_9__0 )?
int alt48=2;
int LA48_0 = input.LA(1);
if ( (LA48_0==45) ) {
alt48=1;
}
switch (alt48) {
case 1 :
// InternalUrml.g:5860:2: rule__Transition__Group_9__0
{
pushFollow(FOLLOW_2);
rule__Transition__Group_9__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup_9());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__9__Impl"
// $ANTLR start "rule__Transition__Group__10"
// InternalUrml.g:5870:1: rule__Transition__Group__10 : rule__Transition__Group__10__Impl ;
public final void rule__Transition__Group__10() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5874:1: ( rule__Transition__Group__10__Impl )
// InternalUrml.g:5875:2: rule__Transition__Group__10__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group__10__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__10"
// $ANTLR start "rule__Transition__Group__10__Impl"
// InternalUrml.g:5881:1: rule__Transition__Group__10__Impl : ( '}' ) ;
public final void rule__Transition__Group__10__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5885:1: ( ( '}' ) )
// InternalUrml.g:5886:1: ( '}' )
{
// InternalUrml.g:5886:1: ( '}' )
// InternalUrml.g:5887:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getRightCurlyBracketKeyword_10());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getRightCurlyBracketKeyword_10());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group__10__Impl"
// $ANTLR start "rule__Transition__Group_7__0"
// InternalUrml.g:5922:1: rule__Transition__Group_7__0 : rule__Transition__Group_7__0__Impl rule__Transition__Group_7__1 ;
public final void rule__Transition__Group_7__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5926:1: ( rule__Transition__Group_7__0__Impl rule__Transition__Group_7__1 )
// InternalUrml.g:5927:2: rule__Transition__Group_7__0__Impl rule__Transition__Group_7__1
{
pushFollow(FOLLOW_5);
rule__Transition__Group_7__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_7__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__0"
// $ANTLR start "rule__Transition__Group_7__0__Impl"
// InternalUrml.g:5934:1: rule__Transition__Group_7__0__Impl : ( 'guard' ) ;
public final void rule__Transition__Group_7__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5938:1: ( ( 'guard' ) )
// InternalUrml.g:5939:1: ( 'guard' )
{
// InternalUrml.g:5939:1: ( 'guard' )
// InternalUrml.g:5940:1: 'guard'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGuardKeyword_7_0());
}
match(input,41,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGuardKeyword_7_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__0__Impl"
// $ANTLR start "rule__Transition__Group_7__1"
// InternalUrml.g:5953:1: rule__Transition__Group_7__1 : rule__Transition__Group_7__1__Impl rule__Transition__Group_7__2 ;
public final void rule__Transition__Group_7__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5957:1: ( rule__Transition__Group_7__1__Impl rule__Transition__Group_7__2 )
// InternalUrml.g:5958:2: rule__Transition__Group_7__1__Impl rule__Transition__Group_7__2
{
pushFollow(FOLLOW_10);
rule__Transition__Group_7__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_7__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__1"
// $ANTLR start "rule__Transition__Group_7__1__Impl"
// InternalUrml.g:5965:1: rule__Transition__Group_7__1__Impl : ( '{' ) ;
public final void rule__Transition__Group_7__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5969:1: ( ( '{' ) )
// InternalUrml.g:5970:1: ( '{' )
{
// InternalUrml.g:5970:1: ( '{' )
// InternalUrml.g:5971:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getLeftCurlyBracketKeyword_7_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getLeftCurlyBracketKeyword_7_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__1__Impl"
// $ANTLR start "rule__Transition__Group_7__2"
// InternalUrml.g:5984:1: rule__Transition__Group_7__2 : rule__Transition__Group_7__2__Impl rule__Transition__Group_7__3 ;
public final void rule__Transition__Group_7__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:5988:1: ( rule__Transition__Group_7__2__Impl rule__Transition__Group_7__3 )
// InternalUrml.g:5989:2: rule__Transition__Group_7__2__Impl rule__Transition__Group_7__3
{
pushFollow(FOLLOW_25);
rule__Transition__Group_7__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_7__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__2"
// $ANTLR start "rule__Transition__Group_7__2__Impl"
// InternalUrml.g:5996:1: rule__Transition__Group_7__2__Impl : ( ( rule__Transition__GuardAssignment_7_2 ) ) ;
public final void rule__Transition__Group_7__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6000:1: ( ( ( rule__Transition__GuardAssignment_7_2 ) ) )
// InternalUrml.g:6001:1: ( ( rule__Transition__GuardAssignment_7_2 ) )
{
// InternalUrml.g:6001:1: ( ( rule__Transition__GuardAssignment_7_2 ) )
// InternalUrml.g:6002:1: ( rule__Transition__GuardAssignment_7_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGuardAssignment_7_2());
}
// InternalUrml.g:6003:1: ( rule__Transition__GuardAssignment_7_2 )
// InternalUrml.g:6003:2: rule__Transition__GuardAssignment_7_2
{
pushFollow(FOLLOW_2);
rule__Transition__GuardAssignment_7_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGuardAssignment_7_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__2__Impl"
// $ANTLR start "rule__Transition__Group_7__3"
// InternalUrml.g:6013:1: rule__Transition__Group_7__3 : rule__Transition__Group_7__3__Impl ;
public final void rule__Transition__Group_7__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6017:1: ( rule__Transition__Group_7__3__Impl )
// InternalUrml.g:6018:2: rule__Transition__Group_7__3__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group_7__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__3"
// $ANTLR start "rule__Transition__Group_7__3__Impl"
// InternalUrml.g:6024:1: rule__Transition__Group_7__3__Impl : ( '}' ) ;
public final void rule__Transition__Group_7__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6028:1: ( ( '}' ) )
// InternalUrml.g:6029:1: ( '}' )
{
// InternalUrml.g:6029:1: ( '}' )
// InternalUrml.g:6030:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getRightCurlyBracketKeyword_7_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getRightCurlyBracketKeyword_7_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_7__3__Impl"
// $ANTLR start "rule__Transition__Group_8__0"
// InternalUrml.g:6051:1: rule__Transition__Group_8__0 : rule__Transition__Group_8__0__Impl rule__Transition__Group_8__1 ;
public final void rule__Transition__Group_8__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6055:1: ( rule__Transition__Group_8__0__Impl rule__Transition__Group_8__1 )
// InternalUrml.g:6056:2: rule__Transition__Group_8__0__Impl rule__Transition__Group_8__1
{
pushFollow(FOLLOW_39);
rule__Transition__Group_8__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_8__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8__0"
// $ANTLR start "rule__Transition__Group_8__0__Impl"
// InternalUrml.g:6063:1: rule__Transition__Group_8__0__Impl : ( 'triggeredBy' ) ;
public final void rule__Transition__Group_8__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6067:1: ( ( 'triggeredBy' ) )
// InternalUrml.g:6068:1: ( 'triggeredBy' )
{
// InternalUrml.g:6068:1: ( 'triggeredBy' )
// InternalUrml.g:6069:1: 'triggeredBy'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTriggeredByKeyword_8_0());
}
match(input,42,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTriggeredByKeyword_8_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8__0__Impl"
// $ANTLR start "rule__Transition__Group_8__1"
// InternalUrml.g:6082:1: rule__Transition__Group_8__1 : rule__Transition__Group_8__1__Impl ;
public final void rule__Transition__Group_8__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6086:1: ( rule__Transition__Group_8__1__Impl )
// InternalUrml.g:6087:2: rule__Transition__Group_8__1__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8__1"
// $ANTLR start "rule__Transition__Group_8__1__Impl"
// InternalUrml.g:6093:1: rule__Transition__Group_8__1__Impl : ( ( rule__Transition__Alternatives_8_1 ) ) ;
public final void rule__Transition__Group_8__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6097:1: ( ( ( rule__Transition__Alternatives_8_1 ) ) )
// InternalUrml.g:6098:1: ( ( rule__Transition__Alternatives_8_1 ) )
{
// InternalUrml.g:6098:1: ( ( rule__Transition__Alternatives_8_1 ) )
// InternalUrml.g:6099:1: ( rule__Transition__Alternatives_8_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getAlternatives_8_1());
}
// InternalUrml.g:6100:1: ( rule__Transition__Alternatives_8_1 )
// InternalUrml.g:6100:2: rule__Transition__Alternatives_8_1
{
pushFollow(FOLLOW_2);
rule__Transition__Alternatives_8_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getAlternatives_8_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8__1__Impl"
// $ANTLR start "rule__Transition__Group_8_1_0__0"
// InternalUrml.g:6114:1: rule__Transition__Group_8_1_0__0 : rule__Transition__Group_8_1_0__0__Impl rule__Transition__Group_8_1_0__1 ;
public final void rule__Transition__Group_8_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6118:1: ( rule__Transition__Group_8_1_0__0__Impl rule__Transition__Group_8_1_0__1 )
// InternalUrml.g:6119:2: rule__Transition__Group_8_1_0__0__Impl rule__Transition__Group_8_1_0__1
{
pushFollow(FOLLOW_40);
rule__Transition__Group_8_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0__0"
// $ANTLR start "rule__Transition__Group_8_1_0__0__Impl"
// InternalUrml.g:6126:1: rule__Transition__Group_8_1_0__0__Impl : ( ( rule__Transition__TriggersAssignment_8_1_0_0 ) ) ;
public final void rule__Transition__Group_8_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6130:1: ( ( ( rule__Transition__TriggersAssignment_8_1_0_0 ) ) )
// InternalUrml.g:6131:1: ( ( rule__Transition__TriggersAssignment_8_1_0_0 ) )
{
// InternalUrml.g:6131:1: ( ( rule__Transition__TriggersAssignment_8_1_0_0 ) )
// InternalUrml.g:6132:1: ( rule__Transition__TriggersAssignment_8_1_0_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTriggersAssignment_8_1_0_0());
}
// InternalUrml.g:6133:1: ( rule__Transition__TriggersAssignment_8_1_0_0 )
// InternalUrml.g:6133:2: rule__Transition__TriggersAssignment_8_1_0_0
{
pushFollow(FOLLOW_2);
rule__Transition__TriggersAssignment_8_1_0_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTriggersAssignment_8_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0__0__Impl"
// $ANTLR start "rule__Transition__Group_8_1_0__1"
// InternalUrml.g:6143:1: rule__Transition__Group_8_1_0__1 : rule__Transition__Group_8_1_0__1__Impl ;
public final void rule__Transition__Group_8_1_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6147:1: ( rule__Transition__Group_8_1_0__1__Impl )
// InternalUrml.g:6148:2: rule__Transition__Group_8_1_0__1__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_0__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0__1"
// $ANTLR start "rule__Transition__Group_8_1_0__1__Impl"
// InternalUrml.g:6154:1: rule__Transition__Group_8_1_0__1__Impl : ( ( rule__Transition__Group_8_1_0_1__0 )* ) ;
public final void rule__Transition__Group_8_1_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6158:1: ( ( ( rule__Transition__Group_8_1_0_1__0 )* ) )
// InternalUrml.g:6159:1: ( ( rule__Transition__Group_8_1_0_1__0 )* )
{
// InternalUrml.g:6159:1: ( ( rule__Transition__Group_8_1_0_1__0 )* )
// InternalUrml.g:6160:1: ( rule__Transition__Group_8_1_0_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGroup_8_1_0_1());
}
// InternalUrml.g:6161:1: ( rule__Transition__Group_8_1_0_1__0 )*
loop49:
do {
int alt49=2;
int LA49_0 = input.LA(1);
if ( (LA49_0==43) ) {
alt49=1;
}
switch (alt49) {
case 1 :
// InternalUrml.g:6161:2: rule__Transition__Group_8_1_0_1__0
{
pushFollow(FOLLOW_41);
rule__Transition__Group_8_1_0_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop49;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGroup_8_1_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0__1__Impl"
// $ANTLR start "rule__Transition__Group_8_1_0_1__0"
// InternalUrml.g:6175:1: rule__Transition__Group_8_1_0_1__0 : rule__Transition__Group_8_1_0_1__0__Impl rule__Transition__Group_8_1_0_1__1 ;
public final void rule__Transition__Group_8_1_0_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6179:1: ( rule__Transition__Group_8_1_0_1__0__Impl rule__Transition__Group_8_1_0_1__1 )
// InternalUrml.g:6180:2: rule__Transition__Group_8_1_0_1__0__Impl rule__Transition__Group_8_1_0_1__1
{
pushFollow(FOLLOW_4);
rule__Transition__Group_8_1_0_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_0_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0_1__0"
// $ANTLR start "rule__Transition__Group_8_1_0_1__0__Impl"
// InternalUrml.g:6187:1: rule__Transition__Group_8_1_0_1__0__Impl : ( 'or' ) ;
public final void rule__Transition__Group_8_1_0_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6191:1: ( ( 'or' ) )
// InternalUrml.g:6192:1: ( 'or' )
{
// InternalUrml.g:6192:1: ( 'or' )
// InternalUrml.g:6193:1: 'or'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getOrKeyword_8_1_0_1_0());
}
match(input,43,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getOrKeyword_8_1_0_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0_1__0__Impl"
// $ANTLR start "rule__Transition__Group_8_1_0_1__1"
// InternalUrml.g:6206:1: rule__Transition__Group_8_1_0_1__1 : rule__Transition__Group_8_1_0_1__1__Impl ;
public final void rule__Transition__Group_8_1_0_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6210:1: ( rule__Transition__Group_8_1_0_1__1__Impl )
// InternalUrml.g:6211:2: rule__Transition__Group_8_1_0_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_0_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0_1__1"
// $ANTLR start "rule__Transition__Group_8_1_0_1__1__Impl"
// InternalUrml.g:6217:1: rule__Transition__Group_8_1_0_1__1__Impl : ( ( rule__Transition__TriggersAssignment_8_1_0_1_1 ) ) ;
public final void rule__Transition__Group_8_1_0_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6221:1: ( ( ( rule__Transition__TriggersAssignment_8_1_0_1_1 ) ) )
// InternalUrml.g:6222:1: ( ( rule__Transition__TriggersAssignment_8_1_0_1_1 ) )
{
// InternalUrml.g:6222:1: ( ( rule__Transition__TriggersAssignment_8_1_0_1_1 ) )
// InternalUrml.g:6223:1: ( rule__Transition__TriggersAssignment_8_1_0_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTriggersAssignment_8_1_0_1_1());
}
// InternalUrml.g:6224:1: ( rule__Transition__TriggersAssignment_8_1_0_1_1 )
// InternalUrml.g:6224:2: rule__Transition__TriggersAssignment_8_1_0_1_1
{
pushFollow(FOLLOW_2);
rule__Transition__TriggersAssignment_8_1_0_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTriggersAssignment_8_1_0_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_0_1__1__Impl"
// $ANTLR start "rule__Transition__Group_8_1_1__0"
// InternalUrml.g:6238:1: rule__Transition__Group_8_1_1__0 : rule__Transition__Group_8_1_1__0__Impl rule__Transition__Group_8_1_1__1 ;
public final void rule__Transition__Group_8_1_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6242:1: ( rule__Transition__Group_8_1_1__0__Impl rule__Transition__Group_8_1_1__1 )
// InternalUrml.g:6243:2: rule__Transition__Group_8_1_1__0__Impl rule__Transition__Group_8_1_1__1
{
pushFollow(FOLLOW_4);
rule__Transition__Group_8_1_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_1__0"
// $ANTLR start "rule__Transition__Group_8_1_1__0__Impl"
// InternalUrml.g:6250:1: rule__Transition__Group_8_1_1__0__Impl : ( 'timeout' ) ;
public final void rule__Transition__Group_8_1_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6254:1: ( ( 'timeout' ) )
// InternalUrml.g:6255:1: ( 'timeout' )
{
// InternalUrml.g:6255:1: ( 'timeout' )
// InternalUrml.g:6256:1: 'timeout'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTimeoutKeyword_8_1_1_0());
}
match(input,44,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTimeoutKeyword_8_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_1__0__Impl"
// $ANTLR start "rule__Transition__Group_8_1_1__1"
// InternalUrml.g:6269:1: rule__Transition__Group_8_1_1__1 : rule__Transition__Group_8_1_1__1__Impl ;
public final void rule__Transition__Group_8_1_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6273:1: ( rule__Transition__Group_8_1_1__1__Impl )
// InternalUrml.g:6274:2: rule__Transition__Group_8_1_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group_8_1_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_1__1"
// $ANTLR start "rule__Transition__Group_8_1_1__1__Impl"
// InternalUrml.g:6280:1: rule__Transition__Group_8_1_1__1__Impl : ( ( rule__Transition__TimerPortAssignment_8_1_1_1 ) ) ;
public final void rule__Transition__Group_8_1_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6284:1: ( ( ( rule__Transition__TimerPortAssignment_8_1_1_1 ) ) )
// InternalUrml.g:6285:1: ( ( rule__Transition__TimerPortAssignment_8_1_1_1 ) )
{
// InternalUrml.g:6285:1: ( ( rule__Transition__TimerPortAssignment_8_1_1_1 ) )
// InternalUrml.g:6286:1: ( rule__Transition__TimerPortAssignment_8_1_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTimerPortAssignment_8_1_1_1());
}
// InternalUrml.g:6287:1: ( rule__Transition__TimerPortAssignment_8_1_1_1 )
// InternalUrml.g:6287:2: rule__Transition__TimerPortAssignment_8_1_1_1
{
pushFollow(FOLLOW_2);
rule__Transition__TimerPortAssignment_8_1_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTimerPortAssignment_8_1_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_8_1_1__1__Impl"
// $ANTLR start "rule__Transition__Group_9__0"
// InternalUrml.g:6301:1: rule__Transition__Group_9__0 : rule__Transition__Group_9__0__Impl rule__Transition__Group_9__1 ;
public final void rule__Transition__Group_9__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6305:1: ( rule__Transition__Group_9__0__Impl rule__Transition__Group_9__1 )
// InternalUrml.g:6306:2: rule__Transition__Group_9__0__Impl rule__Transition__Group_9__1
{
pushFollow(FOLLOW_5);
rule__Transition__Group_9__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_9__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__0"
// $ANTLR start "rule__Transition__Group_9__0__Impl"
// InternalUrml.g:6313:1: rule__Transition__Group_9__0__Impl : ( 'action' ) ;
public final void rule__Transition__Group_9__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6317:1: ( ( 'action' ) )
// InternalUrml.g:6318:1: ( 'action' )
{
// InternalUrml.g:6318:1: ( 'action' )
// InternalUrml.g:6319:1: 'action'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getActionKeyword_9_0());
}
match(input,45,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getActionKeyword_9_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__0__Impl"
// $ANTLR start "rule__Transition__Group_9__1"
// InternalUrml.g:6332:1: rule__Transition__Group_9__1 : rule__Transition__Group_9__1__Impl rule__Transition__Group_9__2 ;
public final void rule__Transition__Group_9__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6336:1: ( rule__Transition__Group_9__1__Impl rule__Transition__Group_9__2 )
// InternalUrml.g:6337:2: rule__Transition__Group_9__1__Impl rule__Transition__Group_9__2
{
pushFollow(FOLLOW_24);
rule__Transition__Group_9__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_9__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__1"
// $ANTLR start "rule__Transition__Group_9__1__Impl"
// InternalUrml.g:6344:1: rule__Transition__Group_9__1__Impl : ( '{' ) ;
public final void rule__Transition__Group_9__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6348:1: ( ( '{' ) )
// InternalUrml.g:6349:1: ( '{' )
{
// InternalUrml.g:6349:1: ( '{' )
// InternalUrml.g:6350:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getLeftCurlyBracketKeyword_9_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getLeftCurlyBracketKeyword_9_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__1__Impl"
// $ANTLR start "rule__Transition__Group_9__2"
// InternalUrml.g:6363:1: rule__Transition__Group_9__2 : rule__Transition__Group_9__2__Impl rule__Transition__Group_9__3 ;
public final void rule__Transition__Group_9__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6367:1: ( rule__Transition__Group_9__2__Impl rule__Transition__Group_9__3 )
// InternalUrml.g:6368:2: rule__Transition__Group_9__2__Impl rule__Transition__Group_9__3
{
pushFollow(FOLLOW_25);
rule__Transition__Group_9__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Transition__Group_9__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__2"
// $ANTLR start "rule__Transition__Group_9__2__Impl"
// InternalUrml.g:6375:1: rule__Transition__Group_9__2__Impl : ( ( rule__Transition__ActionAssignment_9_2 ) ) ;
public final void rule__Transition__Group_9__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6379:1: ( ( ( rule__Transition__ActionAssignment_9_2 ) ) )
// InternalUrml.g:6380:1: ( ( rule__Transition__ActionAssignment_9_2 ) )
{
// InternalUrml.g:6380:1: ( ( rule__Transition__ActionAssignment_9_2 ) )
// InternalUrml.g:6381:1: ( rule__Transition__ActionAssignment_9_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getActionAssignment_9_2());
}
// InternalUrml.g:6382:1: ( rule__Transition__ActionAssignment_9_2 )
// InternalUrml.g:6382:2: rule__Transition__ActionAssignment_9_2
{
pushFollow(FOLLOW_2);
rule__Transition__ActionAssignment_9_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getActionAssignment_9_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__2__Impl"
// $ANTLR start "rule__Transition__Group_9__3"
// InternalUrml.g:6392:1: rule__Transition__Group_9__3 : rule__Transition__Group_9__3__Impl ;
public final void rule__Transition__Group_9__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6396:1: ( rule__Transition__Group_9__3__Impl )
// InternalUrml.g:6397:2: rule__Transition__Group_9__3__Impl
{
pushFollow(FOLLOW_2);
rule__Transition__Group_9__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__3"
// $ANTLR start "rule__Transition__Group_9__3__Impl"
// InternalUrml.g:6403:1: rule__Transition__Group_9__3__Impl : ( '}' ) ;
public final void rule__Transition__Group_9__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6407:1: ( ( '}' ) )
// InternalUrml.g:6408:1: ( '}' )
{
// InternalUrml.g:6408:1: ( '}' )
// InternalUrml.g:6409:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getRightCurlyBracketKeyword_9_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getRightCurlyBracketKeyword_9_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__Group_9__3__Impl"
// $ANTLR start "rule__Trigger_in__Group__0"
// InternalUrml.g:6430:1: rule__Trigger_in__Group__0 : rule__Trigger_in__Group__0__Impl rule__Trigger_in__Group__1 ;
public final void rule__Trigger_in__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6434:1: ( rule__Trigger_in__Group__0__Impl rule__Trigger_in__Group__1 )
// InternalUrml.g:6435:2: rule__Trigger_in__Group__0__Impl rule__Trigger_in__Group__1
{
pushFollow(FOLLOW_29);
rule__Trigger_in__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__0"
// $ANTLR start "rule__Trigger_in__Group__0__Impl"
// InternalUrml.g:6442:1: rule__Trigger_in__Group__0__Impl : ( ( rule__Trigger_in__FromAssignment_0 ) ) ;
public final void rule__Trigger_in__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6446:1: ( ( ( rule__Trigger_in__FromAssignment_0 ) ) )
// InternalUrml.g:6447:1: ( ( rule__Trigger_in__FromAssignment_0 ) )
{
// InternalUrml.g:6447:1: ( ( rule__Trigger_in__FromAssignment_0 ) )
// InternalUrml.g:6448:1: ( rule__Trigger_in__FromAssignment_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getFromAssignment_0());
}
// InternalUrml.g:6449:1: ( rule__Trigger_in__FromAssignment_0 )
// InternalUrml.g:6449:2: rule__Trigger_in__FromAssignment_0
{
pushFollow(FOLLOW_2);
rule__Trigger_in__FromAssignment_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getFromAssignment_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__0__Impl"
// $ANTLR start "rule__Trigger_in__Group__1"
// InternalUrml.g:6459:1: rule__Trigger_in__Group__1 : rule__Trigger_in__Group__1__Impl rule__Trigger_in__Group__2 ;
public final void rule__Trigger_in__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6463:1: ( rule__Trigger_in__Group__1__Impl rule__Trigger_in__Group__2 )
// InternalUrml.g:6464:2: rule__Trigger_in__Group__1__Impl rule__Trigger_in__Group__2
{
pushFollow(FOLLOW_4);
rule__Trigger_in__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__1"
// $ANTLR start "rule__Trigger_in__Group__1__Impl"
// InternalUrml.g:6471:1: rule__Trigger_in__Group__1__Impl : ( '.' ) ;
public final void rule__Trigger_in__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6475:1: ( ( '.' ) )
// InternalUrml.g:6476:1: ( '.' )
{
// InternalUrml.g:6476:1: ( '.' )
// InternalUrml.g:6477:1: '.'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getFullStopKeyword_1());
}
match(input,32,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getFullStopKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__1__Impl"
// $ANTLR start "rule__Trigger_in__Group__2"
// InternalUrml.g:6490:1: rule__Trigger_in__Group__2 : rule__Trigger_in__Group__2__Impl rule__Trigger_in__Group__3 ;
public final void rule__Trigger_in__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6494:1: ( rule__Trigger_in__Group__2__Impl rule__Trigger_in__Group__3 )
// InternalUrml.g:6495:2: rule__Trigger_in__Group__2__Impl rule__Trigger_in__Group__3
{
pushFollow(FOLLOW_15);
rule__Trigger_in__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__2"
// $ANTLR start "rule__Trigger_in__Group__2__Impl"
// InternalUrml.g:6502:1: rule__Trigger_in__Group__2__Impl : ( ( rule__Trigger_in__SignalAssignment_2 ) ) ;
public final void rule__Trigger_in__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6506:1: ( ( ( rule__Trigger_in__SignalAssignment_2 ) ) )
// InternalUrml.g:6507:1: ( ( rule__Trigger_in__SignalAssignment_2 ) )
{
// InternalUrml.g:6507:1: ( ( rule__Trigger_in__SignalAssignment_2 ) )
// InternalUrml.g:6508:1: ( rule__Trigger_in__SignalAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getSignalAssignment_2());
}
// InternalUrml.g:6509:1: ( rule__Trigger_in__SignalAssignment_2 )
// InternalUrml.g:6509:2: rule__Trigger_in__SignalAssignment_2
{
pushFollow(FOLLOW_2);
rule__Trigger_in__SignalAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getSignalAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__2__Impl"
// $ANTLR start "rule__Trigger_in__Group__3"
// InternalUrml.g:6519:1: rule__Trigger_in__Group__3 : rule__Trigger_in__Group__3__Impl rule__Trigger_in__Group__4 ;
public final void rule__Trigger_in__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6523:1: ( rule__Trigger_in__Group__3__Impl rule__Trigger_in__Group__4 )
// InternalUrml.g:6524:2: rule__Trigger_in__Group__3__Impl rule__Trigger_in__Group__4
{
pushFollow(FOLLOW_16);
rule__Trigger_in__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__3"
// $ANTLR start "rule__Trigger_in__Group__3__Impl"
// InternalUrml.g:6531:1: rule__Trigger_in__Group__3__Impl : ( '(' ) ;
public final void rule__Trigger_in__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6535:1: ( ( '(' ) )
// InternalUrml.g:6536:1: ( '(' )
{
// InternalUrml.g:6536:1: ( '(' )
// InternalUrml.g:6537:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getLeftParenthesisKeyword_3());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getLeftParenthesisKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__3__Impl"
// $ANTLR start "rule__Trigger_in__Group__4"
// InternalUrml.g:6550:1: rule__Trigger_in__Group__4 : rule__Trigger_in__Group__4__Impl rule__Trigger_in__Group__5 ;
public final void rule__Trigger_in__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6554:1: ( rule__Trigger_in__Group__4__Impl rule__Trigger_in__Group__5 )
// InternalUrml.g:6555:2: rule__Trigger_in__Group__4__Impl rule__Trigger_in__Group__5
{
pushFollow(FOLLOW_16);
rule__Trigger_in__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__4"
// $ANTLR start "rule__Trigger_in__Group__4__Impl"
// InternalUrml.g:6562:1: rule__Trigger_in__Group__4__Impl : ( ( rule__Trigger_in__Group_4__0 )? ) ;
public final void rule__Trigger_in__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6566:1: ( ( ( rule__Trigger_in__Group_4__0 )? ) )
// InternalUrml.g:6567:1: ( ( rule__Trigger_in__Group_4__0 )? )
{
// InternalUrml.g:6567:1: ( ( rule__Trigger_in__Group_4__0 )? )
// InternalUrml.g:6568:1: ( rule__Trigger_in__Group_4__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getGroup_4());
}
// InternalUrml.g:6569:1: ( rule__Trigger_in__Group_4__0 )?
int alt50=2;
int LA50_0 = input.LA(1);
if ( ((LA50_0>=75 && LA50_0<=76)) ) {
alt50=1;
}
switch (alt50) {
case 1 :
// InternalUrml.g:6569:2: rule__Trigger_in__Group_4__0
{
pushFollow(FOLLOW_2);
rule__Trigger_in__Group_4__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getGroup_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__4__Impl"
// $ANTLR start "rule__Trigger_in__Group__5"
// InternalUrml.g:6579:1: rule__Trigger_in__Group__5 : rule__Trigger_in__Group__5__Impl ;
public final void rule__Trigger_in__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6583:1: ( rule__Trigger_in__Group__5__Impl )
// InternalUrml.g:6584:2: rule__Trigger_in__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__Trigger_in__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__5"
// $ANTLR start "rule__Trigger_in__Group__5__Impl"
// InternalUrml.g:6590:1: rule__Trigger_in__Group__5__Impl : ( ')' ) ;
public final void rule__Trigger_in__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6594:1: ( ( ')' ) )
// InternalUrml.g:6595:1: ( ')' )
{
// InternalUrml.g:6595:1: ( ')' )
// InternalUrml.g:6596:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getRightParenthesisKeyword_5());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getRightParenthesisKeyword_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group__5__Impl"
// $ANTLR start "rule__Trigger_in__Group_4__0"
// InternalUrml.g:6621:1: rule__Trigger_in__Group_4__0 : rule__Trigger_in__Group_4__0__Impl rule__Trigger_in__Group_4__1 ;
public final void rule__Trigger_in__Group_4__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6625:1: ( rule__Trigger_in__Group_4__0__Impl rule__Trigger_in__Group_4__1 )
// InternalUrml.g:6626:2: rule__Trigger_in__Group_4__0__Impl rule__Trigger_in__Group_4__1
{
pushFollow(FOLLOW_17);
rule__Trigger_in__Group_4__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group_4__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4__0"
// $ANTLR start "rule__Trigger_in__Group_4__0__Impl"
// InternalUrml.g:6633:1: rule__Trigger_in__Group_4__0__Impl : ( ( rule__Trigger_in__ParametersAssignment_4_0 ) ) ;
public final void rule__Trigger_in__Group_4__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6637:1: ( ( ( rule__Trigger_in__ParametersAssignment_4_0 ) ) )
// InternalUrml.g:6638:1: ( ( rule__Trigger_in__ParametersAssignment_4_0 ) )
{
// InternalUrml.g:6638:1: ( ( rule__Trigger_in__ParametersAssignment_4_0 ) )
// InternalUrml.g:6639:1: ( rule__Trigger_in__ParametersAssignment_4_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getParametersAssignment_4_0());
}
// InternalUrml.g:6640:1: ( rule__Trigger_in__ParametersAssignment_4_0 )
// InternalUrml.g:6640:2: rule__Trigger_in__ParametersAssignment_4_0
{
pushFollow(FOLLOW_2);
rule__Trigger_in__ParametersAssignment_4_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getParametersAssignment_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4__0__Impl"
// $ANTLR start "rule__Trigger_in__Group_4__1"
// InternalUrml.g:6650:1: rule__Trigger_in__Group_4__1 : rule__Trigger_in__Group_4__1__Impl ;
public final void rule__Trigger_in__Group_4__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6654:1: ( rule__Trigger_in__Group_4__1__Impl )
// InternalUrml.g:6655:2: rule__Trigger_in__Group_4__1__Impl
{
pushFollow(FOLLOW_2);
rule__Trigger_in__Group_4__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4__1"
// $ANTLR start "rule__Trigger_in__Group_4__1__Impl"
// InternalUrml.g:6661:1: rule__Trigger_in__Group_4__1__Impl : ( ( rule__Trigger_in__Group_4_1__0 )* ) ;
public final void rule__Trigger_in__Group_4__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6665:1: ( ( ( rule__Trigger_in__Group_4_1__0 )* ) )
// InternalUrml.g:6666:1: ( ( rule__Trigger_in__Group_4_1__0 )* )
{
// InternalUrml.g:6666:1: ( ( rule__Trigger_in__Group_4_1__0 )* )
// InternalUrml.g:6667:1: ( rule__Trigger_in__Group_4_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getGroup_4_1());
}
// InternalUrml.g:6668:1: ( rule__Trigger_in__Group_4_1__0 )*
loop51:
do {
int alt51=2;
int LA51_0 = input.LA(1);
if ( (LA51_0==22) ) {
alt51=1;
}
switch (alt51) {
case 1 :
// InternalUrml.g:6668:2: rule__Trigger_in__Group_4_1__0
{
pushFollow(FOLLOW_18);
rule__Trigger_in__Group_4_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop51;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getGroup_4_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4__1__Impl"
// $ANTLR start "rule__Trigger_in__Group_4_1__0"
// InternalUrml.g:6682:1: rule__Trigger_in__Group_4_1__0 : rule__Trigger_in__Group_4_1__0__Impl rule__Trigger_in__Group_4_1__1 ;
public final void rule__Trigger_in__Group_4_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6686:1: ( rule__Trigger_in__Group_4_1__0__Impl rule__Trigger_in__Group_4_1__1 )
// InternalUrml.g:6687:2: rule__Trigger_in__Group_4_1__0__Impl rule__Trigger_in__Group_4_1__1
{
pushFollow(FOLLOW_8);
rule__Trigger_in__Group_4_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_in__Group_4_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4_1__0"
// $ANTLR start "rule__Trigger_in__Group_4_1__0__Impl"
// InternalUrml.g:6694:1: rule__Trigger_in__Group_4_1__0__Impl : ( ',' ) ;
public final void rule__Trigger_in__Group_4_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6698:1: ( ( ',' ) )
// InternalUrml.g:6699:1: ( ',' )
{
// InternalUrml.g:6699:1: ( ',' )
// InternalUrml.g:6700:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getCommaKeyword_4_1_0());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getCommaKeyword_4_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4_1__0__Impl"
// $ANTLR start "rule__Trigger_in__Group_4_1__1"
// InternalUrml.g:6713:1: rule__Trigger_in__Group_4_1__1 : rule__Trigger_in__Group_4_1__1__Impl ;
public final void rule__Trigger_in__Group_4_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6717:1: ( rule__Trigger_in__Group_4_1__1__Impl )
// InternalUrml.g:6718:2: rule__Trigger_in__Group_4_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Trigger_in__Group_4_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4_1__1"
// $ANTLR start "rule__Trigger_in__Group_4_1__1__Impl"
// InternalUrml.g:6724:1: rule__Trigger_in__Group_4_1__1__Impl : ( ( rule__Trigger_in__ParametersAssignment_4_1_1 ) ) ;
public final void rule__Trigger_in__Group_4_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6728:1: ( ( ( rule__Trigger_in__ParametersAssignment_4_1_1 ) ) )
// InternalUrml.g:6729:1: ( ( rule__Trigger_in__ParametersAssignment_4_1_1 ) )
{
// InternalUrml.g:6729:1: ( ( rule__Trigger_in__ParametersAssignment_4_1_1 ) )
// InternalUrml.g:6730:1: ( rule__Trigger_in__ParametersAssignment_4_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getParametersAssignment_4_1_1());
}
// InternalUrml.g:6731:1: ( rule__Trigger_in__ParametersAssignment_4_1_1 )
// InternalUrml.g:6731:2: rule__Trigger_in__ParametersAssignment_4_1_1
{
pushFollow(FOLLOW_2);
rule__Trigger_in__ParametersAssignment_4_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getParametersAssignment_4_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__Group_4_1__1__Impl"
// $ANTLR start "rule__IncomingVariable__Group__0"
// InternalUrml.g:6745:1: rule__IncomingVariable__Group__0 : rule__IncomingVariable__Group__0__Impl rule__IncomingVariable__Group__1 ;
public final void rule__IncomingVariable__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6749:1: ( rule__IncomingVariable__Group__0__Impl rule__IncomingVariable__Group__1 )
// InternalUrml.g:6750:2: rule__IncomingVariable__Group__0__Impl rule__IncomingVariable__Group__1
{
pushFollow(FOLLOW_4);
rule__IncomingVariable__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IncomingVariable__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__Group__0"
// $ANTLR start "rule__IncomingVariable__Group__0__Impl"
// InternalUrml.g:6757:1: rule__IncomingVariable__Group__0__Impl : ( ( rule__IncomingVariable__Alternatives_0 ) ) ;
public final void rule__IncomingVariable__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6761:1: ( ( ( rule__IncomingVariable__Alternatives_0 ) ) )
// InternalUrml.g:6762:1: ( ( rule__IncomingVariable__Alternatives_0 ) )
{
// InternalUrml.g:6762:1: ( ( rule__IncomingVariable__Alternatives_0 ) )
// InternalUrml.g:6763:1: ( rule__IncomingVariable__Alternatives_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getAlternatives_0());
}
// InternalUrml.g:6764:1: ( rule__IncomingVariable__Alternatives_0 )
// InternalUrml.g:6764:2: rule__IncomingVariable__Alternatives_0
{
pushFollow(FOLLOW_2);
rule__IncomingVariable__Alternatives_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getAlternatives_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__Group__0__Impl"
// $ANTLR start "rule__IncomingVariable__Group__1"
// InternalUrml.g:6774:1: rule__IncomingVariable__Group__1 : rule__IncomingVariable__Group__1__Impl ;
public final void rule__IncomingVariable__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6778:1: ( rule__IncomingVariable__Group__1__Impl )
// InternalUrml.g:6779:2: rule__IncomingVariable__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__IncomingVariable__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__Group__1"
// $ANTLR start "rule__IncomingVariable__Group__1__Impl"
// InternalUrml.g:6785:1: rule__IncomingVariable__Group__1__Impl : ( ( rule__IncomingVariable__NameAssignment_1 ) ) ;
public final void rule__IncomingVariable__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6789:1: ( ( ( rule__IncomingVariable__NameAssignment_1 ) ) )
// InternalUrml.g:6790:1: ( ( rule__IncomingVariable__NameAssignment_1 ) )
{
// InternalUrml.g:6790:1: ( ( rule__IncomingVariable__NameAssignment_1 ) )
// InternalUrml.g:6791:1: ( rule__IncomingVariable__NameAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getNameAssignment_1());
}
// InternalUrml.g:6792:1: ( rule__IncomingVariable__NameAssignment_1 )
// InternalUrml.g:6792:2: rule__IncomingVariable__NameAssignment_1
{
pushFollow(FOLLOW_2);
rule__IncomingVariable__NameAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getNameAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__Group__1__Impl"
// $ANTLR start "rule__Trigger_out__Group__0"
// InternalUrml.g:6806:1: rule__Trigger_out__Group__0 : rule__Trigger_out__Group__0__Impl rule__Trigger_out__Group__1 ;
public final void rule__Trigger_out__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6810:1: ( rule__Trigger_out__Group__0__Impl rule__Trigger_out__Group__1 )
// InternalUrml.g:6811:2: rule__Trigger_out__Group__0__Impl rule__Trigger_out__Group__1
{
pushFollow(FOLLOW_29);
rule__Trigger_out__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__0"
// $ANTLR start "rule__Trigger_out__Group__0__Impl"
// InternalUrml.g:6818:1: rule__Trigger_out__Group__0__Impl : ( ( rule__Trigger_out__ToAssignment_0 ) ) ;
public final void rule__Trigger_out__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6822:1: ( ( ( rule__Trigger_out__ToAssignment_0 ) ) )
// InternalUrml.g:6823:1: ( ( rule__Trigger_out__ToAssignment_0 ) )
{
// InternalUrml.g:6823:1: ( ( rule__Trigger_out__ToAssignment_0 ) )
// InternalUrml.g:6824:1: ( rule__Trigger_out__ToAssignment_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getToAssignment_0());
}
// InternalUrml.g:6825:1: ( rule__Trigger_out__ToAssignment_0 )
// InternalUrml.g:6825:2: rule__Trigger_out__ToAssignment_0
{
pushFollow(FOLLOW_2);
rule__Trigger_out__ToAssignment_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getToAssignment_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__0__Impl"
// $ANTLR start "rule__Trigger_out__Group__1"
// InternalUrml.g:6835:1: rule__Trigger_out__Group__1 : rule__Trigger_out__Group__1__Impl rule__Trigger_out__Group__2 ;
public final void rule__Trigger_out__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6839:1: ( rule__Trigger_out__Group__1__Impl rule__Trigger_out__Group__2 )
// InternalUrml.g:6840:2: rule__Trigger_out__Group__1__Impl rule__Trigger_out__Group__2
{
pushFollow(FOLLOW_4);
rule__Trigger_out__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__1"
// $ANTLR start "rule__Trigger_out__Group__1__Impl"
// InternalUrml.g:6847:1: rule__Trigger_out__Group__1__Impl : ( '.' ) ;
public final void rule__Trigger_out__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6851:1: ( ( '.' ) )
// InternalUrml.g:6852:1: ( '.' )
{
// InternalUrml.g:6852:1: ( '.' )
// InternalUrml.g:6853:1: '.'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getFullStopKeyword_1());
}
match(input,32,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getFullStopKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__1__Impl"
// $ANTLR start "rule__Trigger_out__Group__2"
// InternalUrml.g:6866:1: rule__Trigger_out__Group__2 : rule__Trigger_out__Group__2__Impl rule__Trigger_out__Group__3 ;
public final void rule__Trigger_out__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6870:1: ( rule__Trigger_out__Group__2__Impl rule__Trigger_out__Group__3 )
// InternalUrml.g:6871:2: rule__Trigger_out__Group__2__Impl rule__Trigger_out__Group__3
{
pushFollow(FOLLOW_15);
rule__Trigger_out__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__2"
// $ANTLR start "rule__Trigger_out__Group__2__Impl"
// InternalUrml.g:6878:1: rule__Trigger_out__Group__2__Impl : ( ( rule__Trigger_out__SignalAssignment_2 ) ) ;
public final void rule__Trigger_out__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6882:1: ( ( ( rule__Trigger_out__SignalAssignment_2 ) ) )
// InternalUrml.g:6883:1: ( ( rule__Trigger_out__SignalAssignment_2 ) )
{
// InternalUrml.g:6883:1: ( ( rule__Trigger_out__SignalAssignment_2 ) )
// InternalUrml.g:6884:1: ( rule__Trigger_out__SignalAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getSignalAssignment_2());
}
// InternalUrml.g:6885:1: ( rule__Trigger_out__SignalAssignment_2 )
// InternalUrml.g:6885:2: rule__Trigger_out__SignalAssignment_2
{
pushFollow(FOLLOW_2);
rule__Trigger_out__SignalAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getSignalAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__2__Impl"
// $ANTLR start "rule__Trigger_out__Group__3"
// InternalUrml.g:6895:1: rule__Trigger_out__Group__3 : rule__Trigger_out__Group__3__Impl rule__Trigger_out__Group__4 ;
public final void rule__Trigger_out__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6899:1: ( rule__Trigger_out__Group__3__Impl rule__Trigger_out__Group__4 )
// InternalUrml.g:6900:2: rule__Trigger_out__Group__3__Impl rule__Trigger_out__Group__4
{
pushFollow(FOLLOW_42);
rule__Trigger_out__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__3"
// $ANTLR start "rule__Trigger_out__Group__3__Impl"
// InternalUrml.g:6907:1: rule__Trigger_out__Group__3__Impl : ( '(' ) ;
public final void rule__Trigger_out__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6911:1: ( ( '(' ) )
// InternalUrml.g:6912:1: ( '(' )
{
// InternalUrml.g:6912:1: ( '(' )
// InternalUrml.g:6913:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getLeftParenthesisKeyword_3());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getLeftParenthesisKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__3__Impl"
// $ANTLR start "rule__Trigger_out__Group__4"
// InternalUrml.g:6926:1: rule__Trigger_out__Group__4 : rule__Trigger_out__Group__4__Impl rule__Trigger_out__Group__5 ;
public final void rule__Trigger_out__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6930:1: ( rule__Trigger_out__Group__4__Impl rule__Trigger_out__Group__5 )
// InternalUrml.g:6931:2: rule__Trigger_out__Group__4__Impl rule__Trigger_out__Group__5
{
pushFollow(FOLLOW_42);
rule__Trigger_out__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__4"
// $ANTLR start "rule__Trigger_out__Group__4__Impl"
// InternalUrml.g:6938:1: rule__Trigger_out__Group__4__Impl : ( ( rule__Trigger_out__Group_4__0 )? ) ;
public final void rule__Trigger_out__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6942:1: ( ( ( rule__Trigger_out__Group_4__0 )? ) )
// InternalUrml.g:6943:1: ( ( rule__Trigger_out__Group_4__0 )? )
{
// InternalUrml.g:6943:1: ( ( rule__Trigger_out__Group_4__0 )? )
// InternalUrml.g:6944:1: ( rule__Trigger_out__Group_4__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getGroup_4());
}
// InternalUrml.g:6945:1: ( rule__Trigger_out__Group_4__0 )?
int alt52=2;
int LA52_0 = input.LA(1);
if ( (LA52_0==RULE_ID||(LA52_0>=RULE_INT && LA52_0<=RULE_BOOLEAN)||LA52_0==20||LA52_0==70||LA52_0==74) ) {
alt52=1;
}
switch (alt52) {
case 1 :
// InternalUrml.g:6945:2: rule__Trigger_out__Group_4__0
{
pushFollow(FOLLOW_2);
rule__Trigger_out__Group_4__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getGroup_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__4__Impl"
// $ANTLR start "rule__Trigger_out__Group__5"
// InternalUrml.g:6955:1: rule__Trigger_out__Group__5 : rule__Trigger_out__Group__5__Impl ;
public final void rule__Trigger_out__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6959:1: ( rule__Trigger_out__Group__5__Impl )
// InternalUrml.g:6960:2: rule__Trigger_out__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__Trigger_out__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__5"
// $ANTLR start "rule__Trigger_out__Group__5__Impl"
// InternalUrml.g:6966:1: rule__Trigger_out__Group__5__Impl : ( ')' ) ;
public final void rule__Trigger_out__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:6970:1: ( ( ')' ) )
// InternalUrml.g:6971:1: ( ')' )
{
// InternalUrml.g:6971:1: ( ')' )
// InternalUrml.g:6972:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getRightParenthesisKeyword_5());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getRightParenthesisKeyword_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group__5__Impl"
// $ANTLR start "rule__Trigger_out__Group_4__0"
// InternalUrml.g:6997:1: rule__Trigger_out__Group_4__0 : rule__Trigger_out__Group_4__0__Impl rule__Trigger_out__Group_4__1 ;
public final void rule__Trigger_out__Group_4__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7001:1: ( rule__Trigger_out__Group_4__0__Impl rule__Trigger_out__Group_4__1 )
// InternalUrml.g:7002:2: rule__Trigger_out__Group_4__0__Impl rule__Trigger_out__Group_4__1
{
pushFollow(FOLLOW_17);
rule__Trigger_out__Group_4__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group_4__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4__0"
// $ANTLR start "rule__Trigger_out__Group_4__0__Impl"
// InternalUrml.g:7009:1: rule__Trigger_out__Group_4__0__Impl : ( ( rule__Trigger_out__ParametersAssignment_4_0 ) ) ;
public final void rule__Trigger_out__Group_4__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7013:1: ( ( ( rule__Trigger_out__ParametersAssignment_4_0 ) ) )
// InternalUrml.g:7014:1: ( ( rule__Trigger_out__ParametersAssignment_4_0 ) )
{
// InternalUrml.g:7014:1: ( ( rule__Trigger_out__ParametersAssignment_4_0 ) )
// InternalUrml.g:7015:1: ( rule__Trigger_out__ParametersAssignment_4_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getParametersAssignment_4_0());
}
// InternalUrml.g:7016:1: ( rule__Trigger_out__ParametersAssignment_4_0 )
// InternalUrml.g:7016:2: rule__Trigger_out__ParametersAssignment_4_0
{
pushFollow(FOLLOW_2);
rule__Trigger_out__ParametersAssignment_4_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getParametersAssignment_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4__0__Impl"
// $ANTLR start "rule__Trigger_out__Group_4__1"
// InternalUrml.g:7026:1: rule__Trigger_out__Group_4__1 : rule__Trigger_out__Group_4__1__Impl ;
public final void rule__Trigger_out__Group_4__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7030:1: ( rule__Trigger_out__Group_4__1__Impl )
// InternalUrml.g:7031:2: rule__Trigger_out__Group_4__1__Impl
{
pushFollow(FOLLOW_2);
rule__Trigger_out__Group_4__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4__1"
// $ANTLR start "rule__Trigger_out__Group_4__1__Impl"
// InternalUrml.g:7037:1: rule__Trigger_out__Group_4__1__Impl : ( ( rule__Trigger_out__Group_4_1__0 )* ) ;
public final void rule__Trigger_out__Group_4__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7041:1: ( ( ( rule__Trigger_out__Group_4_1__0 )* ) )
// InternalUrml.g:7042:1: ( ( rule__Trigger_out__Group_4_1__0 )* )
{
// InternalUrml.g:7042:1: ( ( rule__Trigger_out__Group_4_1__0 )* )
// InternalUrml.g:7043:1: ( rule__Trigger_out__Group_4_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getGroup_4_1());
}
// InternalUrml.g:7044:1: ( rule__Trigger_out__Group_4_1__0 )*
loop53:
do {
int alt53=2;
int LA53_0 = input.LA(1);
if ( (LA53_0==22) ) {
alt53=1;
}
switch (alt53) {
case 1 :
// InternalUrml.g:7044:2: rule__Trigger_out__Group_4_1__0
{
pushFollow(FOLLOW_18);
rule__Trigger_out__Group_4_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop53;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getGroup_4_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4__1__Impl"
// $ANTLR start "rule__Trigger_out__Group_4_1__0"
// InternalUrml.g:7058:1: rule__Trigger_out__Group_4_1__0 : rule__Trigger_out__Group_4_1__0__Impl rule__Trigger_out__Group_4_1__1 ;
public final void rule__Trigger_out__Group_4_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7062:1: ( rule__Trigger_out__Group_4_1__0__Impl rule__Trigger_out__Group_4_1__1 )
// InternalUrml.g:7063:2: rule__Trigger_out__Group_4_1__0__Impl rule__Trigger_out__Group_4_1__1
{
pushFollow(FOLLOW_10);
rule__Trigger_out__Group_4_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Trigger_out__Group_4_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4_1__0"
// $ANTLR start "rule__Trigger_out__Group_4_1__0__Impl"
// InternalUrml.g:7070:1: rule__Trigger_out__Group_4_1__0__Impl : ( ',' ) ;
public final void rule__Trigger_out__Group_4_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7074:1: ( ( ',' ) )
// InternalUrml.g:7075:1: ( ',' )
{
// InternalUrml.g:7075:1: ( ',' )
// InternalUrml.g:7076:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getCommaKeyword_4_1_0());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getCommaKeyword_4_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4_1__0__Impl"
// $ANTLR start "rule__Trigger_out__Group_4_1__1"
// InternalUrml.g:7089:1: rule__Trigger_out__Group_4_1__1 : rule__Trigger_out__Group_4_1__1__Impl ;
public final void rule__Trigger_out__Group_4_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7093:1: ( rule__Trigger_out__Group_4_1__1__Impl )
// InternalUrml.g:7094:2: rule__Trigger_out__Group_4_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Trigger_out__Group_4_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4_1__1"
// $ANTLR start "rule__Trigger_out__Group_4_1__1__Impl"
// InternalUrml.g:7100:1: rule__Trigger_out__Group_4_1__1__Impl : ( ( rule__Trigger_out__ParametersAssignment_4_1_1 ) ) ;
public final void rule__Trigger_out__Group_4_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7104:1: ( ( ( rule__Trigger_out__ParametersAssignment_4_1_1 ) ) )
// InternalUrml.g:7105:1: ( ( rule__Trigger_out__ParametersAssignment_4_1_1 ) )
{
// InternalUrml.g:7105:1: ( ( rule__Trigger_out__ParametersAssignment_4_1_1 ) )
// InternalUrml.g:7106:1: ( rule__Trigger_out__ParametersAssignment_4_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getParametersAssignment_4_1_1());
}
// InternalUrml.g:7107:1: ( rule__Trigger_out__ParametersAssignment_4_1_1 )
// InternalUrml.g:7107:2: rule__Trigger_out__ParametersAssignment_4_1_1
{
pushFollow(FOLLOW_2);
rule__Trigger_out__ParametersAssignment_4_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getParametersAssignment_4_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__Group_4_1__1__Impl"
// $ANTLR start "rule__WhileLoopOperation__Group__0"
// InternalUrml.g:7121:1: rule__WhileLoopOperation__Group__0 : rule__WhileLoopOperation__Group__0__Impl rule__WhileLoopOperation__Group__1 ;
public final void rule__WhileLoopOperation__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7125:1: ( rule__WhileLoopOperation__Group__0__Impl rule__WhileLoopOperation__Group__1 )
// InternalUrml.g:7126:2: rule__WhileLoopOperation__Group__0__Impl rule__WhileLoopOperation__Group__1
{
pushFollow(FOLLOW_10);
rule__WhileLoopOperation__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__0"
// $ANTLR start "rule__WhileLoopOperation__Group__0__Impl"
// InternalUrml.g:7133:1: rule__WhileLoopOperation__Group__0__Impl : ( 'while' ) ;
public final void rule__WhileLoopOperation__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7137:1: ( ( 'while' ) )
// InternalUrml.g:7138:1: ( 'while' )
{
// InternalUrml.g:7138:1: ( 'while' )
// InternalUrml.g:7139:1: 'while'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getWhileKeyword_0());
}
match(input,46,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getWhileKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__0__Impl"
// $ANTLR start "rule__WhileLoopOperation__Group__1"
// InternalUrml.g:7152:1: rule__WhileLoopOperation__Group__1 : rule__WhileLoopOperation__Group__1__Impl rule__WhileLoopOperation__Group__2 ;
public final void rule__WhileLoopOperation__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7156:1: ( rule__WhileLoopOperation__Group__1__Impl rule__WhileLoopOperation__Group__2 )
// InternalUrml.g:7157:2: rule__WhileLoopOperation__Group__1__Impl rule__WhileLoopOperation__Group__2
{
pushFollow(FOLLOW_5);
rule__WhileLoopOperation__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__1"
// $ANTLR start "rule__WhileLoopOperation__Group__1__Impl"
// InternalUrml.g:7164:1: rule__WhileLoopOperation__Group__1__Impl : ( ( rule__WhileLoopOperation__ConditionAssignment_1 ) ) ;
public final void rule__WhileLoopOperation__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7168:1: ( ( ( rule__WhileLoopOperation__ConditionAssignment_1 ) ) )
// InternalUrml.g:7169:1: ( ( rule__WhileLoopOperation__ConditionAssignment_1 ) )
{
// InternalUrml.g:7169:1: ( ( rule__WhileLoopOperation__ConditionAssignment_1 ) )
// InternalUrml.g:7170:1: ( rule__WhileLoopOperation__ConditionAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getConditionAssignment_1());
}
// InternalUrml.g:7171:1: ( rule__WhileLoopOperation__ConditionAssignment_1 )
// InternalUrml.g:7171:2: rule__WhileLoopOperation__ConditionAssignment_1
{
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__ConditionAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getConditionAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__1__Impl"
// $ANTLR start "rule__WhileLoopOperation__Group__2"
// InternalUrml.g:7181:1: rule__WhileLoopOperation__Group__2 : rule__WhileLoopOperation__Group__2__Impl rule__WhileLoopOperation__Group__3 ;
public final void rule__WhileLoopOperation__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7185:1: ( rule__WhileLoopOperation__Group__2__Impl rule__WhileLoopOperation__Group__3 )
// InternalUrml.g:7186:2: rule__WhileLoopOperation__Group__2__Impl rule__WhileLoopOperation__Group__3
{
pushFollow(FOLLOW_24);
rule__WhileLoopOperation__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__2"
// $ANTLR start "rule__WhileLoopOperation__Group__2__Impl"
// InternalUrml.g:7193:1: rule__WhileLoopOperation__Group__2__Impl : ( '{' ) ;
public final void rule__WhileLoopOperation__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7197:1: ( ( '{' ) )
// InternalUrml.g:7198:1: ( '{' )
{
// InternalUrml.g:7198:1: ( '{' )
// InternalUrml.g:7199:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__2__Impl"
// $ANTLR start "rule__WhileLoopOperation__Group__3"
// InternalUrml.g:7212:1: rule__WhileLoopOperation__Group__3 : rule__WhileLoopOperation__Group__3__Impl rule__WhileLoopOperation__Group__4 ;
public final void rule__WhileLoopOperation__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7216:1: ( rule__WhileLoopOperation__Group__3__Impl rule__WhileLoopOperation__Group__4 )
// InternalUrml.g:7217:2: rule__WhileLoopOperation__Group__3__Impl rule__WhileLoopOperation__Group__4
{
pushFollow(FOLLOW_25);
rule__WhileLoopOperation__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__3"
// $ANTLR start "rule__WhileLoopOperation__Group__3__Impl"
// InternalUrml.g:7224:1: rule__WhileLoopOperation__Group__3__Impl : ( ( ( rule__WhileLoopOperation__StatementsAssignment_3 ) ) ( ( rule__WhileLoopOperation__StatementsAssignment_3 )* ) ) ;
public final void rule__WhileLoopOperation__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7228:1: ( ( ( ( rule__WhileLoopOperation__StatementsAssignment_3 ) ) ( ( rule__WhileLoopOperation__StatementsAssignment_3 )* ) ) )
// InternalUrml.g:7229:1: ( ( ( rule__WhileLoopOperation__StatementsAssignment_3 ) ) ( ( rule__WhileLoopOperation__StatementsAssignment_3 )* ) )
{
// InternalUrml.g:7229:1: ( ( ( rule__WhileLoopOperation__StatementsAssignment_3 ) ) ( ( rule__WhileLoopOperation__StatementsAssignment_3 )* ) )
// InternalUrml.g:7230:1: ( ( rule__WhileLoopOperation__StatementsAssignment_3 ) ) ( ( rule__WhileLoopOperation__StatementsAssignment_3 )* )
{
// InternalUrml.g:7230:1: ( ( rule__WhileLoopOperation__StatementsAssignment_3 ) )
// InternalUrml.g:7231:1: ( rule__WhileLoopOperation__StatementsAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getStatementsAssignment_3());
}
// InternalUrml.g:7232:1: ( rule__WhileLoopOperation__StatementsAssignment_3 )
// InternalUrml.g:7232:2: rule__WhileLoopOperation__StatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__WhileLoopOperation__StatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getStatementsAssignment_3());
}
}
// InternalUrml.g:7235:1: ( ( rule__WhileLoopOperation__StatementsAssignment_3 )* )
// InternalUrml.g:7236:1: ( rule__WhileLoopOperation__StatementsAssignment_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getStatementsAssignment_3());
}
// InternalUrml.g:7237:1: ( rule__WhileLoopOperation__StatementsAssignment_3 )*
loop54:
do {
int alt54=2;
int LA54_0 = input.LA(1);
if ( (LA54_0==RULE_ID||(LA54_0>=46 && LA54_0<=47)||(LA54_0>=49 && LA54_0<=52)||(LA54_0>=54 && LA54_0<=56)||(LA54_0>=58 && LA54_0<=59)) ) {
alt54=1;
}
switch (alt54) {
case 1 :
// InternalUrml.g:7237:2: rule__WhileLoopOperation__StatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__WhileLoopOperation__StatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop54;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getStatementsAssignment_3());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__3__Impl"
// $ANTLR start "rule__WhileLoopOperation__Group__4"
// InternalUrml.g:7248:1: rule__WhileLoopOperation__Group__4 : rule__WhileLoopOperation__Group__4__Impl ;
public final void rule__WhileLoopOperation__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7252:1: ( rule__WhileLoopOperation__Group__4__Impl )
// InternalUrml.g:7253:2: rule__WhileLoopOperation__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__WhileLoopOperation__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__4"
// $ANTLR start "rule__WhileLoopOperation__Group__4__Impl"
// InternalUrml.g:7259:1: rule__WhileLoopOperation__Group__4__Impl : ( '}' ) ;
public final void rule__WhileLoopOperation__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7263:1: ( ( '}' ) )
// InternalUrml.g:7264:1: ( '}' )
{
// InternalUrml.g:7264:1: ( '}' )
// InternalUrml.g:7265:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__Group__4__Impl"
// $ANTLR start "rule__IfStatementOperation__Group__0"
// InternalUrml.g:7288:1: rule__IfStatementOperation__Group__0 : rule__IfStatementOperation__Group__0__Impl rule__IfStatementOperation__Group__1 ;
public final void rule__IfStatementOperation__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7292:1: ( rule__IfStatementOperation__Group__0__Impl rule__IfStatementOperation__Group__1 )
// InternalUrml.g:7293:2: rule__IfStatementOperation__Group__0__Impl rule__IfStatementOperation__Group__1
{
pushFollow(FOLLOW_10);
rule__IfStatementOperation__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__0"
// $ANTLR start "rule__IfStatementOperation__Group__0__Impl"
// InternalUrml.g:7300:1: rule__IfStatementOperation__Group__0__Impl : ( 'if' ) ;
public final void rule__IfStatementOperation__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7304:1: ( ( 'if' ) )
// InternalUrml.g:7305:1: ( 'if' )
{
// InternalUrml.g:7305:1: ( 'if' )
// InternalUrml.g:7306:1: 'if'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getIfKeyword_0());
}
match(input,47,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getIfKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__0__Impl"
// $ANTLR start "rule__IfStatementOperation__Group__1"
// InternalUrml.g:7319:1: rule__IfStatementOperation__Group__1 : rule__IfStatementOperation__Group__1__Impl rule__IfStatementOperation__Group__2 ;
public final void rule__IfStatementOperation__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7323:1: ( rule__IfStatementOperation__Group__1__Impl rule__IfStatementOperation__Group__2 )
// InternalUrml.g:7324:2: rule__IfStatementOperation__Group__1__Impl rule__IfStatementOperation__Group__2
{
pushFollow(FOLLOW_5);
rule__IfStatementOperation__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__1"
// $ANTLR start "rule__IfStatementOperation__Group__1__Impl"
// InternalUrml.g:7331:1: rule__IfStatementOperation__Group__1__Impl : ( ( rule__IfStatementOperation__ConditionAssignment_1 ) ) ;
public final void rule__IfStatementOperation__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7335:1: ( ( ( rule__IfStatementOperation__ConditionAssignment_1 ) ) )
// InternalUrml.g:7336:1: ( ( rule__IfStatementOperation__ConditionAssignment_1 ) )
{
// InternalUrml.g:7336:1: ( ( rule__IfStatementOperation__ConditionAssignment_1 ) )
// InternalUrml.g:7337:1: ( rule__IfStatementOperation__ConditionAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getConditionAssignment_1());
}
// InternalUrml.g:7338:1: ( rule__IfStatementOperation__ConditionAssignment_1 )
// InternalUrml.g:7338:2: rule__IfStatementOperation__ConditionAssignment_1
{
pushFollow(FOLLOW_2);
rule__IfStatementOperation__ConditionAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getConditionAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__1__Impl"
// $ANTLR start "rule__IfStatementOperation__Group__2"
// InternalUrml.g:7348:1: rule__IfStatementOperation__Group__2 : rule__IfStatementOperation__Group__2__Impl rule__IfStatementOperation__Group__3 ;
public final void rule__IfStatementOperation__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7352:1: ( rule__IfStatementOperation__Group__2__Impl rule__IfStatementOperation__Group__3 )
// InternalUrml.g:7353:2: rule__IfStatementOperation__Group__2__Impl rule__IfStatementOperation__Group__3
{
pushFollow(FOLLOW_24);
rule__IfStatementOperation__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__2"
// $ANTLR start "rule__IfStatementOperation__Group__2__Impl"
// InternalUrml.g:7360:1: rule__IfStatementOperation__Group__2__Impl : ( '{' ) ;
public final void rule__IfStatementOperation__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7364:1: ( ( '{' ) )
// InternalUrml.g:7365:1: ( '{' )
{
// InternalUrml.g:7365:1: ( '{' )
// InternalUrml.g:7366:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__2__Impl"
// $ANTLR start "rule__IfStatementOperation__Group__3"
// InternalUrml.g:7379:1: rule__IfStatementOperation__Group__3 : rule__IfStatementOperation__Group__3__Impl rule__IfStatementOperation__Group__4 ;
public final void rule__IfStatementOperation__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7383:1: ( rule__IfStatementOperation__Group__3__Impl rule__IfStatementOperation__Group__4 )
// InternalUrml.g:7384:2: rule__IfStatementOperation__Group__3__Impl rule__IfStatementOperation__Group__4
{
pushFollow(FOLLOW_25);
rule__IfStatementOperation__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__3"
// $ANTLR start "rule__IfStatementOperation__Group__3__Impl"
// InternalUrml.g:7391:1: rule__IfStatementOperation__Group__3__Impl : ( ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 )* ) ) ;
public final void rule__IfStatementOperation__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7395:1: ( ( ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 )* ) ) )
// InternalUrml.g:7396:1: ( ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 )* ) )
{
// InternalUrml.g:7396:1: ( ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 )* ) )
// InternalUrml.g:7397:1: ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 )* )
{
// InternalUrml.g:7397:1: ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 ) )
// InternalUrml.g:7398:1: ( rule__IfStatementOperation__ThenStatementsAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getThenStatementsAssignment_3());
}
// InternalUrml.g:7399:1: ( rule__IfStatementOperation__ThenStatementsAssignment_3 )
// InternalUrml.g:7399:2: rule__IfStatementOperation__ThenStatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__IfStatementOperation__ThenStatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getThenStatementsAssignment_3());
}
}
// InternalUrml.g:7402:1: ( ( rule__IfStatementOperation__ThenStatementsAssignment_3 )* )
// InternalUrml.g:7403:1: ( rule__IfStatementOperation__ThenStatementsAssignment_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getThenStatementsAssignment_3());
}
// InternalUrml.g:7404:1: ( rule__IfStatementOperation__ThenStatementsAssignment_3 )*
loop55:
do {
int alt55=2;
int LA55_0 = input.LA(1);
if ( (LA55_0==RULE_ID||(LA55_0>=46 && LA55_0<=47)||(LA55_0>=49 && LA55_0<=52)||(LA55_0>=54 && LA55_0<=56)||(LA55_0>=58 && LA55_0<=59)) ) {
alt55=1;
}
switch (alt55) {
case 1 :
// InternalUrml.g:7404:2: rule__IfStatementOperation__ThenStatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__IfStatementOperation__ThenStatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop55;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getThenStatementsAssignment_3());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__3__Impl"
// $ANTLR start "rule__IfStatementOperation__Group__4"
// InternalUrml.g:7415:1: rule__IfStatementOperation__Group__4 : rule__IfStatementOperation__Group__4__Impl rule__IfStatementOperation__Group__5 ;
public final void rule__IfStatementOperation__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7419:1: ( rule__IfStatementOperation__Group__4__Impl rule__IfStatementOperation__Group__5 )
// InternalUrml.g:7420:2: rule__IfStatementOperation__Group__4__Impl rule__IfStatementOperation__Group__5
{
pushFollow(FOLLOW_43);
rule__IfStatementOperation__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__4"
// $ANTLR start "rule__IfStatementOperation__Group__4__Impl"
// InternalUrml.g:7427:1: rule__IfStatementOperation__Group__4__Impl : ( '}' ) ;
public final void rule__IfStatementOperation__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7431:1: ( ( '}' ) )
// InternalUrml.g:7432:1: ( '}' )
{
// InternalUrml.g:7432:1: ( '}' )
// InternalUrml.g:7433:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__4__Impl"
// $ANTLR start "rule__IfStatementOperation__Group__5"
// InternalUrml.g:7446:1: rule__IfStatementOperation__Group__5 : rule__IfStatementOperation__Group__5__Impl ;
public final void rule__IfStatementOperation__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7450:1: ( rule__IfStatementOperation__Group__5__Impl )
// InternalUrml.g:7451:2: rule__IfStatementOperation__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__5"
// $ANTLR start "rule__IfStatementOperation__Group__5__Impl"
// InternalUrml.g:7457:1: rule__IfStatementOperation__Group__5__Impl : ( ( rule__IfStatementOperation__Group_5__0 )? ) ;
public final void rule__IfStatementOperation__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7461:1: ( ( ( rule__IfStatementOperation__Group_5__0 )? ) )
// InternalUrml.g:7462:1: ( ( rule__IfStatementOperation__Group_5__0 )? )
{
// InternalUrml.g:7462:1: ( ( rule__IfStatementOperation__Group_5__0 )? )
// InternalUrml.g:7463:1: ( rule__IfStatementOperation__Group_5__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getGroup_5());
}
// InternalUrml.g:7464:1: ( rule__IfStatementOperation__Group_5__0 )?
int alt56=2;
int LA56_0 = input.LA(1);
if ( (LA56_0==48) ) {
alt56=1;
}
switch (alt56) {
case 1 :
// InternalUrml.g:7464:2: rule__IfStatementOperation__Group_5__0
{
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group_5__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getGroup_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group__5__Impl"
// $ANTLR start "rule__IfStatementOperation__Group_5__0"
// InternalUrml.g:7486:1: rule__IfStatementOperation__Group_5__0 : rule__IfStatementOperation__Group_5__0__Impl rule__IfStatementOperation__Group_5__1 ;
public final void rule__IfStatementOperation__Group_5__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7490:1: ( rule__IfStatementOperation__Group_5__0__Impl rule__IfStatementOperation__Group_5__1 )
// InternalUrml.g:7491:2: rule__IfStatementOperation__Group_5__0__Impl rule__IfStatementOperation__Group_5__1
{
pushFollow(FOLLOW_5);
rule__IfStatementOperation__Group_5__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group_5__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__0"
// $ANTLR start "rule__IfStatementOperation__Group_5__0__Impl"
// InternalUrml.g:7498:1: rule__IfStatementOperation__Group_5__0__Impl : ( 'else ' ) ;
public final void rule__IfStatementOperation__Group_5__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7502:1: ( ( 'else ' ) )
// InternalUrml.g:7503:1: ( 'else ' )
{
// InternalUrml.g:7503:1: ( 'else ' )
// InternalUrml.g:7504:1: 'else '
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getElseKeyword_5_0());
}
match(input,48,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getElseKeyword_5_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__0__Impl"
// $ANTLR start "rule__IfStatementOperation__Group_5__1"
// InternalUrml.g:7517:1: rule__IfStatementOperation__Group_5__1 : rule__IfStatementOperation__Group_5__1__Impl rule__IfStatementOperation__Group_5__2 ;
public final void rule__IfStatementOperation__Group_5__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7521:1: ( rule__IfStatementOperation__Group_5__1__Impl rule__IfStatementOperation__Group_5__2 )
// InternalUrml.g:7522:2: rule__IfStatementOperation__Group_5__1__Impl rule__IfStatementOperation__Group_5__2
{
pushFollow(FOLLOW_24);
rule__IfStatementOperation__Group_5__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group_5__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__1"
// $ANTLR start "rule__IfStatementOperation__Group_5__1__Impl"
// InternalUrml.g:7529:1: rule__IfStatementOperation__Group_5__1__Impl : ( '{' ) ;
public final void rule__IfStatementOperation__Group_5__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7533:1: ( ( '{' ) )
// InternalUrml.g:7534:1: ( '{' )
{
// InternalUrml.g:7534:1: ( '{' )
// InternalUrml.g:7535:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getLeftCurlyBracketKeyword_5_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getLeftCurlyBracketKeyword_5_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__1__Impl"
// $ANTLR start "rule__IfStatementOperation__Group_5__2"
// InternalUrml.g:7548:1: rule__IfStatementOperation__Group_5__2 : rule__IfStatementOperation__Group_5__2__Impl rule__IfStatementOperation__Group_5__3 ;
public final void rule__IfStatementOperation__Group_5__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7552:1: ( rule__IfStatementOperation__Group_5__2__Impl rule__IfStatementOperation__Group_5__3 )
// InternalUrml.g:7553:2: rule__IfStatementOperation__Group_5__2__Impl rule__IfStatementOperation__Group_5__3
{
pushFollow(FOLLOW_25);
rule__IfStatementOperation__Group_5__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group_5__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__2"
// $ANTLR start "rule__IfStatementOperation__Group_5__2__Impl"
// InternalUrml.g:7560:1: rule__IfStatementOperation__Group_5__2__Impl : ( ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )* ) ) ;
public final void rule__IfStatementOperation__Group_5__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7564:1: ( ( ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )* ) ) )
// InternalUrml.g:7565:1: ( ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )* ) )
{
// InternalUrml.g:7565:1: ( ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )* ) )
// InternalUrml.g:7566:1: ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )* )
{
// InternalUrml.g:7566:1: ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 ) )
// InternalUrml.g:7567:1: ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getElseStatementsAssignment_5_2());
}
// InternalUrml.g:7568:1: ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )
// InternalUrml.g:7568:2: rule__IfStatementOperation__ElseStatementsAssignment_5_2
{
pushFollow(FOLLOW_3);
rule__IfStatementOperation__ElseStatementsAssignment_5_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getElseStatementsAssignment_5_2());
}
}
// InternalUrml.g:7571:1: ( ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )* )
// InternalUrml.g:7572:1: ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getElseStatementsAssignment_5_2());
}
// InternalUrml.g:7573:1: ( rule__IfStatementOperation__ElseStatementsAssignment_5_2 )*
loop57:
do {
int alt57=2;
int LA57_0 = input.LA(1);
if ( (LA57_0==RULE_ID||(LA57_0>=46 && LA57_0<=47)||(LA57_0>=49 && LA57_0<=52)||(LA57_0>=54 && LA57_0<=56)||(LA57_0>=58 && LA57_0<=59)) ) {
alt57=1;
}
switch (alt57) {
case 1 :
// InternalUrml.g:7573:2: rule__IfStatementOperation__ElseStatementsAssignment_5_2
{
pushFollow(FOLLOW_3);
rule__IfStatementOperation__ElseStatementsAssignment_5_2();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop57;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getElseStatementsAssignment_5_2());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__2__Impl"
// $ANTLR start "rule__IfStatementOperation__Group_5__3"
// InternalUrml.g:7584:1: rule__IfStatementOperation__Group_5__3 : rule__IfStatementOperation__Group_5__3__Impl ;
public final void rule__IfStatementOperation__Group_5__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7588:1: ( rule__IfStatementOperation__Group_5__3__Impl )
// InternalUrml.g:7589:2: rule__IfStatementOperation__Group_5__3__Impl
{
pushFollow(FOLLOW_2);
rule__IfStatementOperation__Group_5__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__3"
// $ANTLR start "rule__IfStatementOperation__Group_5__3__Impl"
// InternalUrml.g:7595:1: rule__IfStatementOperation__Group_5__3__Impl : ( '}' ) ;
public final void rule__IfStatementOperation__Group_5__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7599:1: ( ( '}' ) )
// InternalUrml.g:7600:1: ( '}' )
{
// InternalUrml.g:7600:1: ( '}' )
// InternalUrml.g:7601:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getRightCurlyBracketKeyword_5_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getRightCurlyBracketKeyword_5_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__Group_5__3__Impl"
// $ANTLR start "rule__ReturnStatement__Group__0"
// InternalUrml.g:7622:1: rule__ReturnStatement__Group__0 : rule__ReturnStatement__Group__0__Impl rule__ReturnStatement__Group__1 ;
public final void rule__ReturnStatement__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7626:1: ( rule__ReturnStatement__Group__0__Impl rule__ReturnStatement__Group__1 )
// InternalUrml.g:7627:2: rule__ReturnStatement__Group__0__Impl rule__ReturnStatement__Group__1
{
pushFollow(FOLLOW_44);
rule__ReturnStatement__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ReturnStatement__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__Group__0"
// $ANTLR start "rule__ReturnStatement__Group__0__Impl"
// InternalUrml.g:7634:1: rule__ReturnStatement__Group__0__Impl : ( () ) ;
public final void rule__ReturnStatement__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7638:1: ( ( () ) )
// InternalUrml.g:7639:1: ( () )
{
// InternalUrml.g:7639:1: ( () )
// InternalUrml.g:7640:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getReturnStatementAccess().getReturnStatementAction_0());
}
// InternalUrml.g:7641:1: ()
// InternalUrml.g:7643:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getReturnStatementAccess().getReturnStatementAction_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__Group__0__Impl"
// $ANTLR start "rule__ReturnStatement__Group__1"
// InternalUrml.g:7653:1: rule__ReturnStatement__Group__1 : rule__ReturnStatement__Group__1__Impl rule__ReturnStatement__Group__2 ;
public final void rule__ReturnStatement__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7657:1: ( rule__ReturnStatement__Group__1__Impl rule__ReturnStatement__Group__2 )
// InternalUrml.g:7658:2: rule__ReturnStatement__Group__1__Impl rule__ReturnStatement__Group__2
{
pushFollow(FOLLOW_10);
rule__ReturnStatement__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ReturnStatement__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__Group__1"
// $ANTLR start "rule__ReturnStatement__Group__1__Impl"
// InternalUrml.g:7665:1: rule__ReturnStatement__Group__1__Impl : ( 'return' ) ;
public final void rule__ReturnStatement__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7669:1: ( ( 'return' ) )
// InternalUrml.g:7670:1: ( 'return' )
{
// InternalUrml.g:7670:1: ( 'return' )
// InternalUrml.g:7671:1: 'return'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getReturnStatementAccess().getReturnKeyword_1());
}
match(input,49,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getReturnStatementAccess().getReturnKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__Group__1__Impl"
// $ANTLR start "rule__ReturnStatement__Group__2"
// InternalUrml.g:7684:1: rule__ReturnStatement__Group__2 : rule__ReturnStatement__Group__2__Impl ;
public final void rule__ReturnStatement__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7688:1: ( rule__ReturnStatement__Group__2__Impl )
// InternalUrml.g:7689:2: rule__ReturnStatement__Group__2__Impl
{
pushFollow(FOLLOW_2);
rule__ReturnStatement__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__Group__2"
// $ANTLR start "rule__ReturnStatement__Group__2__Impl"
// InternalUrml.g:7695:1: rule__ReturnStatement__Group__2__Impl : ( ( rule__ReturnStatement__ReturnValueAssignment_2 )? ) ;
public final void rule__ReturnStatement__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7699:1: ( ( ( rule__ReturnStatement__ReturnValueAssignment_2 )? ) )
// InternalUrml.g:7700:1: ( ( rule__ReturnStatement__ReturnValueAssignment_2 )? )
{
// InternalUrml.g:7700:1: ( ( rule__ReturnStatement__ReturnValueAssignment_2 )? )
// InternalUrml.g:7701:1: ( rule__ReturnStatement__ReturnValueAssignment_2 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getReturnStatementAccess().getReturnValueAssignment_2());
}
// InternalUrml.g:7702:1: ( rule__ReturnStatement__ReturnValueAssignment_2 )?
int alt58=2;
int LA58_0 = input.LA(1);
if ( ((LA58_0>=RULE_INT && LA58_0<=RULE_BOOLEAN)||LA58_0==20||LA58_0==70||LA58_0==74) ) {
alt58=1;
}
else if ( (LA58_0==RULE_ID) ) {
int LA58_2 = input.LA(2);
if ( (LA58_2==EOF||LA58_2==RULE_ID||LA58_2==14||LA58_2==20||(LA58_2>=46 && LA58_2<=47)||(LA58_2>=49 && LA58_2<=52)||(LA58_2>=54 && LA58_2<=56)||(LA58_2>=58 && LA58_2<=59)||(LA58_2>=61 && LA58_2<=73)) ) {
alt58=1;
}
}
switch (alt58) {
case 1 :
// InternalUrml.g:7702:2: rule__ReturnStatement__ReturnValueAssignment_2
{
pushFollow(FOLLOW_2);
rule__ReturnStatement__ReturnValueAssignment_2();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getReturnStatementAccess().getReturnValueAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__Group__2__Impl"
// $ANTLR start "rule__Variable__Group__0"
// InternalUrml.g:7718:1: rule__Variable__Group__0 : rule__Variable__Group__0__Impl rule__Variable__Group__1 ;
public final void rule__Variable__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7722:1: ( rule__Variable__Group__0__Impl rule__Variable__Group__1 )
// InternalUrml.g:7723:2: rule__Variable__Group__0__Impl rule__Variable__Group__1
{
pushFollow(FOLLOW_8);
rule__Variable__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Variable__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group__0"
// $ANTLR start "rule__Variable__Group__0__Impl"
// InternalUrml.g:7730:1: rule__Variable__Group__0__Impl : ( 'var' ) ;
public final void rule__Variable__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7734:1: ( ( 'var' ) )
// InternalUrml.g:7735:1: ( 'var' )
{
// InternalUrml.g:7735:1: ( 'var' )
// InternalUrml.g:7736:1: 'var'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getVarKeyword_0());
}
match(input,50,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getVarKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group__0__Impl"
// $ANTLR start "rule__Variable__Group__1"
// InternalUrml.g:7749:1: rule__Variable__Group__1 : rule__Variable__Group__1__Impl rule__Variable__Group__2 ;
public final void rule__Variable__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7753:1: ( rule__Variable__Group__1__Impl rule__Variable__Group__2 )
// InternalUrml.g:7754:2: rule__Variable__Group__1__Impl rule__Variable__Group__2
{
pushFollow(FOLLOW_9);
rule__Variable__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Variable__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group__1"
// $ANTLR start "rule__Variable__Group__1__Impl"
// InternalUrml.g:7761:1: rule__Variable__Group__1__Impl : ( ( rule__Variable__VarAssignment_1 ) ) ;
public final void rule__Variable__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7765:1: ( ( ( rule__Variable__VarAssignment_1 ) ) )
// InternalUrml.g:7766:1: ( ( rule__Variable__VarAssignment_1 ) )
{
// InternalUrml.g:7766:1: ( ( rule__Variable__VarAssignment_1 ) )
// InternalUrml.g:7767:1: ( rule__Variable__VarAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getVarAssignment_1());
}
// InternalUrml.g:7768:1: ( rule__Variable__VarAssignment_1 )
// InternalUrml.g:7768:2: rule__Variable__VarAssignment_1
{
pushFollow(FOLLOW_2);
rule__Variable__VarAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getVarAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group__1__Impl"
// $ANTLR start "rule__Variable__Group__2"
// InternalUrml.g:7778:1: rule__Variable__Group__2 : rule__Variable__Group__2__Impl ;
public final void rule__Variable__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7782:1: ( rule__Variable__Group__2__Impl )
// InternalUrml.g:7783:2: rule__Variable__Group__2__Impl
{
pushFollow(FOLLOW_2);
rule__Variable__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group__2"
// $ANTLR start "rule__Variable__Group__2__Impl"
// InternalUrml.g:7789:1: rule__Variable__Group__2__Impl : ( ( rule__Variable__Group_2__0 )? ) ;
public final void rule__Variable__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7793:1: ( ( ( rule__Variable__Group_2__0 )? ) )
// InternalUrml.g:7794:1: ( ( rule__Variable__Group_2__0 )? )
{
// InternalUrml.g:7794:1: ( ( rule__Variable__Group_2__0 )? )
// InternalUrml.g:7795:1: ( rule__Variable__Group_2__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getGroup_2());
}
// InternalUrml.g:7796:1: ( rule__Variable__Group_2__0 )?
int alt59=2;
int LA59_0 = input.LA(1);
if ( (LA59_0==16) ) {
alt59=1;
}
switch (alt59) {
case 1 :
// InternalUrml.g:7796:2: rule__Variable__Group_2__0
{
pushFollow(FOLLOW_2);
rule__Variable__Group_2__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getGroup_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group__2__Impl"
// $ANTLR start "rule__Variable__Group_2__0"
// InternalUrml.g:7812:1: rule__Variable__Group_2__0 : rule__Variable__Group_2__0__Impl rule__Variable__Group_2__1 ;
public final void rule__Variable__Group_2__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7816:1: ( rule__Variable__Group_2__0__Impl rule__Variable__Group_2__1 )
// InternalUrml.g:7817:2: rule__Variable__Group_2__0__Impl rule__Variable__Group_2__1
{
pushFollow(FOLLOW_10);
rule__Variable__Group_2__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Variable__Group_2__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group_2__0"
// $ANTLR start "rule__Variable__Group_2__0__Impl"
// InternalUrml.g:7824:1: rule__Variable__Group_2__0__Impl : ( ( rule__Variable__AssignAssignment_2_0 ) ) ;
public final void rule__Variable__Group_2__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7828:1: ( ( ( rule__Variable__AssignAssignment_2_0 ) ) )
// InternalUrml.g:7829:1: ( ( rule__Variable__AssignAssignment_2_0 ) )
{
// InternalUrml.g:7829:1: ( ( rule__Variable__AssignAssignment_2_0 ) )
// InternalUrml.g:7830:1: ( rule__Variable__AssignAssignment_2_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getAssignAssignment_2_0());
}
// InternalUrml.g:7831:1: ( rule__Variable__AssignAssignment_2_0 )
// InternalUrml.g:7831:2: rule__Variable__AssignAssignment_2_0
{
pushFollow(FOLLOW_2);
rule__Variable__AssignAssignment_2_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getAssignAssignment_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group_2__0__Impl"
// $ANTLR start "rule__Variable__Group_2__1"
// InternalUrml.g:7841:1: rule__Variable__Group_2__1 : rule__Variable__Group_2__1__Impl ;
public final void rule__Variable__Group_2__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7845:1: ( rule__Variable__Group_2__1__Impl )
// InternalUrml.g:7846:2: rule__Variable__Group_2__1__Impl
{
pushFollow(FOLLOW_2);
rule__Variable__Group_2__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group_2__1"
// $ANTLR start "rule__Variable__Group_2__1__Impl"
// InternalUrml.g:7852:1: rule__Variable__Group_2__1__Impl : ( ( rule__Variable__ExpAssignment_2_1 ) ) ;
public final void rule__Variable__Group_2__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7856:1: ( ( ( rule__Variable__ExpAssignment_2_1 ) ) )
// InternalUrml.g:7857:1: ( ( rule__Variable__ExpAssignment_2_1 ) )
{
// InternalUrml.g:7857:1: ( ( rule__Variable__ExpAssignment_2_1 ) )
// InternalUrml.g:7858:1: ( rule__Variable__ExpAssignment_2_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getExpAssignment_2_1());
}
// InternalUrml.g:7859:1: ( rule__Variable__ExpAssignment_2_1 )
// InternalUrml.g:7859:2: rule__Variable__ExpAssignment_2_1
{
pushFollow(FOLLOW_2);
rule__Variable__ExpAssignment_2_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getExpAssignment_2_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__Group_2__1__Impl"
// $ANTLR start "rule__SendTrigger__Group__0"
// InternalUrml.g:7873:1: rule__SendTrigger__Group__0 : rule__SendTrigger__Group__0__Impl rule__SendTrigger__Group__1 ;
public final void rule__SendTrigger__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7877:1: ( rule__SendTrigger__Group__0__Impl rule__SendTrigger__Group__1 )
// InternalUrml.g:7878:2: rule__SendTrigger__Group__0__Impl rule__SendTrigger__Group__1
{
pushFollow(FOLLOW_4);
rule__SendTrigger__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__SendTrigger__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group__0"
// $ANTLR start "rule__SendTrigger__Group__0__Impl"
// InternalUrml.g:7885:1: rule__SendTrigger__Group__0__Impl : ( 'send' ) ;
public final void rule__SendTrigger__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7889:1: ( ( 'send' ) )
// InternalUrml.g:7890:1: ( 'send' )
{
// InternalUrml.g:7890:1: ( 'send' )
// InternalUrml.g:7891:1: 'send'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getSendKeyword_0());
}
match(input,51,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getSendKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group__0__Impl"
// $ANTLR start "rule__SendTrigger__Group__1"
// InternalUrml.g:7904:1: rule__SendTrigger__Group__1 : rule__SendTrigger__Group__1__Impl rule__SendTrigger__Group__2 ;
public final void rule__SendTrigger__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7908:1: ( rule__SendTrigger__Group__1__Impl rule__SendTrigger__Group__2 )
// InternalUrml.g:7909:2: rule__SendTrigger__Group__1__Impl rule__SendTrigger__Group__2
{
pushFollow(FOLLOW_28);
rule__SendTrigger__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__SendTrigger__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group__1"
// $ANTLR start "rule__SendTrigger__Group__1__Impl"
// InternalUrml.g:7916:1: rule__SendTrigger__Group__1__Impl : ( ( rule__SendTrigger__TriggersAssignment_1 ) ) ;
public final void rule__SendTrigger__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7920:1: ( ( ( rule__SendTrigger__TriggersAssignment_1 ) ) )
// InternalUrml.g:7921:1: ( ( rule__SendTrigger__TriggersAssignment_1 ) )
{
// InternalUrml.g:7921:1: ( ( rule__SendTrigger__TriggersAssignment_1 ) )
// InternalUrml.g:7922:1: ( rule__SendTrigger__TriggersAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getTriggersAssignment_1());
}
// InternalUrml.g:7923:1: ( rule__SendTrigger__TriggersAssignment_1 )
// InternalUrml.g:7923:2: rule__SendTrigger__TriggersAssignment_1
{
pushFollow(FOLLOW_2);
rule__SendTrigger__TriggersAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getTriggersAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group__1__Impl"
// $ANTLR start "rule__SendTrigger__Group__2"
// InternalUrml.g:7933:1: rule__SendTrigger__Group__2 : rule__SendTrigger__Group__2__Impl ;
public final void rule__SendTrigger__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7937:1: ( rule__SendTrigger__Group__2__Impl )
// InternalUrml.g:7938:2: rule__SendTrigger__Group__2__Impl
{
pushFollow(FOLLOW_2);
rule__SendTrigger__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group__2"
// $ANTLR start "rule__SendTrigger__Group__2__Impl"
// InternalUrml.g:7944:1: rule__SendTrigger__Group__2__Impl : ( ( rule__SendTrigger__Group_2__0 )* ) ;
public final void rule__SendTrigger__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7948:1: ( ( ( rule__SendTrigger__Group_2__0 )* ) )
// InternalUrml.g:7949:1: ( ( rule__SendTrigger__Group_2__0 )* )
{
// InternalUrml.g:7949:1: ( ( rule__SendTrigger__Group_2__0 )* )
// InternalUrml.g:7950:1: ( rule__SendTrigger__Group_2__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getGroup_2());
}
// InternalUrml.g:7951:1: ( rule__SendTrigger__Group_2__0 )*
loop60:
do {
int alt60=2;
int LA60_0 = input.LA(1);
if ( (LA60_0==31) ) {
alt60=1;
}
switch (alt60) {
case 1 :
// InternalUrml.g:7951:2: rule__SendTrigger__Group_2__0
{
pushFollow(FOLLOW_45);
rule__SendTrigger__Group_2__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop60;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getGroup_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group__2__Impl"
// $ANTLR start "rule__SendTrigger__Group_2__0"
// InternalUrml.g:7967:1: rule__SendTrigger__Group_2__0 : rule__SendTrigger__Group_2__0__Impl rule__SendTrigger__Group_2__1 ;
public final void rule__SendTrigger__Group_2__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7971:1: ( rule__SendTrigger__Group_2__0__Impl rule__SendTrigger__Group_2__1 )
// InternalUrml.g:7972:2: rule__SendTrigger__Group_2__0__Impl rule__SendTrigger__Group_2__1
{
pushFollow(FOLLOW_4);
rule__SendTrigger__Group_2__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__SendTrigger__Group_2__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group_2__0"
// $ANTLR start "rule__SendTrigger__Group_2__0__Impl"
// InternalUrml.g:7979:1: rule__SendTrigger__Group_2__0__Impl : ( 'and' ) ;
public final void rule__SendTrigger__Group_2__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:7983:1: ( ( 'and' ) )
// InternalUrml.g:7984:1: ( 'and' )
{
// InternalUrml.g:7984:1: ( 'and' )
// InternalUrml.g:7985:1: 'and'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getAndKeyword_2_0());
}
match(input,31,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getAndKeyword_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group_2__0__Impl"
// $ANTLR start "rule__SendTrigger__Group_2__1"
// InternalUrml.g:7998:1: rule__SendTrigger__Group_2__1 : rule__SendTrigger__Group_2__1__Impl ;
public final void rule__SendTrigger__Group_2__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8002:1: ( rule__SendTrigger__Group_2__1__Impl )
// InternalUrml.g:8003:2: rule__SendTrigger__Group_2__1__Impl
{
pushFollow(FOLLOW_2);
rule__SendTrigger__Group_2__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group_2__1"
// $ANTLR start "rule__SendTrigger__Group_2__1__Impl"
// InternalUrml.g:8009:1: rule__SendTrigger__Group_2__1__Impl : ( ( rule__SendTrigger__TriggersAssignment_2_1 ) ) ;
public final void rule__SendTrigger__Group_2__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8013:1: ( ( ( rule__SendTrigger__TriggersAssignment_2_1 ) ) )
// InternalUrml.g:8014:1: ( ( rule__SendTrigger__TriggersAssignment_2_1 ) )
{
// InternalUrml.g:8014:1: ( ( rule__SendTrigger__TriggersAssignment_2_1 ) )
// InternalUrml.g:8015:1: ( rule__SendTrigger__TriggersAssignment_2_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getTriggersAssignment_2_1());
}
// InternalUrml.g:8016:1: ( rule__SendTrigger__TriggersAssignment_2_1 )
// InternalUrml.g:8016:2: rule__SendTrigger__TriggersAssignment_2_1
{
pushFollow(FOLLOW_2);
rule__SendTrigger__TriggersAssignment_2_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getTriggersAssignment_2_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__Group_2__1__Impl"
// $ANTLR start "rule__InformTimer__Group__0"
// InternalUrml.g:8030:1: rule__InformTimer__Group__0 : rule__InformTimer__Group__0__Impl rule__InformTimer__Group__1 ;
public final void rule__InformTimer__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8034:1: ( rule__InformTimer__Group__0__Impl rule__InformTimer__Group__1 )
// InternalUrml.g:8035:2: rule__InformTimer__Group__0__Impl rule__InformTimer__Group__1
{
pushFollow(FOLLOW_4);
rule__InformTimer__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__InformTimer__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__0"
// $ANTLR start "rule__InformTimer__Group__0__Impl"
// InternalUrml.g:8042:1: rule__InformTimer__Group__0__Impl : ( 'inform' ) ;
public final void rule__InformTimer__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8046:1: ( ( 'inform' ) )
// InternalUrml.g:8047:1: ( 'inform' )
{
// InternalUrml.g:8047:1: ( 'inform' )
// InternalUrml.g:8048:1: 'inform'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getInformKeyword_0());
}
match(input,52,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getInformKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__0__Impl"
// $ANTLR start "rule__InformTimer__Group__1"
// InternalUrml.g:8061:1: rule__InformTimer__Group__1 : rule__InformTimer__Group__1__Impl rule__InformTimer__Group__2 ;
public final void rule__InformTimer__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8065:1: ( rule__InformTimer__Group__1__Impl rule__InformTimer__Group__2 )
// InternalUrml.g:8066:2: rule__InformTimer__Group__1__Impl rule__InformTimer__Group__2
{
pushFollow(FOLLOW_46);
rule__InformTimer__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__InformTimer__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__1"
// $ANTLR start "rule__InformTimer__Group__1__Impl"
// InternalUrml.g:8073:1: rule__InformTimer__Group__1__Impl : ( ( rule__InformTimer__TimerPortAssignment_1 ) ) ;
public final void rule__InformTimer__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8077:1: ( ( ( rule__InformTimer__TimerPortAssignment_1 ) ) )
// InternalUrml.g:8078:1: ( ( rule__InformTimer__TimerPortAssignment_1 ) )
{
// InternalUrml.g:8078:1: ( ( rule__InformTimer__TimerPortAssignment_1 ) )
// InternalUrml.g:8079:1: ( rule__InformTimer__TimerPortAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getTimerPortAssignment_1());
}
// InternalUrml.g:8080:1: ( rule__InformTimer__TimerPortAssignment_1 )
// InternalUrml.g:8080:2: rule__InformTimer__TimerPortAssignment_1
{
pushFollow(FOLLOW_2);
rule__InformTimer__TimerPortAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getTimerPortAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__1__Impl"
// $ANTLR start "rule__InformTimer__Group__2"
// InternalUrml.g:8090:1: rule__InformTimer__Group__2 : rule__InformTimer__Group__2__Impl rule__InformTimer__Group__3 ;
public final void rule__InformTimer__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8094:1: ( rule__InformTimer__Group__2__Impl rule__InformTimer__Group__3 )
// InternalUrml.g:8095:2: rule__InformTimer__Group__2__Impl rule__InformTimer__Group__3
{
pushFollow(FOLLOW_10);
rule__InformTimer__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__InformTimer__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__2"
// $ANTLR start "rule__InformTimer__Group__2__Impl"
// InternalUrml.g:8102:1: rule__InformTimer__Group__2__Impl : ( 'in' ) ;
public final void rule__InformTimer__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8106:1: ( ( 'in' ) )
// InternalUrml.g:8107:1: ( 'in' )
{
// InternalUrml.g:8107:1: ( 'in' )
// InternalUrml.g:8108:1: 'in'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getInKeyword_2());
}
match(input,53,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getInKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__2__Impl"
// $ANTLR start "rule__InformTimer__Group__3"
// InternalUrml.g:8121:1: rule__InformTimer__Group__3 : rule__InformTimer__Group__3__Impl ;
public final void rule__InformTimer__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8125:1: ( rule__InformTimer__Group__3__Impl )
// InternalUrml.g:8126:2: rule__InformTimer__Group__3__Impl
{
pushFollow(FOLLOW_2);
rule__InformTimer__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__3"
// $ANTLR start "rule__InformTimer__Group__3__Impl"
// InternalUrml.g:8132:1: rule__InformTimer__Group__3__Impl : ( ( rule__InformTimer__TimeAssignment_3 ) ) ;
public final void rule__InformTimer__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8136:1: ( ( ( rule__InformTimer__TimeAssignment_3 ) ) )
// InternalUrml.g:8137:1: ( ( rule__InformTimer__TimeAssignment_3 ) )
{
// InternalUrml.g:8137:1: ( ( rule__InformTimer__TimeAssignment_3 ) )
// InternalUrml.g:8138:1: ( rule__InformTimer__TimeAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getTimeAssignment_3());
}
// InternalUrml.g:8139:1: ( rule__InformTimer__TimeAssignment_3 )
// InternalUrml.g:8139:2: rule__InformTimer__TimeAssignment_3
{
pushFollow(FOLLOW_2);
rule__InformTimer__TimeAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getTimeAssignment_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__Group__3__Impl"
// $ANTLR start "rule__NoOp__Group__0"
// InternalUrml.g:8157:1: rule__NoOp__Group__0 : rule__NoOp__Group__0__Impl rule__NoOp__Group__1 ;
public final void rule__NoOp__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8161:1: ( rule__NoOp__Group__0__Impl rule__NoOp__Group__1 )
// InternalUrml.g:8162:2: rule__NoOp__Group__0__Impl rule__NoOp__Group__1
{
pushFollow(FOLLOW_47);
rule__NoOp__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__NoOp__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NoOp__Group__0"
// $ANTLR start "rule__NoOp__Group__0__Impl"
// InternalUrml.g:8169:1: rule__NoOp__Group__0__Impl : ( () ) ;
public final void rule__NoOp__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8173:1: ( ( () ) )
// InternalUrml.g:8174:1: ( () )
{
// InternalUrml.g:8174:1: ( () )
// InternalUrml.g:8175:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNoOpAccess().getNoOpAction_0());
}
// InternalUrml.g:8176:1: ()
// InternalUrml.g:8178:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getNoOpAccess().getNoOpAction_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NoOp__Group__0__Impl"
// $ANTLR start "rule__NoOp__Group__1"
// InternalUrml.g:8188:1: rule__NoOp__Group__1 : rule__NoOp__Group__1__Impl ;
public final void rule__NoOp__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8192:1: ( rule__NoOp__Group__1__Impl )
// InternalUrml.g:8193:2: rule__NoOp__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__NoOp__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NoOp__Group__1"
// $ANTLR start "rule__NoOp__Group__1__Impl"
// InternalUrml.g:8199:1: rule__NoOp__Group__1__Impl : ( 'noop' ) ;
public final void rule__NoOp__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8203:1: ( ( 'noop' ) )
// InternalUrml.g:8204:1: ( 'noop' )
{
// InternalUrml.g:8204:1: ( 'noop' )
// InternalUrml.g:8205:1: 'noop'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNoOpAccess().getNoopKeyword_1());
}
match(input,54,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getNoOpAccess().getNoopKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NoOp__Group__1__Impl"
// $ANTLR start "rule__Invoke__Group__0"
// InternalUrml.g:8222:1: rule__Invoke__Group__0 : rule__Invoke__Group__0__Impl rule__Invoke__Group__1 ;
public final void rule__Invoke__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8226:1: ( rule__Invoke__Group__0__Impl rule__Invoke__Group__1 )
// InternalUrml.g:8227:2: rule__Invoke__Group__0__Impl rule__Invoke__Group__1
{
pushFollow(FOLLOW_4);
rule__Invoke__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Invoke__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__0"
// $ANTLR start "rule__Invoke__Group__0__Impl"
// InternalUrml.g:8234:1: rule__Invoke__Group__0__Impl : ( 'call' ) ;
public final void rule__Invoke__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8238:1: ( ( 'call' ) )
// InternalUrml.g:8239:1: ( 'call' )
{
// InternalUrml.g:8239:1: ( 'call' )
// InternalUrml.g:8240:1: 'call'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getCallKeyword_0());
}
match(input,55,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getCallKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__0__Impl"
// $ANTLR start "rule__Invoke__Group__1"
// InternalUrml.g:8253:1: rule__Invoke__Group__1 : rule__Invoke__Group__1__Impl rule__Invoke__Group__2 ;
public final void rule__Invoke__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8257:1: ( rule__Invoke__Group__1__Impl rule__Invoke__Group__2 )
// InternalUrml.g:8258:2: rule__Invoke__Group__1__Impl rule__Invoke__Group__2
{
pushFollow(FOLLOW_15);
rule__Invoke__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Invoke__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__1"
// $ANTLR start "rule__Invoke__Group__1__Impl"
// InternalUrml.g:8265:1: rule__Invoke__Group__1__Impl : ( ( rule__Invoke__OperationAssignment_1 ) ) ;
public final void rule__Invoke__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8269:1: ( ( ( rule__Invoke__OperationAssignment_1 ) ) )
// InternalUrml.g:8270:1: ( ( rule__Invoke__OperationAssignment_1 ) )
{
// InternalUrml.g:8270:1: ( ( rule__Invoke__OperationAssignment_1 ) )
// InternalUrml.g:8271:1: ( rule__Invoke__OperationAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getOperationAssignment_1());
}
// InternalUrml.g:8272:1: ( rule__Invoke__OperationAssignment_1 )
// InternalUrml.g:8272:2: rule__Invoke__OperationAssignment_1
{
pushFollow(FOLLOW_2);
rule__Invoke__OperationAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getOperationAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__1__Impl"
// $ANTLR start "rule__Invoke__Group__2"
// InternalUrml.g:8282:1: rule__Invoke__Group__2 : rule__Invoke__Group__2__Impl rule__Invoke__Group__3 ;
public final void rule__Invoke__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8286:1: ( rule__Invoke__Group__2__Impl rule__Invoke__Group__3 )
// InternalUrml.g:8287:2: rule__Invoke__Group__2__Impl rule__Invoke__Group__3
{
pushFollow(FOLLOW_42);
rule__Invoke__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Invoke__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__2"
// $ANTLR start "rule__Invoke__Group__2__Impl"
// InternalUrml.g:8294:1: rule__Invoke__Group__2__Impl : ( '(' ) ;
public final void rule__Invoke__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8298:1: ( ( '(' ) )
// InternalUrml.g:8299:1: ( '(' )
{
// InternalUrml.g:8299:1: ( '(' )
// InternalUrml.g:8300:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getLeftParenthesisKeyword_2());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getLeftParenthesisKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__2__Impl"
// $ANTLR start "rule__Invoke__Group__3"
// InternalUrml.g:8313:1: rule__Invoke__Group__3 : rule__Invoke__Group__3__Impl rule__Invoke__Group__4 ;
public final void rule__Invoke__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8317:1: ( rule__Invoke__Group__3__Impl rule__Invoke__Group__4 )
// InternalUrml.g:8318:2: rule__Invoke__Group__3__Impl rule__Invoke__Group__4
{
pushFollow(FOLLOW_42);
rule__Invoke__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Invoke__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__3"
// $ANTLR start "rule__Invoke__Group__3__Impl"
// InternalUrml.g:8325:1: rule__Invoke__Group__3__Impl : ( ( rule__Invoke__Group_3__0 )? ) ;
public final void rule__Invoke__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8329:1: ( ( ( rule__Invoke__Group_3__0 )? ) )
// InternalUrml.g:8330:1: ( ( rule__Invoke__Group_3__0 )? )
{
// InternalUrml.g:8330:1: ( ( rule__Invoke__Group_3__0 )? )
// InternalUrml.g:8331:1: ( rule__Invoke__Group_3__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getGroup_3());
}
// InternalUrml.g:8332:1: ( rule__Invoke__Group_3__0 )?
int alt61=2;
int LA61_0 = input.LA(1);
if ( (LA61_0==RULE_ID||(LA61_0>=RULE_INT && LA61_0<=RULE_BOOLEAN)||LA61_0==20||LA61_0==70||LA61_0==74) ) {
alt61=1;
}
switch (alt61) {
case 1 :
// InternalUrml.g:8332:2: rule__Invoke__Group_3__0
{
pushFollow(FOLLOW_2);
rule__Invoke__Group_3__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getGroup_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__3__Impl"
// $ANTLR start "rule__Invoke__Group__4"
// InternalUrml.g:8342:1: rule__Invoke__Group__4 : rule__Invoke__Group__4__Impl ;
public final void rule__Invoke__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8346:1: ( rule__Invoke__Group__4__Impl )
// InternalUrml.g:8347:2: rule__Invoke__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__Invoke__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__4"
// $ANTLR start "rule__Invoke__Group__4__Impl"
// InternalUrml.g:8353:1: rule__Invoke__Group__4__Impl : ( ')' ) ;
public final void rule__Invoke__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8357:1: ( ( ')' ) )
// InternalUrml.g:8358:1: ( ')' )
{
// InternalUrml.g:8358:1: ( ')' )
// InternalUrml.g:8359:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getRightParenthesisKeyword_4());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getRightParenthesisKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group__4__Impl"
// $ANTLR start "rule__Invoke__Group_3__0"
// InternalUrml.g:8382:1: rule__Invoke__Group_3__0 : rule__Invoke__Group_3__0__Impl rule__Invoke__Group_3__1 ;
public final void rule__Invoke__Group_3__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8386:1: ( rule__Invoke__Group_3__0__Impl rule__Invoke__Group_3__1 )
// InternalUrml.g:8387:2: rule__Invoke__Group_3__0__Impl rule__Invoke__Group_3__1
{
pushFollow(FOLLOW_17);
rule__Invoke__Group_3__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Invoke__Group_3__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3__0"
// $ANTLR start "rule__Invoke__Group_3__0__Impl"
// InternalUrml.g:8394:1: rule__Invoke__Group_3__0__Impl : ( ( rule__Invoke__ParametersAssignment_3_0 ) ) ;
public final void rule__Invoke__Group_3__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8398:1: ( ( ( rule__Invoke__ParametersAssignment_3_0 ) ) )
// InternalUrml.g:8399:1: ( ( rule__Invoke__ParametersAssignment_3_0 ) )
{
// InternalUrml.g:8399:1: ( ( rule__Invoke__ParametersAssignment_3_0 ) )
// InternalUrml.g:8400:1: ( rule__Invoke__ParametersAssignment_3_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getParametersAssignment_3_0());
}
// InternalUrml.g:8401:1: ( rule__Invoke__ParametersAssignment_3_0 )
// InternalUrml.g:8401:2: rule__Invoke__ParametersAssignment_3_0
{
pushFollow(FOLLOW_2);
rule__Invoke__ParametersAssignment_3_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getParametersAssignment_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3__0__Impl"
// $ANTLR start "rule__Invoke__Group_3__1"
// InternalUrml.g:8411:1: rule__Invoke__Group_3__1 : rule__Invoke__Group_3__1__Impl ;
public final void rule__Invoke__Group_3__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8415:1: ( rule__Invoke__Group_3__1__Impl )
// InternalUrml.g:8416:2: rule__Invoke__Group_3__1__Impl
{
pushFollow(FOLLOW_2);
rule__Invoke__Group_3__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3__1"
// $ANTLR start "rule__Invoke__Group_3__1__Impl"
// InternalUrml.g:8422:1: rule__Invoke__Group_3__1__Impl : ( ( rule__Invoke__Group_3_1__0 )* ) ;
public final void rule__Invoke__Group_3__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8426:1: ( ( ( rule__Invoke__Group_3_1__0 )* ) )
// InternalUrml.g:8427:1: ( ( rule__Invoke__Group_3_1__0 )* )
{
// InternalUrml.g:8427:1: ( ( rule__Invoke__Group_3_1__0 )* )
// InternalUrml.g:8428:1: ( rule__Invoke__Group_3_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getGroup_3_1());
}
// InternalUrml.g:8429:1: ( rule__Invoke__Group_3_1__0 )*
loop62:
do {
int alt62=2;
int LA62_0 = input.LA(1);
if ( (LA62_0==22) ) {
alt62=1;
}
switch (alt62) {
case 1 :
// InternalUrml.g:8429:2: rule__Invoke__Group_3_1__0
{
pushFollow(FOLLOW_18);
rule__Invoke__Group_3_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop62;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getGroup_3_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3__1__Impl"
// $ANTLR start "rule__Invoke__Group_3_1__0"
// InternalUrml.g:8443:1: rule__Invoke__Group_3_1__0 : rule__Invoke__Group_3_1__0__Impl rule__Invoke__Group_3_1__1 ;
public final void rule__Invoke__Group_3_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8447:1: ( rule__Invoke__Group_3_1__0__Impl rule__Invoke__Group_3_1__1 )
// InternalUrml.g:8448:2: rule__Invoke__Group_3_1__0__Impl rule__Invoke__Group_3_1__1
{
pushFollow(FOLLOW_10);
rule__Invoke__Group_3_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Invoke__Group_3_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3_1__0"
// $ANTLR start "rule__Invoke__Group_3_1__0__Impl"
// InternalUrml.g:8455:1: rule__Invoke__Group_3_1__0__Impl : ( ',' ) ;
public final void rule__Invoke__Group_3_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8459:1: ( ( ',' ) )
// InternalUrml.g:8460:1: ( ',' )
{
// InternalUrml.g:8460:1: ( ',' )
// InternalUrml.g:8461:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getCommaKeyword_3_1_0());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getCommaKeyword_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3_1__0__Impl"
// $ANTLR start "rule__Invoke__Group_3_1__1"
// InternalUrml.g:8474:1: rule__Invoke__Group_3_1__1 : rule__Invoke__Group_3_1__1__Impl ;
public final void rule__Invoke__Group_3_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8478:1: ( rule__Invoke__Group_3_1__1__Impl )
// InternalUrml.g:8479:2: rule__Invoke__Group_3_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__Invoke__Group_3_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3_1__1"
// $ANTLR start "rule__Invoke__Group_3_1__1__Impl"
// InternalUrml.g:8485:1: rule__Invoke__Group_3_1__1__Impl : ( ( rule__Invoke__ParametersAssignment_3_1_1 ) ) ;
public final void rule__Invoke__Group_3_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8489:1: ( ( ( rule__Invoke__ParametersAssignment_3_1_1 ) ) )
// InternalUrml.g:8490:1: ( ( rule__Invoke__ParametersAssignment_3_1_1 ) )
{
// InternalUrml.g:8490:1: ( ( rule__Invoke__ParametersAssignment_3_1_1 ) )
// InternalUrml.g:8491:1: ( rule__Invoke__ParametersAssignment_3_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getParametersAssignment_3_1_1());
}
// InternalUrml.g:8492:1: ( rule__Invoke__ParametersAssignment_3_1_1 )
// InternalUrml.g:8492:2: rule__Invoke__ParametersAssignment_3_1_1
{
pushFollow(FOLLOW_2);
rule__Invoke__ParametersAssignment_3_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getParametersAssignment_3_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__Group_3_1__1__Impl"
// $ANTLR start "rule__Assignment__Group__0"
// InternalUrml.g:8506:1: rule__Assignment__Group__0 : rule__Assignment__Group__0__Impl rule__Assignment__Group__1 ;
public final void rule__Assignment__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8510:1: ( rule__Assignment__Group__0__Impl rule__Assignment__Group__1 )
// InternalUrml.g:8511:2: rule__Assignment__Group__0__Impl rule__Assignment__Group__1
{
pushFollow(FOLLOW_9);
rule__Assignment__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Assignment__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__Group__0"
// $ANTLR start "rule__Assignment__Group__0__Impl"
// InternalUrml.g:8518:1: rule__Assignment__Group__0__Impl : ( ( rule__Assignment__LvalueAssignment_0 ) ) ;
public final void rule__Assignment__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8522:1: ( ( ( rule__Assignment__LvalueAssignment_0 ) ) )
// InternalUrml.g:8523:1: ( ( rule__Assignment__LvalueAssignment_0 ) )
{
// InternalUrml.g:8523:1: ( ( rule__Assignment__LvalueAssignment_0 ) )
// InternalUrml.g:8524:1: ( rule__Assignment__LvalueAssignment_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getLvalueAssignment_0());
}
// InternalUrml.g:8525:1: ( rule__Assignment__LvalueAssignment_0 )
// InternalUrml.g:8525:2: rule__Assignment__LvalueAssignment_0
{
pushFollow(FOLLOW_2);
rule__Assignment__LvalueAssignment_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getLvalueAssignment_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__Group__0__Impl"
// $ANTLR start "rule__Assignment__Group__1"
// InternalUrml.g:8535:1: rule__Assignment__Group__1 : rule__Assignment__Group__1__Impl rule__Assignment__Group__2 ;
public final void rule__Assignment__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8539:1: ( rule__Assignment__Group__1__Impl rule__Assignment__Group__2 )
// InternalUrml.g:8540:2: rule__Assignment__Group__1__Impl rule__Assignment__Group__2
{
pushFollow(FOLLOW_10);
rule__Assignment__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__Assignment__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__Group__1"
// $ANTLR start "rule__Assignment__Group__1__Impl"
// InternalUrml.g:8547:1: rule__Assignment__Group__1__Impl : ( ':=' ) ;
public final void rule__Assignment__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8551:1: ( ( ':=' ) )
// InternalUrml.g:8552:1: ( ':=' )
{
// InternalUrml.g:8552:1: ( ':=' )
// InternalUrml.g:8553:1: ':='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getColonEqualsSignKeyword_1());
}
match(input,16,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getColonEqualsSignKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__Group__1__Impl"
// $ANTLR start "rule__Assignment__Group__2"
// InternalUrml.g:8566:1: rule__Assignment__Group__2 : rule__Assignment__Group__2__Impl ;
public final void rule__Assignment__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8570:1: ( rule__Assignment__Group__2__Impl )
// InternalUrml.g:8571:2: rule__Assignment__Group__2__Impl
{
pushFollow(FOLLOW_2);
rule__Assignment__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__Group__2"
// $ANTLR start "rule__Assignment__Group__2__Impl"
// InternalUrml.g:8577:1: rule__Assignment__Group__2__Impl : ( ( rule__Assignment__ExpAssignment_2 ) ) ;
public final void rule__Assignment__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8581:1: ( ( ( rule__Assignment__ExpAssignment_2 ) ) )
// InternalUrml.g:8582:1: ( ( rule__Assignment__ExpAssignment_2 ) )
{
// InternalUrml.g:8582:1: ( ( rule__Assignment__ExpAssignment_2 ) )
// InternalUrml.g:8583:1: ( rule__Assignment__ExpAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getExpAssignment_2());
}
// InternalUrml.g:8584:1: ( rule__Assignment__ExpAssignment_2 )
// InternalUrml.g:8584:2: rule__Assignment__ExpAssignment_2
{
pushFollow(FOLLOW_2);
rule__Assignment__ExpAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getExpAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__Group__2__Impl"
// $ANTLR start "rule__WhileLoop__Group__0"
// InternalUrml.g:8600:1: rule__WhileLoop__Group__0 : rule__WhileLoop__Group__0__Impl rule__WhileLoop__Group__1 ;
public final void rule__WhileLoop__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8604:1: ( rule__WhileLoop__Group__0__Impl rule__WhileLoop__Group__1 )
// InternalUrml.g:8605:2: rule__WhileLoop__Group__0__Impl rule__WhileLoop__Group__1
{
pushFollow(FOLLOW_10);
rule__WhileLoop__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoop__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__0"
// $ANTLR start "rule__WhileLoop__Group__0__Impl"
// InternalUrml.g:8612:1: rule__WhileLoop__Group__0__Impl : ( 'while' ) ;
public final void rule__WhileLoop__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8616:1: ( ( 'while' ) )
// InternalUrml.g:8617:1: ( 'while' )
{
// InternalUrml.g:8617:1: ( 'while' )
// InternalUrml.g:8618:1: 'while'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getWhileKeyword_0());
}
match(input,46,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getWhileKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__0__Impl"
// $ANTLR start "rule__WhileLoop__Group__1"
// InternalUrml.g:8631:1: rule__WhileLoop__Group__1 : rule__WhileLoop__Group__1__Impl rule__WhileLoop__Group__2 ;
public final void rule__WhileLoop__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8635:1: ( rule__WhileLoop__Group__1__Impl rule__WhileLoop__Group__2 )
// InternalUrml.g:8636:2: rule__WhileLoop__Group__1__Impl rule__WhileLoop__Group__2
{
pushFollow(FOLLOW_5);
rule__WhileLoop__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoop__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__1"
// $ANTLR start "rule__WhileLoop__Group__1__Impl"
// InternalUrml.g:8643:1: rule__WhileLoop__Group__1__Impl : ( ( rule__WhileLoop__ConditionAssignment_1 ) ) ;
public final void rule__WhileLoop__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8647:1: ( ( ( rule__WhileLoop__ConditionAssignment_1 ) ) )
// InternalUrml.g:8648:1: ( ( rule__WhileLoop__ConditionAssignment_1 ) )
{
// InternalUrml.g:8648:1: ( ( rule__WhileLoop__ConditionAssignment_1 ) )
// InternalUrml.g:8649:1: ( rule__WhileLoop__ConditionAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getConditionAssignment_1());
}
// InternalUrml.g:8650:1: ( rule__WhileLoop__ConditionAssignment_1 )
// InternalUrml.g:8650:2: rule__WhileLoop__ConditionAssignment_1
{
pushFollow(FOLLOW_2);
rule__WhileLoop__ConditionAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getConditionAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__1__Impl"
// $ANTLR start "rule__WhileLoop__Group__2"
// InternalUrml.g:8660:1: rule__WhileLoop__Group__2 : rule__WhileLoop__Group__2__Impl rule__WhileLoop__Group__3 ;
public final void rule__WhileLoop__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8664:1: ( rule__WhileLoop__Group__2__Impl rule__WhileLoop__Group__3 )
// InternalUrml.g:8665:2: rule__WhileLoop__Group__2__Impl rule__WhileLoop__Group__3
{
pushFollow(FOLLOW_24);
rule__WhileLoop__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoop__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__2"
// $ANTLR start "rule__WhileLoop__Group__2__Impl"
// InternalUrml.g:8672:1: rule__WhileLoop__Group__2__Impl : ( '{' ) ;
public final void rule__WhileLoop__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8676:1: ( ( '{' ) )
// InternalUrml.g:8677:1: ( '{' )
{
// InternalUrml.g:8677:1: ( '{' )
// InternalUrml.g:8678:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__2__Impl"
// $ANTLR start "rule__WhileLoop__Group__3"
// InternalUrml.g:8691:1: rule__WhileLoop__Group__3 : rule__WhileLoop__Group__3__Impl rule__WhileLoop__Group__4 ;
public final void rule__WhileLoop__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8695:1: ( rule__WhileLoop__Group__3__Impl rule__WhileLoop__Group__4 )
// InternalUrml.g:8696:2: rule__WhileLoop__Group__3__Impl rule__WhileLoop__Group__4
{
pushFollow(FOLLOW_25);
rule__WhileLoop__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__WhileLoop__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__3"
// $ANTLR start "rule__WhileLoop__Group__3__Impl"
// InternalUrml.g:8703:1: rule__WhileLoop__Group__3__Impl : ( ( ( rule__WhileLoop__StatementsAssignment_3 ) ) ( ( rule__WhileLoop__StatementsAssignment_3 )* ) ) ;
public final void rule__WhileLoop__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8707:1: ( ( ( ( rule__WhileLoop__StatementsAssignment_3 ) ) ( ( rule__WhileLoop__StatementsAssignment_3 )* ) ) )
// InternalUrml.g:8708:1: ( ( ( rule__WhileLoop__StatementsAssignment_3 ) ) ( ( rule__WhileLoop__StatementsAssignment_3 )* ) )
{
// InternalUrml.g:8708:1: ( ( ( rule__WhileLoop__StatementsAssignment_3 ) ) ( ( rule__WhileLoop__StatementsAssignment_3 )* ) )
// InternalUrml.g:8709:1: ( ( rule__WhileLoop__StatementsAssignment_3 ) ) ( ( rule__WhileLoop__StatementsAssignment_3 )* )
{
// InternalUrml.g:8709:1: ( ( rule__WhileLoop__StatementsAssignment_3 ) )
// InternalUrml.g:8710:1: ( rule__WhileLoop__StatementsAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getStatementsAssignment_3());
}
// InternalUrml.g:8711:1: ( rule__WhileLoop__StatementsAssignment_3 )
// InternalUrml.g:8711:2: rule__WhileLoop__StatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__WhileLoop__StatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getStatementsAssignment_3());
}
}
// InternalUrml.g:8714:1: ( ( rule__WhileLoop__StatementsAssignment_3 )* )
// InternalUrml.g:8715:1: ( rule__WhileLoop__StatementsAssignment_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getStatementsAssignment_3());
}
// InternalUrml.g:8716:1: ( rule__WhileLoop__StatementsAssignment_3 )*
loop63:
do {
int alt63=2;
int LA63_0 = input.LA(1);
if ( (LA63_0==RULE_ID||(LA63_0>=46 && LA63_0<=47)||(LA63_0>=50 && LA63_0<=52)||(LA63_0>=54 && LA63_0<=56)||(LA63_0>=58 && LA63_0<=59)) ) {
alt63=1;
}
switch (alt63) {
case 1 :
// InternalUrml.g:8716:2: rule__WhileLoop__StatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__WhileLoop__StatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop63;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getStatementsAssignment_3());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__3__Impl"
// $ANTLR start "rule__WhileLoop__Group__4"
// InternalUrml.g:8727:1: rule__WhileLoop__Group__4 : rule__WhileLoop__Group__4__Impl ;
public final void rule__WhileLoop__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8731:1: ( rule__WhileLoop__Group__4__Impl )
// InternalUrml.g:8732:2: rule__WhileLoop__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__WhileLoop__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__4"
// $ANTLR start "rule__WhileLoop__Group__4__Impl"
// InternalUrml.g:8738:1: rule__WhileLoop__Group__4__Impl : ( '}' ) ;
public final void rule__WhileLoop__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8742:1: ( ( '}' ) )
// InternalUrml.g:8743:1: ( '}' )
{
// InternalUrml.g:8743:1: ( '}' )
// InternalUrml.g:8744:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__Group__4__Impl"
// $ANTLR start "rule__IfStatement__Group__0"
// InternalUrml.g:8767:1: rule__IfStatement__Group__0 : rule__IfStatement__Group__0__Impl rule__IfStatement__Group__1 ;
public final void rule__IfStatement__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8771:1: ( rule__IfStatement__Group__0__Impl rule__IfStatement__Group__1 )
// InternalUrml.g:8772:2: rule__IfStatement__Group__0__Impl rule__IfStatement__Group__1
{
pushFollow(FOLLOW_10);
rule__IfStatement__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__0"
// $ANTLR start "rule__IfStatement__Group__0__Impl"
// InternalUrml.g:8779:1: rule__IfStatement__Group__0__Impl : ( 'if' ) ;
public final void rule__IfStatement__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8783:1: ( ( 'if' ) )
// InternalUrml.g:8784:1: ( 'if' )
{
// InternalUrml.g:8784:1: ( 'if' )
// InternalUrml.g:8785:1: 'if'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getIfKeyword_0());
}
match(input,47,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getIfKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__0__Impl"
// $ANTLR start "rule__IfStatement__Group__1"
// InternalUrml.g:8798:1: rule__IfStatement__Group__1 : rule__IfStatement__Group__1__Impl rule__IfStatement__Group__2 ;
public final void rule__IfStatement__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8802:1: ( rule__IfStatement__Group__1__Impl rule__IfStatement__Group__2 )
// InternalUrml.g:8803:2: rule__IfStatement__Group__1__Impl rule__IfStatement__Group__2
{
pushFollow(FOLLOW_5);
rule__IfStatement__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__1"
// $ANTLR start "rule__IfStatement__Group__1__Impl"
// InternalUrml.g:8810:1: rule__IfStatement__Group__1__Impl : ( ( rule__IfStatement__ConditionAssignment_1 ) ) ;
public final void rule__IfStatement__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8814:1: ( ( ( rule__IfStatement__ConditionAssignment_1 ) ) )
// InternalUrml.g:8815:1: ( ( rule__IfStatement__ConditionAssignment_1 ) )
{
// InternalUrml.g:8815:1: ( ( rule__IfStatement__ConditionAssignment_1 ) )
// InternalUrml.g:8816:1: ( rule__IfStatement__ConditionAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getConditionAssignment_1());
}
// InternalUrml.g:8817:1: ( rule__IfStatement__ConditionAssignment_1 )
// InternalUrml.g:8817:2: rule__IfStatement__ConditionAssignment_1
{
pushFollow(FOLLOW_2);
rule__IfStatement__ConditionAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getConditionAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__1__Impl"
// $ANTLR start "rule__IfStatement__Group__2"
// InternalUrml.g:8827:1: rule__IfStatement__Group__2 : rule__IfStatement__Group__2__Impl rule__IfStatement__Group__3 ;
public final void rule__IfStatement__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8831:1: ( rule__IfStatement__Group__2__Impl rule__IfStatement__Group__3 )
// InternalUrml.g:8832:2: rule__IfStatement__Group__2__Impl rule__IfStatement__Group__3
{
pushFollow(FOLLOW_24);
rule__IfStatement__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__2"
// $ANTLR start "rule__IfStatement__Group__2__Impl"
// InternalUrml.g:8839:1: rule__IfStatement__Group__2__Impl : ( '{' ) ;
public final void rule__IfStatement__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8843:1: ( ( '{' ) )
// InternalUrml.g:8844:1: ( '{' )
{
// InternalUrml.g:8844:1: ( '{' )
// InternalUrml.g:8845:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getLeftCurlyBracketKeyword_2());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getLeftCurlyBracketKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__2__Impl"
// $ANTLR start "rule__IfStatement__Group__3"
// InternalUrml.g:8858:1: rule__IfStatement__Group__3 : rule__IfStatement__Group__3__Impl rule__IfStatement__Group__4 ;
public final void rule__IfStatement__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8862:1: ( rule__IfStatement__Group__3__Impl rule__IfStatement__Group__4 )
// InternalUrml.g:8863:2: rule__IfStatement__Group__3__Impl rule__IfStatement__Group__4
{
pushFollow(FOLLOW_25);
rule__IfStatement__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__3"
// $ANTLR start "rule__IfStatement__Group__3__Impl"
// InternalUrml.g:8870:1: rule__IfStatement__Group__3__Impl : ( ( ( rule__IfStatement__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatement__ThenStatementsAssignment_3 )* ) ) ;
public final void rule__IfStatement__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8874:1: ( ( ( ( rule__IfStatement__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatement__ThenStatementsAssignment_3 )* ) ) )
// InternalUrml.g:8875:1: ( ( ( rule__IfStatement__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatement__ThenStatementsAssignment_3 )* ) )
{
// InternalUrml.g:8875:1: ( ( ( rule__IfStatement__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatement__ThenStatementsAssignment_3 )* ) )
// InternalUrml.g:8876:1: ( ( rule__IfStatement__ThenStatementsAssignment_3 ) ) ( ( rule__IfStatement__ThenStatementsAssignment_3 )* )
{
// InternalUrml.g:8876:1: ( ( rule__IfStatement__ThenStatementsAssignment_3 ) )
// InternalUrml.g:8877:1: ( rule__IfStatement__ThenStatementsAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getThenStatementsAssignment_3());
}
// InternalUrml.g:8878:1: ( rule__IfStatement__ThenStatementsAssignment_3 )
// InternalUrml.g:8878:2: rule__IfStatement__ThenStatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__IfStatement__ThenStatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getThenStatementsAssignment_3());
}
}
// InternalUrml.g:8881:1: ( ( rule__IfStatement__ThenStatementsAssignment_3 )* )
// InternalUrml.g:8882:1: ( rule__IfStatement__ThenStatementsAssignment_3 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getThenStatementsAssignment_3());
}
// InternalUrml.g:8883:1: ( rule__IfStatement__ThenStatementsAssignment_3 )*
loop64:
do {
int alt64=2;
int LA64_0 = input.LA(1);
if ( (LA64_0==RULE_ID||(LA64_0>=46 && LA64_0<=47)||(LA64_0>=50 && LA64_0<=52)||(LA64_0>=54 && LA64_0<=56)||(LA64_0>=58 && LA64_0<=59)) ) {
alt64=1;
}
switch (alt64) {
case 1 :
// InternalUrml.g:8883:2: rule__IfStatement__ThenStatementsAssignment_3
{
pushFollow(FOLLOW_3);
rule__IfStatement__ThenStatementsAssignment_3();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop64;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getThenStatementsAssignment_3());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__3__Impl"
// $ANTLR start "rule__IfStatement__Group__4"
// InternalUrml.g:8894:1: rule__IfStatement__Group__4 : rule__IfStatement__Group__4__Impl rule__IfStatement__Group__5 ;
public final void rule__IfStatement__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8898:1: ( rule__IfStatement__Group__4__Impl rule__IfStatement__Group__5 )
// InternalUrml.g:8899:2: rule__IfStatement__Group__4__Impl rule__IfStatement__Group__5
{
pushFollow(FOLLOW_43);
rule__IfStatement__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__4"
// $ANTLR start "rule__IfStatement__Group__4__Impl"
// InternalUrml.g:8906:1: rule__IfStatement__Group__4__Impl : ( '}' ) ;
public final void rule__IfStatement__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8910:1: ( ( '}' ) )
// InternalUrml.g:8911:1: ( '}' )
{
// InternalUrml.g:8911:1: ( '}' )
// InternalUrml.g:8912:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getRightCurlyBracketKeyword_4());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getRightCurlyBracketKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__4__Impl"
// $ANTLR start "rule__IfStatement__Group__5"
// InternalUrml.g:8925:1: rule__IfStatement__Group__5 : rule__IfStatement__Group__5__Impl ;
public final void rule__IfStatement__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8929:1: ( rule__IfStatement__Group__5__Impl )
// InternalUrml.g:8930:2: rule__IfStatement__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__IfStatement__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__5"
// $ANTLR start "rule__IfStatement__Group__5__Impl"
// InternalUrml.g:8936:1: rule__IfStatement__Group__5__Impl : ( ( rule__IfStatement__Group_5__0 )? ) ;
public final void rule__IfStatement__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8940:1: ( ( ( rule__IfStatement__Group_5__0 )? ) )
// InternalUrml.g:8941:1: ( ( rule__IfStatement__Group_5__0 )? )
{
// InternalUrml.g:8941:1: ( ( rule__IfStatement__Group_5__0 )? )
// InternalUrml.g:8942:1: ( rule__IfStatement__Group_5__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getGroup_5());
}
// InternalUrml.g:8943:1: ( rule__IfStatement__Group_5__0 )?
int alt65=2;
int LA65_0 = input.LA(1);
if ( (LA65_0==48) ) {
alt65=1;
}
switch (alt65) {
case 1 :
// InternalUrml.g:8943:2: rule__IfStatement__Group_5__0
{
pushFollow(FOLLOW_2);
rule__IfStatement__Group_5__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getGroup_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group__5__Impl"
// $ANTLR start "rule__IfStatement__Group_5__0"
// InternalUrml.g:8965:1: rule__IfStatement__Group_5__0 : rule__IfStatement__Group_5__0__Impl rule__IfStatement__Group_5__1 ;
public final void rule__IfStatement__Group_5__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8969:1: ( rule__IfStatement__Group_5__0__Impl rule__IfStatement__Group_5__1 )
// InternalUrml.g:8970:2: rule__IfStatement__Group_5__0__Impl rule__IfStatement__Group_5__1
{
pushFollow(FOLLOW_5);
rule__IfStatement__Group_5__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group_5__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__0"
// $ANTLR start "rule__IfStatement__Group_5__0__Impl"
// InternalUrml.g:8977:1: rule__IfStatement__Group_5__0__Impl : ( 'else ' ) ;
public final void rule__IfStatement__Group_5__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:8981:1: ( ( 'else ' ) )
// InternalUrml.g:8982:1: ( 'else ' )
{
// InternalUrml.g:8982:1: ( 'else ' )
// InternalUrml.g:8983:1: 'else '
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getElseKeyword_5_0());
}
match(input,48,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getElseKeyword_5_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__0__Impl"
// $ANTLR start "rule__IfStatement__Group_5__1"
// InternalUrml.g:8996:1: rule__IfStatement__Group_5__1 : rule__IfStatement__Group_5__1__Impl rule__IfStatement__Group_5__2 ;
public final void rule__IfStatement__Group_5__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9000:1: ( rule__IfStatement__Group_5__1__Impl rule__IfStatement__Group_5__2 )
// InternalUrml.g:9001:2: rule__IfStatement__Group_5__1__Impl rule__IfStatement__Group_5__2
{
pushFollow(FOLLOW_24);
rule__IfStatement__Group_5__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group_5__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__1"
// $ANTLR start "rule__IfStatement__Group_5__1__Impl"
// InternalUrml.g:9008:1: rule__IfStatement__Group_5__1__Impl : ( '{' ) ;
public final void rule__IfStatement__Group_5__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9012:1: ( ( '{' ) )
// InternalUrml.g:9013:1: ( '{' )
{
// InternalUrml.g:9013:1: ( '{' )
// InternalUrml.g:9014:1: '{'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getLeftCurlyBracketKeyword_5_1());
}
match(input,13,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getLeftCurlyBracketKeyword_5_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__1__Impl"
// $ANTLR start "rule__IfStatement__Group_5__2"
// InternalUrml.g:9027:1: rule__IfStatement__Group_5__2 : rule__IfStatement__Group_5__2__Impl rule__IfStatement__Group_5__3 ;
public final void rule__IfStatement__Group_5__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9031:1: ( rule__IfStatement__Group_5__2__Impl rule__IfStatement__Group_5__3 )
// InternalUrml.g:9032:2: rule__IfStatement__Group_5__2__Impl rule__IfStatement__Group_5__3
{
pushFollow(FOLLOW_25);
rule__IfStatement__Group_5__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IfStatement__Group_5__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__2"
// $ANTLR start "rule__IfStatement__Group_5__2__Impl"
// InternalUrml.g:9039:1: rule__IfStatement__Group_5__2__Impl : ( ( ( rule__IfStatement__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatement__ElseStatementsAssignment_5_2 )* ) ) ;
public final void rule__IfStatement__Group_5__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9043:1: ( ( ( ( rule__IfStatement__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatement__ElseStatementsAssignment_5_2 )* ) ) )
// InternalUrml.g:9044:1: ( ( ( rule__IfStatement__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatement__ElseStatementsAssignment_5_2 )* ) )
{
// InternalUrml.g:9044:1: ( ( ( rule__IfStatement__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatement__ElseStatementsAssignment_5_2 )* ) )
// InternalUrml.g:9045:1: ( ( rule__IfStatement__ElseStatementsAssignment_5_2 ) ) ( ( rule__IfStatement__ElseStatementsAssignment_5_2 )* )
{
// InternalUrml.g:9045:1: ( ( rule__IfStatement__ElseStatementsAssignment_5_2 ) )
// InternalUrml.g:9046:1: ( rule__IfStatement__ElseStatementsAssignment_5_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getElseStatementsAssignment_5_2());
}
// InternalUrml.g:9047:1: ( rule__IfStatement__ElseStatementsAssignment_5_2 )
// InternalUrml.g:9047:2: rule__IfStatement__ElseStatementsAssignment_5_2
{
pushFollow(FOLLOW_3);
rule__IfStatement__ElseStatementsAssignment_5_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getElseStatementsAssignment_5_2());
}
}
// InternalUrml.g:9050:1: ( ( rule__IfStatement__ElseStatementsAssignment_5_2 )* )
// InternalUrml.g:9051:1: ( rule__IfStatement__ElseStatementsAssignment_5_2 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getElseStatementsAssignment_5_2());
}
// InternalUrml.g:9052:1: ( rule__IfStatement__ElseStatementsAssignment_5_2 )*
loop66:
do {
int alt66=2;
int LA66_0 = input.LA(1);
if ( (LA66_0==RULE_ID||(LA66_0>=46 && LA66_0<=47)||(LA66_0>=50 && LA66_0<=52)||(LA66_0>=54 && LA66_0<=56)||(LA66_0>=58 && LA66_0<=59)) ) {
alt66=1;
}
switch (alt66) {
case 1 :
// InternalUrml.g:9052:2: rule__IfStatement__ElseStatementsAssignment_5_2
{
pushFollow(FOLLOW_3);
rule__IfStatement__ElseStatementsAssignment_5_2();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop66;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getElseStatementsAssignment_5_2());
}
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__2__Impl"
// $ANTLR start "rule__IfStatement__Group_5__3"
// InternalUrml.g:9063:1: rule__IfStatement__Group_5__3 : rule__IfStatement__Group_5__3__Impl ;
public final void rule__IfStatement__Group_5__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9067:1: ( rule__IfStatement__Group_5__3__Impl )
// InternalUrml.g:9068:2: rule__IfStatement__Group_5__3__Impl
{
pushFollow(FOLLOW_2);
rule__IfStatement__Group_5__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__3"
// $ANTLR start "rule__IfStatement__Group_5__3__Impl"
// InternalUrml.g:9074:1: rule__IfStatement__Group_5__3__Impl : ( '}' ) ;
public final void rule__IfStatement__Group_5__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9078:1: ( ( '}' ) )
// InternalUrml.g:9079:1: ( '}' )
{
// InternalUrml.g:9079:1: ( '}' )
// InternalUrml.g:9080:1: '}'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getRightCurlyBracketKeyword_5_3());
}
match(input,14,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getRightCurlyBracketKeyword_5_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__Group_5__3__Impl"
// $ANTLR start "rule__LogStatement__Group__0"
// InternalUrml.g:9101:1: rule__LogStatement__Group__0 : rule__LogStatement__Group__0__Impl rule__LogStatement__Group__1 ;
public final void rule__LogStatement__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9105:1: ( rule__LogStatement__Group__0__Impl rule__LogStatement__Group__1 )
// InternalUrml.g:9106:2: rule__LogStatement__Group__0__Impl rule__LogStatement__Group__1
{
pushFollow(FOLLOW_4);
rule__LogStatement__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__LogStatement__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__0"
// $ANTLR start "rule__LogStatement__Group__0__Impl"
// InternalUrml.g:9113:1: rule__LogStatement__Group__0__Impl : ( 'log' ) ;
public final void rule__LogStatement__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9117:1: ( ( 'log' ) )
// InternalUrml.g:9118:1: ( 'log' )
{
// InternalUrml.g:9118:1: ( 'log' )
// InternalUrml.g:9119:1: 'log'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getLogKeyword_0());
}
match(input,56,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getLogKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__0__Impl"
// $ANTLR start "rule__LogStatement__Group__1"
// InternalUrml.g:9132:1: rule__LogStatement__Group__1 : rule__LogStatement__Group__1__Impl rule__LogStatement__Group__2 ;
public final void rule__LogStatement__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9136:1: ( rule__LogStatement__Group__1__Impl rule__LogStatement__Group__2 )
// InternalUrml.g:9137:2: rule__LogStatement__Group__1__Impl rule__LogStatement__Group__2
{
pushFollow(FOLLOW_48);
rule__LogStatement__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__LogStatement__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__1"
// $ANTLR start "rule__LogStatement__Group__1__Impl"
// InternalUrml.g:9144:1: rule__LogStatement__Group__1__Impl : ( ( rule__LogStatement__LogPortAssignment_1 ) ) ;
public final void rule__LogStatement__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9148:1: ( ( ( rule__LogStatement__LogPortAssignment_1 ) ) )
// InternalUrml.g:9149:1: ( ( rule__LogStatement__LogPortAssignment_1 ) )
{
// InternalUrml.g:9149:1: ( ( rule__LogStatement__LogPortAssignment_1 ) )
// InternalUrml.g:9150:1: ( rule__LogStatement__LogPortAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getLogPortAssignment_1());
}
// InternalUrml.g:9151:1: ( rule__LogStatement__LogPortAssignment_1 )
// InternalUrml.g:9151:2: rule__LogStatement__LogPortAssignment_1
{
pushFollow(FOLLOW_2);
rule__LogStatement__LogPortAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getLogPortAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__1__Impl"
// $ANTLR start "rule__LogStatement__Group__2"
// InternalUrml.g:9161:1: rule__LogStatement__Group__2 : rule__LogStatement__Group__2__Impl rule__LogStatement__Group__3 ;
public final void rule__LogStatement__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9165:1: ( rule__LogStatement__Group__2__Impl rule__LogStatement__Group__3 )
// InternalUrml.g:9166:2: rule__LogStatement__Group__2__Impl rule__LogStatement__Group__3
{
pushFollow(FOLLOW_49);
rule__LogStatement__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__LogStatement__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__2"
// $ANTLR start "rule__LogStatement__Group__2__Impl"
// InternalUrml.g:9173:1: rule__LogStatement__Group__2__Impl : ( 'with' ) ;
public final void rule__LogStatement__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9177:1: ( ( 'with' ) )
// InternalUrml.g:9178:1: ( 'with' )
{
// InternalUrml.g:9178:1: ( 'with' )
// InternalUrml.g:9179:1: 'with'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getWithKeyword_2());
}
match(input,57,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getWithKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__2__Impl"
// $ANTLR start "rule__LogStatement__Group__3"
// InternalUrml.g:9192:1: rule__LogStatement__Group__3 : rule__LogStatement__Group__3__Impl ;
public final void rule__LogStatement__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9196:1: ( rule__LogStatement__Group__3__Impl )
// InternalUrml.g:9197:2: rule__LogStatement__Group__3__Impl
{
pushFollow(FOLLOW_2);
rule__LogStatement__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__3"
// $ANTLR start "rule__LogStatement__Group__3__Impl"
// InternalUrml.g:9203:1: rule__LogStatement__Group__3__Impl : ( ( rule__LogStatement__LeftAssignment_3 ) ) ;
public final void rule__LogStatement__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9207:1: ( ( ( rule__LogStatement__LeftAssignment_3 ) ) )
// InternalUrml.g:9208:1: ( ( rule__LogStatement__LeftAssignment_3 ) )
{
// InternalUrml.g:9208:1: ( ( rule__LogStatement__LeftAssignment_3 ) )
// InternalUrml.g:9209:1: ( rule__LogStatement__LeftAssignment_3 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getLeftAssignment_3());
}
// InternalUrml.g:9210:1: ( rule__LogStatement__LeftAssignment_3 )
// InternalUrml.g:9210:2: rule__LogStatement__LeftAssignment_3
{
pushFollow(FOLLOW_2);
rule__LogStatement__LeftAssignment_3();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getLeftAssignment_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__Group__3__Impl"
// $ANTLR start "rule__ChooseStatement__Group__0"
// InternalUrml.g:9228:1: rule__ChooseStatement__Group__0 : rule__ChooseStatement__Group__0__Impl rule__ChooseStatement__Group__1 ;
public final void rule__ChooseStatement__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9232:1: ( rule__ChooseStatement__Group__0__Impl rule__ChooseStatement__Group__1 )
// InternalUrml.g:9233:2: rule__ChooseStatement__Group__0__Impl rule__ChooseStatement__Group__1
{
pushFollow(FOLLOW_15);
rule__ChooseStatement__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__0"
// $ANTLR start "rule__ChooseStatement__Group__0__Impl"
// InternalUrml.g:9240:1: rule__ChooseStatement__Group__0__Impl : ( 'choose' ) ;
public final void rule__ChooseStatement__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9244:1: ( ( 'choose' ) )
// InternalUrml.g:9245:1: ( 'choose' )
{
// InternalUrml.g:9245:1: ( 'choose' )
// InternalUrml.g:9246:1: 'choose'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getChooseKeyword_0());
}
match(input,58,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getChooseKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__0__Impl"
// $ANTLR start "rule__ChooseStatement__Group__1"
// InternalUrml.g:9259:1: rule__ChooseStatement__Group__1 : rule__ChooseStatement__Group__1__Impl rule__ChooseStatement__Group__2 ;
public final void rule__ChooseStatement__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9263:1: ( rule__ChooseStatement__Group__1__Impl rule__ChooseStatement__Group__2 )
// InternalUrml.g:9264:2: rule__ChooseStatement__Group__1__Impl rule__ChooseStatement__Group__2
{
pushFollow(FOLLOW_4);
rule__ChooseStatement__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__1"
// $ANTLR start "rule__ChooseStatement__Group__1__Impl"
// InternalUrml.g:9271:1: rule__ChooseStatement__Group__1__Impl : ( '(' ) ;
public final void rule__ChooseStatement__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9275:1: ( ( '(' ) )
// InternalUrml.g:9276:1: ( '(' )
{
// InternalUrml.g:9276:1: ( '(' )
// InternalUrml.g:9277:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getLeftParenthesisKeyword_1());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getLeftParenthesisKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__1__Impl"
// $ANTLR start "rule__ChooseStatement__Group__2"
// InternalUrml.g:9290:1: rule__ChooseStatement__Group__2 : rule__ChooseStatement__Group__2__Impl rule__ChooseStatement__Group__3 ;
public final void rule__ChooseStatement__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9294:1: ( rule__ChooseStatement__Group__2__Impl rule__ChooseStatement__Group__3 )
// InternalUrml.g:9295:2: rule__ChooseStatement__Group__2__Impl rule__ChooseStatement__Group__3
{
pushFollow(FOLLOW_17);
rule__ChooseStatement__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__2"
// $ANTLR start "rule__ChooseStatement__Group__2__Impl"
// InternalUrml.g:9302:1: rule__ChooseStatement__Group__2__Impl : ( ( rule__ChooseStatement__XAssignment_2 ) ) ;
public final void rule__ChooseStatement__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9306:1: ( ( ( rule__ChooseStatement__XAssignment_2 ) ) )
// InternalUrml.g:9307:1: ( ( rule__ChooseStatement__XAssignment_2 ) )
{
// InternalUrml.g:9307:1: ( ( rule__ChooseStatement__XAssignment_2 ) )
// InternalUrml.g:9308:1: ( rule__ChooseStatement__XAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getXAssignment_2());
}
// InternalUrml.g:9309:1: ( rule__ChooseStatement__XAssignment_2 )
// InternalUrml.g:9309:2: rule__ChooseStatement__XAssignment_2
{
pushFollow(FOLLOW_2);
rule__ChooseStatement__XAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getXAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__2__Impl"
// $ANTLR start "rule__ChooseStatement__Group__3"
// InternalUrml.g:9319:1: rule__ChooseStatement__Group__3 : rule__ChooseStatement__Group__3__Impl rule__ChooseStatement__Group__4 ;
public final void rule__ChooseStatement__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9323:1: ( rule__ChooseStatement__Group__3__Impl rule__ChooseStatement__Group__4 )
// InternalUrml.g:9324:2: rule__ChooseStatement__Group__3__Impl rule__ChooseStatement__Group__4
{
pushFollow(FOLLOW_10);
rule__ChooseStatement__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__3"
// $ANTLR start "rule__ChooseStatement__Group__3__Impl"
// InternalUrml.g:9331:1: rule__ChooseStatement__Group__3__Impl : ( ',' ) ;
public final void rule__ChooseStatement__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9335:1: ( ( ',' ) )
// InternalUrml.g:9336:1: ( ',' )
{
// InternalUrml.g:9336:1: ( ',' )
// InternalUrml.g:9337:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getCommaKeyword_3());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getCommaKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__3__Impl"
// $ANTLR start "rule__ChooseStatement__Group__4"
// InternalUrml.g:9350:1: rule__ChooseStatement__Group__4 : rule__ChooseStatement__Group__4__Impl rule__ChooseStatement__Group__5 ;
public final void rule__ChooseStatement__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9354:1: ( rule__ChooseStatement__Group__4__Impl rule__ChooseStatement__Group__5 )
// InternalUrml.g:9355:2: rule__ChooseStatement__Group__4__Impl rule__ChooseStatement__Group__5
{
pushFollow(FOLLOW_50);
rule__ChooseStatement__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__4"
// $ANTLR start "rule__ChooseStatement__Group__4__Impl"
// InternalUrml.g:9362:1: rule__ChooseStatement__Group__4__Impl : ( ( rule__ChooseStatement__EAssignment_4 ) ) ;
public final void rule__ChooseStatement__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9366:1: ( ( ( rule__ChooseStatement__EAssignment_4 ) ) )
// InternalUrml.g:9367:1: ( ( rule__ChooseStatement__EAssignment_4 ) )
{
// InternalUrml.g:9367:1: ( ( rule__ChooseStatement__EAssignment_4 ) )
// InternalUrml.g:9368:1: ( rule__ChooseStatement__EAssignment_4 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getEAssignment_4());
}
// InternalUrml.g:9369:1: ( rule__ChooseStatement__EAssignment_4 )
// InternalUrml.g:9369:2: rule__ChooseStatement__EAssignment_4
{
pushFollow(FOLLOW_2);
rule__ChooseStatement__EAssignment_4();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getEAssignment_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__4__Impl"
// $ANTLR start "rule__ChooseStatement__Group__5"
// InternalUrml.g:9379:1: rule__ChooseStatement__Group__5 : rule__ChooseStatement__Group__5__Impl ;
public final void rule__ChooseStatement__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9383:1: ( rule__ChooseStatement__Group__5__Impl )
// InternalUrml.g:9384:2: rule__ChooseStatement__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__ChooseStatement__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__5"
// $ANTLR start "rule__ChooseStatement__Group__5__Impl"
// InternalUrml.g:9390:1: rule__ChooseStatement__Group__5__Impl : ( ')' ) ;
public final void rule__ChooseStatement__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9394:1: ( ( ')' ) )
// InternalUrml.g:9395:1: ( ')' )
{
// InternalUrml.g:9395:1: ( ')' )
// InternalUrml.g:9396:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getRightParenthesisKeyword_5());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getRightParenthesisKeyword_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__Group__5__Impl"
// $ANTLR start "rule__FlipStatement__Group__0"
// InternalUrml.g:9421:1: rule__FlipStatement__Group__0 : rule__FlipStatement__Group__0__Impl rule__FlipStatement__Group__1 ;
public final void rule__FlipStatement__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9425:1: ( rule__FlipStatement__Group__0__Impl rule__FlipStatement__Group__1 )
// InternalUrml.g:9426:2: rule__FlipStatement__Group__0__Impl rule__FlipStatement__Group__1
{
pushFollow(FOLLOW_15);
rule__FlipStatement__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__0"
// $ANTLR start "rule__FlipStatement__Group__0__Impl"
// InternalUrml.g:9433:1: rule__FlipStatement__Group__0__Impl : ( 'flip' ) ;
public final void rule__FlipStatement__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9437:1: ( ( 'flip' ) )
// InternalUrml.g:9438:1: ( 'flip' )
{
// InternalUrml.g:9438:1: ( 'flip' )
// InternalUrml.g:9439:1: 'flip'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getFlipKeyword_0());
}
match(input,59,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getFlipKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__0__Impl"
// $ANTLR start "rule__FlipStatement__Group__1"
// InternalUrml.g:9452:1: rule__FlipStatement__Group__1 : rule__FlipStatement__Group__1__Impl rule__FlipStatement__Group__2 ;
public final void rule__FlipStatement__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9456:1: ( rule__FlipStatement__Group__1__Impl rule__FlipStatement__Group__2 )
// InternalUrml.g:9457:2: rule__FlipStatement__Group__1__Impl rule__FlipStatement__Group__2
{
pushFollow(FOLLOW_4);
rule__FlipStatement__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__1"
// $ANTLR start "rule__FlipStatement__Group__1__Impl"
// InternalUrml.g:9464:1: rule__FlipStatement__Group__1__Impl : ( '(' ) ;
public final void rule__FlipStatement__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9468:1: ( ( '(' ) )
// InternalUrml.g:9469:1: ( '(' )
{
// InternalUrml.g:9469:1: ( '(' )
// InternalUrml.g:9470:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getLeftParenthesisKeyword_1());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getLeftParenthesisKeyword_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__1__Impl"
// $ANTLR start "rule__FlipStatement__Group__2"
// InternalUrml.g:9483:1: rule__FlipStatement__Group__2 : rule__FlipStatement__Group__2__Impl rule__FlipStatement__Group__3 ;
public final void rule__FlipStatement__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9487:1: ( rule__FlipStatement__Group__2__Impl rule__FlipStatement__Group__3 )
// InternalUrml.g:9488:2: rule__FlipStatement__Group__2__Impl rule__FlipStatement__Group__3
{
pushFollow(FOLLOW_17);
rule__FlipStatement__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__2"
// $ANTLR start "rule__FlipStatement__Group__2__Impl"
// InternalUrml.g:9495:1: rule__FlipStatement__Group__2__Impl : ( ( rule__FlipStatement__XAssignment_2 ) ) ;
public final void rule__FlipStatement__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9499:1: ( ( ( rule__FlipStatement__XAssignment_2 ) ) )
// InternalUrml.g:9500:1: ( ( rule__FlipStatement__XAssignment_2 ) )
{
// InternalUrml.g:9500:1: ( ( rule__FlipStatement__XAssignment_2 ) )
// InternalUrml.g:9501:1: ( rule__FlipStatement__XAssignment_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getXAssignment_2());
}
// InternalUrml.g:9502:1: ( rule__FlipStatement__XAssignment_2 )
// InternalUrml.g:9502:2: rule__FlipStatement__XAssignment_2
{
pushFollow(FOLLOW_2);
rule__FlipStatement__XAssignment_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getXAssignment_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__2__Impl"
// $ANTLR start "rule__FlipStatement__Group__3"
// InternalUrml.g:9512:1: rule__FlipStatement__Group__3 : rule__FlipStatement__Group__3__Impl rule__FlipStatement__Group__4 ;
public final void rule__FlipStatement__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9516:1: ( rule__FlipStatement__Group__3__Impl rule__FlipStatement__Group__4 )
// InternalUrml.g:9517:2: rule__FlipStatement__Group__3__Impl rule__FlipStatement__Group__4
{
pushFollow(FOLLOW_10);
rule__FlipStatement__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__3"
// $ANTLR start "rule__FlipStatement__Group__3__Impl"
// InternalUrml.g:9524:1: rule__FlipStatement__Group__3__Impl : ( ',' ) ;
public final void rule__FlipStatement__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9528:1: ( ( ',' ) )
// InternalUrml.g:9529:1: ( ',' )
{
// InternalUrml.g:9529:1: ( ',' )
// InternalUrml.g:9530:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getCommaKeyword_3());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getCommaKeyword_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__3__Impl"
// $ANTLR start "rule__FlipStatement__Group__4"
// InternalUrml.g:9543:1: rule__FlipStatement__Group__4 : rule__FlipStatement__Group__4__Impl rule__FlipStatement__Group__5 ;
public final void rule__FlipStatement__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9547:1: ( rule__FlipStatement__Group__4__Impl rule__FlipStatement__Group__5 )
// InternalUrml.g:9548:2: rule__FlipStatement__Group__4__Impl rule__FlipStatement__Group__5
{
pushFollow(FOLLOW_50);
rule__FlipStatement__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__5();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__4"
// $ANTLR start "rule__FlipStatement__Group__4__Impl"
// InternalUrml.g:9555:1: rule__FlipStatement__Group__4__Impl : ( ( rule__FlipStatement__EAssignment_4 ) ) ;
public final void rule__FlipStatement__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9559:1: ( ( ( rule__FlipStatement__EAssignment_4 ) ) )
// InternalUrml.g:9560:1: ( ( rule__FlipStatement__EAssignment_4 ) )
{
// InternalUrml.g:9560:1: ( ( rule__FlipStatement__EAssignment_4 ) )
// InternalUrml.g:9561:1: ( rule__FlipStatement__EAssignment_4 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getEAssignment_4());
}
// InternalUrml.g:9562:1: ( rule__FlipStatement__EAssignment_4 )
// InternalUrml.g:9562:2: rule__FlipStatement__EAssignment_4
{
pushFollow(FOLLOW_2);
rule__FlipStatement__EAssignment_4();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getEAssignment_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__4__Impl"
// $ANTLR start "rule__FlipStatement__Group__5"
// InternalUrml.g:9572:1: rule__FlipStatement__Group__5 : rule__FlipStatement__Group__5__Impl ;
public final void rule__FlipStatement__Group__5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9576:1: ( rule__FlipStatement__Group__5__Impl )
// InternalUrml.g:9577:2: rule__FlipStatement__Group__5__Impl
{
pushFollow(FOLLOW_2);
rule__FlipStatement__Group__5__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__5"
// $ANTLR start "rule__FlipStatement__Group__5__Impl"
// InternalUrml.g:9583:1: rule__FlipStatement__Group__5__Impl : ( ')' ) ;
public final void rule__FlipStatement__Group__5__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9587:1: ( ( ')' ) )
// InternalUrml.g:9588:1: ( ')' )
{
// InternalUrml.g:9588:1: ( ')' )
// InternalUrml.g:9589:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getRightParenthesisKeyword_5());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getRightParenthesisKeyword_5());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__Group__5__Impl"
// $ANTLR start "rule__StringExpression__Group__0"
// InternalUrml.g:9614:1: rule__StringExpression__Group__0 : rule__StringExpression__Group__0__Impl rule__StringExpression__Group__1 ;
public final void rule__StringExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9618:1: ( rule__StringExpression__Group__0__Impl rule__StringExpression__Group__1 )
// InternalUrml.g:9619:2: rule__StringExpression__Group__0__Impl rule__StringExpression__Group__1
{
pushFollow(FOLLOW_51);
rule__StringExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StringExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group__0"
// $ANTLR start "rule__StringExpression__Group__0__Impl"
// InternalUrml.g:9626:1: rule__StringExpression__Group__0__Impl : ( ruleIndividualExpression ) ;
public final void rule__StringExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9630:1: ( ( ruleIndividualExpression ) )
// InternalUrml.g:9631:1: ( ruleIndividualExpression )
{
// InternalUrml.g:9631:1: ( ruleIndividualExpression )
// InternalUrml.g:9632:1: ruleIndividualExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getIndividualExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleIndividualExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getIndividualExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group__0__Impl"
// $ANTLR start "rule__StringExpression__Group__1"
// InternalUrml.g:9643:1: rule__StringExpression__Group__1 : rule__StringExpression__Group__1__Impl ;
public final void rule__StringExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9647:1: ( rule__StringExpression__Group__1__Impl )
// InternalUrml.g:9648:2: rule__StringExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__StringExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group__1"
// $ANTLR start "rule__StringExpression__Group__1__Impl"
// InternalUrml.g:9654:1: rule__StringExpression__Group__1__Impl : ( ( rule__StringExpression__Group_1__0 )* ) ;
public final void rule__StringExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9658:1: ( ( ( rule__StringExpression__Group_1__0 )* ) )
// InternalUrml.g:9659:1: ( ( rule__StringExpression__Group_1__0 )* )
{
// InternalUrml.g:9659:1: ( ( rule__StringExpression__Group_1__0 )* )
// InternalUrml.g:9660:1: ( rule__StringExpression__Group_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getGroup_1());
}
// InternalUrml.g:9661:1: ( rule__StringExpression__Group_1__0 )*
loop67:
do {
int alt67=2;
int LA67_0 = input.LA(1);
if ( (LA67_0==60) ) {
alt67=1;
}
switch (alt67) {
case 1 :
// InternalUrml.g:9661:2: rule__StringExpression__Group_1__0
{
pushFollow(FOLLOW_52);
rule__StringExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop67;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group__1__Impl"
// $ANTLR start "rule__StringExpression__Group_1__0"
// InternalUrml.g:9675:1: rule__StringExpression__Group_1__0 : rule__StringExpression__Group_1__0__Impl ;
public final void rule__StringExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9679:1: ( rule__StringExpression__Group_1__0__Impl )
// InternalUrml.g:9680:2: rule__StringExpression__Group_1__0__Impl
{
pushFollow(FOLLOW_2);
rule__StringExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1__0"
// $ANTLR start "rule__StringExpression__Group_1__0__Impl"
// InternalUrml.g:9686:1: rule__StringExpression__Group_1__0__Impl : ( ( rule__StringExpression__Group_1_0__0 ) ) ;
public final void rule__StringExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9690:1: ( ( ( rule__StringExpression__Group_1_0__0 ) ) )
// InternalUrml.g:9691:1: ( ( rule__StringExpression__Group_1_0__0 ) )
{
// InternalUrml.g:9691:1: ( ( rule__StringExpression__Group_1_0__0 ) )
// InternalUrml.g:9692:1: ( rule__StringExpression__Group_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getGroup_1_0());
}
// InternalUrml.g:9693:1: ( rule__StringExpression__Group_1_0__0 )
// InternalUrml.g:9693:2: rule__StringExpression__Group_1_0__0
{
pushFollow(FOLLOW_2);
rule__StringExpression__Group_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getGroup_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1__0__Impl"
// $ANTLR start "rule__StringExpression__Group_1_0__0"
// InternalUrml.g:9705:1: rule__StringExpression__Group_1_0__0 : rule__StringExpression__Group_1_0__0__Impl rule__StringExpression__Group_1_0__1 ;
public final void rule__StringExpression__Group_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9709:1: ( rule__StringExpression__Group_1_0__0__Impl rule__StringExpression__Group_1_0__1 )
// InternalUrml.g:9710:2: rule__StringExpression__Group_1_0__0__Impl rule__StringExpression__Group_1_0__1
{
pushFollow(FOLLOW_51);
rule__StringExpression__Group_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StringExpression__Group_1_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1_0__0"
// $ANTLR start "rule__StringExpression__Group_1_0__0__Impl"
// InternalUrml.g:9717:1: rule__StringExpression__Group_1_0__0__Impl : ( () ) ;
public final void rule__StringExpression__Group_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9721:1: ( ( () ) )
// InternalUrml.g:9722:1: ( () )
{
// InternalUrml.g:9722:1: ( () )
// InternalUrml.g:9723:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getConcatenateExpressionLeftAction_1_0_0());
}
// InternalUrml.g:9724:1: ()
// InternalUrml.g:9726:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getConcatenateExpressionLeftAction_1_0_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1_0__0__Impl"
// $ANTLR start "rule__StringExpression__Group_1_0__1"
// InternalUrml.g:9736:1: rule__StringExpression__Group_1_0__1 : rule__StringExpression__Group_1_0__1__Impl rule__StringExpression__Group_1_0__2 ;
public final void rule__StringExpression__Group_1_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9740:1: ( rule__StringExpression__Group_1_0__1__Impl rule__StringExpression__Group_1_0__2 )
// InternalUrml.g:9741:2: rule__StringExpression__Group_1_0__1__Impl rule__StringExpression__Group_1_0__2
{
pushFollow(FOLLOW_49);
rule__StringExpression__Group_1_0__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__StringExpression__Group_1_0__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1_0__1"
// $ANTLR start "rule__StringExpression__Group_1_0__1__Impl"
// InternalUrml.g:9748:1: rule__StringExpression__Group_1_0__1__Impl : ( '^' ) ;
public final void rule__StringExpression__Group_1_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9752:1: ( ( '^' ) )
// InternalUrml.g:9753:1: ( '^' )
{
// InternalUrml.g:9753:1: ( '^' )
// InternalUrml.g:9754:1: '^'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getCircumflexAccentKeyword_1_0_1());
}
match(input,60,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getCircumflexAccentKeyword_1_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1_0__1__Impl"
// $ANTLR start "rule__StringExpression__Group_1_0__2"
// InternalUrml.g:9767:1: rule__StringExpression__Group_1_0__2 : rule__StringExpression__Group_1_0__2__Impl ;
public final void rule__StringExpression__Group_1_0__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9771:1: ( rule__StringExpression__Group_1_0__2__Impl )
// InternalUrml.g:9772:2: rule__StringExpression__Group_1_0__2__Impl
{
pushFollow(FOLLOW_2);
rule__StringExpression__Group_1_0__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1_0__2"
// $ANTLR start "rule__StringExpression__Group_1_0__2__Impl"
// InternalUrml.g:9778:1: rule__StringExpression__Group_1_0__2__Impl : ( ( rule__StringExpression__RestAssignment_1_0_2 ) ) ;
public final void rule__StringExpression__Group_1_0__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9782:1: ( ( ( rule__StringExpression__RestAssignment_1_0_2 ) ) )
// InternalUrml.g:9783:1: ( ( rule__StringExpression__RestAssignment_1_0_2 ) )
{
// InternalUrml.g:9783:1: ( ( rule__StringExpression__RestAssignment_1_0_2 ) )
// InternalUrml.g:9784:1: ( rule__StringExpression__RestAssignment_1_0_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getRestAssignment_1_0_2());
}
// InternalUrml.g:9785:1: ( rule__StringExpression__RestAssignment_1_0_2 )
// InternalUrml.g:9785:2: rule__StringExpression__RestAssignment_1_0_2
{
pushFollow(FOLLOW_2);
rule__StringExpression__RestAssignment_1_0_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getRestAssignment_1_0_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__Group_1_0__2__Impl"
// $ANTLR start "rule__ConditionalOrExpression__Group__0"
// InternalUrml.g:9801:1: rule__ConditionalOrExpression__Group__0 : rule__ConditionalOrExpression__Group__0__Impl rule__ConditionalOrExpression__Group__1 ;
public final void rule__ConditionalOrExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9805:1: ( rule__ConditionalOrExpression__Group__0__Impl rule__ConditionalOrExpression__Group__1 )
// InternalUrml.g:9806:2: rule__ConditionalOrExpression__Group__0__Impl rule__ConditionalOrExpression__Group__1
{
pushFollow(FOLLOW_53);
rule__ConditionalOrExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group__0"
// $ANTLR start "rule__ConditionalOrExpression__Group__0__Impl"
// InternalUrml.g:9813:1: rule__ConditionalOrExpression__Group__0__Impl : ( ruleConditionalAndExpression ) ;
public final void rule__ConditionalOrExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9817:1: ( ( ruleConditionalAndExpression ) )
// InternalUrml.g:9818:1: ( ruleConditionalAndExpression )
{
// InternalUrml.g:9818:1: ( ruleConditionalAndExpression )
// InternalUrml.g:9819:1: ruleConditionalAndExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getConditionalAndExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleConditionalAndExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getConditionalAndExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group__0__Impl"
// $ANTLR start "rule__ConditionalOrExpression__Group__1"
// InternalUrml.g:9830:1: rule__ConditionalOrExpression__Group__1 : rule__ConditionalOrExpression__Group__1__Impl ;
public final void rule__ConditionalOrExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9834:1: ( rule__ConditionalOrExpression__Group__1__Impl )
// InternalUrml.g:9835:2: rule__ConditionalOrExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group__1"
// $ANTLR start "rule__ConditionalOrExpression__Group__1__Impl"
// InternalUrml.g:9841:1: rule__ConditionalOrExpression__Group__1__Impl : ( ( rule__ConditionalOrExpression__Group_1__0 )* ) ;
public final void rule__ConditionalOrExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9845:1: ( ( ( rule__ConditionalOrExpression__Group_1__0 )* ) )
// InternalUrml.g:9846:1: ( ( rule__ConditionalOrExpression__Group_1__0 )* )
{
// InternalUrml.g:9846:1: ( ( rule__ConditionalOrExpression__Group_1__0 )* )
// InternalUrml.g:9847:1: ( rule__ConditionalOrExpression__Group_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getGroup_1());
}
// InternalUrml.g:9848:1: ( rule__ConditionalOrExpression__Group_1__0 )*
loop68:
do {
int alt68=2;
int LA68_0 = input.LA(1);
if ( (LA68_0==61) ) {
alt68=1;
}
switch (alt68) {
case 1 :
// InternalUrml.g:9848:2: rule__ConditionalOrExpression__Group_1__0
{
pushFollow(FOLLOW_54);
rule__ConditionalOrExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop68;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group__1__Impl"
// $ANTLR start "rule__ConditionalOrExpression__Group_1__0"
// InternalUrml.g:9862:1: rule__ConditionalOrExpression__Group_1__0 : rule__ConditionalOrExpression__Group_1__0__Impl ;
public final void rule__ConditionalOrExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9866:1: ( rule__ConditionalOrExpression__Group_1__0__Impl )
// InternalUrml.g:9867:2: rule__ConditionalOrExpression__Group_1__0__Impl
{
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1__0"
// $ANTLR start "rule__ConditionalOrExpression__Group_1__0__Impl"
// InternalUrml.g:9873:1: rule__ConditionalOrExpression__Group_1__0__Impl : ( ( rule__ConditionalOrExpression__Group_1_0__0 ) ) ;
public final void rule__ConditionalOrExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9877:1: ( ( ( rule__ConditionalOrExpression__Group_1_0__0 ) ) )
// InternalUrml.g:9878:1: ( ( rule__ConditionalOrExpression__Group_1_0__0 ) )
{
// InternalUrml.g:9878:1: ( ( rule__ConditionalOrExpression__Group_1_0__0 ) )
// InternalUrml.g:9879:1: ( rule__ConditionalOrExpression__Group_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getGroup_1_0());
}
// InternalUrml.g:9880:1: ( rule__ConditionalOrExpression__Group_1_0__0 )
// InternalUrml.g:9880:2: rule__ConditionalOrExpression__Group_1_0__0
{
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getGroup_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1__0__Impl"
// $ANTLR start "rule__ConditionalOrExpression__Group_1_0__0"
// InternalUrml.g:9892:1: rule__ConditionalOrExpression__Group_1_0__0 : rule__ConditionalOrExpression__Group_1_0__0__Impl rule__ConditionalOrExpression__Group_1_0__1 ;
public final void rule__ConditionalOrExpression__Group_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9896:1: ( rule__ConditionalOrExpression__Group_1_0__0__Impl rule__ConditionalOrExpression__Group_1_0__1 )
// InternalUrml.g:9897:2: rule__ConditionalOrExpression__Group_1_0__0__Impl rule__ConditionalOrExpression__Group_1_0__1
{
pushFollow(FOLLOW_53);
rule__ConditionalOrExpression__Group_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group_1_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1_0__0"
// $ANTLR start "rule__ConditionalOrExpression__Group_1_0__0__Impl"
// InternalUrml.g:9904:1: rule__ConditionalOrExpression__Group_1_0__0__Impl : ( () ) ;
public final void rule__ConditionalOrExpression__Group_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9908:1: ( ( () ) )
// InternalUrml.g:9909:1: ( () )
{
// InternalUrml.g:9909:1: ( () )
// InternalUrml.g:9910:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getConditionalOrExpressionLeftAction_1_0_0());
}
// InternalUrml.g:9911:1: ()
// InternalUrml.g:9913:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getConditionalOrExpressionLeftAction_1_0_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1_0__0__Impl"
// $ANTLR start "rule__ConditionalOrExpression__Group_1_0__1"
// InternalUrml.g:9923:1: rule__ConditionalOrExpression__Group_1_0__1 : rule__ConditionalOrExpression__Group_1_0__1__Impl rule__ConditionalOrExpression__Group_1_0__2 ;
public final void rule__ConditionalOrExpression__Group_1_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9927:1: ( rule__ConditionalOrExpression__Group_1_0__1__Impl rule__ConditionalOrExpression__Group_1_0__2 )
// InternalUrml.g:9928:2: rule__ConditionalOrExpression__Group_1_0__1__Impl rule__ConditionalOrExpression__Group_1_0__2
{
pushFollow(FOLLOW_10);
rule__ConditionalOrExpression__Group_1_0__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group_1_0__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1_0__1"
// $ANTLR start "rule__ConditionalOrExpression__Group_1_0__1__Impl"
// InternalUrml.g:9935:1: rule__ConditionalOrExpression__Group_1_0__1__Impl : ( '||' ) ;
public final void rule__ConditionalOrExpression__Group_1_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9939:1: ( ( '||' ) )
// InternalUrml.g:9940:1: ( '||' )
{
// InternalUrml.g:9940:1: ( '||' )
// InternalUrml.g:9941:1: '||'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getVerticalLineVerticalLineKeyword_1_0_1());
}
match(input,61,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getVerticalLineVerticalLineKeyword_1_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1_0__1__Impl"
// $ANTLR start "rule__ConditionalOrExpression__Group_1_0__2"
// InternalUrml.g:9954:1: rule__ConditionalOrExpression__Group_1_0__2 : rule__ConditionalOrExpression__Group_1_0__2__Impl ;
public final void rule__ConditionalOrExpression__Group_1_0__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9958:1: ( rule__ConditionalOrExpression__Group_1_0__2__Impl )
// InternalUrml.g:9959:2: rule__ConditionalOrExpression__Group_1_0__2__Impl
{
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__Group_1_0__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1_0__2"
// $ANTLR start "rule__ConditionalOrExpression__Group_1_0__2__Impl"
// InternalUrml.g:9965:1: rule__ConditionalOrExpression__Group_1_0__2__Impl : ( ( rule__ConditionalOrExpression__RestAssignment_1_0_2 ) ) ;
public final void rule__ConditionalOrExpression__Group_1_0__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9969:1: ( ( ( rule__ConditionalOrExpression__RestAssignment_1_0_2 ) ) )
// InternalUrml.g:9970:1: ( ( rule__ConditionalOrExpression__RestAssignment_1_0_2 ) )
{
// InternalUrml.g:9970:1: ( ( rule__ConditionalOrExpression__RestAssignment_1_0_2 ) )
// InternalUrml.g:9971:1: ( rule__ConditionalOrExpression__RestAssignment_1_0_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getRestAssignment_1_0_2());
}
// InternalUrml.g:9972:1: ( rule__ConditionalOrExpression__RestAssignment_1_0_2 )
// InternalUrml.g:9972:2: rule__ConditionalOrExpression__RestAssignment_1_0_2
{
pushFollow(FOLLOW_2);
rule__ConditionalOrExpression__RestAssignment_1_0_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getRestAssignment_1_0_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__Group_1_0__2__Impl"
// $ANTLR start "rule__ConditionalAndExpression__Group__0"
// InternalUrml.g:9988:1: rule__ConditionalAndExpression__Group__0 : rule__ConditionalAndExpression__Group__0__Impl rule__ConditionalAndExpression__Group__1 ;
public final void rule__ConditionalAndExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:9992:1: ( rule__ConditionalAndExpression__Group__0__Impl rule__ConditionalAndExpression__Group__1 )
// InternalUrml.g:9993:2: rule__ConditionalAndExpression__Group__0__Impl rule__ConditionalAndExpression__Group__1
{
pushFollow(FOLLOW_55);
rule__ConditionalAndExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group__0"
// $ANTLR start "rule__ConditionalAndExpression__Group__0__Impl"
// InternalUrml.g:10000:1: rule__ConditionalAndExpression__Group__0__Impl : ( ruleRelationalOpExpression ) ;
public final void rule__ConditionalAndExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10004:1: ( ( ruleRelationalOpExpression ) )
// InternalUrml.g:10005:1: ( ruleRelationalOpExpression )
{
// InternalUrml.g:10005:1: ( ruleRelationalOpExpression )
// InternalUrml.g:10006:1: ruleRelationalOpExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getRelationalOpExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleRelationalOpExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getRelationalOpExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group__0__Impl"
// $ANTLR start "rule__ConditionalAndExpression__Group__1"
// InternalUrml.g:10017:1: rule__ConditionalAndExpression__Group__1 : rule__ConditionalAndExpression__Group__1__Impl ;
public final void rule__ConditionalAndExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10021:1: ( rule__ConditionalAndExpression__Group__1__Impl )
// InternalUrml.g:10022:2: rule__ConditionalAndExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group__1"
// $ANTLR start "rule__ConditionalAndExpression__Group__1__Impl"
// InternalUrml.g:10028:1: rule__ConditionalAndExpression__Group__1__Impl : ( ( rule__ConditionalAndExpression__Group_1__0 )* ) ;
public final void rule__ConditionalAndExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10032:1: ( ( ( rule__ConditionalAndExpression__Group_1__0 )* ) )
// InternalUrml.g:10033:1: ( ( rule__ConditionalAndExpression__Group_1__0 )* )
{
// InternalUrml.g:10033:1: ( ( rule__ConditionalAndExpression__Group_1__0 )* )
// InternalUrml.g:10034:1: ( rule__ConditionalAndExpression__Group_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getGroup_1());
}
// InternalUrml.g:10035:1: ( rule__ConditionalAndExpression__Group_1__0 )*
loop69:
do {
int alt69=2;
int LA69_0 = input.LA(1);
if ( (LA69_0==62) ) {
alt69=1;
}
switch (alt69) {
case 1 :
// InternalUrml.g:10035:2: rule__ConditionalAndExpression__Group_1__0
{
pushFollow(FOLLOW_56);
rule__ConditionalAndExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop69;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group__1__Impl"
// $ANTLR start "rule__ConditionalAndExpression__Group_1__0"
// InternalUrml.g:10049:1: rule__ConditionalAndExpression__Group_1__0 : rule__ConditionalAndExpression__Group_1__0__Impl ;
public final void rule__ConditionalAndExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10053:1: ( rule__ConditionalAndExpression__Group_1__0__Impl )
// InternalUrml.g:10054:2: rule__ConditionalAndExpression__Group_1__0__Impl
{
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1__0"
// $ANTLR start "rule__ConditionalAndExpression__Group_1__0__Impl"
// InternalUrml.g:10060:1: rule__ConditionalAndExpression__Group_1__0__Impl : ( ( rule__ConditionalAndExpression__Group_1_0__0 ) ) ;
public final void rule__ConditionalAndExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10064:1: ( ( ( rule__ConditionalAndExpression__Group_1_0__0 ) ) )
// InternalUrml.g:10065:1: ( ( rule__ConditionalAndExpression__Group_1_0__0 ) )
{
// InternalUrml.g:10065:1: ( ( rule__ConditionalAndExpression__Group_1_0__0 ) )
// InternalUrml.g:10066:1: ( rule__ConditionalAndExpression__Group_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getGroup_1_0());
}
// InternalUrml.g:10067:1: ( rule__ConditionalAndExpression__Group_1_0__0 )
// InternalUrml.g:10067:2: rule__ConditionalAndExpression__Group_1_0__0
{
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getGroup_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1__0__Impl"
// $ANTLR start "rule__ConditionalAndExpression__Group_1_0__0"
// InternalUrml.g:10079:1: rule__ConditionalAndExpression__Group_1_0__0 : rule__ConditionalAndExpression__Group_1_0__0__Impl rule__ConditionalAndExpression__Group_1_0__1 ;
public final void rule__ConditionalAndExpression__Group_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10083:1: ( rule__ConditionalAndExpression__Group_1_0__0__Impl rule__ConditionalAndExpression__Group_1_0__1 )
// InternalUrml.g:10084:2: rule__ConditionalAndExpression__Group_1_0__0__Impl rule__ConditionalAndExpression__Group_1_0__1
{
pushFollow(FOLLOW_55);
rule__ConditionalAndExpression__Group_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group_1_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1_0__0"
// $ANTLR start "rule__ConditionalAndExpression__Group_1_0__0__Impl"
// InternalUrml.g:10091:1: rule__ConditionalAndExpression__Group_1_0__0__Impl : ( () ) ;
public final void rule__ConditionalAndExpression__Group_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10095:1: ( ( () ) )
// InternalUrml.g:10096:1: ( () )
{
// InternalUrml.g:10096:1: ( () )
// InternalUrml.g:10097:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getConditionalAndExpressionLeftAction_1_0_0());
}
// InternalUrml.g:10098:1: ()
// InternalUrml.g:10100:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getConditionalAndExpressionLeftAction_1_0_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1_0__0__Impl"
// $ANTLR start "rule__ConditionalAndExpression__Group_1_0__1"
// InternalUrml.g:10110:1: rule__ConditionalAndExpression__Group_1_0__1 : rule__ConditionalAndExpression__Group_1_0__1__Impl rule__ConditionalAndExpression__Group_1_0__2 ;
public final void rule__ConditionalAndExpression__Group_1_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10114:1: ( rule__ConditionalAndExpression__Group_1_0__1__Impl rule__ConditionalAndExpression__Group_1_0__2 )
// InternalUrml.g:10115:2: rule__ConditionalAndExpression__Group_1_0__1__Impl rule__ConditionalAndExpression__Group_1_0__2
{
pushFollow(FOLLOW_10);
rule__ConditionalAndExpression__Group_1_0__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group_1_0__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1_0__1"
// $ANTLR start "rule__ConditionalAndExpression__Group_1_0__1__Impl"
// InternalUrml.g:10122:1: rule__ConditionalAndExpression__Group_1_0__1__Impl : ( '&&' ) ;
public final void rule__ConditionalAndExpression__Group_1_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10126:1: ( ( '&&' ) )
// InternalUrml.g:10127:1: ( '&&' )
{
// InternalUrml.g:10127:1: ( '&&' )
// InternalUrml.g:10128:1: '&&'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getAmpersandAmpersandKeyword_1_0_1());
}
match(input,62,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getAmpersandAmpersandKeyword_1_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1_0__1__Impl"
// $ANTLR start "rule__ConditionalAndExpression__Group_1_0__2"
// InternalUrml.g:10141:1: rule__ConditionalAndExpression__Group_1_0__2 : rule__ConditionalAndExpression__Group_1_0__2__Impl ;
public final void rule__ConditionalAndExpression__Group_1_0__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10145:1: ( rule__ConditionalAndExpression__Group_1_0__2__Impl )
// InternalUrml.g:10146:2: rule__ConditionalAndExpression__Group_1_0__2__Impl
{
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__Group_1_0__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1_0__2"
// $ANTLR start "rule__ConditionalAndExpression__Group_1_0__2__Impl"
// InternalUrml.g:10152:1: rule__ConditionalAndExpression__Group_1_0__2__Impl : ( ( rule__ConditionalAndExpression__RestAssignment_1_0_2 ) ) ;
public final void rule__ConditionalAndExpression__Group_1_0__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10156:1: ( ( ( rule__ConditionalAndExpression__RestAssignment_1_0_2 ) ) )
// InternalUrml.g:10157:1: ( ( rule__ConditionalAndExpression__RestAssignment_1_0_2 ) )
{
// InternalUrml.g:10157:1: ( ( rule__ConditionalAndExpression__RestAssignment_1_0_2 ) )
// InternalUrml.g:10158:1: ( rule__ConditionalAndExpression__RestAssignment_1_0_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getRestAssignment_1_0_2());
}
// InternalUrml.g:10159:1: ( rule__ConditionalAndExpression__RestAssignment_1_0_2 )
// InternalUrml.g:10159:2: rule__ConditionalAndExpression__RestAssignment_1_0_2
{
pushFollow(FOLLOW_2);
rule__ConditionalAndExpression__RestAssignment_1_0_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getRestAssignment_1_0_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__Group_1_0__2__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group__0"
// InternalUrml.g:10175:1: rule__RelationalOpExpression__Group__0 : rule__RelationalOpExpression__Group__0__Impl rule__RelationalOpExpression__Group__1 ;
public final void rule__RelationalOpExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10179:1: ( rule__RelationalOpExpression__Group__0__Impl rule__RelationalOpExpression__Group__1 )
// InternalUrml.g:10180:2: rule__RelationalOpExpression__Group__0__Impl rule__RelationalOpExpression__Group__1
{
pushFollow(FOLLOW_57);
rule__RelationalOpExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group__0"
// $ANTLR start "rule__RelationalOpExpression__Group__0__Impl"
// InternalUrml.g:10187:1: rule__RelationalOpExpression__Group__0__Impl : ( ruleAdditiveExpression ) ;
public final void rule__RelationalOpExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10191:1: ( ( ruleAdditiveExpression ) )
// InternalUrml.g:10192:1: ( ruleAdditiveExpression )
{
// InternalUrml.g:10192:1: ( ruleAdditiveExpression )
// InternalUrml.g:10193:1: ruleAdditiveExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getAdditiveExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleAdditiveExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getAdditiveExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group__1"
// InternalUrml.g:10204:1: rule__RelationalOpExpression__Group__1 : rule__RelationalOpExpression__Group__1__Impl ;
public final void rule__RelationalOpExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10208:1: ( rule__RelationalOpExpression__Group__1__Impl )
// InternalUrml.g:10209:2: rule__RelationalOpExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group__1"
// $ANTLR start "rule__RelationalOpExpression__Group__1__Impl"
// InternalUrml.g:10215:1: rule__RelationalOpExpression__Group__1__Impl : ( ( rule__RelationalOpExpression__Group_1__0 )* ) ;
public final void rule__RelationalOpExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10219:1: ( ( ( rule__RelationalOpExpression__Group_1__0 )* ) )
// InternalUrml.g:10220:1: ( ( rule__RelationalOpExpression__Group_1__0 )* )
{
// InternalUrml.g:10220:1: ( ( rule__RelationalOpExpression__Group_1__0 )* )
// InternalUrml.g:10221:1: ( rule__RelationalOpExpression__Group_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1());
}
// InternalUrml.g:10222:1: ( rule__RelationalOpExpression__Group_1__0 )*
loop70:
do {
int alt70=2;
int LA70_0 = input.LA(1);
if ( ((LA70_0>=63 && LA70_0<=68)) ) {
alt70=1;
}
switch (alt70) {
case 1 :
// InternalUrml.g:10222:2: rule__RelationalOpExpression__Group_1__0
{
pushFollow(FOLLOW_58);
rule__RelationalOpExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop70;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1__0"
// InternalUrml.g:10236:1: rule__RelationalOpExpression__Group_1__0 : rule__RelationalOpExpression__Group_1__0__Impl rule__RelationalOpExpression__Group_1__1 ;
public final void rule__RelationalOpExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10240:1: ( rule__RelationalOpExpression__Group_1__0__Impl rule__RelationalOpExpression__Group_1__1 )
// InternalUrml.g:10241:2: rule__RelationalOpExpression__Group_1__0__Impl rule__RelationalOpExpression__Group_1__1
{
pushFollow(FOLLOW_10);
rule__RelationalOpExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1__0__Impl"
// InternalUrml.g:10248:1: rule__RelationalOpExpression__Group_1__0__Impl : ( ( rule__RelationalOpExpression__Group_1_0__0 ) ) ;
public final void rule__RelationalOpExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10252:1: ( ( ( rule__RelationalOpExpression__Group_1_0__0 ) ) )
// InternalUrml.g:10253:1: ( ( rule__RelationalOpExpression__Group_1_0__0 ) )
{
// InternalUrml.g:10253:1: ( ( rule__RelationalOpExpression__Group_1_0__0 ) )
// InternalUrml.g:10254:1: ( rule__RelationalOpExpression__Group_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0());
}
// InternalUrml.g:10255:1: ( rule__RelationalOpExpression__Group_1_0__0 )
// InternalUrml.g:10255:2: rule__RelationalOpExpression__Group_1_0__0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGroup_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1__1"
// InternalUrml.g:10265:1: rule__RelationalOpExpression__Group_1__1 : rule__RelationalOpExpression__Group_1__1__Impl ;
public final void rule__RelationalOpExpression__Group_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10269:1: ( rule__RelationalOpExpression__Group_1__1__Impl )
// InternalUrml.g:10270:2: rule__RelationalOpExpression__Group_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1__1__Impl"
// InternalUrml.g:10276:1: rule__RelationalOpExpression__Group_1__1__Impl : ( ( rule__RelationalOpExpression__RestAssignment_1_1 ) ) ;
public final void rule__RelationalOpExpression__Group_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10280:1: ( ( ( rule__RelationalOpExpression__RestAssignment_1_1 ) ) )
// InternalUrml.g:10281:1: ( ( rule__RelationalOpExpression__RestAssignment_1_1 ) )
{
// InternalUrml.g:10281:1: ( ( rule__RelationalOpExpression__RestAssignment_1_1 ) )
// InternalUrml.g:10282:1: ( rule__RelationalOpExpression__RestAssignment_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getRestAssignment_1_1());
}
// InternalUrml.g:10283:1: ( rule__RelationalOpExpression__RestAssignment_1_1 )
// InternalUrml.g:10283:2: rule__RelationalOpExpression__RestAssignment_1_1
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__RestAssignment_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getRestAssignment_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0__0"
// InternalUrml.g:10297:1: rule__RelationalOpExpression__Group_1_0__0 : rule__RelationalOpExpression__Group_1_0__0__Impl ;
public final void rule__RelationalOpExpression__Group_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10301:1: ( rule__RelationalOpExpression__Group_1_0__0__Impl )
// InternalUrml.g:10302:2: rule__RelationalOpExpression__Group_1_0__0__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0__0__Impl"
// InternalUrml.g:10308:1: rule__RelationalOpExpression__Group_1_0__0__Impl : ( ( rule__RelationalOpExpression__Alternatives_1_0_0 ) ) ;
public final void rule__RelationalOpExpression__Group_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10312:1: ( ( ( rule__RelationalOpExpression__Alternatives_1_0_0 ) ) )
// InternalUrml.g:10313:1: ( ( rule__RelationalOpExpression__Alternatives_1_0_0 ) )
{
// InternalUrml.g:10313:1: ( ( rule__RelationalOpExpression__Alternatives_1_0_0 ) )
// InternalUrml.g:10314:1: ( rule__RelationalOpExpression__Alternatives_1_0_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getAlternatives_1_0_0());
}
// InternalUrml.g:10315:1: ( rule__RelationalOpExpression__Alternatives_1_0_0 )
// InternalUrml.g:10315:2: rule__RelationalOpExpression__Alternatives_1_0_0
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Alternatives_1_0_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getAlternatives_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_0__0"
// InternalUrml.g:10327:1: rule__RelationalOpExpression__Group_1_0_0_0__0 : rule__RelationalOpExpression__Group_1_0_0_0__0__Impl rule__RelationalOpExpression__Group_1_0_0_0__1 ;
public final void rule__RelationalOpExpression__Group_1_0_0_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10331:1: ( rule__RelationalOpExpression__Group_1_0_0_0__0__Impl rule__RelationalOpExpression__Group_1_0_0_0__1 )
// InternalUrml.g:10332:2: rule__RelationalOpExpression__Group_1_0_0_0__0__Impl rule__RelationalOpExpression__Group_1_0_0_0__1
{
pushFollow(FOLLOW_59);
rule__RelationalOpExpression__Group_1_0_0_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_0__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_0__0__Impl"
// InternalUrml.g:10339:1: rule__RelationalOpExpression__Group_1_0_0_0__0__Impl : ( () ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10343:1: ( ( () ) )
// InternalUrml.g:10344:1: ( () )
{
// InternalUrml.g:10344:1: ( () )
// InternalUrml.g:10345:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getLessThanOrEqualLeftAction_1_0_0_0_0());
}
// InternalUrml.g:10346:1: ()
// InternalUrml.g:10348:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getLessThanOrEqualLeftAction_1_0_0_0_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_0__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_0__1"
// InternalUrml.g:10358:1: rule__RelationalOpExpression__Group_1_0_0_0__1 : rule__RelationalOpExpression__Group_1_0_0_0__1__Impl ;
public final void rule__RelationalOpExpression__Group_1_0_0_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10362:1: ( rule__RelationalOpExpression__Group_1_0_0_0__1__Impl )
// InternalUrml.g:10363:2: rule__RelationalOpExpression__Group_1_0_0_0__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_0__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_0__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_0__1__Impl"
// InternalUrml.g:10369:1: rule__RelationalOpExpression__Group_1_0_0_0__1__Impl : ( '<=' ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10373:1: ( ( '<=' ) )
// InternalUrml.g:10374:1: ( '<=' )
{
// InternalUrml.g:10374:1: ( '<=' )
// InternalUrml.g:10375:1: '<='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getLessThanSignEqualsSignKeyword_1_0_0_0_1());
}
match(input,63,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getLessThanSignEqualsSignKeyword_1_0_0_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_0__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_1__0"
// InternalUrml.g:10392:1: rule__RelationalOpExpression__Group_1_0_0_1__0 : rule__RelationalOpExpression__Group_1_0_0_1__0__Impl rule__RelationalOpExpression__Group_1_0_0_1__1 ;
public final void rule__RelationalOpExpression__Group_1_0_0_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10396:1: ( rule__RelationalOpExpression__Group_1_0_0_1__0__Impl rule__RelationalOpExpression__Group_1_0_0_1__1 )
// InternalUrml.g:10397:2: rule__RelationalOpExpression__Group_1_0_0_1__0__Impl rule__RelationalOpExpression__Group_1_0_0_1__1
{
pushFollow(FOLLOW_60);
rule__RelationalOpExpression__Group_1_0_0_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_1__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_1__0__Impl"
// InternalUrml.g:10404:1: rule__RelationalOpExpression__Group_1_0_0_1__0__Impl : ( () ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10408:1: ( ( () ) )
// InternalUrml.g:10409:1: ( () )
{
// InternalUrml.g:10409:1: ( () )
// InternalUrml.g:10410:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getLessThanLeftAction_1_0_0_1_0());
}
// InternalUrml.g:10411:1: ()
// InternalUrml.g:10413:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getLessThanLeftAction_1_0_0_1_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_1__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_1__1"
// InternalUrml.g:10423:1: rule__RelationalOpExpression__Group_1_0_0_1__1 : rule__RelationalOpExpression__Group_1_0_0_1__1__Impl ;
public final void rule__RelationalOpExpression__Group_1_0_0_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10427:1: ( rule__RelationalOpExpression__Group_1_0_0_1__1__Impl )
// InternalUrml.g:10428:2: rule__RelationalOpExpression__Group_1_0_0_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_1__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_1__1__Impl"
// InternalUrml.g:10434:1: rule__RelationalOpExpression__Group_1_0_0_1__1__Impl : ( '<' ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10438:1: ( ( '<' ) )
// InternalUrml.g:10439:1: ( '<' )
{
// InternalUrml.g:10439:1: ( '<' )
// InternalUrml.g:10440:1: '<'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getLessThanSignKeyword_1_0_0_1_1());
}
match(input,64,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getLessThanSignKeyword_1_0_0_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_1__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_2__0"
// InternalUrml.g:10457:1: rule__RelationalOpExpression__Group_1_0_0_2__0 : rule__RelationalOpExpression__Group_1_0_0_2__0__Impl rule__RelationalOpExpression__Group_1_0_0_2__1 ;
public final void rule__RelationalOpExpression__Group_1_0_0_2__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10461:1: ( rule__RelationalOpExpression__Group_1_0_0_2__0__Impl rule__RelationalOpExpression__Group_1_0_0_2__1 )
// InternalUrml.g:10462:2: rule__RelationalOpExpression__Group_1_0_0_2__0__Impl rule__RelationalOpExpression__Group_1_0_0_2__1
{
pushFollow(FOLLOW_61);
rule__RelationalOpExpression__Group_1_0_0_2__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_2__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_2__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_2__0__Impl"
// InternalUrml.g:10469:1: rule__RelationalOpExpression__Group_1_0_0_2__0__Impl : ( () ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_2__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10473:1: ( ( () ) )
// InternalUrml.g:10474:1: ( () )
{
// InternalUrml.g:10474:1: ( () )
// InternalUrml.g:10475:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanOrEqualLeftAction_1_0_0_2_0());
}
// InternalUrml.g:10476:1: ()
// InternalUrml.g:10478:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanOrEqualLeftAction_1_0_0_2_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_2__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_2__1"
// InternalUrml.g:10488:1: rule__RelationalOpExpression__Group_1_0_0_2__1 : rule__RelationalOpExpression__Group_1_0_0_2__1__Impl ;
public final void rule__RelationalOpExpression__Group_1_0_0_2__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10492:1: ( rule__RelationalOpExpression__Group_1_0_0_2__1__Impl )
// InternalUrml.g:10493:2: rule__RelationalOpExpression__Group_1_0_0_2__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_2__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_2__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_2__1__Impl"
// InternalUrml.g:10499:1: rule__RelationalOpExpression__Group_1_0_0_2__1__Impl : ( '>=' ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_2__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10503:1: ( ( '>=' ) )
// InternalUrml.g:10504:1: ( '>=' )
{
// InternalUrml.g:10504:1: ( '>=' )
// InternalUrml.g:10505:1: '>='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanSignEqualsSignKeyword_1_0_0_2_1());
}
match(input,65,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanSignEqualsSignKeyword_1_0_0_2_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_2__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_3__0"
// InternalUrml.g:10522:1: rule__RelationalOpExpression__Group_1_0_0_3__0 : rule__RelationalOpExpression__Group_1_0_0_3__0__Impl rule__RelationalOpExpression__Group_1_0_0_3__1 ;
public final void rule__RelationalOpExpression__Group_1_0_0_3__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10526:1: ( rule__RelationalOpExpression__Group_1_0_0_3__0__Impl rule__RelationalOpExpression__Group_1_0_0_3__1 )
// InternalUrml.g:10527:2: rule__RelationalOpExpression__Group_1_0_0_3__0__Impl rule__RelationalOpExpression__Group_1_0_0_3__1
{
pushFollow(FOLLOW_62);
rule__RelationalOpExpression__Group_1_0_0_3__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_3__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_3__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_3__0__Impl"
// InternalUrml.g:10534:1: rule__RelationalOpExpression__Group_1_0_0_3__0__Impl : ( () ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_3__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10538:1: ( ( () ) )
// InternalUrml.g:10539:1: ( () )
{
// InternalUrml.g:10539:1: ( () )
// InternalUrml.g:10540:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanLeftAction_1_0_0_3_0());
}
// InternalUrml.g:10541:1: ()
// InternalUrml.g:10543:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanLeftAction_1_0_0_3_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_3__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_3__1"
// InternalUrml.g:10553:1: rule__RelationalOpExpression__Group_1_0_0_3__1 : rule__RelationalOpExpression__Group_1_0_0_3__1__Impl ;
public final void rule__RelationalOpExpression__Group_1_0_0_3__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10557:1: ( rule__RelationalOpExpression__Group_1_0_0_3__1__Impl )
// InternalUrml.g:10558:2: rule__RelationalOpExpression__Group_1_0_0_3__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_3__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_3__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_3__1__Impl"
// InternalUrml.g:10564:1: rule__RelationalOpExpression__Group_1_0_0_3__1__Impl : ( '>' ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_3__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10568:1: ( ( '>' ) )
// InternalUrml.g:10569:1: ( '>' )
{
// InternalUrml.g:10569:1: ( '>' )
// InternalUrml.g:10570:1: '>'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanSignKeyword_1_0_0_3_1());
}
match(input,66,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getGreaterThanSignKeyword_1_0_0_3_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_3__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_4__0"
// InternalUrml.g:10587:1: rule__RelationalOpExpression__Group_1_0_0_4__0 : rule__RelationalOpExpression__Group_1_0_0_4__0__Impl rule__RelationalOpExpression__Group_1_0_0_4__1 ;
public final void rule__RelationalOpExpression__Group_1_0_0_4__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10591:1: ( rule__RelationalOpExpression__Group_1_0_0_4__0__Impl rule__RelationalOpExpression__Group_1_0_0_4__1 )
// InternalUrml.g:10592:2: rule__RelationalOpExpression__Group_1_0_0_4__0__Impl rule__RelationalOpExpression__Group_1_0_0_4__1
{
pushFollow(FOLLOW_63);
rule__RelationalOpExpression__Group_1_0_0_4__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_4__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_4__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_4__0__Impl"
// InternalUrml.g:10599:1: rule__RelationalOpExpression__Group_1_0_0_4__0__Impl : ( () ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_4__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10603:1: ( ( () ) )
// InternalUrml.g:10604:1: ( () )
{
// InternalUrml.g:10604:1: ( () )
// InternalUrml.g:10605:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getEqualLeftAction_1_0_0_4_0());
}
// InternalUrml.g:10606:1: ()
// InternalUrml.g:10608:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getEqualLeftAction_1_0_0_4_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_4__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_4__1"
// InternalUrml.g:10618:1: rule__RelationalOpExpression__Group_1_0_0_4__1 : rule__RelationalOpExpression__Group_1_0_0_4__1__Impl ;
public final void rule__RelationalOpExpression__Group_1_0_0_4__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10622:1: ( rule__RelationalOpExpression__Group_1_0_0_4__1__Impl )
// InternalUrml.g:10623:2: rule__RelationalOpExpression__Group_1_0_0_4__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_4__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_4__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_4__1__Impl"
// InternalUrml.g:10629:1: rule__RelationalOpExpression__Group_1_0_0_4__1__Impl : ( '==' ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_4__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10633:1: ( ( '==' ) )
// InternalUrml.g:10634:1: ( '==' )
{
// InternalUrml.g:10634:1: ( '==' )
// InternalUrml.g:10635:1: '=='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getEqualsSignEqualsSignKeyword_1_0_0_4_1());
}
match(input,67,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getEqualsSignEqualsSignKeyword_1_0_0_4_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_4__1__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_5__0"
// InternalUrml.g:10652:1: rule__RelationalOpExpression__Group_1_0_0_5__0 : rule__RelationalOpExpression__Group_1_0_0_5__0__Impl rule__RelationalOpExpression__Group_1_0_0_5__1 ;
public final void rule__RelationalOpExpression__Group_1_0_0_5__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10656:1: ( rule__RelationalOpExpression__Group_1_0_0_5__0__Impl rule__RelationalOpExpression__Group_1_0_0_5__1 )
// InternalUrml.g:10657:2: rule__RelationalOpExpression__Group_1_0_0_5__0__Impl rule__RelationalOpExpression__Group_1_0_0_5__1
{
pushFollow(FOLLOW_57);
rule__RelationalOpExpression__Group_1_0_0_5__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_5__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_5__0"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_5__0__Impl"
// InternalUrml.g:10664:1: rule__RelationalOpExpression__Group_1_0_0_5__0__Impl : ( () ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_5__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10668:1: ( ( () ) )
// InternalUrml.g:10669:1: ( () )
{
// InternalUrml.g:10669:1: ( () )
// InternalUrml.g:10670:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getNotEqualLeftAction_1_0_0_5_0());
}
// InternalUrml.g:10671:1: ()
// InternalUrml.g:10673:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getNotEqualLeftAction_1_0_0_5_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_5__0__Impl"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_5__1"
// InternalUrml.g:10683:1: rule__RelationalOpExpression__Group_1_0_0_5__1 : rule__RelationalOpExpression__Group_1_0_0_5__1__Impl ;
public final void rule__RelationalOpExpression__Group_1_0_0_5__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10687:1: ( rule__RelationalOpExpression__Group_1_0_0_5__1__Impl )
// InternalUrml.g:10688:2: rule__RelationalOpExpression__Group_1_0_0_5__1__Impl
{
pushFollow(FOLLOW_2);
rule__RelationalOpExpression__Group_1_0_0_5__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_5__1"
// $ANTLR start "rule__RelationalOpExpression__Group_1_0_0_5__1__Impl"
// InternalUrml.g:10694:1: rule__RelationalOpExpression__Group_1_0_0_5__1__Impl : ( '!=' ) ;
public final void rule__RelationalOpExpression__Group_1_0_0_5__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10698:1: ( ( '!=' ) )
// InternalUrml.g:10699:1: ( '!=' )
{
// InternalUrml.g:10699:1: ( '!=' )
// InternalUrml.g:10700:1: '!='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getExclamationMarkEqualsSignKeyword_1_0_0_5_1());
}
match(input,68,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getExclamationMarkEqualsSignKeyword_1_0_0_5_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__Group_1_0_0_5__1__Impl"
// $ANTLR start "rule__AdditiveExpression__Group__0"
// InternalUrml.g:10717:1: rule__AdditiveExpression__Group__0 : rule__AdditiveExpression__Group__0__Impl rule__AdditiveExpression__Group__1 ;
public final void rule__AdditiveExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10721:1: ( rule__AdditiveExpression__Group__0__Impl rule__AdditiveExpression__Group__1 )
// InternalUrml.g:10722:2: rule__AdditiveExpression__Group__0__Impl rule__AdditiveExpression__Group__1
{
pushFollow(FOLLOW_64);
rule__AdditiveExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group__0"
// $ANTLR start "rule__AdditiveExpression__Group__0__Impl"
// InternalUrml.g:10729:1: rule__AdditiveExpression__Group__0__Impl : ( ruleMultiplicativeExpression ) ;
public final void rule__AdditiveExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10733:1: ( ( ruleMultiplicativeExpression ) )
// InternalUrml.g:10734:1: ( ruleMultiplicativeExpression )
{
// InternalUrml.g:10734:1: ( ruleMultiplicativeExpression )
// InternalUrml.g:10735:1: ruleMultiplicativeExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getMultiplicativeExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleMultiplicativeExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getMultiplicativeExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group__0__Impl"
// $ANTLR start "rule__AdditiveExpression__Group__1"
// InternalUrml.g:10746:1: rule__AdditiveExpression__Group__1 : rule__AdditiveExpression__Group__1__Impl ;
public final void rule__AdditiveExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10750:1: ( rule__AdditiveExpression__Group__1__Impl )
// InternalUrml.g:10751:2: rule__AdditiveExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group__1"
// $ANTLR start "rule__AdditiveExpression__Group__1__Impl"
// InternalUrml.g:10757:1: rule__AdditiveExpression__Group__1__Impl : ( ( rule__AdditiveExpression__Group_1__0 )* ) ;
public final void rule__AdditiveExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10761:1: ( ( ( rule__AdditiveExpression__Group_1__0 )* ) )
// InternalUrml.g:10762:1: ( ( rule__AdditiveExpression__Group_1__0 )* )
{
// InternalUrml.g:10762:1: ( ( rule__AdditiveExpression__Group_1__0 )* )
// InternalUrml.g:10763:1: ( rule__AdditiveExpression__Group_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getGroup_1());
}
// InternalUrml.g:10764:1: ( rule__AdditiveExpression__Group_1__0 )*
loop71:
do {
int alt71=2;
int LA71_0 = input.LA(1);
if ( ((LA71_0>=69 && LA71_0<=70)) ) {
alt71=1;
}
switch (alt71) {
case 1 :
// InternalUrml.g:10764:2: rule__AdditiveExpression__Group_1__0
{
pushFollow(FOLLOW_65);
rule__AdditiveExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop71;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group__1__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1__0"
// InternalUrml.g:10778:1: rule__AdditiveExpression__Group_1__0 : rule__AdditiveExpression__Group_1__0__Impl rule__AdditiveExpression__Group_1__1 ;
public final void rule__AdditiveExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10782:1: ( rule__AdditiveExpression__Group_1__0__Impl rule__AdditiveExpression__Group_1__1 )
// InternalUrml.g:10783:2: rule__AdditiveExpression__Group_1__0__Impl rule__AdditiveExpression__Group_1__1
{
pushFollow(FOLLOW_10);
rule__AdditiveExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1__0"
// $ANTLR start "rule__AdditiveExpression__Group_1__0__Impl"
// InternalUrml.g:10790:1: rule__AdditiveExpression__Group_1__0__Impl : ( ( rule__AdditiveExpression__Group_1_0__0 ) ) ;
public final void rule__AdditiveExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10794:1: ( ( ( rule__AdditiveExpression__Group_1_0__0 ) ) )
// InternalUrml.g:10795:1: ( ( rule__AdditiveExpression__Group_1_0__0 ) )
{
// InternalUrml.g:10795:1: ( ( rule__AdditiveExpression__Group_1_0__0 ) )
// InternalUrml.g:10796:1: ( rule__AdditiveExpression__Group_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getGroup_1_0());
}
// InternalUrml.g:10797:1: ( rule__AdditiveExpression__Group_1_0__0 )
// InternalUrml.g:10797:2: rule__AdditiveExpression__Group_1_0__0
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getGroup_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1__0__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1__1"
// InternalUrml.g:10807:1: rule__AdditiveExpression__Group_1__1 : rule__AdditiveExpression__Group_1__1__Impl ;
public final void rule__AdditiveExpression__Group_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10811:1: ( rule__AdditiveExpression__Group_1__1__Impl )
// InternalUrml.g:10812:2: rule__AdditiveExpression__Group_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1__1"
// $ANTLR start "rule__AdditiveExpression__Group_1__1__Impl"
// InternalUrml.g:10818:1: rule__AdditiveExpression__Group_1__1__Impl : ( ( rule__AdditiveExpression__RestAssignment_1_1 ) ) ;
public final void rule__AdditiveExpression__Group_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10822:1: ( ( ( rule__AdditiveExpression__RestAssignment_1_1 ) ) )
// InternalUrml.g:10823:1: ( ( rule__AdditiveExpression__RestAssignment_1_1 ) )
{
// InternalUrml.g:10823:1: ( ( rule__AdditiveExpression__RestAssignment_1_1 ) )
// InternalUrml.g:10824:1: ( rule__AdditiveExpression__RestAssignment_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getRestAssignment_1_1());
}
// InternalUrml.g:10825:1: ( rule__AdditiveExpression__RestAssignment_1_1 )
// InternalUrml.g:10825:2: rule__AdditiveExpression__RestAssignment_1_1
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__RestAssignment_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getRestAssignment_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1__1__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1_0__0"
// InternalUrml.g:10839:1: rule__AdditiveExpression__Group_1_0__0 : rule__AdditiveExpression__Group_1_0__0__Impl ;
public final void rule__AdditiveExpression__Group_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10843:1: ( rule__AdditiveExpression__Group_1_0__0__Impl )
// InternalUrml.g:10844:2: rule__AdditiveExpression__Group_1_0__0__Impl
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0__0"
// $ANTLR start "rule__AdditiveExpression__Group_1_0__0__Impl"
// InternalUrml.g:10850:1: rule__AdditiveExpression__Group_1_0__0__Impl : ( ( rule__AdditiveExpression__Alternatives_1_0_0 ) ) ;
public final void rule__AdditiveExpression__Group_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10854:1: ( ( ( rule__AdditiveExpression__Alternatives_1_0_0 ) ) )
// InternalUrml.g:10855:1: ( ( rule__AdditiveExpression__Alternatives_1_0_0 ) )
{
// InternalUrml.g:10855:1: ( ( rule__AdditiveExpression__Alternatives_1_0_0 ) )
// InternalUrml.g:10856:1: ( rule__AdditiveExpression__Alternatives_1_0_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getAlternatives_1_0_0());
}
// InternalUrml.g:10857:1: ( rule__AdditiveExpression__Alternatives_1_0_0 )
// InternalUrml.g:10857:2: rule__AdditiveExpression__Alternatives_1_0_0
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Alternatives_1_0_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getAlternatives_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0__0__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_0__0"
// InternalUrml.g:10869:1: rule__AdditiveExpression__Group_1_0_0_0__0 : rule__AdditiveExpression__Group_1_0_0_0__0__Impl rule__AdditiveExpression__Group_1_0_0_0__1 ;
public final void rule__AdditiveExpression__Group_1_0_0_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10873:1: ( rule__AdditiveExpression__Group_1_0_0_0__0__Impl rule__AdditiveExpression__Group_1_0_0_0__1 )
// InternalUrml.g:10874:2: rule__AdditiveExpression__Group_1_0_0_0__0__Impl rule__AdditiveExpression__Group_1_0_0_0__1
{
pushFollow(FOLLOW_66);
rule__AdditiveExpression__Group_1_0_0_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0_0_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_0__0"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_0__0__Impl"
// InternalUrml.g:10881:1: rule__AdditiveExpression__Group_1_0_0_0__0__Impl : ( () ) ;
public final void rule__AdditiveExpression__Group_1_0_0_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10885:1: ( ( () ) )
// InternalUrml.g:10886:1: ( () )
{
// InternalUrml.g:10886:1: ( () )
// InternalUrml.g:10887:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getPlusLeftAction_1_0_0_0_0());
}
// InternalUrml.g:10888:1: ()
// InternalUrml.g:10890:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getPlusLeftAction_1_0_0_0_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_0__0__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_0__1"
// InternalUrml.g:10900:1: rule__AdditiveExpression__Group_1_0_0_0__1 : rule__AdditiveExpression__Group_1_0_0_0__1__Impl ;
public final void rule__AdditiveExpression__Group_1_0_0_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10904:1: ( rule__AdditiveExpression__Group_1_0_0_0__1__Impl )
// InternalUrml.g:10905:2: rule__AdditiveExpression__Group_1_0_0_0__1__Impl
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0_0_0__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_0__1"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_0__1__Impl"
// InternalUrml.g:10911:1: rule__AdditiveExpression__Group_1_0_0_0__1__Impl : ( '+' ) ;
public final void rule__AdditiveExpression__Group_1_0_0_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10915:1: ( ( '+' ) )
// InternalUrml.g:10916:1: ( '+' )
{
// InternalUrml.g:10916:1: ( '+' )
// InternalUrml.g:10917:1: '+'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getPlusSignKeyword_1_0_0_0_1());
}
match(input,69,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getPlusSignKeyword_1_0_0_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_0__1__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_1__0"
// InternalUrml.g:10934:1: rule__AdditiveExpression__Group_1_0_0_1__0 : rule__AdditiveExpression__Group_1_0_0_1__0__Impl rule__AdditiveExpression__Group_1_0_0_1__1 ;
public final void rule__AdditiveExpression__Group_1_0_0_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10938:1: ( rule__AdditiveExpression__Group_1_0_0_1__0__Impl rule__AdditiveExpression__Group_1_0_0_1__1 )
// InternalUrml.g:10939:2: rule__AdditiveExpression__Group_1_0_0_1__0__Impl rule__AdditiveExpression__Group_1_0_0_1__1
{
pushFollow(FOLLOW_64);
rule__AdditiveExpression__Group_1_0_0_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0_0_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_1__0"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_1__0__Impl"
// InternalUrml.g:10946:1: rule__AdditiveExpression__Group_1_0_0_1__0__Impl : ( () ) ;
public final void rule__AdditiveExpression__Group_1_0_0_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10950:1: ( ( () ) )
// InternalUrml.g:10951:1: ( () )
{
// InternalUrml.g:10951:1: ( () )
// InternalUrml.g:10952:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getMinusLeftAction_1_0_0_1_0());
}
// InternalUrml.g:10953:1: ()
// InternalUrml.g:10955:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getMinusLeftAction_1_0_0_1_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_1__0__Impl"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_1__1"
// InternalUrml.g:10965:1: rule__AdditiveExpression__Group_1_0_0_1__1 : rule__AdditiveExpression__Group_1_0_0_1__1__Impl ;
public final void rule__AdditiveExpression__Group_1_0_0_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10969:1: ( rule__AdditiveExpression__Group_1_0_0_1__1__Impl )
// InternalUrml.g:10970:2: rule__AdditiveExpression__Group_1_0_0_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__AdditiveExpression__Group_1_0_0_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_1__1"
// $ANTLR start "rule__AdditiveExpression__Group_1_0_0_1__1__Impl"
// InternalUrml.g:10976:1: rule__AdditiveExpression__Group_1_0_0_1__1__Impl : ( '-' ) ;
public final void rule__AdditiveExpression__Group_1_0_0_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:10980:1: ( ( '-' ) )
// InternalUrml.g:10981:1: ( '-' )
{
// InternalUrml.g:10981:1: ( '-' )
// InternalUrml.g:10982:1: '-'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getHyphenMinusKeyword_1_0_0_1_1());
}
match(input,70,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getHyphenMinusKeyword_1_0_0_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__Group_1_0_0_1__1__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group__0"
// InternalUrml.g:10999:1: rule__MultiplicativeExpression__Group__0 : rule__MultiplicativeExpression__Group__0__Impl rule__MultiplicativeExpression__Group__1 ;
public final void rule__MultiplicativeExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11003:1: ( rule__MultiplicativeExpression__Group__0__Impl rule__MultiplicativeExpression__Group__1 )
// InternalUrml.g:11004:2: rule__MultiplicativeExpression__Group__0__Impl rule__MultiplicativeExpression__Group__1
{
pushFollow(FOLLOW_67);
rule__MultiplicativeExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group__0"
// $ANTLR start "rule__MultiplicativeExpression__Group__0__Impl"
// InternalUrml.g:11011:1: rule__MultiplicativeExpression__Group__0__Impl : ( ruleUnaryExpression ) ;
public final void rule__MultiplicativeExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11015:1: ( ( ruleUnaryExpression ) )
// InternalUrml.g:11016:1: ( ruleUnaryExpression )
{
// InternalUrml.g:11016:1: ( ruleUnaryExpression )
// InternalUrml.g:11017:1: ruleUnaryExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getUnaryExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleUnaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getUnaryExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group__0__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group__1"
// InternalUrml.g:11028:1: rule__MultiplicativeExpression__Group__1 : rule__MultiplicativeExpression__Group__1__Impl ;
public final void rule__MultiplicativeExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11032:1: ( rule__MultiplicativeExpression__Group__1__Impl )
// InternalUrml.g:11033:2: rule__MultiplicativeExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group__1"
// $ANTLR start "rule__MultiplicativeExpression__Group__1__Impl"
// InternalUrml.g:11039:1: rule__MultiplicativeExpression__Group__1__Impl : ( ( rule__MultiplicativeExpression__Group_1__0 )* ) ;
public final void rule__MultiplicativeExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11043:1: ( ( ( rule__MultiplicativeExpression__Group_1__0 )* ) )
// InternalUrml.g:11044:1: ( ( rule__MultiplicativeExpression__Group_1__0 )* )
{
// InternalUrml.g:11044:1: ( ( rule__MultiplicativeExpression__Group_1__0 )* )
// InternalUrml.g:11045:1: ( rule__MultiplicativeExpression__Group_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1());
}
// InternalUrml.g:11046:1: ( rule__MultiplicativeExpression__Group_1__0 )*
loop72:
do {
int alt72=2;
int LA72_0 = input.LA(1);
if ( ((LA72_0>=71 && LA72_0<=73)) ) {
alt72=1;
}
switch (alt72) {
case 1 :
// InternalUrml.g:11046:2: rule__MultiplicativeExpression__Group_1__0
{
pushFollow(FOLLOW_68);
rule__MultiplicativeExpression__Group_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop72;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group__1__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1__0"
// InternalUrml.g:11060:1: rule__MultiplicativeExpression__Group_1__0 : rule__MultiplicativeExpression__Group_1__0__Impl rule__MultiplicativeExpression__Group_1__1 ;
public final void rule__MultiplicativeExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11064:1: ( rule__MultiplicativeExpression__Group_1__0__Impl rule__MultiplicativeExpression__Group_1__1 )
// InternalUrml.g:11065:2: rule__MultiplicativeExpression__Group_1__0__Impl rule__MultiplicativeExpression__Group_1__1
{
pushFollow(FOLLOW_10);
rule__MultiplicativeExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1__0"
// $ANTLR start "rule__MultiplicativeExpression__Group_1__0__Impl"
// InternalUrml.g:11072:1: rule__MultiplicativeExpression__Group_1__0__Impl : ( ( rule__MultiplicativeExpression__Group_1_0__0 ) ) ;
public final void rule__MultiplicativeExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11076:1: ( ( ( rule__MultiplicativeExpression__Group_1_0__0 ) ) )
// InternalUrml.g:11077:1: ( ( rule__MultiplicativeExpression__Group_1_0__0 ) )
{
// InternalUrml.g:11077:1: ( ( rule__MultiplicativeExpression__Group_1_0__0 ) )
// InternalUrml.g:11078:1: ( rule__MultiplicativeExpression__Group_1_0__0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0());
}
// InternalUrml.g:11079:1: ( rule__MultiplicativeExpression__Group_1_0__0 )
// InternalUrml.g:11079:2: rule__MultiplicativeExpression__Group_1_0__0
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0__0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getGroup_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1__0__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1__1"
// InternalUrml.g:11089:1: rule__MultiplicativeExpression__Group_1__1 : rule__MultiplicativeExpression__Group_1__1__Impl ;
public final void rule__MultiplicativeExpression__Group_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11093:1: ( rule__MultiplicativeExpression__Group_1__1__Impl )
// InternalUrml.g:11094:2: rule__MultiplicativeExpression__Group_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1__1"
// $ANTLR start "rule__MultiplicativeExpression__Group_1__1__Impl"
// InternalUrml.g:11100:1: rule__MultiplicativeExpression__Group_1__1__Impl : ( ( rule__MultiplicativeExpression__RestAssignment_1_1 ) ) ;
public final void rule__MultiplicativeExpression__Group_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11104:1: ( ( ( rule__MultiplicativeExpression__RestAssignment_1_1 ) ) )
// InternalUrml.g:11105:1: ( ( rule__MultiplicativeExpression__RestAssignment_1_1 ) )
{
// InternalUrml.g:11105:1: ( ( rule__MultiplicativeExpression__RestAssignment_1_1 ) )
// InternalUrml.g:11106:1: ( rule__MultiplicativeExpression__RestAssignment_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getRestAssignment_1_1());
}
// InternalUrml.g:11107:1: ( rule__MultiplicativeExpression__RestAssignment_1_1 )
// InternalUrml.g:11107:2: rule__MultiplicativeExpression__RestAssignment_1_1
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__RestAssignment_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getRestAssignment_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1__1__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0__0"
// InternalUrml.g:11121:1: rule__MultiplicativeExpression__Group_1_0__0 : rule__MultiplicativeExpression__Group_1_0__0__Impl ;
public final void rule__MultiplicativeExpression__Group_1_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11125:1: ( rule__MultiplicativeExpression__Group_1_0__0__Impl )
// InternalUrml.g:11126:2: rule__MultiplicativeExpression__Group_1_0__0__Impl
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0__0__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0__0"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0__0__Impl"
// InternalUrml.g:11132:1: rule__MultiplicativeExpression__Group_1_0__0__Impl : ( ( rule__MultiplicativeExpression__Alternatives_1_0_0 ) ) ;
public final void rule__MultiplicativeExpression__Group_1_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11136:1: ( ( ( rule__MultiplicativeExpression__Alternatives_1_0_0 ) ) )
// InternalUrml.g:11137:1: ( ( rule__MultiplicativeExpression__Alternatives_1_0_0 ) )
{
// InternalUrml.g:11137:1: ( ( rule__MultiplicativeExpression__Alternatives_1_0_0 ) )
// InternalUrml.g:11138:1: ( rule__MultiplicativeExpression__Alternatives_1_0_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getAlternatives_1_0_0());
}
// InternalUrml.g:11139:1: ( rule__MultiplicativeExpression__Alternatives_1_0_0 )
// InternalUrml.g:11139:2: rule__MultiplicativeExpression__Alternatives_1_0_0
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Alternatives_1_0_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getAlternatives_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0__0__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_0__0"
// InternalUrml.g:11151:1: rule__MultiplicativeExpression__Group_1_0_0_0__0 : rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl rule__MultiplicativeExpression__Group_1_0_0_0__1 ;
public final void rule__MultiplicativeExpression__Group_1_0_0_0__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11155:1: ( rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl rule__MultiplicativeExpression__Group_1_0_0_0__1 )
// InternalUrml.g:11156:2: rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl rule__MultiplicativeExpression__Group_1_0_0_0__1
{
pushFollow(FOLLOW_69);
rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_0__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_0__0"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl"
// InternalUrml.g:11163:1: rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl : ( () ) ;
public final void rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11167:1: ( ( () ) )
// InternalUrml.g:11168:1: ( () )
{
// InternalUrml.g:11168:1: ( () )
// InternalUrml.g:11169:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getMultiplyLeftAction_1_0_0_0_0());
}
// InternalUrml.g:11170:1: ()
// InternalUrml.g:11172:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getMultiplyLeftAction_1_0_0_0_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_0__0__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_0__1"
// InternalUrml.g:11182:1: rule__MultiplicativeExpression__Group_1_0_0_0__1 : rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl ;
public final void rule__MultiplicativeExpression__Group_1_0_0_0__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11186:1: ( rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl )
// InternalUrml.g:11187:2: rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_0__1"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl"
// InternalUrml.g:11193:1: rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl : ( '*' ) ;
public final void rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11197:1: ( ( '*' ) )
// InternalUrml.g:11198:1: ( '*' )
{
// InternalUrml.g:11198:1: ( '*' )
// InternalUrml.g:11199:1: '*'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getAsteriskKeyword_1_0_0_0_1());
}
match(input,71,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getAsteriskKeyword_1_0_0_0_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_0__1__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_1__0"
// InternalUrml.g:11216:1: rule__MultiplicativeExpression__Group_1_0_0_1__0 : rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl rule__MultiplicativeExpression__Group_1_0_0_1__1 ;
public final void rule__MultiplicativeExpression__Group_1_0_0_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11220:1: ( rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl rule__MultiplicativeExpression__Group_1_0_0_1__1 )
// InternalUrml.g:11221:2: rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl rule__MultiplicativeExpression__Group_1_0_0_1__1
{
pushFollow(FOLLOW_70);
rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_1__0"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl"
// InternalUrml.g:11228:1: rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl : ( () ) ;
public final void rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11232:1: ( ( () ) )
// InternalUrml.g:11233:1: ( () )
{
// InternalUrml.g:11233:1: ( () )
// InternalUrml.g:11234:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getDivideLeftAction_1_0_0_1_0());
}
// InternalUrml.g:11235:1: ()
// InternalUrml.g:11237:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getDivideLeftAction_1_0_0_1_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_1__0__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_1__1"
// InternalUrml.g:11247:1: rule__MultiplicativeExpression__Group_1_0_0_1__1 : rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl ;
public final void rule__MultiplicativeExpression__Group_1_0_0_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11251:1: ( rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl )
// InternalUrml.g:11252:2: rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_1__1"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl"
// InternalUrml.g:11258:1: rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl : ( '/' ) ;
public final void rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11262:1: ( ( '/' ) )
// InternalUrml.g:11263:1: ( '/' )
{
// InternalUrml.g:11263:1: ( '/' )
// InternalUrml.g:11264:1: '/'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getSolidusKeyword_1_0_0_1_1());
}
match(input,72,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getSolidusKeyword_1_0_0_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_1__1__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_2__0"
// InternalUrml.g:11281:1: rule__MultiplicativeExpression__Group_1_0_0_2__0 : rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl rule__MultiplicativeExpression__Group_1_0_0_2__1 ;
public final void rule__MultiplicativeExpression__Group_1_0_0_2__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11285:1: ( rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl rule__MultiplicativeExpression__Group_1_0_0_2__1 )
// InternalUrml.g:11286:2: rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl rule__MultiplicativeExpression__Group_1_0_0_2__1
{
pushFollow(FOLLOW_67);
rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_2__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_2__0"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl"
// InternalUrml.g:11293:1: rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl : ( () ) ;
public final void rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11297:1: ( ( () ) )
// InternalUrml.g:11298:1: ( () )
{
// InternalUrml.g:11298:1: ( () )
// InternalUrml.g:11299:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getModuloLeftAction_1_0_0_2_0());
}
// InternalUrml.g:11300:1: ()
// InternalUrml.g:11302:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getModuloLeftAction_1_0_0_2_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_2__0__Impl"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_2__1"
// InternalUrml.g:11312:1: rule__MultiplicativeExpression__Group_1_0_0_2__1 : rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl ;
public final void rule__MultiplicativeExpression__Group_1_0_0_2__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11316:1: ( rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl )
// InternalUrml.g:11317:2: rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl
{
pushFollow(FOLLOW_2);
rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_2__1"
// $ANTLR start "rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl"
// InternalUrml.g:11323:1: rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl : ( '%' ) ;
public final void rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11327:1: ( ( '%' ) )
// InternalUrml.g:11328:1: ( '%' )
{
// InternalUrml.g:11328:1: ( '%' )
// InternalUrml.g:11329:1: '%'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getPercentSignKeyword_1_0_0_2_1());
}
match(input,73,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getPercentSignKeyword_1_0_0_2_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__Group_1_0_0_2__1__Impl"
// $ANTLR start "rule__UnaryExpression__Group_1__0"
// InternalUrml.g:11346:1: rule__UnaryExpression__Group_1__0 : rule__UnaryExpression__Group_1__0__Impl rule__UnaryExpression__Group_1__1 ;
public final void rule__UnaryExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11350:1: ( rule__UnaryExpression__Group_1__0__Impl rule__UnaryExpression__Group_1__1 )
// InternalUrml.g:11351:2: rule__UnaryExpression__Group_1__0__Impl rule__UnaryExpression__Group_1__1
{
pushFollow(FOLLOW_10);
rule__UnaryExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__UnaryExpression__Group_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Group_1__0"
// $ANTLR start "rule__UnaryExpression__Group_1__0__Impl"
// InternalUrml.g:11358:1: rule__UnaryExpression__Group_1__0__Impl : ( () ) ;
public final void rule__UnaryExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11362:1: ( ( () ) )
// InternalUrml.g:11363:1: ( () )
{
// InternalUrml.g:11363:1: ( () )
// InternalUrml.g:11364:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getUnaryExpressionAction_1_0());
}
// InternalUrml.g:11365:1: ()
// InternalUrml.g:11367:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getUnaryExpressionAction_1_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Group_1__0__Impl"
// $ANTLR start "rule__UnaryExpression__Group_1__1"
// InternalUrml.g:11377:1: rule__UnaryExpression__Group_1__1 : rule__UnaryExpression__Group_1__1__Impl rule__UnaryExpression__Group_1__2 ;
public final void rule__UnaryExpression__Group_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11381:1: ( rule__UnaryExpression__Group_1__1__Impl rule__UnaryExpression__Group_1__2 )
// InternalUrml.g:11382:2: rule__UnaryExpression__Group_1__1__Impl rule__UnaryExpression__Group_1__2
{
pushFollow(FOLLOW_10);
rule__UnaryExpression__Group_1__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__UnaryExpression__Group_1__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Group_1__1"
// $ANTLR start "rule__UnaryExpression__Group_1__1__Impl"
// InternalUrml.g:11389:1: rule__UnaryExpression__Group_1__1__Impl : ( '-' ) ;
public final void rule__UnaryExpression__Group_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11393:1: ( ( '-' ) )
// InternalUrml.g:11394:1: ( '-' )
{
// InternalUrml.g:11394:1: ( '-' )
// InternalUrml.g:11395:1: '-'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getHyphenMinusKeyword_1_1());
}
match(input,70,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getHyphenMinusKeyword_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Group_1__1__Impl"
// $ANTLR start "rule__UnaryExpression__Group_1__2"
// InternalUrml.g:11408:1: rule__UnaryExpression__Group_1__2 : rule__UnaryExpression__Group_1__2__Impl ;
public final void rule__UnaryExpression__Group_1__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11412:1: ( rule__UnaryExpression__Group_1__2__Impl )
// InternalUrml.g:11413:2: rule__UnaryExpression__Group_1__2__Impl
{
pushFollow(FOLLOW_2);
rule__UnaryExpression__Group_1__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Group_1__2"
// $ANTLR start "rule__UnaryExpression__Group_1__2__Impl"
// InternalUrml.g:11419:1: rule__UnaryExpression__Group_1__2__Impl : ( ( rule__UnaryExpression__ExpAssignment_1_2 ) ) ;
public final void rule__UnaryExpression__Group_1__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11423:1: ( ( ( rule__UnaryExpression__ExpAssignment_1_2 ) ) )
// InternalUrml.g:11424:1: ( ( rule__UnaryExpression__ExpAssignment_1_2 ) )
{
// InternalUrml.g:11424:1: ( ( rule__UnaryExpression__ExpAssignment_1_2 ) )
// InternalUrml.g:11425:1: ( rule__UnaryExpression__ExpAssignment_1_2 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getExpAssignment_1_2());
}
// InternalUrml.g:11426:1: ( rule__UnaryExpression__ExpAssignment_1_2 )
// InternalUrml.g:11426:2: rule__UnaryExpression__ExpAssignment_1_2
{
pushFollow(FOLLOW_2);
rule__UnaryExpression__ExpAssignment_1_2();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getExpAssignment_1_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__Group_1__2__Impl"
// $ANTLR start "rule__NotBooleanExpression__Group__0"
// InternalUrml.g:11442:1: rule__NotBooleanExpression__Group__0 : rule__NotBooleanExpression__Group__0__Impl rule__NotBooleanExpression__Group__1 ;
public final void rule__NotBooleanExpression__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11446:1: ( rule__NotBooleanExpression__Group__0__Impl rule__NotBooleanExpression__Group__1 )
// InternalUrml.g:11447:2: rule__NotBooleanExpression__Group__0__Impl rule__NotBooleanExpression__Group__1
{
pushFollow(FOLLOW_10);
rule__NotBooleanExpression__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__NotBooleanExpression__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NotBooleanExpression__Group__0"
// $ANTLR start "rule__NotBooleanExpression__Group__0__Impl"
// InternalUrml.g:11454:1: rule__NotBooleanExpression__Group__0__Impl : ( '!' ) ;
public final void rule__NotBooleanExpression__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11458:1: ( ( '!' ) )
// InternalUrml.g:11459:1: ( '!' )
{
// InternalUrml.g:11459:1: ( '!' )
// InternalUrml.g:11460:1: '!'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNotBooleanExpressionAccess().getExclamationMarkKeyword_0());
}
match(input,74,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getNotBooleanExpressionAccess().getExclamationMarkKeyword_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NotBooleanExpression__Group__0__Impl"
// $ANTLR start "rule__NotBooleanExpression__Group__1"
// InternalUrml.g:11473:1: rule__NotBooleanExpression__Group__1 : rule__NotBooleanExpression__Group__1__Impl ;
public final void rule__NotBooleanExpression__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11477:1: ( rule__NotBooleanExpression__Group__1__Impl )
// InternalUrml.g:11478:2: rule__NotBooleanExpression__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__NotBooleanExpression__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NotBooleanExpression__Group__1"
// $ANTLR start "rule__NotBooleanExpression__Group__1__Impl"
// InternalUrml.g:11484:1: rule__NotBooleanExpression__Group__1__Impl : ( ( rule__NotBooleanExpression__ExpAssignment_1 ) ) ;
public final void rule__NotBooleanExpression__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11488:1: ( ( ( rule__NotBooleanExpression__ExpAssignment_1 ) ) )
// InternalUrml.g:11489:1: ( ( rule__NotBooleanExpression__ExpAssignment_1 ) )
{
// InternalUrml.g:11489:1: ( ( rule__NotBooleanExpression__ExpAssignment_1 ) )
// InternalUrml.g:11490:1: ( rule__NotBooleanExpression__ExpAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNotBooleanExpressionAccess().getExpAssignment_1());
}
// InternalUrml.g:11491:1: ( rule__NotBooleanExpression__ExpAssignment_1 )
// InternalUrml.g:11491:2: rule__NotBooleanExpression__ExpAssignment_1
{
pushFollow(FOLLOW_2);
rule__NotBooleanExpression__ExpAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getNotBooleanExpressionAccess().getExpAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NotBooleanExpression__Group__1__Impl"
// $ANTLR start "rule__PrimaryExpression__Group_1__0"
// InternalUrml.g:11505:1: rule__PrimaryExpression__Group_1__0 : rule__PrimaryExpression__Group_1__0__Impl rule__PrimaryExpression__Group_1__1 ;
public final void rule__PrimaryExpression__Group_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11509:1: ( rule__PrimaryExpression__Group_1__0__Impl rule__PrimaryExpression__Group_1__1 )
// InternalUrml.g:11510:2: rule__PrimaryExpression__Group_1__0__Impl rule__PrimaryExpression__Group_1__1
{
pushFollow(FOLLOW_10);
rule__PrimaryExpression__Group_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__PrimaryExpression__Group_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Group_1__0"
// $ANTLR start "rule__PrimaryExpression__Group_1__0__Impl"
// InternalUrml.g:11517:1: rule__PrimaryExpression__Group_1__0__Impl : ( '(' ) ;
public final void rule__PrimaryExpression__Group_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11521:1: ( ( '(' ) )
// InternalUrml.g:11522:1: ( '(' )
{
// InternalUrml.g:11522:1: ( '(' )
// InternalUrml.g:11523:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionAccess().getLeftParenthesisKeyword_1_0());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionAccess().getLeftParenthesisKeyword_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Group_1__0__Impl"
// $ANTLR start "rule__PrimaryExpression__Group_1__1"
// InternalUrml.g:11536:1: rule__PrimaryExpression__Group_1__1 : rule__PrimaryExpression__Group_1__1__Impl rule__PrimaryExpression__Group_1__2 ;
public final void rule__PrimaryExpression__Group_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11540:1: ( rule__PrimaryExpression__Group_1__1__Impl rule__PrimaryExpression__Group_1__2 )
// InternalUrml.g:11541:2: rule__PrimaryExpression__Group_1__1__Impl rule__PrimaryExpression__Group_1__2
{
pushFollow(FOLLOW_50);
rule__PrimaryExpression__Group_1__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__PrimaryExpression__Group_1__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Group_1__1"
// $ANTLR start "rule__PrimaryExpression__Group_1__1__Impl"
// InternalUrml.g:11548:1: rule__PrimaryExpression__Group_1__1__Impl : ( ruleExpression ) ;
public final void rule__PrimaryExpression__Group_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11552:1: ( ( ruleExpression ) )
// InternalUrml.g:11553:1: ( ruleExpression )
{
// InternalUrml.g:11553:1: ( ruleExpression )
// InternalUrml.g:11554:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionAccess().getExpressionParserRuleCall_1_1());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionAccess().getExpressionParserRuleCall_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Group_1__1__Impl"
// $ANTLR start "rule__PrimaryExpression__Group_1__2"
// InternalUrml.g:11565:1: rule__PrimaryExpression__Group_1__2 : rule__PrimaryExpression__Group_1__2__Impl ;
public final void rule__PrimaryExpression__Group_1__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11569:1: ( rule__PrimaryExpression__Group_1__2__Impl )
// InternalUrml.g:11570:2: rule__PrimaryExpression__Group_1__2__Impl
{
pushFollow(FOLLOW_2);
rule__PrimaryExpression__Group_1__2__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Group_1__2"
// $ANTLR start "rule__PrimaryExpression__Group_1__2__Impl"
// InternalUrml.g:11576:1: rule__PrimaryExpression__Group_1__2__Impl : ( ')' ) ;
public final void rule__PrimaryExpression__Group_1__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11580:1: ( ( ')' ) )
// InternalUrml.g:11581:1: ( ')' )
{
// InternalUrml.g:11581:1: ( ')' )
// InternalUrml.g:11582:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPrimaryExpressionAccess().getRightParenthesisKeyword_1_2());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPrimaryExpressionAccess().getRightParenthesisKeyword_1_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__PrimaryExpression__Group_1__2__Impl"
// $ANTLR start "rule__IntLiteral__Group__0"
// InternalUrml.g:11601:1: rule__IntLiteral__Group__0 : rule__IntLiteral__Group__0__Impl rule__IntLiteral__Group__1 ;
public final void rule__IntLiteral__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11605:1: ( rule__IntLiteral__Group__0__Impl rule__IntLiteral__Group__1 )
// InternalUrml.g:11606:2: rule__IntLiteral__Group__0__Impl rule__IntLiteral__Group__1
{
pushFollow(FOLLOW_71);
rule__IntLiteral__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__IntLiteral__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IntLiteral__Group__0"
// $ANTLR start "rule__IntLiteral__Group__0__Impl"
// InternalUrml.g:11613:1: rule__IntLiteral__Group__0__Impl : ( () ) ;
public final void rule__IntLiteral__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11617:1: ( ( () ) )
// InternalUrml.g:11618:1: ( () )
{
// InternalUrml.g:11618:1: ( () )
// InternalUrml.g:11619:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntLiteralAccess().getIntLiteralAction_0());
}
// InternalUrml.g:11620:1: ()
// InternalUrml.g:11622:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIntLiteralAccess().getIntLiteralAction_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IntLiteral__Group__0__Impl"
// $ANTLR start "rule__IntLiteral__Group__1"
// InternalUrml.g:11632:1: rule__IntLiteral__Group__1 : rule__IntLiteral__Group__1__Impl ;
public final void rule__IntLiteral__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11636:1: ( rule__IntLiteral__Group__1__Impl )
// InternalUrml.g:11637:2: rule__IntLiteral__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__IntLiteral__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IntLiteral__Group__1"
// $ANTLR start "rule__IntLiteral__Group__1__Impl"
// InternalUrml.g:11643:1: rule__IntLiteral__Group__1__Impl : ( ( rule__IntLiteral__IntAssignment_1 ) ) ;
public final void rule__IntLiteral__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11647:1: ( ( ( rule__IntLiteral__IntAssignment_1 ) ) )
// InternalUrml.g:11648:1: ( ( rule__IntLiteral__IntAssignment_1 ) )
{
// InternalUrml.g:11648:1: ( ( rule__IntLiteral__IntAssignment_1 ) )
// InternalUrml.g:11649:1: ( rule__IntLiteral__IntAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntLiteralAccess().getIntAssignment_1());
}
// InternalUrml.g:11650:1: ( rule__IntLiteral__IntAssignment_1 )
// InternalUrml.g:11650:2: rule__IntLiteral__IntAssignment_1
{
pushFollow(FOLLOW_2);
rule__IntLiteral__IntAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIntLiteralAccess().getIntAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IntLiteral__Group__1__Impl"
// $ANTLR start "rule__FunctionCall__Group__0"
// InternalUrml.g:11664:1: rule__FunctionCall__Group__0 : rule__FunctionCall__Group__0__Impl rule__FunctionCall__Group__1 ;
public final void rule__FunctionCall__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11668:1: ( rule__FunctionCall__Group__0__Impl rule__FunctionCall__Group__1 )
// InternalUrml.g:11669:2: rule__FunctionCall__Group__0__Impl rule__FunctionCall__Group__1
{
pushFollow(FOLLOW_72);
rule__FunctionCall__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FunctionCall__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__0"
// $ANTLR start "rule__FunctionCall__Group__0__Impl"
// InternalUrml.g:11676:1: rule__FunctionCall__Group__0__Impl : ( () ) ;
public final void rule__FunctionCall__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11680:1: ( ( () ) )
// InternalUrml.g:11681:1: ( () )
{
// InternalUrml.g:11681:1: ( () )
// InternalUrml.g:11682:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getFunctionCallAction_0());
}
// InternalUrml.g:11683:1: ()
// InternalUrml.g:11685:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getFunctionCallAction_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__0__Impl"
// $ANTLR start "rule__FunctionCall__Group__1"
// InternalUrml.g:11695:1: rule__FunctionCall__Group__1 : rule__FunctionCall__Group__1__Impl rule__FunctionCall__Group__2 ;
public final void rule__FunctionCall__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11699:1: ( rule__FunctionCall__Group__1__Impl rule__FunctionCall__Group__2 )
// InternalUrml.g:11700:2: rule__FunctionCall__Group__1__Impl rule__FunctionCall__Group__2
{
pushFollow(FOLLOW_15);
rule__FunctionCall__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FunctionCall__Group__2();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__1"
// $ANTLR start "rule__FunctionCall__Group__1__Impl"
// InternalUrml.g:11707:1: rule__FunctionCall__Group__1__Impl : ( ( rule__FunctionCall__CallAssignment_1 ) ) ;
public final void rule__FunctionCall__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11711:1: ( ( ( rule__FunctionCall__CallAssignment_1 ) ) )
// InternalUrml.g:11712:1: ( ( rule__FunctionCall__CallAssignment_1 ) )
{
// InternalUrml.g:11712:1: ( ( rule__FunctionCall__CallAssignment_1 ) )
// InternalUrml.g:11713:1: ( rule__FunctionCall__CallAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getCallAssignment_1());
}
// InternalUrml.g:11714:1: ( rule__FunctionCall__CallAssignment_1 )
// InternalUrml.g:11714:2: rule__FunctionCall__CallAssignment_1
{
pushFollow(FOLLOW_2);
rule__FunctionCall__CallAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getCallAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__1__Impl"
// $ANTLR start "rule__FunctionCall__Group__2"
// InternalUrml.g:11724:1: rule__FunctionCall__Group__2 : rule__FunctionCall__Group__2__Impl rule__FunctionCall__Group__3 ;
public final void rule__FunctionCall__Group__2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11728:1: ( rule__FunctionCall__Group__2__Impl rule__FunctionCall__Group__3 )
// InternalUrml.g:11729:2: rule__FunctionCall__Group__2__Impl rule__FunctionCall__Group__3
{
pushFollow(FOLLOW_42);
rule__FunctionCall__Group__2__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FunctionCall__Group__3();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__2"
// $ANTLR start "rule__FunctionCall__Group__2__Impl"
// InternalUrml.g:11736:1: rule__FunctionCall__Group__2__Impl : ( '(' ) ;
public final void rule__FunctionCall__Group__2__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11740:1: ( ( '(' ) )
// InternalUrml.g:11741:1: ( '(' )
{
// InternalUrml.g:11741:1: ( '(' )
// InternalUrml.g:11742:1: '('
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getLeftParenthesisKeyword_2());
}
match(input,20,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getLeftParenthesisKeyword_2());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__2__Impl"
// $ANTLR start "rule__FunctionCall__Group__3"
// InternalUrml.g:11755:1: rule__FunctionCall__Group__3 : rule__FunctionCall__Group__3__Impl rule__FunctionCall__Group__4 ;
public final void rule__FunctionCall__Group__3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11759:1: ( rule__FunctionCall__Group__3__Impl rule__FunctionCall__Group__4 )
// InternalUrml.g:11760:2: rule__FunctionCall__Group__3__Impl rule__FunctionCall__Group__4
{
pushFollow(FOLLOW_42);
rule__FunctionCall__Group__3__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FunctionCall__Group__4();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__3"
// $ANTLR start "rule__FunctionCall__Group__3__Impl"
// InternalUrml.g:11767:1: rule__FunctionCall__Group__3__Impl : ( ( rule__FunctionCall__Group_3__0 )? ) ;
public final void rule__FunctionCall__Group__3__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11771:1: ( ( ( rule__FunctionCall__Group_3__0 )? ) )
// InternalUrml.g:11772:1: ( ( rule__FunctionCall__Group_3__0 )? )
{
// InternalUrml.g:11772:1: ( ( rule__FunctionCall__Group_3__0 )? )
// InternalUrml.g:11773:1: ( rule__FunctionCall__Group_3__0 )?
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getGroup_3());
}
// InternalUrml.g:11774:1: ( rule__FunctionCall__Group_3__0 )?
int alt73=2;
int LA73_0 = input.LA(1);
if ( (LA73_0==RULE_ID||(LA73_0>=RULE_INT && LA73_0<=RULE_BOOLEAN)||LA73_0==20||LA73_0==70||LA73_0==74) ) {
alt73=1;
}
switch (alt73) {
case 1 :
// InternalUrml.g:11774:2: rule__FunctionCall__Group_3__0
{
pushFollow(FOLLOW_2);
rule__FunctionCall__Group_3__0();
state._fsp--;
if (state.failed) return ;
}
break;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getGroup_3());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__3__Impl"
// $ANTLR start "rule__FunctionCall__Group__4"
// InternalUrml.g:11784:1: rule__FunctionCall__Group__4 : rule__FunctionCall__Group__4__Impl ;
public final void rule__FunctionCall__Group__4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11788:1: ( rule__FunctionCall__Group__4__Impl )
// InternalUrml.g:11789:2: rule__FunctionCall__Group__4__Impl
{
pushFollow(FOLLOW_2);
rule__FunctionCall__Group__4__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__4"
// $ANTLR start "rule__FunctionCall__Group__4__Impl"
// InternalUrml.g:11795:1: rule__FunctionCall__Group__4__Impl : ( ')' ) ;
public final void rule__FunctionCall__Group__4__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11799:1: ( ( ')' ) )
// InternalUrml.g:11800:1: ( ')' )
{
// InternalUrml.g:11800:1: ( ')' )
// InternalUrml.g:11801:1: ')'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getRightParenthesisKeyword_4());
}
match(input,21,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getRightParenthesisKeyword_4());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group__4__Impl"
// $ANTLR start "rule__FunctionCall__Group_3__0"
// InternalUrml.g:11824:1: rule__FunctionCall__Group_3__0 : rule__FunctionCall__Group_3__0__Impl rule__FunctionCall__Group_3__1 ;
public final void rule__FunctionCall__Group_3__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11828:1: ( rule__FunctionCall__Group_3__0__Impl rule__FunctionCall__Group_3__1 )
// InternalUrml.g:11829:2: rule__FunctionCall__Group_3__0__Impl rule__FunctionCall__Group_3__1
{
pushFollow(FOLLOW_17);
rule__FunctionCall__Group_3__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FunctionCall__Group_3__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3__0"
// $ANTLR start "rule__FunctionCall__Group_3__0__Impl"
// InternalUrml.g:11836:1: rule__FunctionCall__Group_3__0__Impl : ( ( rule__FunctionCall__ParamsAssignment_3_0 ) ) ;
public final void rule__FunctionCall__Group_3__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11840:1: ( ( ( rule__FunctionCall__ParamsAssignment_3_0 ) ) )
// InternalUrml.g:11841:1: ( ( rule__FunctionCall__ParamsAssignment_3_0 ) )
{
// InternalUrml.g:11841:1: ( ( rule__FunctionCall__ParamsAssignment_3_0 ) )
// InternalUrml.g:11842:1: ( rule__FunctionCall__ParamsAssignment_3_0 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getParamsAssignment_3_0());
}
// InternalUrml.g:11843:1: ( rule__FunctionCall__ParamsAssignment_3_0 )
// InternalUrml.g:11843:2: rule__FunctionCall__ParamsAssignment_3_0
{
pushFollow(FOLLOW_2);
rule__FunctionCall__ParamsAssignment_3_0();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getParamsAssignment_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3__0__Impl"
// $ANTLR start "rule__FunctionCall__Group_3__1"
// InternalUrml.g:11853:1: rule__FunctionCall__Group_3__1 : rule__FunctionCall__Group_3__1__Impl ;
public final void rule__FunctionCall__Group_3__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11857:1: ( rule__FunctionCall__Group_3__1__Impl )
// InternalUrml.g:11858:2: rule__FunctionCall__Group_3__1__Impl
{
pushFollow(FOLLOW_2);
rule__FunctionCall__Group_3__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3__1"
// $ANTLR start "rule__FunctionCall__Group_3__1__Impl"
// InternalUrml.g:11864:1: rule__FunctionCall__Group_3__1__Impl : ( ( rule__FunctionCall__Group_3_1__0 )* ) ;
public final void rule__FunctionCall__Group_3__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11868:1: ( ( ( rule__FunctionCall__Group_3_1__0 )* ) )
// InternalUrml.g:11869:1: ( ( rule__FunctionCall__Group_3_1__0 )* )
{
// InternalUrml.g:11869:1: ( ( rule__FunctionCall__Group_3_1__0 )* )
// InternalUrml.g:11870:1: ( rule__FunctionCall__Group_3_1__0 )*
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getGroup_3_1());
}
// InternalUrml.g:11871:1: ( rule__FunctionCall__Group_3_1__0 )*
loop74:
do {
int alt74=2;
int LA74_0 = input.LA(1);
if ( (LA74_0==22) ) {
alt74=1;
}
switch (alt74) {
case 1 :
// InternalUrml.g:11871:2: rule__FunctionCall__Group_3_1__0
{
pushFollow(FOLLOW_18);
rule__FunctionCall__Group_3_1__0();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop74;
}
} while (true);
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getGroup_3_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3__1__Impl"
// $ANTLR start "rule__FunctionCall__Group_3_1__0"
// InternalUrml.g:11885:1: rule__FunctionCall__Group_3_1__0 : rule__FunctionCall__Group_3_1__0__Impl rule__FunctionCall__Group_3_1__1 ;
public final void rule__FunctionCall__Group_3_1__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11889:1: ( rule__FunctionCall__Group_3_1__0__Impl rule__FunctionCall__Group_3_1__1 )
// InternalUrml.g:11890:2: rule__FunctionCall__Group_3_1__0__Impl rule__FunctionCall__Group_3_1__1
{
pushFollow(FOLLOW_10);
rule__FunctionCall__Group_3_1__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__FunctionCall__Group_3_1__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3_1__0"
// $ANTLR start "rule__FunctionCall__Group_3_1__0__Impl"
// InternalUrml.g:11897:1: rule__FunctionCall__Group_3_1__0__Impl : ( ',' ) ;
public final void rule__FunctionCall__Group_3_1__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11901:1: ( ( ',' ) )
// InternalUrml.g:11902:1: ( ',' )
{
// InternalUrml.g:11902:1: ( ',' )
// InternalUrml.g:11903:1: ','
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getCommaKeyword_3_1_0());
}
match(input,22,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getCommaKeyword_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3_1__0__Impl"
// $ANTLR start "rule__FunctionCall__Group_3_1__1"
// InternalUrml.g:11916:1: rule__FunctionCall__Group_3_1__1 : rule__FunctionCall__Group_3_1__1__Impl ;
public final void rule__FunctionCall__Group_3_1__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11920:1: ( rule__FunctionCall__Group_3_1__1__Impl )
// InternalUrml.g:11921:2: rule__FunctionCall__Group_3_1__1__Impl
{
pushFollow(FOLLOW_2);
rule__FunctionCall__Group_3_1__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3_1__1"
// $ANTLR start "rule__FunctionCall__Group_3_1__1__Impl"
// InternalUrml.g:11927:1: rule__FunctionCall__Group_3_1__1__Impl : ( ( rule__FunctionCall__ParamsAssignment_3_1_1 ) ) ;
public final void rule__FunctionCall__Group_3_1__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11931:1: ( ( ( rule__FunctionCall__ParamsAssignment_3_1_1 ) ) )
// InternalUrml.g:11932:1: ( ( rule__FunctionCall__ParamsAssignment_3_1_1 ) )
{
// InternalUrml.g:11932:1: ( ( rule__FunctionCall__ParamsAssignment_3_1_1 ) )
// InternalUrml.g:11933:1: ( rule__FunctionCall__ParamsAssignment_3_1_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getParamsAssignment_3_1_1());
}
// InternalUrml.g:11934:1: ( rule__FunctionCall__ParamsAssignment_3_1_1 )
// InternalUrml.g:11934:2: rule__FunctionCall__ParamsAssignment_3_1_1
{
pushFollow(FOLLOW_2);
rule__FunctionCall__ParamsAssignment_3_1_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getParamsAssignment_3_1_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__Group_3_1__1__Impl"
// $ANTLR start "rule__BoolLiteral__Group__0"
// InternalUrml.g:11948:1: rule__BoolLiteral__Group__0 : rule__BoolLiteral__Group__0__Impl rule__BoolLiteral__Group__1 ;
public final void rule__BoolLiteral__Group__0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11952:1: ( rule__BoolLiteral__Group__0__Impl rule__BoolLiteral__Group__1 )
// InternalUrml.g:11953:2: rule__BoolLiteral__Group__0__Impl rule__BoolLiteral__Group__1
{
pushFollow(FOLLOW_73);
rule__BoolLiteral__Group__0__Impl();
state._fsp--;
if (state.failed) return ;
pushFollow(FOLLOW_2);
rule__BoolLiteral__Group__1();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__BoolLiteral__Group__0"
// $ANTLR start "rule__BoolLiteral__Group__0__Impl"
// InternalUrml.g:11960:1: rule__BoolLiteral__Group__0__Impl : ( () ) ;
public final void rule__BoolLiteral__Group__0__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11964:1: ( ( () ) )
// InternalUrml.g:11965:1: ( () )
{
// InternalUrml.g:11965:1: ( () )
// InternalUrml.g:11966:1: ()
{
if ( state.backtracking==0 ) {
before(grammarAccess.getBoolLiteralAccess().getBoolLiteralAction_0());
}
// InternalUrml.g:11967:1: ()
// InternalUrml.g:11969:1:
{
}
if ( state.backtracking==0 ) {
after(grammarAccess.getBoolLiteralAccess().getBoolLiteralAction_0());
}
}
}
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__BoolLiteral__Group__0__Impl"
// $ANTLR start "rule__BoolLiteral__Group__1"
// InternalUrml.g:11979:1: rule__BoolLiteral__Group__1 : rule__BoolLiteral__Group__1__Impl ;
public final void rule__BoolLiteral__Group__1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11983:1: ( rule__BoolLiteral__Group__1__Impl )
// InternalUrml.g:11984:2: rule__BoolLiteral__Group__1__Impl
{
pushFollow(FOLLOW_2);
rule__BoolLiteral__Group__1__Impl();
state._fsp--;
if (state.failed) return ;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__BoolLiteral__Group__1"
// $ANTLR start "rule__BoolLiteral__Group__1__Impl"
// InternalUrml.g:11990:1: rule__BoolLiteral__Group__1__Impl : ( ( rule__BoolLiteral__TrueAssignment_1 ) ) ;
public final void rule__BoolLiteral__Group__1__Impl() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:11994:1: ( ( ( rule__BoolLiteral__TrueAssignment_1 ) ) )
// InternalUrml.g:11995:1: ( ( rule__BoolLiteral__TrueAssignment_1 ) )
{
// InternalUrml.g:11995:1: ( ( rule__BoolLiteral__TrueAssignment_1 ) )
// InternalUrml.g:11996:1: ( rule__BoolLiteral__TrueAssignment_1 )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getBoolLiteralAccess().getTrueAssignment_1());
}
// InternalUrml.g:11997:1: ( rule__BoolLiteral__TrueAssignment_1 )
// InternalUrml.g:11997:2: rule__BoolLiteral__TrueAssignment_1
{
pushFollow(FOLLOW_2);
rule__BoolLiteral__TrueAssignment_1();
state._fsp--;
if (state.failed) return ;
}
if ( state.backtracking==0 ) {
after(grammarAccess.getBoolLiteralAccess().getTrueAssignment_1());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__BoolLiteral__Group__1__Impl"
// $ANTLR start "rule__Model__NameAssignment_1"
// InternalUrml.g:12012:1: rule__Model__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__Model__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12016:1: ( ( RULE_ID ) )
// InternalUrml.g:12017:1: ( RULE_ID )
{
// InternalUrml.g:12017:1: ( RULE_ID )
// InternalUrml.g:12018:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__NameAssignment_1"
// $ANTLR start "rule__Model__CapsulesAssignment_3_0"
// InternalUrml.g:12027:1: rule__Model__CapsulesAssignment_3_0 : ( ruleCapsule ) ;
public final void rule__Model__CapsulesAssignment_3_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12031:1: ( ( ruleCapsule ) )
// InternalUrml.g:12032:1: ( ruleCapsule )
{
// InternalUrml.g:12032:1: ( ruleCapsule )
// InternalUrml.g:12033:1: ruleCapsule
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getCapsulesCapsuleParserRuleCall_3_0_0());
}
pushFollow(FOLLOW_2);
ruleCapsule();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getCapsulesCapsuleParserRuleCall_3_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__CapsulesAssignment_3_0"
// $ANTLR start "rule__Model__ProtocolsAssignment_3_1"
// InternalUrml.g:12042:1: rule__Model__ProtocolsAssignment_3_1 : ( ruleProtocol ) ;
public final void rule__Model__ProtocolsAssignment_3_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12046:1: ( ( ruleProtocol ) )
// InternalUrml.g:12047:1: ( ruleProtocol )
{
// InternalUrml.g:12047:1: ( ruleProtocol )
// InternalUrml.g:12048:1: ruleProtocol
{
if ( state.backtracking==0 ) {
before(grammarAccess.getModelAccess().getProtocolsProtocolParserRuleCall_3_1_0());
}
pushFollow(FOLLOW_2);
ruleProtocol();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getModelAccess().getProtocolsProtocolParserRuleCall_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Model__ProtocolsAssignment_3_1"
// $ANTLR start "rule__LocalVar__IsBoolAssignment_0_0"
// InternalUrml.g:12057:1: rule__LocalVar__IsBoolAssignment_0_0 : ( ( 'bool' ) ) ;
public final void rule__LocalVar__IsBoolAssignment_0_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12061:1: ( ( ( 'bool' ) ) )
// InternalUrml.g:12062:1: ( ( 'bool' ) )
{
// InternalUrml.g:12062:1: ( ( 'bool' ) )
// InternalUrml.g:12063:1: ( 'bool' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getIsBoolBoolKeyword_0_0_0());
}
// InternalUrml.g:12064:1: ( 'bool' )
// InternalUrml.g:12065:1: 'bool'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getIsBoolBoolKeyword_0_0_0());
}
match(input,75,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getIsBoolBoolKeyword_0_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getIsBoolBoolKeyword_0_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__IsBoolAssignment_0_0"
// $ANTLR start "rule__LocalVar__IsIntAssignment_0_1"
// InternalUrml.g:12080:1: rule__LocalVar__IsIntAssignment_0_1 : ( ( 'int' ) ) ;
public final void rule__LocalVar__IsIntAssignment_0_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12084:1: ( ( ( 'int' ) ) )
// InternalUrml.g:12085:1: ( ( 'int' ) )
{
// InternalUrml.g:12085:1: ( ( 'int' ) )
// InternalUrml.g:12086:1: ( 'int' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getIsIntIntKeyword_0_1_0());
}
// InternalUrml.g:12087:1: ( 'int' )
// InternalUrml.g:12088:1: 'int'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getIsIntIntKeyword_0_1_0());
}
match(input,76,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getIsIntIntKeyword_0_1_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getIsIntIntKeyword_0_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__IsIntAssignment_0_1"
// $ANTLR start "rule__LocalVar__NameAssignment_1"
// InternalUrml.g:12103:1: rule__LocalVar__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__LocalVar__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12107:1: ( ( RULE_ID ) )
// InternalUrml.g:12108:1: ( RULE_ID )
{
// InternalUrml.g:12108:1: ( RULE_ID )
// InternalUrml.g:12109:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLocalVarAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLocalVarAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LocalVar__NameAssignment_1"
// $ANTLR start "rule__Attribute__IsBoolAssignment_1_0"
// InternalUrml.g:12118:1: rule__Attribute__IsBoolAssignment_1_0 : ( ( 'bool' ) ) ;
public final void rule__Attribute__IsBoolAssignment_1_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12122:1: ( ( ( 'bool' ) ) )
// InternalUrml.g:12123:1: ( ( 'bool' ) )
{
// InternalUrml.g:12123:1: ( ( 'bool' ) )
// InternalUrml.g:12124:1: ( 'bool' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getIsBoolBoolKeyword_1_0_0());
}
// InternalUrml.g:12125:1: ( 'bool' )
// InternalUrml.g:12126:1: 'bool'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getIsBoolBoolKeyword_1_0_0());
}
match(input,75,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getIsBoolBoolKeyword_1_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getIsBoolBoolKeyword_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__IsBoolAssignment_1_0"
// $ANTLR start "rule__Attribute__IsIntAssignment_1_1"
// InternalUrml.g:12141:1: rule__Attribute__IsIntAssignment_1_1 : ( ( 'int' ) ) ;
public final void rule__Attribute__IsIntAssignment_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12145:1: ( ( ( 'int' ) ) )
// InternalUrml.g:12146:1: ( ( 'int' ) )
{
// InternalUrml.g:12146:1: ( ( 'int' ) )
// InternalUrml.g:12147:1: ( 'int' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getIsIntIntKeyword_1_1_0());
}
// InternalUrml.g:12148:1: ( 'int' )
// InternalUrml.g:12149:1: 'int'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getIsIntIntKeyword_1_1_0());
}
match(input,76,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getIsIntIntKeyword_1_1_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getIsIntIntKeyword_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__IsIntAssignment_1_1"
// $ANTLR start "rule__Attribute__NameAssignment_2"
// InternalUrml.g:12164:1: rule__Attribute__NameAssignment_2 : ( RULE_ID ) ;
public final void rule__Attribute__NameAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12168:1: ( ( RULE_ID ) )
// InternalUrml.g:12169:1: ( RULE_ID )
{
// InternalUrml.g:12169:1: ( RULE_ID )
// InternalUrml.g:12170:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getNameIDTerminalRuleCall_2_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getNameIDTerminalRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__NameAssignment_2"
// $ANTLR start "rule__Attribute__DefaultValueAssignment_3_1"
// InternalUrml.g:12179:1: rule__Attribute__DefaultValueAssignment_3_1 : ( ruleExpression ) ;
public final void rule__Attribute__DefaultValueAssignment_3_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12183:1: ( ( ruleExpression ) )
// InternalUrml.g:12184:1: ( ruleExpression )
{
// InternalUrml.g:12184:1: ( ruleExpression )
// InternalUrml.g:12185:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAttributeAccess().getDefaultValueExpressionParserRuleCall_3_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAttributeAccess().getDefaultValueExpressionParserRuleCall_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Attribute__DefaultValueAssignment_3_1"
// $ANTLR start "rule__Protocol__NameAssignment_1"
// InternalUrml.g:12194:1: rule__Protocol__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__Protocol__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12198:1: ( ( RULE_ID ) )
// InternalUrml.g:12199:1: ( RULE_ID )
{
// InternalUrml.g:12199:1: ( RULE_ID )
// InternalUrml.g:12200:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__NameAssignment_1"
// $ANTLR start "rule__Protocol__IncomingMessagesAssignment_3_0_2"
// InternalUrml.g:12209:1: rule__Protocol__IncomingMessagesAssignment_3_0_2 : ( ruleSignal ) ;
public final void rule__Protocol__IncomingMessagesAssignment_3_0_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12213:1: ( ( ruleSignal ) )
// InternalUrml.g:12214:1: ( ruleSignal )
{
// InternalUrml.g:12214:1: ( ruleSignal )
// InternalUrml.g:12215:1: ruleSignal
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getIncomingMessagesSignalParserRuleCall_3_0_2_0());
}
pushFollow(FOLLOW_2);
ruleSignal();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getIncomingMessagesSignalParserRuleCall_3_0_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__IncomingMessagesAssignment_3_0_2"
// $ANTLR start "rule__Protocol__OutgoingMessagesAssignment_3_1_2"
// InternalUrml.g:12224:1: rule__Protocol__OutgoingMessagesAssignment_3_1_2 : ( ruleSignal ) ;
public final void rule__Protocol__OutgoingMessagesAssignment_3_1_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12228:1: ( ( ruleSignal ) )
// InternalUrml.g:12229:1: ( ruleSignal )
{
// InternalUrml.g:12229:1: ( ruleSignal )
// InternalUrml.g:12230:1: ruleSignal
{
if ( state.backtracking==0 ) {
before(grammarAccess.getProtocolAccess().getOutgoingMessagesSignalParserRuleCall_3_1_2_0());
}
pushFollow(FOLLOW_2);
ruleSignal();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getProtocolAccess().getOutgoingMessagesSignalParserRuleCall_3_1_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Protocol__OutgoingMessagesAssignment_3_1_2"
// $ANTLR start "rule__Signal__NameAssignment_0"
// InternalUrml.g:12239:1: rule__Signal__NameAssignment_0 : ( RULE_ID ) ;
public final void rule__Signal__NameAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12243:1: ( ( RULE_ID ) )
// InternalUrml.g:12244:1: ( RULE_ID )
{
// InternalUrml.g:12244:1: ( RULE_ID )
// InternalUrml.g:12245:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getNameIDTerminalRuleCall_0_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getNameIDTerminalRuleCall_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__NameAssignment_0"
// $ANTLR start "rule__Signal__LocalVarsAssignment_2_0"
// InternalUrml.g:12254:1: rule__Signal__LocalVarsAssignment_2_0 : ( ruleLocalVar ) ;
public final void rule__Signal__LocalVarsAssignment_2_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12258:1: ( ( ruleLocalVar ) )
// InternalUrml.g:12259:1: ( ruleLocalVar )
{
// InternalUrml.g:12259:1: ( ruleLocalVar )
// InternalUrml.g:12260:1: ruleLocalVar
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getLocalVarsLocalVarParserRuleCall_2_0_0());
}
pushFollow(FOLLOW_2);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getLocalVarsLocalVarParserRuleCall_2_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__LocalVarsAssignment_2_0"
// $ANTLR start "rule__Signal__LocalVarsAssignment_2_1_1"
// InternalUrml.g:12269:1: rule__Signal__LocalVarsAssignment_2_1_1 : ( ruleLocalVar ) ;
public final void rule__Signal__LocalVarsAssignment_2_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12273:1: ( ( ruleLocalVar ) )
// InternalUrml.g:12274:1: ( ruleLocalVar )
{
// InternalUrml.g:12274:1: ( ruleLocalVar )
// InternalUrml.g:12275:1: ruleLocalVar
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSignalAccess().getLocalVarsLocalVarParserRuleCall_2_1_1_0());
}
pushFollow(FOLLOW_2);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSignalAccess().getLocalVarsLocalVarParserRuleCall_2_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Signal__LocalVarsAssignment_2_1_1"
// $ANTLR start "rule__Capsule__RootAssignment_0"
// InternalUrml.g:12284:1: rule__Capsule__RootAssignment_0 : ( ( 'root' ) ) ;
public final void rule__Capsule__RootAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12288:1: ( ( ( 'root' ) ) )
// InternalUrml.g:12289:1: ( ( 'root' ) )
{
// InternalUrml.g:12289:1: ( ( 'root' ) )
// InternalUrml.g:12290:1: ( 'root' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getRootRootKeyword_0_0());
}
// InternalUrml.g:12291:1: ( 'root' )
// InternalUrml.g:12292:1: 'root'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getRootRootKeyword_0_0());
}
match(input,77,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getRootRootKeyword_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getRootRootKeyword_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__RootAssignment_0"
// $ANTLR start "rule__Capsule__NameAssignment_2"
// InternalUrml.g:12307:1: rule__Capsule__NameAssignment_2 : ( RULE_ID ) ;
public final void rule__Capsule__NameAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12311:1: ( ( RULE_ID ) )
// InternalUrml.g:12312:1: ( RULE_ID )
{
// InternalUrml.g:12312:1: ( RULE_ID )
// InternalUrml.g:12313:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getNameIDTerminalRuleCall_2_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getNameIDTerminalRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__NameAssignment_2"
// $ANTLR start "rule__Capsule__InterfacePortsAssignment_4_0_1"
// InternalUrml.g:12322:1: rule__Capsule__InterfacePortsAssignment_4_0_1 : ( rulePort ) ;
public final void rule__Capsule__InterfacePortsAssignment_4_0_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12326:1: ( ( rulePort ) )
// InternalUrml.g:12327:1: ( rulePort )
{
// InternalUrml.g:12327:1: ( rulePort )
// InternalUrml.g:12328:1: rulePort
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getInterfacePortsPortParserRuleCall_4_0_1_0());
}
pushFollow(FOLLOW_2);
rulePort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getInterfacePortsPortParserRuleCall_4_0_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__InterfacePortsAssignment_4_0_1"
// $ANTLR start "rule__Capsule__InternalPortsAssignment_4_1"
// InternalUrml.g:12337:1: rule__Capsule__InternalPortsAssignment_4_1 : ( rulePort ) ;
public final void rule__Capsule__InternalPortsAssignment_4_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12341:1: ( ( rulePort ) )
// InternalUrml.g:12342:1: ( rulePort )
{
// InternalUrml.g:12342:1: ( rulePort )
// InternalUrml.g:12343:1: rulePort
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getInternalPortsPortParserRuleCall_4_1_0());
}
pushFollow(FOLLOW_2);
rulePort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getInternalPortsPortParserRuleCall_4_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__InternalPortsAssignment_4_1"
// $ANTLR start "rule__Capsule__TimerPortsAssignment_4_2"
// InternalUrml.g:12352:1: rule__Capsule__TimerPortsAssignment_4_2 : ( ruleTimerPort ) ;
public final void rule__Capsule__TimerPortsAssignment_4_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12356:1: ( ( ruleTimerPort ) )
// InternalUrml.g:12357:1: ( ruleTimerPort )
{
// InternalUrml.g:12357:1: ( ruleTimerPort )
// InternalUrml.g:12358:1: ruleTimerPort
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getTimerPortsTimerPortParserRuleCall_4_2_0());
}
pushFollow(FOLLOW_2);
ruleTimerPort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getTimerPortsTimerPortParserRuleCall_4_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__TimerPortsAssignment_4_2"
// $ANTLR start "rule__Capsule__LogPortsAssignment_4_3"
// InternalUrml.g:12367:1: rule__Capsule__LogPortsAssignment_4_3 : ( ruleLogPort ) ;
public final void rule__Capsule__LogPortsAssignment_4_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12371:1: ( ( ruleLogPort ) )
// InternalUrml.g:12372:1: ( ruleLogPort )
{
// InternalUrml.g:12372:1: ( ruleLogPort )
// InternalUrml.g:12373:1: ruleLogPort
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getLogPortsLogPortParserRuleCall_4_3_0());
}
pushFollow(FOLLOW_2);
ruleLogPort();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getLogPortsLogPortParserRuleCall_4_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__LogPortsAssignment_4_3"
// $ANTLR start "rule__Capsule__AttributesAssignment_4_4"
// InternalUrml.g:12382:1: rule__Capsule__AttributesAssignment_4_4 : ( ruleAttribute ) ;
public final void rule__Capsule__AttributesAssignment_4_4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12386:1: ( ( ruleAttribute ) )
// InternalUrml.g:12387:1: ( ruleAttribute )
{
// InternalUrml.g:12387:1: ( ruleAttribute )
// InternalUrml.g:12388:1: ruleAttribute
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getAttributesAttributeParserRuleCall_4_4_0());
}
pushFollow(FOLLOW_2);
ruleAttribute();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getAttributesAttributeParserRuleCall_4_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__AttributesAssignment_4_4"
// $ANTLR start "rule__Capsule__CapsuleInstsAssignment_4_5"
// InternalUrml.g:12397:1: rule__Capsule__CapsuleInstsAssignment_4_5 : ( ruleCapsuleInst ) ;
public final void rule__Capsule__CapsuleInstsAssignment_4_5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12401:1: ( ( ruleCapsuleInst ) )
// InternalUrml.g:12402:1: ( ruleCapsuleInst )
{
// InternalUrml.g:12402:1: ( ruleCapsuleInst )
// InternalUrml.g:12403:1: ruleCapsuleInst
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getCapsuleInstsCapsuleInstParserRuleCall_4_5_0());
}
pushFollow(FOLLOW_2);
ruleCapsuleInst();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getCapsuleInstsCapsuleInstParserRuleCall_4_5_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__CapsuleInstsAssignment_4_5"
// $ANTLR start "rule__Capsule__ConnectorsAssignment_4_6"
// InternalUrml.g:12412:1: rule__Capsule__ConnectorsAssignment_4_6 : ( ruleConnector ) ;
public final void rule__Capsule__ConnectorsAssignment_4_6() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12416:1: ( ( ruleConnector ) )
// InternalUrml.g:12417:1: ( ruleConnector )
{
// InternalUrml.g:12417:1: ( ruleConnector )
// InternalUrml.g:12418:1: ruleConnector
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getConnectorsConnectorParserRuleCall_4_6_0());
}
pushFollow(FOLLOW_2);
ruleConnector();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getConnectorsConnectorParserRuleCall_4_6_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__ConnectorsAssignment_4_6"
// $ANTLR start "rule__Capsule__OperationsAssignment_4_7"
// InternalUrml.g:12427:1: rule__Capsule__OperationsAssignment_4_7 : ( ruleOperation ) ;
public final void rule__Capsule__OperationsAssignment_4_7() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12431:1: ( ( ruleOperation ) )
// InternalUrml.g:12432:1: ( ruleOperation )
{
// InternalUrml.g:12432:1: ( ruleOperation )
// InternalUrml.g:12433:1: ruleOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getOperationsOperationParserRuleCall_4_7_0());
}
pushFollow(FOLLOW_2);
ruleOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getOperationsOperationParserRuleCall_4_7_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__OperationsAssignment_4_7"
// $ANTLR start "rule__Capsule__StatemachinesAssignment_4_8"
// InternalUrml.g:12442:1: rule__Capsule__StatemachinesAssignment_4_8 : ( ruleStateMachine ) ;
public final void rule__Capsule__StatemachinesAssignment_4_8() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12446:1: ( ( ruleStateMachine ) )
// InternalUrml.g:12447:1: ( ruleStateMachine )
{
// InternalUrml.g:12447:1: ( ruleStateMachine )
// InternalUrml.g:12448:1: ruleStateMachine
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleAccess().getStatemachinesStateMachineParserRuleCall_4_8_0());
}
pushFollow(FOLLOW_2);
ruleStateMachine();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleAccess().getStatemachinesStateMachineParserRuleCall_4_8_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Capsule__StatemachinesAssignment_4_8"
// $ANTLR start "rule__Operation__IsBoolAssignment_1_0"
// InternalUrml.g:12457:1: rule__Operation__IsBoolAssignment_1_0 : ( ( 'bool' ) ) ;
public final void rule__Operation__IsBoolAssignment_1_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12461:1: ( ( ( 'bool' ) ) )
// InternalUrml.g:12462:1: ( ( 'bool' ) )
{
// InternalUrml.g:12462:1: ( ( 'bool' ) )
// InternalUrml.g:12463:1: ( 'bool' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsBoolBoolKeyword_1_0_0());
}
// InternalUrml.g:12464:1: ( 'bool' )
// InternalUrml.g:12465:1: 'bool'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsBoolBoolKeyword_1_0_0());
}
match(input,75,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsBoolBoolKeyword_1_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsBoolBoolKeyword_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__IsBoolAssignment_1_0"
// $ANTLR start "rule__Operation__IsIntAssignment_1_1"
// InternalUrml.g:12480:1: rule__Operation__IsIntAssignment_1_1 : ( ( 'int' ) ) ;
public final void rule__Operation__IsIntAssignment_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12484:1: ( ( ( 'int' ) ) )
// InternalUrml.g:12485:1: ( ( 'int' ) )
{
// InternalUrml.g:12485:1: ( ( 'int' ) )
// InternalUrml.g:12486:1: ( 'int' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsIntIntKeyword_1_1_0());
}
// InternalUrml.g:12487:1: ( 'int' )
// InternalUrml.g:12488:1: 'int'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsIntIntKeyword_1_1_0());
}
match(input,76,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsIntIntKeyword_1_1_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsIntIntKeyword_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__IsIntAssignment_1_1"
// $ANTLR start "rule__Operation__IsVoidAssignment_1_2"
// InternalUrml.g:12503:1: rule__Operation__IsVoidAssignment_1_2 : ( ( 'void' ) ) ;
public final void rule__Operation__IsVoidAssignment_1_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12507:1: ( ( ( 'void' ) ) )
// InternalUrml.g:12508:1: ( ( 'void' ) )
{
// InternalUrml.g:12508:1: ( ( 'void' ) )
// InternalUrml.g:12509:1: ( 'void' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsVoidVoidKeyword_1_2_0());
}
// InternalUrml.g:12510:1: ( 'void' )
// InternalUrml.g:12511:1: 'void'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getIsVoidVoidKeyword_1_2_0());
}
match(input,78,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsVoidVoidKeyword_1_2_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getIsVoidVoidKeyword_1_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__IsVoidAssignment_1_2"
// $ANTLR start "rule__Operation__NameAssignment_2"
// InternalUrml.g:12526:1: rule__Operation__NameAssignment_2 : ( RULE_ID ) ;
public final void rule__Operation__NameAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12530:1: ( ( RULE_ID ) )
// InternalUrml.g:12531:1: ( RULE_ID )
{
// InternalUrml.g:12531:1: ( RULE_ID )
// InternalUrml.g:12532:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getNameIDTerminalRuleCall_2_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getNameIDTerminalRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__NameAssignment_2"
// $ANTLR start "rule__Operation__LocalVarsAssignment_4_0"
// InternalUrml.g:12541:1: rule__Operation__LocalVarsAssignment_4_0 : ( ruleLocalVar ) ;
public final void rule__Operation__LocalVarsAssignment_4_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12545:1: ( ( ruleLocalVar ) )
// InternalUrml.g:12546:1: ( ruleLocalVar )
{
// InternalUrml.g:12546:1: ( ruleLocalVar )
// InternalUrml.g:12547:1: ruleLocalVar
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getLocalVarsLocalVarParserRuleCall_4_0_0());
}
pushFollow(FOLLOW_2);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getLocalVarsLocalVarParserRuleCall_4_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__LocalVarsAssignment_4_0"
// $ANTLR start "rule__Operation__LocalVarsAssignment_4_1_1"
// InternalUrml.g:12556:1: rule__Operation__LocalVarsAssignment_4_1_1 : ( ruleLocalVar ) ;
public final void rule__Operation__LocalVarsAssignment_4_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12560:1: ( ( ruleLocalVar ) )
// InternalUrml.g:12561:1: ( ruleLocalVar )
{
// InternalUrml.g:12561:1: ( ruleLocalVar )
// InternalUrml.g:12562:1: ruleLocalVar
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getLocalVarsLocalVarParserRuleCall_4_1_1_0());
}
pushFollow(FOLLOW_2);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getLocalVarsLocalVarParserRuleCall_4_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__LocalVarsAssignment_4_1_1"
// $ANTLR start "rule__Operation__OperationCodeAssignment_7"
// InternalUrml.g:12571:1: rule__Operation__OperationCodeAssignment_7 : ( ruleOperationCode ) ;
public final void rule__Operation__OperationCodeAssignment_7() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12575:1: ( ( ruleOperationCode ) )
// InternalUrml.g:12576:1: ( ruleOperationCode )
{
// InternalUrml.g:12576:1: ( ruleOperationCode )
// InternalUrml.g:12577:1: ruleOperationCode
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationAccess().getOperationCodeOperationCodeParserRuleCall_7_0());
}
pushFollow(FOLLOW_2);
ruleOperationCode();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationAccess().getOperationCodeOperationCodeParserRuleCall_7_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Operation__OperationCodeAssignment_7"
// $ANTLR start "rule__TimerPort__NameAssignment_1"
// InternalUrml.g:12586:1: rule__TimerPort__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__TimerPort__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12590:1: ( ( RULE_ID ) )
// InternalUrml.g:12591:1: ( RULE_ID )
{
// InternalUrml.g:12591:1: ( RULE_ID )
// InternalUrml.g:12592:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTimerPortAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTimerPortAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__TimerPort__NameAssignment_1"
// $ANTLR start "rule__LogPort__NameAssignment_1"
// InternalUrml.g:12601:1: rule__LogPort__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__LogPort__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12605:1: ( ( RULE_ID ) )
// InternalUrml.g:12606:1: ( RULE_ID )
{
// InternalUrml.g:12606:1: ( RULE_ID )
// InternalUrml.g:12607:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogPortAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogPortAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogPort__NameAssignment_1"
// $ANTLR start "rule__Port__ConjugatedAssignment_1"
// InternalUrml.g:12616:1: rule__Port__ConjugatedAssignment_1 : ( ( '~' ) ) ;
public final void rule__Port__ConjugatedAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12620:1: ( ( ( '~' ) ) )
// InternalUrml.g:12621:1: ( ( '~' ) )
{
// InternalUrml.g:12621:1: ( ( '~' ) )
// InternalUrml.g:12622:1: ( '~' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getConjugatedTildeKeyword_1_0());
}
// InternalUrml.g:12623:1: ( '~' )
// InternalUrml.g:12624:1: '~'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getConjugatedTildeKeyword_1_0());
}
match(input,79,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getConjugatedTildeKeyword_1_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getConjugatedTildeKeyword_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__ConjugatedAssignment_1"
// $ANTLR start "rule__Port__NameAssignment_2"
// InternalUrml.g:12639:1: rule__Port__NameAssignment_2 : ( RULE_ID ) ;
public final void rule__Port__NameAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12643:1: ( ( RULE_ID ) )
// InternalUrml.g:12644:1: ( RULE_ID )
{
// InternalUrml.g:12644:1: ( RULE_ID )
// InternalUrml.g:12645:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getNameIDTerminalRuleCall_2_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getNameIDTerminalRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__NameAssignment_2"
// $ANTLR start "rule__Port__ProtocolAssignment_4"
// InternalUrml.g:12654:1: rule__Port__ProtocolAssignment_4 : ( ( RULE_ID ) ) ;
public final void rule__Port__ProtocolAssignment_4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12658:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12659:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12659:1: ( ( RULE_ID ) )
// InternalUrml.g:12660:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getProtocolProtocolCrossReference_4_0());
}
// InternalUrml.g:12661:1: ( RULE_ID )
// InternalUrml.g:12662:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getPortAccess().getProtocolProtocolIDTerminalRuleCall_4_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getProtocolProtocolIDTerminalRuleCall_4_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getPortAccess().getProtocolProtocolCrossReference_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Port__ProtocolAssignment_4"
// $ANTLR start "rule__Connector__CapsuleInst1Assignment_1_0"
// InternalUrml.g:12673:1: rule__Connector__CapsuleInst1Assignment_1_0 : ( ( RULE_ID ) ) ;
public final void rule__Connector__CapsuleInst1Assignment_1_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12677:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12678:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12678:1: ( ( RULE_ID ) )
// InternalUrml.g:12679:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getCapsuleInst1CapsuleInstCrossReference_1_0_0());
}
// InternalUrml.g:12680:1: ( RULE_ID )
// InternalUrml.g:12681:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getCapsuleInst1CapsuleInstIDTerminalRuleCall_1_0_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getCapsuleInst1CapsuleInstIDTerminalRuleCall_1_0_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getCapsuleInst1CapsuleInstCrossReference_1_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__CapsuleInst1Assignment_1_0"
// $ANTLR start "rule__Connector__Port1Assignment_2"
// InternalUrml.g:12692:1: rule__Connector__Port1Assignment_2 : ( ( RULE_ID ) ) ;
public final void rule__Connector__Port1Assignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12696:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12697:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12697:1: ( ( RULE_ID ) )
// InternalUrml.g:12698:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getPort1PortCrossReference_2_0());
}
// InternalUrml.g:12699:1: ( RULE_ID )
// InternalUrml.g:12700:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getPort1PortIDTerminalRuleCall_2_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getPort1PortIDTerminalRuleCall_2_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getPort1PortCrossReference_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Port1Assignment_2"
// $ANTLR start "rule__Connector__CapsuleInst2Assignment_4_0"
// InternalUrml.g:12711:1: rule__Connector__CapsuleInst2Assignment_4_0 : ( ( RULE_ID ) ) ;
public final void rule__Connector__CapsuleInst2Assignment_4_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12715:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12716:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12716:1: ( ( RULE_ID ) )
// InternalUrml.g:12717:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getCapsuleInst2CapsuleInstCrossReference_4_0_0());
}
// InternalUrml.g:12718:1: ( RULE_ID )
// InternalUrml.g:12719:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getCapsuleInst2CapsuleInstIDTerminalRuleCall_4_0_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getCapsuleInst2CapsuleInstIDTerminalRuleCall_4_0_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getCapsuleInst2CapsuleInstCrossReference_4_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__CapsuleInst2Assignment_4_0"
// $ANTLR start "rule__Connector__Port2Assignment_5"
// InternalUrml.g:12730:1: rule__Connector__Port2Assignment_5 : ( ( RULE_ID ) ) ;
public final void rule__Connector__Port2Assignment_5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12734:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12735:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12735:1: ( ( RULE_ID ) )
// InternalUrml.g:12736:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getPort2PortCrossReference_5_0());
}
// InternalUrml.g:12737:1: ( RULE_ID )
// InternalUrml.g:12738:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConnectorAccess().getPort2PortIDTerminalRuleCall_5_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getPort2PortIDTerminalRuleCall_5_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getConnectorAccess().getPort2PortCrossReference_5_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Connector__Port2Assignment_5"
// $ANTLR start "rule__CapsuleInst__NameAssignment_1"
// InternalUrml.g:12749:1: rule__CapsuleInst__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__CapsuleInst__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12753:1: ( ( RULE_ID ) )
// InternalUrml.g:12754:1: ( RULE_ID )
{
// InternalUrml.g:12754:1: ( RULE_ID )
// InternalUrml.g:12755:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__NameAssignment_1"
// $ANTLR start "rule__CapsuleInst__TypeAssignment_3"
// InternalUrml.g:12764:1: rule__CapsuleInst__TypeAssignment_3 : ( ( RULE_ID ) ) ;
public final void rule__CapsuleInst__TypeAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12768:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12769:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12769:1: ( ( RULE_ID ) )
// InternalUrml.g:12770:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getTypeCapsuleCrossReference_3_0());
}
// InternalUrml.g:12771:1: ( RULE_ID )
// InternalUrml.g:12772:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getCapsuleInstAccess().getTypeCapsuleIDTerminalRuleCall_3_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getTypeCapsuleIDTerminalRuleCall_3_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getCapsuleInstAccess().getTypeCapsuleCrossReference_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__CapsuleInst__TypeAssignment_3"
// $ANTLR start "rule__StateMachine__StatesAssignment_3_0"
// InternalUrml.g:12783:1: rule__StateMachine__StatesAssignment_3_0 : ( ruleState_ ) ;
public final void rule__StateMachine__StatesAssignment_3_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12787:1: ( ( ruleState_ ) )
// InternalUrml.g:12788:1: ( ruleState_ )
{
// InternalUrml.g:12788:1: ( ruleState_ )
// InternalUrml.g:12789:1: ruleState_
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getStatesState_ParserRuleCall_3_0_0());
}
pushFollow(FOLLOW_2);
ruleState_();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getStatesState_ParserRuleCall_3_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__StatesAssignment_3_0"
// $ANTLR start "rule__StateMachine__TransitionsAssignment_3_1"
// InternalUrml.g:12798:1: rule__StateMachine__TransitionsAssignment_3_1 : ( ruleTransition ) ;
public final void rule__StateMachine__TransitionsAssignment_3_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12802:1: ( ( ruleTransition ) )
// InternalUrml.g:12803:1: ( ruleTransition )
{
// InternalUrml.g:12803:1: ( ruleTransition )
// InternalUrml.g:12804:1: ruleTransition
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStateMachineAccess().getTransitionsTransitionParserRuleCall_3_1_0());
}
pushFollow(FOLLOW_2);
ruleTransition();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStateMachineAccess().getTransitionsTransitionParserRuleCall_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StateMachine__TransitionsAssignment_3_1"
// $ANTLR start "rule__State___FinalAssignment_0"
// InternalUrml.g:12813:1: rule__State___FinalAssignment_0 : ( ( 'final' ) ) ;
public final void rule__State___FinalAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12817:1: ( ( ( 'final' ) ) )
// InternalUrml.g:12818:1: ( ( 'final' ) )
{
// InternalUrml.g:12818:1: ( ( 'final' ) )
// InternalUrml.g:12819:1: ( 'final' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getFinalFinalKeyword_0_0());
}
// InternalUrml.g:12820:1: ( 'final' )
// InternalUrml.g:12821:1: 'final'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getFinalFinalKeyword_0_0());
}
match(input,80,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getFinalFinalKeyword_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getFinalFinalKeyword_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___FinalAssignment_0"
// $ANTLR start "rule__State___NameAssignment_2"
// InternalUrml.g:12836:1: rule__State___NameAssignment_2 : ( RULE_ID ) ;
public final void rule__State___NameAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12840:1: ( ( RULE_ID ) )
// InternalUrml.g:12841:1: ( RULE_ID )
{
// InternalUrml.g:12841:1: ( RULE_ID )
// InternalUrml.g:12842:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getNameIDTerminalRuleCall_2_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getNameIDTerminalRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___NameAssignment_2"
// $ANTLR start "rule__State___EntryCodeAssignment_3_1_2"
// InternalUrml.g:12851:1: rule__State___EntryCodeAssignment_3_1_2 : ( ruleActionCode ) ;
public final void rule__State___EntryCodeAssignment_3_1_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12855:1: ( ( ruleActionCode ) )
// InternalUrml.g:12856:1: ( ruleActionCode )
{
// InternalUrml.g:12856:1: ( ruleActionCode )
// InternalUrml.g:12857:1: ruleActionCode
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getEntryCodeActionCodeParserRuleCall_3_1_2_0());
}
pushFollow(FOLLOW_2);
ruleActionCode();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getEntryCodeActionCodeParserRuleCall_3_1_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___EntryCodeAssignment_3_1_2"
// $ANTLR start "rule__State___ExitCodeAssignment_3_2_2"
// InternalUrml.g:12866:1: rule__State___ExitCodeAssignment_3_2_2 : ( ruleActionCode ) ;
public final void rule__State___ExitCodeAssignment_3_2_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12870:1: ( ( ruleActionCode ) )
// InternalUrml.g:12871:1: ( ruleActionCode )
{
// InternalUrml.g:12871:1: ( ruleActionCode )
// InternalUrml.g:12872:1: ruleActionCode
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getExitCodeActionCodeParserRuleCall_3_2_2_0());
}
pushFollow(FOLLOW_2);
ruleActionCode();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getExitCodeActionCodeParserRuleCall_3_2_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___ExitCodeAssignment_3_2_2"
// $ANTLR start "rule__State___SubstatemachineAssignment_3_3_1"
// InternalUrml.g:12881:1: rule__State___SubstatemachineAssignment_3_3_1 : ( ruleStateMachine ) ;
public final void rule__State___SubstatemachineAssignment_3_3_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12885:1: ( ( ruleStateMachine ) )
// InternalUrml.g:12886:1: ( ruleStateMachine )
{
// InternalUrml.g:12886:1: ( ruleStateMachine )
// InternalUrml.g:12887:1: ruleStateMachine
{
if ( state.backtracking==0 ) {
before(grammarAccess.getState_Access().getSubstatemachineStateMachineParserRuleCall_3_3_1_0());
}
pushFollow(FOLLOW_2);
ruleStateMachine();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getState_Access().getSubstatemachineStateMachineParserRuleCall_3_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__State___SubstatemachineAssignment_3_3_1"
// $ANTLR start "rule__Transition__NameAssignment_1"
// InternalUrml.g:12896:1: rule__Transition__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__Transition__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12900:1: ( ( RULE_ID ) )
// InternalUrml.g:12901:1: ( RULE_ID )
{
// InternalUrml.g:12901:1: ( RULE_ID )
// InternalUrml.g:12902:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__NameAssignment_1"
// $ANTLR start "rule__Transition__InitAssignment_3_0"
// InternalUrml.g:12911:1: rule__Transition__InitAssignment_3_0 : ( ( 'initial' ) ) ;
public final void rule__Transition__InitAssignment_3_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12915:1: ( ( ( 'initial' ) ) )
// InternalUrml.g:12916:1: ( ( 'initial' ) )
{
// InternalUrml.g:12916:1: ( ( 'initial' ) )
// InternalUrml.g:12917:1: ( 'initial' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getInitInitialKeyword_3_0_0());
}
// InternalUrml.g:12918:1: ( 'initial' )
// InternalUrml.g:12919:1: 'initial'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getInitInitialKeyword_3_0_0());
}
match(input,81,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getInitInitialKeyword_3_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getInitInitialKeyword_3_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__InitAssignment_3_0"
// $ANTLR start "rule__Transition__FromAssignment_3_1"
// InternalUrml.g:12934:1: rule__Transition__FromAssignment_3_1 : ( ( RULE_ID ) ) ;
public final void rule__Transition__FromAssignment_3_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12938:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12939:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12939:1: ( ( RULE_ID ) )
// InternalUrml.g:12940:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getFromState_CrossReference_3_1_0());
}
// InternalUrml.g:12941:1: ( RULE_ID )
// InternalUrml.g:12942:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getFromState_IDTerminalRuleCall_3_1_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getFromState_IDTerminalRuleCall_3_1_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getFromState_CrossReference_3_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__FromAssignment_3_1"
// $ANTLR start "rule__Transition__ToAssignment_5"
// InternalUrml.g:12953:1: rule__Transition__ToAssignment_5 : ( ( RULE_ID ) ) ;
public final void rule__Transition__ToAssignment_5() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12957:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:12958:1: ( ( RULE_ID ) )
{
// InternalUrml.g:12958:1: ( ( RULE_ID ) )
// InternalUrml.g:12959:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getToState_CrossReference_5_0());
}
// InternalUrml.g:12960:1: ( RULE_ID )
// InternalUrml.g:12961:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getToState_IDTerminalRuleCall_5_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getToState_IDTerminalRuleCall_5_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getToState_CrossReference_5_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__ToAssignment_5"
// $ANTLR start "rule__Transition__GuardAssignment_7_2"
// InternalUrml.g:12972:1: rule__Transition__GuardAssignment_7_2 : ( ruleExpression ) ;
public final void rule__Transition__GuardAssignment_7_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12976:1: ( ( ruleExpression ) )
// InternalUrml.g:12977:1: ( ruleExpression )
{
// InternalUrml.g:12977:1: ( ruleExpression )
// InternalUrml.g:12978:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getGuardExpressionParserRuleCall_7_2_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getGuardExpressionParserRuleCall_7_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__GuardAssignment_7_2"
// $ANTLR start "rule__Transition__TriggersAssignment_8_1_0_0"
// InternalUrml.g:12987:1: rule__Transition__TriggersAssignment_8_1_0_0 : ( ruleTrigger_in ) ;
public final void rule__Transition__TriggersAssignment_8_1_0_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:12991:1: ( ( ruleTrigger_in ) )
// InternalUrml.g:12992:1: ( ruleTrigger_in )
{
// InternalUrml.g:12992:1: ( ruleTrigger_in )
// InternalUrml.g:12993:1: ruleTrigger_in
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTriggersTrigger_inParserRuleCall_8_1_0_0_0());
}
pushFollow(FOLLOW_2);
ruleTrigger_in();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTriggersTrigger_inParserRuleCall_8_1_0_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__TriggersAssignment_8_1_0_0"
// $ANTLR start "rule__Transition__TriggersAssignment_8_1_0_1_1"
// InternalUrml.g:13002:1: rule__Transition__TriggersAssignment_8_1_0_1_1 : ( ruleTrigger_in ) ;
public final void rule__Transition__TriggersAssignment_8_1_0_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13006:1: ( ( ruleTrigger_in ) )
// InternalUrml.g:13007:1: ( ruleTrigger_in )
{
// InternalUrml.g:13007:1: ( ruleTrigger_in )
// InternalUrml.g:13008:1: ruleTrigger_in
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTriggersTrigger_inParserRuleCall_8_1_0_1_1_0());
}
pushFollow(FOLLOW_2);
ruleTrigger_in();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTriggersTrigger_inParserRuleCall_8_1_0_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__TriggersAssignment_8_1_0_1_1"
// $ANTLR start "rule__Transition__TimerPortAssignment_8_1_1_1"
// InternalUrml.g:13017:1: rule__Transition__TimerPortAssignment_8_1_1_1 : ( ( RULE_ID ) ) ;
public final void rule__Transition__TimerPortAssignment_8_1_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13021:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13022:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13022:1: ( ( RULE_ID ) )
// InternalUrml.g:13023:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTimerPortTimerPortCrossReference_8_1_1_1_0());
}
// InternalUrml.g:13024:1: ( RULE_ID )
// InternalUrml.g:13025:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getTimerPortTimerPortIDTerminalRuleCall_8_1_1_1_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTimerPortTimerPortIDTerminalRuleCall_8_1_1_1_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getTimerPortTimerPortCrossReference_8_1_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__TimerPortAssignment_8_1_1_1"
// $ANTLR start "rule__Transition__UniversalAssignment_8_1_2"
// InternalUrml.g:13036:1: rule__Transition__UniversalAssignment_8_1_2 : ( ( '*' ) ) ;
public final void rule__Transition__UniversalAssignment_8_1_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13040:1: ( ( ( '*' ) ) )
// InternalUrml.g:13041:1: ( ( '*' ) )
{
// InternalUrml.g:13041:1: ( ( '*' ) )
// InternalUrml.g:13042:1: ( '*' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getUniversalAsteriskKeyword_8_1_2_0());
}
// InternalUrml.g:13043:1: ( '*' )
// InternalUrml.g:13044:1: '*'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getUniversalAsteriskKeyword_8_1_2_0());
}
match(input,71,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getUniversalAsteriskKeyword_8_1_2_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getUniversalAsteriskKeyword_8_1_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__UniversalAssignment_8_1_2"
// $ANTLR start "rule__Transition__ActionAssignment_9_2"
// InternalUrml.g:13059:1: rule__Transition__ActionAssignment_9_2 : ( ruleActionCode ) ;
public final void rule__Transition__ActionAssignment_9_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13063:1: ( ( ruleActionCode ) )
// InternalUrml.g:13064:1: ( ruleActionCode )
{
// InternalUrml.g:13064:1: ( ruleActionCode )
// InternalUrml.g:13065:1: ruleActionCode
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTransitionAccess().getActionActionCodeParserRuleCall_9_2_0());
}
pushFollow(FOLLOW_2);
ruleActionCode();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTransitionAccess().getActionActionCodeParserRuleCall_9_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Transition__ActionAssignment_9_2"
// $ANTLR start "rule__Trigger_in__FromAssignment_0"
// InternalUrml.g:13074:1: rule__Trigger_in__FromAssignment_0 : ( ( RULE_ID ) ) ;
public final void rule__Trigger_in__FromAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13078:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13079:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13079:1: ( ( RULE_ID ) )
// InternalUrml.g:13080:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getFromPortCrossReference_0_0());
}
// InternalUrml.g:13081:1: ( RULE_ID )
// InternalUrml.g:13082:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getFromPortIDTerminalRuleCall_0_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getFromPortIDTerminalRuleCall_0_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getFromPortCrossReference_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__FromAssignment_0"
// $ANTLR start "rule__Trigger_in__SignalAssignment_2"
// InternalUrml.g:13093:1: rule__Trigger_in__SignalAssignment_2 : ( ( RULE_ID ) ) ;
public final void rule__Trigger_in__SignalAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13097:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13098:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13098:1: ( ( RULE_ID ) )
// InternalUrml.g:13099:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getSignalSignalCrossReference_2_0());
}
// InternalUrml.g:13100:1: ( RULE_ID )
// InternalUrml.g:13101:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getSignalSignalIDTerminalRuleCall_2_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getSignalSignalIDTerminalRuleCall_2_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getSignalSignalCrossReference_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__SignalAssignment_2"
// $ANTLR start "rule__Trigger_in__ParametersAssignment_4_0"
// InternalUrml.g:13112:1: rule__Trigger_in__ParametersAssignment_4_0 : ( ruleIncomingVariable ) ;
public final void rule__Trigger_in__ParametersAssignment_4_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13116:1: ( ( ruleIncomingVariable ) )
// InternalUrml.g:13117:1: ( ruleIncomingVariable )
{
// InternalUrml.g:13117:1: ( ruleIncomingVariable )
// InternalUrml.g:13118:1: ruleIncomingVariable
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getParametersIncomingVariableParserRuleCall_4_0_0());
}
pushFollow(FOLLOW_2);
ruleIncomingVariable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getParametersIncomingVariableParserRuleCall_4_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__ParametersAssignment_4_0"
// $ANTLR start "rule__Trigger_in__ParametersAssignment_4_1_1"
// InternalUrml.g:13127:1: rule__Trigger_in__ParametersAssignment_4_1_1 : ( ruleIncomingVariable ) ;
public final void rule__Trigger_in__ParametersAssignment_4_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13131:1: ( ( ruleIncomingVariable ) )
// InternalUrml.g:13132:1: ( ruleIncomingVariable )
{
// InternalUrml.g:13132:1: ( ruleIncomingVariable )
// InternalUrml.g:13133:1: ruleIncomingVariable
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_inAccess().getParametersIncomingVariableParserRuleCall_4_1_1_0());
}
pushFollow(FOLLOW_2);
ruleIncomingVariable();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_inAccess().getParametersIncomingVariableParserRuleCall_4_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_in__ParametersAssignment_4_1_1"
// $ANTLR start "rule__IncomingVariable__IsBoolAssignment_0_0"
// InternalUrml.g:13142:1: rule__IncomingVariable__IsBoolAssignment_0_0 : ( ( 'bool' ) ) ;
public final void rule__IncomingVariable__IsBoolAssignment_0_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13146:1: ( ( ( 'bool' ) ) )
// InternalUrml.g:13147:1: ( ( 'bool' ) )
{
// InternalUrml.g:13147:1: ( ( 'bool' ) )
// InternalUrml.g:13148:1: ( 'bool' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getIsBoolBoolKeyword_0_0_0());
}
// InternalUrml.g:13149:1: ( 'bool' )
// InternalUrml.g:13150:1: 'bool'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getIsBoolBoolKeyword_0_0_0());
}
match(input,75,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getIsBoolBoolKeyword_0_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getIsBoolBoolKeyword_0_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__IsBoolAssignment_0_0"
// $ANTLR start "rule__IncomingVariable__IsIntAssignment_0_1"
// InternalUrml.g:13165:1: rule__IncomingVariable__IsIntAssignment_0_1 : ( ( 'int' ) ) ;
public final void rule__IncomingVariable__IsIntAssignment_0_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13169:1: ( ( ( 'int' ) ) )
// InternalUrml.g:13170:1: ( ( 'int' ) )
{
// InternalUrml.g:13170:1: ( ( 'int' ) )
// InternalUrml.g:13171:1: ( 'int' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getIsIntIntKeyword_0_1_0());
}
// InternalUrml.g:13172:1: ( 'int' )
// InternalUrml.g:13173:1: 'int'
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getIsIntIntKeyword_0_1_0());
}
match(input,76,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getIsIntIntKeyword_0_1_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getIsIntIntKeyword_0_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__IsIntAssignment_0_1"
// $ANTLR start "rule__IncomingVariable__NameAssignment_1"
// InternalUrml.g:13188:1: rule__IncomingVariable__NameAssignment_1 : ( RULE_ID ) ;
public final void rule__IncomingVariable__NameAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13192:1: ( ( RULE_ID ) )
// InternalUrml.g:13193:1: ( RULE_ID )
{
// InternalUrml.g:13193:1: ( RULE_ID )
// InternalUrml.g:13194:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIncomingVariableAccess().getNameIDTerminalRuleCall_1_0());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIncomingVariableAccess().getNameIDTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IncomingVariable__NameAssignment_1"
// $ANTLR start "rule__Trigger_out__ToAssignment_0"
// InternalUrml.g:13203:1: rule__Trigger_out__ToAssignment_0 : ( ( RULE_ID ) ) ;
public final void rule__Trigger_out__ToAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13207:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13208:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13208:1: ( ( RULE_ID ) )
// InternalUrml.g:13209:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getToPortCrossReference_0_0());
}
// InternalUrml.g:13210:1: ( RULE_ID )
// InternalUrml.g:13211:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getToPortIDTerminalRuleCall_0_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getToPortIDTerminalRuleCall_0_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getToPortCrossReference_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__ToAssignment_0"
// $ANTLR start "rule__Trigger_out__SignalAssignment_2"
// InternalUrml.g:13222:1: rule__Trigger_out__SignalAssignment_2 : ( ( RULE_ID ) ) ;
public final void rule__Trigger_out__SignalAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13226:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13227:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13227:1: ( ( RULE_ID ) )
// InternalUrml.g:13228:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getSignalSignalCrossReference_2_0());
}
// InternalUrml.g:13229:1: ( RULE_ID )
// InternalUrml.g:13230:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getSignalSignalIDTerminalRuleCall_2_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getSignalSignalIDTerminalRuleCall_2_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getSignalSignalCrossReference_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__SignalAssignment_2"
// $ANTLR start "rule__Trigger_out__ParametersAssignment_4_0"
// InternalUrml.g:13241:1: rule__Trigger_out__ParametersAssignment_4_0 : ( ruleExpression ) ;
public final void rule__Trigger_out__ParametersAssignment_4_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13245:1: ( ( ruleExpression ) )
// InternalUrml.g:13246:1: ( ruleExpression )
{
// InternalUrml.g:13246:1: ( ruleExpression )
// InternalUrml.g:13247:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getParametersExpressionParserRuleCall_4_0_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getParametersExpressionParserRuleCall_4_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__ParametersAssignment_4_0"
// $ANTLR start "rule__Trigger_out__ParametersAssignment_4_1_1"
// InternalUrml.g:13256:1: rule__Trigger_out__ParametersAssignment_4_1_1 : ( ruleExpression ) ;
public final void rule__Trigger_out__ParametersAssignment_4_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13260:1: ( ( ruleExpression ) )
// InternalUrml.g:13261:1: ( ruleExpression )
{
// InternalUrml.g:13261:1: ( ruleExpression )
// InternalUrml.g:13262:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getTrigger_outAccess().getParametersExpressionParserRuleCall_4_1_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getTrigger_outAccess().getParametersExpressionParserRuleCall_4_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Trigger_out__ParametersAssignment_4_1_1"
// $ANTLR start "rule__OperationCode__StatementsAssignment"
// InternalUrml.g:13271:1: rule__OperationCode__StatementsAssignment : ( ruleStatementOperation ) ;
public final void rule__OperationCode__StatementsAssignment() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13275:1: ( ( ruleStatementOperation ) )
// InternalUrml.g:13276:1: ( ruleStatementOperation )
{
// InternalUrml.g:13276:1: ( ruleStatementOperation )
// InternalUrml.g:13277:1: ruleStatementOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getOperationCodeAccess().getStatementsStatementOperationParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getOperationCodeAccess().getStatementsStatementOperationParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__OperationCode__StatementsAssignment"
// $ANTLR start "rule__WhileLoopOperation__ConditionAssignment_1"
// InternalUrml.g:13286:1: rule__WhileLoopOperation__ConditionAssignment_1 : ( ruleExpression ) ;
public final void rule__WhileLoopOperation__ConditionAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13290:1: ( ( ruleExpression ) )
// InternalUrml.g:13291:1: ( ruleExpression )
{
// InternalUrml.g:13291:1: ( ruleExpression )
// InternalUrml.g:13292:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getConditionExpressionParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getConditionExpressionParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__ConditionAssignment_1"
// $ANTLR start "rule__WhileLoopOperation__StatementsAssignment_3"
// InternalUrml.g:13301:1: rule__WhileLoopOperation__StatementsAssignment_3 : ( ruleStatementOperation ) ;
public final void rule__WhileLoopOperation__StatementsAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13305:1: ( ( ruleStatementOperation ) )
// InternalUrml.g:13306:1: ( ruleStatementOperation )
{
// InternalUrml.g:13306:1: ( ruleStatementOperation )
// InternalUrml.g:13307:1: ruleStatementOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopOperationAccess().getStatementsStatementOperationParserRuleCall_3_0());
}
pushFollow(FOLLOW_2);
ruleStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopOperationAccess().getStatementsStatementOperationParserRuleCall_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoopOperation__StatementsAssignment_3"
// $ANTLR start "rule__IfStatementOperation__ConditionAssignment_1"
// InternalUrml.g:13316:1: rule__IfStatementOperation__ConditionAssignment_1 : ( ruleExpression ) ;
public final void rule__IfStatementOperation__ConditionAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13320:1: ( ( ruleExpression ) )
// InternalUrml.g:13321:1: ( ruleExpression )
{
// InternalUrml.g:13321:1: ( ruleExpression )
// InternalUrml.g:13322:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getConditionExpressionParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getConditionExpressionParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__ConditionAssignment_1"
// $ANTLR start "rule__IfStatementOperation__ThenStatementsAssignment_3"
// InternalUrml.g:13331:1: rule__IfStatementOperation__ThenStatementsAssignment_3 : ( ruleStatementOperation ) ;
public final void rule__IfStatementOperation__ThenStatementsAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13335:1: ( ( ruleStatementOperation ) )
// InternalUrml.g:13336:1: ( ruleStatementOperation )
{
// InternalUrml.g:13336:1: ( ruleStatementOperation )
// InternalUrml.g:13337:1: ruleStatementOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getThenStatementsStatementOperationParserRuleCall_3_0());
}
pushFollow(FOLLOW_2);
ruleStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getThenStatementsStatementOperationParserRuleCall_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__ThenStatementsAssignment_3"
// $ANTLR start "rule__IfStatementOperation__ElseStatementsAssignment_5_2"
// InternalUrml.g:13346:1: rule__IfStatementOperation__ElseStatementsAssignment_5_2 : ( ruleStatementOperation ) ;
public final void rule__IfStatementOperation__ElseStatementsAssignment_5_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13350:1: ( ( ruleStatementOperation ) )
// InternalUrml.g:13351:1: ( ruleStatementOperation )
{
// InternalUrml.g:13351:1: ( ruleStatementOperation )
// InternalUrml.g:13352:1: ruleStatementOperation
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementOperationAccess().getElseStatementsStatementOperationParserRuleCall_5_2_0());
}
pushFollow(FOLLOW_2);
ruleStatementOperation();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementOperationAccess().getElseStatementsStatementOperationParserRuleCall_5_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatementOperation__ElseStatementsAssignment_5_2"
// $ANTLR start "rule__ReturnStatement__ReturnValueAssignment_2"
// InternalUrml.g:13361:1: rule__ReturnStatement__ReturnValueAssignment_2 : ( ruleExpression ) ;
public final void rule__ReturnStatement__ReturnValueAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13365:1: ( ( ruleExpression ) )
// InternalUrml.g:13366:1: ( ruleExpression )
{
// InternalUrml.g:13366:1: ( ruleExpression )
// InternalUrml.g:13367:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getReturnStatementAccess().getReturnValueExpressionParserRuleCall_2_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getReturnStatementAccess().getReturnValueExpressionParserRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ReturnStatement__ReturnValueAssignment_2"
// $ANTLR start "rule__ActionCode__StatementsAssignment"
// InternalUrml.g:13376:1: rule__ActionCode__StatementsAssignment : ( ruleStatement ) ;
public final void rule__ActionCode__StatementsAssignment() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13380:1: ( ( ruleStatement ) )
// InternalUrml.g:13381:1: ( ruleStatement )
{
// InternalUrml.g:13381:1: ( ruleStatement )
// InternalUrml.g:13382:1: ruleStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getActionCodeAccess().getStatementsStatementParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getActionCodeAccess().getStatementsStatementParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ActionCode__StatementsAssignment"
// $ANTLR start "rule__Variable__VarAssignment_1"
// InternalUrml.g:13391:1: rule__Variable__VarAssignment_1 : ( ruleLocalVar ) ;
public final void rule__Variable__VarAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13395:1: ( ( ruleLocalVar ) )
// InternalUrml.g:13396:1: ( ruleLocalVar )
{
// InternalUrml.g:13396:1: ( ruleLocalVar )
// InternalUrml.g:13397:1: ruleLocalVar
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getVarLocalVarParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleLocalVar();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getVarLocalVarParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__VarAssignment_1"
// $ANTLR start "rule__Variable__AssignAssignment_2_0"
// InternalUrml.g:13406:1: rule__Variable__AssignAssignment_2_0 : ( ( ':=' ) ) ;
public final void rule__Variable__AssignAssignment_2_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13410:1: ( ( ( ':=' ) ) )
// InternalUrml.g:13411:1: ( ( ':=' ) )
{
// InternalUrml.g:13411:1: ( ( ':=' ) )
// InternalUrml.g:13412:1: ( ':=' )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getAssignColonEqualsSignKeyword_2_0_0());
}
// InternalUrml.g:13413:1: ( ':=' )
// InternalUrml.g:13414:1: ':='
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getAssignColonEqualsSignKeyword_2_0_0());
}
match(input,16,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getAssignColonEqualsSignKeyword_2_0_0());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getAssignColonEqualsSignKeyword_2_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__AssignAssignment_2_0"
// $ANTLR start "rule__Variable__ExpAssignment_2_1"
// InternalUrml.g:13429:1: rule__Variable__ExpAssignment_2_1 : ( ruleExpression ) ;
public final void rule__Variable__ExpAssignment_2_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13433:1: ( ( ruleExpression ) )
// InternalUrml.g:13434:1: ( ruleExpression )
{
// InternalUrml.g:13434:1: ( ruleExpression )
// InternalUrml.g:13435:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getVariableAccess().getExpExpressionParserRuleCall_2_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getVariableAccess().getExpExpressionParserRuleCall_2_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Variable__ExpAssignment_2_1"
// $ANTLR start "rule__SendTrigger__TriggersAssignment_1"
// InternalUrml.g:13444:1: rule__SendTrigger__TriggersAssignment_1 : ( ruleTrigger_out ) ;
public final void rule__SendTrigger__TriggersAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13448:1: ( ( ruleTrigger_out ) )
// InternalUrml.g:13449:1: ( ruleTrigger_out )
{
// InternalUrml.g:13449:1: ( ruleTrigger_out )
// InternalUrml.g:13450:1: ruleTrigger_out
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getTriggersTrigger_outParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleTrigger_out();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getTriggersTrigger_outParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__TriggersAssignment_1"
// $ANTLR start "rule__SendTrigger__TriggersAssignment_2_1"
// InternalUrml.g:13459:1: rule__SendTrigger__TriggersAssignment_2_1 : ( ruleTrigger_out ) ;
public final void rule__SendTrigger__TriggersAssignment_2_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13463:1: ( ( ruleTrigger_out ) )
// InternalUrml.g:13464:1: ( ruleTrigger_out )
{
// InternalUrml.g:13464:1: ( ruleTrigger_out )
// InternalUrml.g:13465:1: ruleTrigger_out
{
if ( state.backtracking==0 ) {
before(grammarAccess.getSendTriggerAccess().getTriggersTrigger_outParserRuleCall_2_1_0());
}
pushFollow(FOLLOW_2);
ruleTrigger_out();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getSendTriggerAccess().getTriggersTrigger_outParserRuleCall_2_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__SendTrigger__TriggersAssignment_2_1"
// $ANTLR start "rule__InformTimer__TimerPortAssignment_1"
// InternalUrml.g:13474:1: rule__InformTimer__TimerPortAssignment_1 : ( ( RULE_ID ) ) ;
public final void rule__InformTimer__TimerPortAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13478:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13479:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13479:1: ( ( RULE_ID ) )
// InternalUrml.g:13480:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getTimerPortTimerPortCrossReference_1_0());
}
// InternalUrml.g:13481:1: ( RULE_ID )
// InternalUrml.g:13482:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getTimerPortTimerPortIDTerminalRuleCall_1_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getTimerPortTimerPortIDTerminalRuleCall_1_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getTimerPortTimerPortCrossReference_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__TimerPortAssignment_1"
// $ANTLR start "rule__InformTimer__TimeAssignment_3"
// InternalUrml.g:13493:1: rule__InformTimer__TimeAssignment_3 : ( ruleAdditiveExpression ) ;
public final void rule__InformTimer__TimeAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13497:1: ( ( ruleAdditiveExpression ) )
// InternalUrml.g:13498:1: ( ruleAdditiveExpression )
{
// InternalUrml.g:13498:1: ( ruleAdditiveExpression )
// InternalUrml.g:13499:1: ruleAdditiveExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInformTimerAccess().getTimeAdditiveExpressionParserRuleCall_3_0());
}
pushFollow(FOLLOW_2);
ruleAdditiveExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInformTimerAccess().getTimeAdditiveExpressionParserRuleCall_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__InformTimer__TimeAssignment_3"
// $ANTLR start "rule__Invoke__OperationAssignment_1"
// InternalUrml.g:13508:1: rule__Invoke__OperationAssignment_1 : ( ( RULE_ID ) ) ;
public final void rule__Invoke__OperationAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13512:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13513:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13513:1: ( ( RULE_ID ) )
// InternalUrml.g:13514:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getOperationOperationCrossReference_1_0());
}
// InternalUrml.g:13515:1: ( RULE_ID )
// InternalUrml.g:13516:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getOperationOperationIDTerminalRuleCall_1_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getOperationOperationIDTerminalRuleCall_1_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getOperationOperationCrossReference_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__OperationAssignment_1"
// $ANTLR start "rule__Invoke__ParametersAssignment_3_0"
// InternalUrml.g:13527:1: rule__Invoke__ParametersAssignment_3_0 : ( ruleExpression ) ;
public final void rule__Invoke__ParametersAssignment_3_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13531:1: ( ( ruleExpression ) )
// InternalUrml.g:13532:1: ( ruleExpression )
{
// InternalUrml.g:13532:1: ( ruleExpression )
// InternalUrml.g:13533:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getParametersExpressionParserRuleCall_3_0_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getParametersExpressionParserRuleCall_3_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__ParametersAssignment_3_0"
// $ANTLR start "rule__Invoke__ParametersAssignment_3_1_1"
// InternalUrml.g:13542:1: rule__Invoke__ParametersAssignment_3_1_1 : ( ruleExpression ) ;
public final void rule__Invoke__ParametersAssignment_3_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13546:1: ( ( ruleExpression ) )
// InternalUrml.g:13547:1: ( ruleExpression )
{
// InternalUrml.g:13547:1: ( ruleExpression )
// InternalUrml.g:13548:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getInvokeAccess().getParametersExpressionParserRuleCall_3_1_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getInvokeAccess().getParametersExpressionParserRuleCall_3_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Invoke__ParametersAssignment_3_1_1"
// $ANTLR start "rule__Assignment__LvalueAssignment_0"
// InternalUrml.g:13557:1: rule__Assignment__LvalueAssignment_0 : ( ( RULE_ID ) ) ;
public final void rule__Assignment__LvalueAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13561:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13562:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13562:1: ( ( RULE_ID ) )
// InternalUrml.g:13563:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getLvalueAssignableCrossReference_0_0());
}
// InternalUrml.g:13564:1: ( RULE_ID )
// InternalUrml.g:13565:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getLvalueAssignableIDTerminalRuleCall_0_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getLvalueAssignableIDTerminalRuleCall_0_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getLvalueAssignableCrossReference_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__LvalueAssignment_0"
// $ANTLR start "rule__Assignment__ExpAssignment_2"
// InternalUrml.g:13576:1: rule__Assignment__ExpAssignment_2 : ( ruleExpression ) ;
public final void rule__Assignment__ExpAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13580:1: ( ( ruleExpression ) )
// InternalUrml.g:13581:1: ( ruleExpression )
{
// InternalUrml.g:13581:1: ( ruleExpression )
// InternalUrml.g:13582:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAssignmentAccess().getExpExpressionParserRuleCall_2_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAssignmentAccess().getExpExpressionParserRuleCall_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Assignment__ExpAssignment_2"
// $ANTLR start "rule__WhileLoop__ConditionAssignment_1"
// InternalUrml.g:13591:1: rule__WhileLoop__ConditionAssignment_1 : ( ruleExpression ) ;
public final void rule__WhileLoop__ConditionAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13595:1: ( ( ruleExpression ) )
// InternalUrml.g:13596:1: ( ruleExpression )
{
// InternalUrml.g:13596:1: ( ruleExpression )
// InternalUrml.g:13597:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getConditionExpressionParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getConditionExpressionParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__ConditionAssignment_1"
// $ANTLR start "rule__WhileLoop__StatementsAssignment_3"
// InternalUrml.g:13606:1: rule__WhileLoop__StatementsAssignment_3 : ( ruleStatement ) ;
public final void rule__WhileLoop__StatementsAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13610:1: ( ( ruleStatement ) )
// InternalUrml.g:13611:1: ( ruleStatement )
{
// InternalUrml.g:13611:1: ( ruleStatement )
// InternalUrml.g:13612:1: ruleStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getWhileLoopAccess().getStatementsStatementParserRuleCall_3_0());
}
pushFollow(FOLLOW_2);
ruleStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getWhileLoopAccess().getStatementsStatementParserRuleCall_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__WhileLoop__StatementsAssignment_3"
// $ANTLR start "rule__IfStatement__ConditionAssignment_1"
// InternalUrml.g:13621:1: rule__IfStatement__ConditionAssignment_1 : ( ruleExpression ) ;
public final void rule__IfStatement__ConditionAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13625:1: ( ( ruleExpression ) )
// InternalUrml.g:13626:1: ( ruleExpression )
{
// InternalUrml.g:13626:1: ( ruleExpression )
// InternalUrml.g:13627:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getConditionExpressionParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getConditionExpressionParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__ConditionAssignment_1"
// $ANTLR start "rule__IfStatement__ThenStatementsAssignment_3"
// InternalUrml.g:13636:1: rule__IfStatement__ThenStatementsAssignment_3 : ( ruleStatement ) ;
public final void rule__IfStatement__ThenStatementsAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13640:1: ( ( ruleStatement ) )
// InternalUrml.g:13641:1: ( ruleStatement )
{
// InternalUrml.g:13641:1: ( ruleStatement )
// InternalUrml.g:13642:1: ruleStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getThenStatementsStatementParserRuleCall_3_0());
}
pushFollow(FOLLOW_2);
ruleStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getThenStatementsStatementParserRuleCall_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__ThenStatementsAssignment_3"
// $ANTLR start "rule__IfStatement__ElseStatementsAssignment_5_2"
// InternalUrml.g:13651:1: rule__IfStatement__ElseStatementsAssignment_5_2 : ( ruleStatement ) ;
public final void rule__IfStatement__ElseStatementsAssignment_5_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13655:1: ( ( ruleStatement ) )
// InternalUrml.g:13656:1: ( ruleStatement )
{
// InternalUrml.g:13656:1: ( ruleStatement )
// InternalUrml.g:13657:1: ruleStatement
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIfStatementAccess().getElseStatementsStatementParserRuleCall_5_2_0());
}
pushFollow(FOLLOW_2);
ruleStatement();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIfStatementAccess().getElseStatementsStatementParserRuleCall_5_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IfStatement__ElseStatementsAssignment_5_2"
// $ANTLR start "rule__LogStatement__LogPortAssignment_1"
// InternalUrml.g:13666:1: rule__LogStatement__LogPortAssignment_1 : ( ( RULE_ID ) ) ;
public final void rule__LogStatement__LogPortAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13670:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13671:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13671:1: ( ( RULE_ID ) )
// InternalUrml.g:13672:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getLogPortLogPortCrossReference_1_0());
}
// InternalUrml.g:13673:1: ( RULE_ID )
// InternalUrml.g:13674:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getLogPortLogPortIDTerminalRuleCall_1_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getLogPortLogPortIDTerminalRuleCall_1_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getLogPortLogPortCrossReference_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__LogPortAssignment_1"
// $ANTLR start "rule__LogStatement__LeftAssignment_3"
// InternalUrml.g:13685:1: rule__LogStatement__LeftAssignment_3 : ( ruleStringExpression ) ;
public final void rule__LogStatement__LeftAssignment_3() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13689:1: ( ( ruleStringExpression ) )
// InternalUrml.g:13690:1: ( ruleStringExpression )
{
// InternalUrml.g:13690:1: ( ruleStringExpression )
// InternalUrml.g:13691:1: ruleStringExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getLogStatementAccess().getLeftStringExpressionParserRuleCall_3_0());
}
pushFollow(FOLLOW_2);
ruleStringExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getLogStatementAccess().getLeftStringExpressionParserRuleCall_3_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__LogStatement__LeftAssignment_3"
// $ANTLR start "rule__ChooseStatement__XAssignment_2"
// InternalUrml.g:13700:1: rule__ChooseStatement__XAssignment_2 : ( ( RULE_ID ) ) ;
public final void rule__ChooseStatement__XAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13704:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13705:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13705:1: ( ( RULE_ID ) )
// InternalUrml.g:13706:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getXLocalVarCrossReference_2_0());
}
// InternalUrml.g:13707:1: ( RULE_ID )
// InternalUrml.g:13708:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getXLocalVarIDTerminalRuleCall_2_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getXLocalVarIDTerminalRuleCall_2_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getXLocalVarCrossReference_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__XAssignment_2"
// $ANTLR start "rule__ChooseStatement__EAssignment_4"
// InternalUrml.g:13719:1: rule__ChooseStatement__EAssignment_4 : ( ruleIntegerExpression ) ;
public final void rule__ChooseStatement__EAssignment_4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13723:1: ( ( ruleIntegerExpression ) )
// InternalUrml.g:13724:1: ( ruleIntegerExpression )
{
// InternalUrml.g:13724:1: ( ruleIntegerExpression )
// InternalUrml.g:13725:1: ruleIntegerExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getChooseStatementAccess().getEIntegerExpressionParserRuleCall_4_0());
}
pushFollow(FOLLOW_2);
ruleIntegerExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getChooseStatementAccess().getEIntegerExpressionParserRuleCall_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ChooseStatement__EAssignment_4"
// $ANTLR start "rule__FlipStatement__XAssignment_2"
// InternalUrml.g:13734:1: rule__FlipStatement__XAssignment_2 : ( ( RULE_ID ) ) ;
public final void rule__FlipStatement__XAssignment_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13738:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13739:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13739:1: ( ( RULE_ID ) )
// InternalUrml.g:13740:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getXLocalVarCrossReference_2_0());
}
// InternalUrml.g:13741:1: ( RULE_ID )
// InternalUrml.g:13742:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getXLocalVarIDTerminalRuleCall_2_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getXLocalVarIDTerminalRuleCall_2_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getXLocalVarCrossReference_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__XAssignment_2"
// $ANTLR start "rule__FlipStatement__EAssignment_4"
// InternalUrml.g:13753:1: rule__FlipStatement__EAssignment_4 : ( ruleIntegerExpression ) ;
public final void rule__FlipStatement__EAssignment_4() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13757:1: ( ( ruleIntegerExpression ) )
// InternalUrml.g:13758:1: ( ruleIntegerExpression )
{
// InternalUrml.g:13758:1: ( ruleIntegerExpression )
// InternalUrml.g:13759:1: ruleIntegerExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFlipStatementAccess().getEIntegerExpressionParserRuleCall_4_0());
}
pushFollow(FOLLOW_2);
ruleIntegerExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFlipStatementAccess().getEIntegerExpressionParserRuleCall_4_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FlipStatement__EAssignment_4"
// $ANTLR start "rule__IntegerExpression__ExprAssignment"
// InternalUrml.g:13768:1: rule__IntegerExpression__ExprAssignment : ( ruleExpression ) ;
public final void rule__IntegerExpression__ExprAssignment() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13772:1: ( ( ruleExpression ) )
// InternalUrml.g:13773:1: ( ruleExpression )
{
// InternalUrml.g:13773:1: ( ruleExpression )
// InternalUrml.g:13774:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntegerExpressionAccess().getExprExpressionParserRuleCall_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIntegerExpressionAccess().getExprExpressionParserRuleCall_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IntegerExpression__ExprAssignment"
// $ANTLR start "rule__StringExpression__RestAssignment_1_0_2"
// InternalUrml.g:13783:1: rule__StringExpression__RestAssignment_1_0_2 : ( ruleIndividualExpression ) ;
public final void rule__StringExpression__RestAssignment_1_0_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13787:1: ( ( ruleIndividualExpression ) )
// InternalUrml.g:13788:1: ( ruleIndividualExpression )
{
// InternalUrml.g:13788:1: ( ruleIndividualExpression )
// InternalUrml.g:13789:1: ruleIndividualExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getStringExpressionAccess().getRestIndividualExpressionParserRuleCall_1_0_2_0());
}
pushFollow(FOLLOW_2);
ruleIndividualExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getStringExpressionAccess().getRestIndividualExpressionParserRuleCall_1_0_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__StringExpression__RestAssignment_1_0_2"
// $ANTLR start "rule__IndividualExpression__ExprAssignment_0"
// InternalUrml.g:13798:1: rule__IndividualExpression__ExprAssignment_0 : ( ruleExpression ) ;
public final void rule__IndividualExpression__ExprAssignment_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13802:1: ( ( ruleExpression ) )
// InternalUrml.g:13803:1: ( ruleExpression )
{
// InternalUrml.g:13803:1: ( ruleExpression )
// InternalUrml.g:13804:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIndividualExpressionAccess().getExprExpressionParserRuleCall_0_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIndividualExpressionAccess().getExprExpressionParserRuleCall_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IndividualExpression__ExprAssignment_0"
// $ANTLR start "rule__IndividualExpression__StrAssignment_1"
// InternalUrml.g:13813:1: rule__IndividualExpression__StrAssignment_1 : ( RULE_STRING ) ;
public final void rule__IndividualExpression__StrAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13817:1: ( ( RULE_STRING ) )
// InternalUrml.g:13818:1: ( RULE_STRING )
{
// InternalUrml.g:13818:1: ( RULE_STRING )
// InternalUrml.g:13819:1: RULE_STRING
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIndividualExpressionAccess().getStrSTRINGTerminalRuleCall_1_0());
}
match(input,RULE_STRING,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIndividualExpressionAccess().getStrSTRINGTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IndividualExpression__StrAssignment_1"
// $ANTLR start "rule__ConditionalOrExpression__RestAssignment_1_0_2"
// InternalUrml.g:13828:1: rule__ConditionalOrExpression__RestAssignment_1_0_2 : ( ruleConditionalAndExpression ) ;
public final void rule__ConditionalOrExpression__RestAssignment_1_0_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13832:1: ( ( ruleConditionalAndExpression ) )
// InternalUrml.g:13833:1: ( ruleConditionalAndExpression )
{
// InternalUrml.g:13833:1: ( ruleConditionalAndExpression )
// InternalUrml.g:13834:1: ruleConditionalAndExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalOrExpressionAccess().getRestConditionalAndExpressionParserRuleCall_1_0_2_0());
}
pushFollow(FOLLOW_2);
ruleConditionalAndExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalOrExpressionAccess().getRestConditionalAndExpressionParserRuleCall_1_0_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalOrExpression__RestAssignment_1_0_2"
// $ANTLR start "rule__ConditionalAndExpression__RestAssignment_1_0_2"
// InternalUrml.g:13843:1: rule__ConditionalAndExpression__RestAssignment_1_0_2 : ( ruleRelationalOpExpression ) ;
public final void rule__ConditionalAndExpression__RestAssignment_1_0_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13847:1: ( ( ruleRelationalOpExpression ) )
// InternalUrml.g:13848:1: ( ruleRelationalOpExpression )
{
// InternalUrml.g:13848:1: ( ruleRelationalOpExpression )
// InternalUrml.g:13849:1: ruleRelationalOpExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getConditionalAndExpressionAccess().getRestRelationalOpExpressionParserRuleCall_1_0_2_0());
}
pushFollow(FOLLOW_2);
ruleRelationalOpExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getConditionalAndExpressionAccess().getRestRelationalOpExpressionParserRuleCall_1_0_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__ConditionalAndExpression__RestAssignment_1_0_2"
// $ANTLR start "rule__RelationalOpExpression__RestAssignment_1_1"
// InternalUrml.g:13858:1: rule__RelationalOpExpression__RestAssignment_1_1 : ( ruleAdditiveExpression ) ;
public final void rule__RelationalOpExpression__RestAssignment_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13862:1: ( ( ruleAdditiveExpression ) )
// InternalUrml.g:13863:1: ( ruleAdditiveExpression )
{
// InternalUrml.g:13863:1: ( ruleAdditiveExpression )
// InternalUrml.g:13864:1: ruleAdditiveExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getRelationalOpExpressionAccess().getRestAdditiveExpressionParserRuleCall_1_1_0());
}
pushFollow(FOLLOW_2);
ruleAdditiveExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getRelationalOpExpressionAccess().getRestAdditiveExpressionParserRuleCall_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__RelationalOpExpression__RestAssignment_1_1"
// $ANTLR start "rule__AdditiveExpression__RestAssignment_1_1"
// InternalUrml.g:13873:1: rule__AdditiveExpression__RestAssignment_1_1 : ( ruleMultiplicativeExpression ) ;
public final void rule__AdditiveExpression__RestAssignment_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13877:1: ( ( ruleMultiplicativeExpression ) )
// InternalUrml.g:13878:1: ( ruleMultiplicativeExpression )
{
// InternalUrml.g:13878:1: ( ruleMultiplicativeExpression )
// InternalUrml.g:13879:1: ruleMultiplicativeExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getAdditiveExpressionAccess().getRestMultiplicativeExpressionParserRuleCall_1_1_0());
}
pushFollow(FOLLOW_2);
ruleMultiplicativeExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getAdditiveExpressionAccess().getRestMultiplicativeExpressionParserRuleCall_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__AdditiveExpression__RestAssignment_1_1"
// $ANTLR start "rule__MultiplicativeExpression__RestAssignment_1_1"
// InternalUrml.g:13888:1: rule__MultiplicativeExpression__RestAssignment_1_1 : ( ruleUnaryExpression ) ;
public final void rule__MultiplicativeExpression__RestAssignment_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13892:1: ( ( ruleUnaryExpression ) )
// InternalUrml.g:13893:1: ( ruleUnaryExpression )
{
// InternalUrml.g:13893:1: ( ruleUnaryExpression )
// InternalUrml.g:13894:1: ruleUnaryExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getMultiplicativeExpressionAccess().getRestUnaryExpressionParserRuleCall_1_1_0());
}
pushFollow(FOLLOW_2);
ruleUnaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getMultiplicativeExpressionAccess().getRestUnaryExpressionParserRuleCall_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__MultiplicativeExpression__RestAssignment_1_1"
// $ANTLR start "rule__UnaryExpression__ExpAssignment_1_2"
// InternalUrml.g:13903:1: rule__UnaryExpression__ExpAssignment_1_2 : ( ruleUnaryExpression ) ;
public final void rule__UnaryExpression__ExpAssignment_1_2() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13907:1: ( ( ruleUnaryExpression ) )
// InternalUrml.g:13908:1: ( ruleUnaryExpression )
{
// InternalUrml.g:13908:1: ( ruleUnaryExpression )
// InternalUrml.g:13909:1: ruleUnaryExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getUnaryExpressionAccess().getExpUnaryExpressionParserRuleCall_1_2_0());
}
pushFollow(FOLLOW_2);
ruleUnaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getUnaryExpressionAccess().getExpUnaryExpressionParserRuleCall_1_2_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__UnaryExpression__ExpAssignment_1_2"
// $ANTLR start "rule__NotBooleanExpression__ExpAssignment_1"
// InternalUrml.g:13918:1: rule__NotBooleanExpression__ExpAssignment_1 : ( ruleUnaryExpression ) ;
public final void rule__NotBooleanExpression__ExpAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13922:1: ( ( ruleUnaryExpression ) )
// InternalUrml.g:13923:1: ( ruleUnaryExpression )
{
// InternalUrml.g:13923:1: ( ruleUnaryExpression )
// InternalUrml.g:13924:1: ruleUnaryExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getNotBooleanExpressionAccess().getExpUnaryExpressionParserRuleCall_1_0());
}
pushFollow(FOLLOW_2);
ruleUnaryExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getNotBooleanExpressionAccess().getExpUnaryExpressionParserRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__NotBooleanExpression__ExpAssignment_1"
// $ANTLR start "rule__IntLiteral__IntAssignment_1"
// InternalUrml.g:13933:1: rule__IntLiteral__IntAssignment_1 : ( RULE_INT ) ;
public final void rule__IntLiteral__IntAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13937:1: ( ( RULE_INT ) )
// InternalUrml.g:13938:1: ( RULE_INT )
{
// InternalUrml.g:13938:1: ( RULE_INT )
// InternalUrml.g:13939:1: RULE_INT
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIntLiteralAccess().getIntINTTerminalRuleCall_1_0());
}
match(input,RULE_INT,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIntLiteralAccess().getIntINTTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__IntLiteral__IntAssignment_1"
// $ANTLR start "rule__Identifier__IdAssignment"
// InternalUrml.g:13948:1: rule__Identifier__IdAssignment : ( ( RULE_ID ) ) ;
public final void rule__Identifier__IdAssignment() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13952:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13953:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13953:1: ( ( RULE_ID ) )
// InternalUrml.g:13954:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIdentifierAccess().getIdIdentifiableCrossReference_0());
}
// InternalUrml.g:13955:1: ( RULE_ID )
// InternalUrml.g:13956:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getIdentifierAccess().getIdIdentifiableIDTerminalRuleCall_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getIdentifierAccess().getIdIdentifiableIDTerminalRuleCall_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getIdentifierAccess().getIdIdentifiableCrossReference_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__Identifier__IdAssignment"
// $ANTLR start "rule__FunctionCall__CallAssignment_1"
// InternalUrml.g:13967:1: rule__FunctionCall__CallAssignment_1 : ( ( RULE_ID ) ) ;
public final void rule__FunctionCall__CallAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13971:1: ( ( ( RULE_ID ) ) )
// InternalUrml.g:13972:1: ( ( RULE_ID ) )
{
// InternalUrml.g:13972:1: ( ( RULE_ID ) )
// InternalUrml.g:13973:1: ( RULE_ID )
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getCallOperationCrossReference_1_0());
}
// InternalUrml.g:13974:1: ( RULE_ID )
// InternalUrml.g:13975:1: RULE_ID
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getCallOperationIDTerminalRuleCall_1_0_1());
}
match(input,RULE_ID,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getCallOperationIDTerminalRuleCall_1_0_1());
}
}
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getCallOperationCrossReference_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__CallAssignment_1"
// $ANTLR start "rule__FunctionCall__ParamsAssignment_3_0"
// InternalUrml.g:13986:1: rule__FunctionCall__ParamsAssignment_3_0 : ( ruleExpression ) ;
public final void rule__FunctionCall__ParamsAssignment_3_0() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:13990:1: ( ( ruleExpression ) )
// InternalUrml.g:13991:1: ( ruleExpression )
{
// InternalUrml.g:13991:1: ( ruleExpression )
// InternalUrml.g:13992:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getParamsExpressionParserRuleCall_3_0_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getParamsExpressionParserRuleCall_3_0_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__ParamsAssignment_3_0"
// $ANTLR start "rule__FunctionCall__ParamsAssignment_3_1_1"
// InternalUrml.g:14001:1: rule__FunctionCall__ParamsAssignment_3_1_1 : ( ruleExpression ) ;
public final void rule__FunctionCall__ParamsAssignment_3_1_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:14005:1: ( ( ruleExpression ) )
// InternalUrml.g:14006:1: ( ruleExpression )
{
// InternalUrml.g:14006:1: ( ruleExpression )
// InternalUrml.g:14007:1: ruleExpression
{
if ( state.backtracking==0 ) {
before(grammarAccess.getFunctionCallAccess().getParamsExpressionParserRuleCall_3_1_1_0());
}
pushFollow(FOLLOW_2);
ruleExpression();
state._fsp--;
if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getFunctionCallAccess().getParamsExpressionParserRuleCall_3_1_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__FunctionCall__ParamsAssignment_3_1_1"
// $ANTLR start "rule__BoolLiteral__TrueAssignment_1"
// InternalUrml.g:14016:1: rule__BoolLiteral__TrueAssignment_1 : ( RULE_BOOLEAN ) ;
public final void rule__BoolLiteral__TrueAssignment_1() throws RecognitionException {
int stackSize = keepStackSize();
try {
// InternalUrml.g:14020:1: ( ( RULE_BOOLEAN ) )
// InternalUrml.g:14021:1: ( RULE_BOOLEAN )
{
// InternalUrml.g:14021:1: ( RULE_BOOLEAN )
// InternalUrml.g:14022:1: RULE_BOOLEAN
{
if ( state.backtracking==0 ) {
before(grammarAccess.getBoolLiteralAccess().getTrueBOOLEANTerminalRuleCall_1_0());
}
match(input,RULE_BOOLEAN,FOLLOW_2); if (state.failed) return ;
if ( state.backtracking==0 ) {
after(grammarAccess.getBoolLiteralAccess().getTrueBOOLEANTerminalRuleCall_1_0());
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
restoreStackSize(stackSize);
}
return ;
}
// $ANTLR end "rule__BoolLiteral__TrueAssignment_1"
// Delegated rules
public static final BitSet FOLLOW_1 = new BitSet(new long[]{0x0000000000000000L});
public static final BitSet FOLLOW_2 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_3 = new BitSet(new long[]{0x0DDEC00000000012L});
public static final BitSet FOLLOW_4 = new BitSet(new long[]{0x0000000000000010L});
public static final BitSet FOLLOW_5 = new BitSet(new long[]{0x0000000000002000L});
public static final BitSet FOLLOW_6 = new BitSet(new long[]{0x0000000000824000L,0x0000000000002000L});
public static final BitSet FOLLOW_7 = new BitSet(new long[]{0x0000000000820002L,0x0000000000002000L});
public static final BitSet FOLLOW_8 = new BitSet(new long[]{0x0000000000000000L,0x0000000000001800L});
public static final BitSet FOLLOW_9 = new BitSet(new long[]{0x0000000000010000L});
public static final BitSet FOLLOW_10 = new BitSet(new long[]{0x00000000001000D0L,0x0000000000000440L});
public static final BitSet FOLLOW_11 = new BitSet(new long[]{0x00000000000C4000L});
public static final BitSet FOLLOW_12 = new BitSet(new long[]{0x00000000000C0002L});
public static final BitSet FOLLOW_13 = new BitSet(new long[]{0x0000000000004010L});
public static final BitSet FOLLOW_14 = new BitSet(new long[]{0x0000000000000012L});
public static final BitSet FOLLOW_15 = new BitSet(new long[]{0x0000000000100000L});
public static final BitSet FOLLOW_16 = new BitSet(new long[]{0x0000000000200000L,0x0000000000001800L});
public static final BitSet FOLLOW_17 = new BitSet(new long[]{0x0000000000400000L});
public static final BitSet FOLLOW_18 = new BitSet(new long[]{0x0000000000400002L});
public static final BitSet FOLLOW_19 = new BitSet(new long[]{0x0000000000800000L,0x0000000000002000L});
public static final BitSet FOLLOW_20 = new BitSet(new long[]{0x000000065F00C000L});
public static final BitSet FOLLOW_21 = new BitSet(new long[]{0x000000065F008002L});
public static final BitSet FOLLOW_22 = new BitSet(new long[]{0x0000000010000000L});
public static final BitSet FOLLOW_23 = new BitSet(new long[]{0x0000000000000000L,0x0000000000005800L});
public static final BitSet FOLLOW_24 = new BitSet(new long[]{0x0DDEC00000000010L});
public static final BitSet FOLLOW_25 = new BitSet(new long[]{0x0000000000004000L});
public static final BitSet FOLLOW_26 = new BitSet(new long[]{0x0000000000000010L,0x0000000000008000L});
public static final BitSet FOLLOW_27 = new BitSet(new long[]{0x0000000020000000L});
public static final BitSet FOLLOW_28 = new BitSet(new long[]{0x0000000080000000L});
public static final BitSet FOLLOW_29 = new BitSet(new long[]{0x0000000100000000L});
public static final BitSet FOLLOW_30 = new BitSet(new long[]{0x000000065F008000L});
public static final BitSet FOLLOW_31 = new BitSet(new long[]{0x0000008800004000L,0x0000000000010000L});
public static final BitSet FOLLOW_32 = new BitSet(new long[]{0x0000008800000002L,0x0000000000010000L});
public static final BitSet FOLLOW_33 = new BitSet(new long[]{0x0000000800000000L,0x0000000000010000L});
public static final BitSet FOLLOW_34 = new BitSet(new long[]{0x0000007000004000L});
public static final BitSet FOLLOW_35 = new BitSet(new long[]{0x0000000020000010L});
public static final BitSet FOLLOW_36 = new BitSet(new long[]{0x0000000000000010L,0x0000000000020000L});
public static final BitSet FOLLOW_37 = new BitSet(new long[]{0x0000010000000000L});
public static final BitSet FOLLOW_38 = new BitSet(new long[]{0x0000260000004000L});
public static final BitSet FOLLOW_39 = new BitSet(new long[]{0x0000100000000010L,0x0000000000000080L});
public static final BitSet FOLLOW_40 = new BitSet(new long[]{0x0000080000000000L});
public static final BitSet FOLLOW_41 = new BitSet(new long[]{0x0000080000000002L});
public static final BitSet FOLLOW_42 = new BitSet(new long[]{0x00000000003000D0L,0x0000000000000440L});
public static final BitSet FOLLOW_43 = new BitSet(new long[]{0x0001000000000000L});
public static final BitSet FOLLOW_44 = new BitSet(new long[]{0x0002000000000000L});
public static final BitSet FOLLOW_45 = new BitSet(new long[]{0x0000000080000002L});
public static final BitSet FOLLOW_46 = new BitSet(new long[]{0x0020000000000000L});
public static final BitSet FOLLOW_47 = new BitSet(new long[]{0x0040000000000000L});
public static final BitSet FOLLOW_48 = new BitSet(new long[]{0x0200000000000000L});
public static final BitSet FOLLOW_49 = new BitSet(new long[]{0x00000000001000F0L,0x0000000000000440L});
public static final BitSet FOLLOW_50 = new BitSet(new long[]{0x0000000000200000L});
public static final BitSet FOLLOW_51 = new BitSet(new long[]{0x1000000000000000L});
public static final BitSet FOLLOW_52 = new BitSet(new long[]{0x1000000000000002L});
public static final BitSet FOLLOW_53 = new BitSet(new long[]{0x2000000000000000L});
public static final BitSet FOLLOW_54 = new BitSet(new long[]{0x2000000000000002L});
public static final BitSet FOLLOW_55 = new BitSet(new long[]{0x4000000000000000L});
public static final BitSet FOLLOW_56 = new BitSet(new long[]{0x4000000000000002L});
public static final BitSet FOLLOW_57 = new BitSet(new long[]{0x8000000000000000L,0x000000000000001FL});
public static final BitSet FOLLOW_58 = new BitSet(new long[]{0x8000000000000002L,0x000000000000001FL});
public static final BitSet FOLLOW_59 = new BitSet(new long[]{0x8000000000000000L});
public static final BitSet FOLLOW_60 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000001L});
public static final BitSet FOLLOW_61 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000002L});
public static final BitSet FOLLOW_62 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000004L});
public static final BitSet FOLLOW_63 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000008L});
public static final BitSet FOLLOW_64 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000060L});
public static final BitSet FOLLOW_65 = new BitSet(new long[]{0x0000000000000002L,0x0000000000000060L});
public static final BitSet FOLLOW_66 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000020L});
public static final BitSet FOLLOW_67 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000380L});
public static final BitSet FOLLOW_68 = new BitSet(new long[]{0x0000000000000002L,0x0000000000000380L});
public static final BitSet FOLLOW_69 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000080L});
public static final BitSet FOLLOW_70 = new BitSet(new long[]{0x0000000000000000L,0x0000000000000100L});
public static final BitSet FOLLOW_71 = new BitSet(new long[]{0x0000000000000040L});
public static final BitSet FOLLOW_72 = new BitSet(new long[]{0x00000000000000D0L});
public static final BitSet FOLLOW_73 = new BitSet(new long[]{0x0000000000000080L});
}<file_sep>/ca.queensu.cs.mase.urml.ui/src/ca/queensu/cs/mase/ui/interpreter/launch/IUrmlLaunchConfigurationConstants.java
package ca.queensu.cs.mase.ui.interpreter.launch;
public interface IUrmlLaunchConfigurationConstants {
public static final String ATTR_MODEL_NAME = "model name";
public static final String ATTR_EXEC_CONFIG = "exec config";
public static final String EXEC_FIRST_TRANSITION = "first transition";
public static final String EXEC_RANDOM_TRANSITION = "random transition";
public static final String EXEC_INTERACTIVE = "interactive";
public static final String EXEC_EXPORT_F_H_TRANSITION = "export first transition high";
public static final String EXEC_EXPORT_F_L_TRANSITION = "export first transition low";
public static final String EXEC_EXPORT_R_H_TRANSITION = "export random transition high";
public static final String EXEC_EXPORT_R_L_TRANSITION = "export random transition low";
public static final String EXEC_EXPORT_I_H = "export interactive high";
public static final String EXEC_EXPORT_I_L = "export interactive low";
public static final String ATTR_EXIT_COND = "exit condition";
public static final String EXIT_SECONDS = "seconds";
public static final String EXIT_TRANSITIONS = "transitions";
public static final String EXIT_INFINITE = "infinite";
public static final String ATTR_EXIT_SECONDS = "exit seconds";
public static final String ATTR_EXIT_TRANSITIONS = "exit transitions";
}
<file_sep>/README.md
# URML
## About the URML toolkit
This toolkit is used by [Dr. <NAME>](http://research.cs.queensu.ca/~dingel/) at Queen's University's Faculty of Computing as part of his [CISC836](http://research.cs.queensu.ca/~dingel/cisc836_W16/) course (Models in Software Engineering). It was created by <NAME>, MSc as part of his thesis, where the toolkit is used to generate Java code based on software models. Recently as part of my summer research, it had been modified by me to resolve the code generator issue, where it would just hang and deadlock.
### Installing
If you are using a Windows machine, please install [Git](http://git-scm.com/download/win).
To clone the repository to Eclipse:
```
https://github.com/rchung95/urml.git
```
If you need some further instructions, please click [here](http://research.cs.queensu.ca/~dingel/cisc836_W16/eclipse.html)
### Example
I have provided a very small example to help understand the model. Feel free to edit it and play around with it.
### Instructions on creating your model
**1.** Ensure your JRE is the latest, when I wrote this, the latest is 1.8.
**2.** Go to ca.queensu.cs.mase.urml > src > Urml.xtext and write your keyword(s) in.
**3.** Right click the Urml.xtext file, click run as and generate xtext artifact. This will generate the GenerateUrml.mwe2 file which you will use later.
**4.** Within ca.queensu.ca.mase.urml, go to ca.queensu.cs.mase.generator.dispatchers and open the StatementGenerator.xtend file and add the functionality of the keyword(s) you added to Urml.xtext.
**5.** Right click GenerateUrml.mwe2 and run as MWE2 Workflow.
**6.** Right click ca.queensu.cs.mase.urml and run as Eclipse Application. This will open up another IDE.
##Credit
All credits for this toolkit goes to [Keith Yip](https://github.com/kiwi4boy/).
Modified by [<NAME>](https://github.com/rchung95)
| e3e639adc93d18b1b8e61bcfc04f3854d66882ea | [
"Markdown",
"Java"
] | 3 | Java | rchung95/urml | 74078be14a3dd07ef3a362c97df3fe5ca5eb40e8 | 0936f9614961712b859bb7f2799a08058acd7bee |
refs/heads/main | <repo_name>divyesh1099/chat_application<file_sep>/src/App.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import './App.css';
import Login from './components/Login';
import Chat from './components/Chat';
// function App() {
// useEffect(()=>{
// const name=window.prompt('Enter a username');
// setUsername(name);
// }, [])
// }
class App extends Component{
render() {
return (
<Router>
<div>
<h2>Welcome to MD Chat Application</h2>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<ul className="navbar-nav mr-auto">
<li><Link to={'/'} className="nav-link"> Login </Link></li>
<li><Link to={'/chat'} className="nav-link">Chat</Link></li>
</ul>
</nav>
<hr />
<Switch>
<Route exact path='/' component={Login} />
<Route path='/chat' component={Chat} />
</Switch>
</div>
</Router>
);
}
}
export default App;
<file_sep>/src/firebase.js
import firebase from "firebase";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "chat-application-7234b.firebaseapp.com",
projectId: "chat-application-7234b",
storageBucket: "chat-application-7234b.appspot.com",
messagingSenderId: "1080670429882",
appId: "1:1080670429882:web:d4e3dac67dcd7acc045883"
};
const app = firebase.initializeApp(firebaseConfig);
const database = app.firestore();
export default database;
<file_sep>/src/components/Login.js
// Login.js
import React, { Component, useState } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Chat from './Chat';
const [username, setUsername]= useState('Guest');
class Login extends Component {
render() {
return (
<Router>
<div>
<h2>Login</h2>
<form>
<input name="firstName" type="text" placeholder="<NAME>" />
<input name="lastName" type="text" placeholder="<NAME>" />
<button type="submit">Login</button>
</form>
</div>
<li><Link to={'/chat'} className="nav-link">Chat</Link></li>
<Switch>
<Route path='/chat' component={Chat} />
</Switch>
</Router>
);
}
}
export default Login;<file_sep>/src/components/Chat.js
// Chat.js
import React, { Component,useEffect, useState } from 'react';
import database from '../firebase';
import firebase from 'firebase';
import '../App.css';
const [input, setInput] = useState('');
const [list, setList] = useState([]);
useEffect(()=>{
//this code will run ONCE when the app component loads/mounts.
database.collection('messages').orderBy('timestamp', 'desc').onSnapshot((snapshot) => {
setList(snapshot.docs.map(doc => ({
id: doc.id,
data: doc.data()
})))
})
}, [])
const sendMessage = (event) => {
event.preventDefault(); // Prevents Refreshing.
// console.log("You Pressed a button");
const chatMessage = {
name: username,
message: input,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}
database.collection('messages').add(chatMessage);
setInput("");
};
class Chat extends Component {
render() {
return (
<div className="app">
<h1>This is a chat application!</h1>
{list.map(({id, data: { message, timestamp, name } }) => (
<h3 key={id} className='chatMessage'>
{name}:{message}
</h3>
))}
<form>
<input value={input} onChange={event => setInput(event.target.value)}/>
<button onClick={sendMessage} type="submit">Send message</button>
</form>
</div>
);
}
}
export default Chat; | ee946e37ad4ec2104bbe41e44016e8a535e92eab | [
"JavaScript"
] | 4 | JavaScript | divyesh1099/chat_application | eca3d65740b49667607bee762f60c19d4cb51684 | 64909f5ad7ef04fb1ea39d754cd2f26878fc3609 |
refs/heads/master | <repo_name>matthklo/libxpf<file_sep>/include/xpf/threadlock.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_THREADLOCK_HEADER_
#define _XPF_THREADLOCK_HEADER_
#include "platform.h"
#include "thread.h"
namespace xpf {
class XPF_API ThreadLock
{
public:
ThreadLock();
~ThreadLock(); // ThreadLock shall not be derived
void lock();
bool tryLock();
bool isLocked() const;
void unlock();
ThreadID getOwner() const;
private:
// Non-copyable
ThreadLock(const ThreadLock& that);
ThreadLock& operator = (const ThreadLock& that);
vptr pImpl;
};
// Header-only
class ScopedThreadLock
{
public:
explicit ScopedThreadLock(ThreadLock * lock) : mLock(lock) { mLock->lock(); }
explicit ScopedThreadLock(ThreadLock & lock) : mLock(&lock) { mLock->lock(); }
~ScopedThreadLock() { mLock->unlock(); }
private:
// non-copyable
ScopedThreadLock( const ScopedThreadLock& that) { xpfAssert( ( "non-copyable object", false ) ); }
ScopedThreadLock& operator = ( const ScopedThreadLock& that ) { xpfAssert( ( "non-copyable object", false ) ); return *this; }
ThreadLock *mLock;
};
} // end of namespace xpf
#endif // _XPF_THREADLOCK_HEADER_
<file_sep>/include/xpf/compiler.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_COMPILER_HEADER_
#define _XPF_COMPILER_HEADER_
/*
* Determines:
* 1. Compiler vendors & versions.
* 2. Debug/release configurations.
* Impl:
* 1. Library exporting macro.
* 2. Handy macros for working with compiler.
*/
#if defined(__cplusplus)
# define XPF_COMPILER_CXX 1
#else
# define XPF_COMPILER_C 1
#endif
//==========----- Compiler vendor and version -----==========//
#if !defined(XPF_COMPILER_SPECIFIED) && defined(_MSC_VER)
# if _MSC_VER >= 1700
// Visual Studio 2012
# define XPF_COMPILER_MSVC110 1
# elif _MSC_VER >= 1600
// Visual Studio 2010
# define XPF_COMPILER_MSVC100 1
# elif _MSC_VER >= 1500
// Visual Studio 2008
# define XPF_COMPILER_MSVC90 1
# elif _MSC_VER >= 1400
// Visual Studio 2005
# define XPF_COMPILER_MSVC80 1
# else
# error Your Visual Studio version is too old.
# endif
# if defined(XPF_COMPILER_CXX) && defined(_CPPRTTI)
# define XPF_COMPILER_CXX_RTTI 1
# endif
# define XPF_COMPILER_MSVC 1
# define XPF_COMPILER_SPECIFIED 1
#endif
#if !defined(XPF_COMPILER_SPECIFIED) && defined(__GNUC__)
# if __GNUC__ >= 4
# define XPF_COMPILER_GNUC4 1
# else
# error Your GNUC (or LLVM with GNUC frontend) version is too old.
# endif
# define XPF_COMPILER_GNUC 1
# if defined(__llvm__)
# define XPF_COMPILER_LLVM 1
# endif
# if defined(XPF_COMPILER_CXX) && defined(__GXX_RTTI)
# define XPF_COMPILER_CXX_RTTI 1
# endif
# define XPF_COMPILER_SPECIFIED 1
#endif
#if !defined(XPF_COMPILER_SPECIFIED) && (defined(__ICC) || defined(__INTEL_COMPILER))
# define XPF_COMPILER_INTEL 1
# if defined(XPF_COMPILER_CXX) && defined(__INTEL_RTTI__)
# define XPF_COMPILER_CXX_RTTI 1
# endif
# define XPF_COMPILER_SPECIFIED 1
#endif
//==========----- Library exporting / function visibility macros -----==========//
#if defined(XPF_STATIC_LIBRARY) || defined(XPF_BUILD_STATIC_LIBRARY)
# define XPF_API
#else
# if defined(XPF_COMPILER_MSVC)
# if defined(XPF_BUILD_LIBRARY)
# define XPF_API __declspec(dllexport)
# else
# define XPF_API __declspec(dllimport)
# endif
# elif defined(XPF_COMPILER_GNUC)
# if defined(XPF_BUILD_LIBRARY)
# define XPF_API __attribute__ ((visibility("default")))
# else
# define XPF_API
# endif
# else
# define XPF_API
# endif
#endif
#if defined(XPF_COMPILER_CXX)
# define XPF_EXTERNC extern "C"
# define XPF_EXTERNC_BEGIN extern "C" {
# define XPF_EXTERNC_END }
#else
# define XPF_EXTERNC
# define XPF_EXTERNC_BEGIN
# define XPF_EXTERNC_END
#endif
//==========----- Build configurations -----==========//
#if defined(_WIN32)
# if defined(_MT)
# if defined(_DLL)
# define XPF_WINCRT_DLL 1
# else
# define XPF_WINCRT_STATIC 1
# endif
# else
# error Single-thread version of Windows crt is not supported.
# endif
# if defined(_DEBUG)
# define XPF_BUILD_DEBUG 1
# else
# define XPF_BUILD_RELEASE 1
# endif
#else
# if !defined(NDEBUG)
# define XPF_BUILD_DEBUG 1
# else
# define XPF_BUILD_RELEASE 1
# endif
#endif
//==========----- Handy macros -----==========//
// Manual branch predictions (currently only work with GNUC compiler)
//
// Please note that manual branch prediction usually work worse than built-in
// CPU branch prediction when the branch code has temporal locality and the
// distribution of branch occurances are in kind of pattern (i.e. not random).
//
// To know more about branch prediction, please refer to:
// http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array
#if defined(XPF_COMPILER_GNUC)
#define xpfLikely(x) __builtin_expect((x),1)
#define xpfUnlikely(x) __builtin_expect((x),0)
#else
#define xpfLikely(x) x
#define xpfUnlikely(x) x
#endif
// Supress unused local variable warning
#define XPF_NOTUSED(x) x
//==========----------==========//
#endif // _XPF_COMPILER_HEADER_
<file_sep>/include/xpf/atomic.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_ATOMIC_HEADER_
#define _XPF_ATOMIC_HEADER_
#include "platform.h"
#ifdef XPF_COMPILER_MSVC
# if _MSC_VER < 1400
# error Atmoic intrinsics only work on MSVC 2005 or later version.
# endif
# define XPF_HAVE_ATOMIC_OPERATIONS
# include <intrin.h>
// Atomic ADD: Returns the value before adding.
// Ex:
// xpf::s32 val, addend = 10;
// xpf::s32 old = xpfAtomicAdd(&val, addend);
#define xpfAtomicAdd(_Ptr, _Add) _InterlockedExchangeAdd((volatile long*)_Ptr, _Add)
#define xpfAtomicAdd64(_Ptr, _Add) _InterlockedExchangeAdd64((volatile __int64*)_Ptr, _Add)
// Atomic OR: Returns the value before OR.
// Ex:
// xpf::s32 val, mask = 0xf0f0f0f0;
// xpf::s32 old = xpfAtomicOr(&val, mask);
#define xpfAtomicOr(_Ptr, _Mask) _InterlockedOr((volatile long*)_Ptr, _Mask)
#define xpfAtomicOr8(_Ptr, _Mask) _InterlockedOr8((volatile char*)_Ptr, _Mask)
#define xpfAtomicOr16(_Ptr, _Mask) _InterlockedOr16((volatile short*)_Ptr, _Mask)
#define xpfAtomicOr64(_Ptr, _Mask) _InterlockedOr64((volatile __int64*)_Ptr, _Mask)
// Atomic AND: Returns the value before AND.
// Ex:
// xpf::s32 val, mask = 0xf0f0f0f0;
// xpf::s32 old = xpfAtomicAnd(&val, mask);
#define xpfAtomicAnd(_Ptr, _Mask) _InterlockedAnd((volatile long*)_Ptr, _Mask)
#define xpfAtomicAnd8(_Ptr, _Mask) _InterlockedAnd8((volatile char*)_Ptr, _Mask)
#define xpfAtomicAnd16(_Ptr, _Mask) _InterlockedAnd16((volatile short*)_Ptr, _Mask)
#define xpfAtomicAnd64(_Ptr, _Mask) _InterlockedAnd64((volatile __int64*)_Ptr, _Mask)
// Atomic XOR: Returns the value before XOR.
// Ex:
// xpf::s32 val, mask = 0xf0f0f0f0;
// xpf::s32 old = xpfAtomicXor(&val, mask);
#define xpfAtomicXor(_Ptr, _Mask) _InterlockedXor((volatile long*)_Ptr, _Mask)
#define xpfAtomicXor8(_Ptr, _Mask) _InterlockedXor8((volatile char*)_Ptr, _Mask)
#define xpfAtomicXor16(_Ptr, _Mask) _InterlockedXor16((volatile short*)_Ptr, _Mask)
#define xpfAtomicXor64(_Ptr, _Mask) _InterlockedXor64((volatile __int64*)_Ptr, _Mask)
// Atomic Compare-and-swap operation (CAS): Compare the value pointed by '_Dest' to '_Comperand'.
// If equal, swap the value to be '_Exchange'.
// Return the initial value store in '_Dest' BEFORE the operation.
#define xpfAtomicCAS(_Dest, _Comperand, _Exchange) _InterlockedCompareExchange((volatile long*)_Dest, _Exchange, _Comperand)
#define xpfAtomicCAS16(_Dest, _Comperand, _Exchange) _InterlockedCompareExchange16((volatile short*)_Dest, _Exchange, _Comperand)
#define xpfAtomicCAS64(_Dest, _Comperand, _Exchange) _InterlockedCompareExchange64((volatile __int64*)_Dest, _Exchange, _Comperand)
#elif defined(XPF_COMPILER_GNUC)
# define XPF_HAVE_ATOMIC_OPERATIONS
// Atomic ADD: Returns the value before adding.
// Ex:
// xpf::s32 val, addend = 10;
// xpf::s32 old = xpfAtomicAdd(&val, addend);
#define xpfAtomicAdd(_Ptr, _Add) __sync_fetch_and_add(_Ptr, _Add)
#define xpfAtomicAdd64(_Ptr, _Add) __sync_fetch_and_add(_Ptr, _Add)
// Atomic OR: Returns the value before OR.
// Ex:
// xpf::s32 val, mask = 0xf0f0f0f0;
// xpf::s32 old = xpfAtomicOr(&val, mask);
#define xpfAtomicOr(_Ptr, _Mask) __sync_fetch_and_or(_Ptr, _Mask)
#define xpfAtomicOr8(_Ptr, _Mask) __sync_fetch_and_or(_Ptr, _Mask)
#define xpfAtomicOr16(_Ptr, _Mask) __sync_fetch_and_or(_Ptr, _Mask)
#define xpfAtomicOr64(_Ptr, _Mask) __sync_fetch_and_or(_Ptr, _Mask)
// Atomic AND: Returns the value before AND.
// Ex:
// xpf::s32 val, mask = 0xf0f0f0f0;
// xpf::s32 old = xpfAtomicAnd(&val, mask);
#define xpfAtomicAnd(_Ptr, _Mask) __sync_fetch_and_and(_Ptr, _Mask)
#define xpfAtomicAnd8(_Ptr, _Mask) __sync_fetch_and_and(_Ptr, _Mask)
#define xpfAtomicAnd16(_Ptr, _Mask) __sync_fetch_and_and(_Ptr, _Mask)
#define xpfAtomicAnd64(_Ptr, _Mask) __sync_fetch_and_and(_Ptr, _Mask)
// Atomic XOR: Returns the value before XOR.
// Ex:
// xpf::s32 val, mask = 0xf0f0f0f0;
// xpf::s32 old = xpfAtomicXor(&val, mask);
#define xpfAtomicXor(_Ptr, _Mask) __sync_fetch_and_xor(_Ptr, _Mask)
#define xpfAtomicXor8(_Ptr, _Mask) __sync_fetch_and_xor(_Ptr, _Mask)
#define xpfAtomicXor16(_Ptr, _Mask) __sync_fetch_and_xor(_Ptr, _Mask)
#define xpfAtomicXor64(_Ptr, _Mask) __sync_fetch_and_xor(_Ptr, _Mask)
// Atomic Compare-and-swap operation (CAS): Compare the value pointed by '_Dest' to '_Comperand'.
// If equal, swap the value to be '_Exchange'.
// Return the initial value store in '_Dest' BEFORE the operation.
#define xpfAtomicCAS(_Dest, _Comperand, _Exchange) __sync_val_compare_and_swap(_Dest, _Comperand, _Exchange)
#define xpfAtomicCAS16(_Dest, _Comperand, _Exchange) __sync_val_compare_and_swap(_Dest, _Comperand, _Exchange)
#define xpfAtomicCAS64(_Dest, _Comperand, _Exchange) __sync_val_compare_and_swap(_Dest, _Comperand, _Exchange)
#else
# error Atomic operations have not yet implemented for your compiler.
#endif
#endif // _XPF_ATOMIC_HEADER_<file_sep>/tests/network/async_server.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include "async_server.h"
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <stdio.h>
#include <string.h>
using namespace xpf;
WorkerThread::WorkerThread(NetIoMux *mux)
: mMux(mux)
{
}
WorkerThread::~WorkerThread()
{
}
u32 WorkerThread::run(u64 udata)
{
printf("WorkerThread ID = %llu\n", Thread::getID());
mMux->run();
return 0;
}
//=================------------------=====================//
TestAsyncServer::TestAsyncServer(u32 threadNum)
{
mMux = new NetIoMux();
xpfAssert(threadNum > 0);
for (u32 i = 0; i < threadNum; ++i)
{
mThreads.push_back(new WorkerThread(mMux));
}
mListeningEp = NetEndpoint::create(NetEndpoint::ProtocolIPv4 | NetEndpoint::ProtocolTCP,
"localhost", "50123");
xpfAssert(mListeningEp != 0);
mMux->join(mListeningEp);
}
TestAsyncServer::~TestAsyncServer()
{
stop();
for (std::vector<NetEndpoint*>::iterator it = mClients.begin();
it != mClients.end(); ++it)
{
NetEndpoint *ep = *it;
Buffer *b = (Buffer*)ep->getUserData();
mMux->depart(ep);
delete ep;
delete b;
}
delete mListeningEp;
delete mMux;
mMux = 0;
}
void TestAsyncServer::start()
{
if (mListeningEp)
mMux->asyncAccept(mListeningEp, this);
printf("[Serv] Starting worker threads ...\n");
for (u32 i = 0; i < mThreads.size(); ++i)
mThreads[i]->start();
}
void TestAsyncServer::stop()
{
if (mThreads.empty())
return;
mMux->disable();
printf("[Serv] Joining async server worker threads ...\n");
while (!mThreads.empty())
{
for (u32 i = 0; i < mThreads.size(); ++i)
{
bool joined = mThreads[i]->join();
if (joined)
{
delete mThreads[i];
mThreads[i] = mThreads.back();
mThreads.pop_back();
}
}
}
printf("[Serv] All worker threads of async server have been joined.\n");
}
void TestAsyncServer::onIoCompleted(
NetIoMux::EIoType type,
NetEndpoint::EError ec,
NetEndpoint *sep,
vptr tepOrPeer,
const c8 *buf,
u32 len)
{
switch (type)
{
case NetIoMux::EIT_ACCEPT:
AcceptCb(ec, sep, (NetEndpoint*)tepOrPeer);
break;
case NetIoMux::EIT_RECV:
RecvCb(ec, sep, buf, len);
break;
case NetIoMux::EIT_SEND:
SendCb(ec, sep, buf, len);
break;
default:
xpfAssert(("Unexpected NetIoMux::EIoType.", false));
break;
}
}
void TestAsyncServer::AcceptCb(NetEndpoint::EError ec, NetEndpoint* listeningEp, NetEndpoint* acceptedEp)
{
xpfAssert(listeningEp == mListeningEp);
if (ec != NetEndpoint::EE_SUCCESS)
{
printf("[Serv] Disable NetIoMux - accept failed. \n");
mMux->disable();
}
else
{
Buffer *b = new Buffer;
b->Used = 0;
acceptedEp->setUserData((vptr)b);
printf("[Serv] A new connection accepted.\n");
mMux->asyncRecv(acceptedEp, b->RData, 2048, this);
mMux->asyncAccept(listeningEp, this);
}
}
void TestAsyncServer::RecvCb(NetEndpoint::EError ec, NetEndpoint* ep, const c8* buf, u32 bytes)
{
if (ec != NetEndpoint::EE_SUCCESS)
{
printf("[Serv] Recv error.\n");
}
else if (bytes == 0)
{
printf("[Serv] Recv - End of data.\n");
}
else
{
Buffer *b = (Buffer*)ep->getUserData();
const u16 tbytes = b->Used + bytes;
u16 idx = 0;
while (true)
{
u16 sum = 0;
u16 packetlen = *(u16*)(&b->RData[idx]) + sizeof(u16);
xpfAssert(packetlen <= 2048);
if (idx + packetlen > tbytes)
{
printf("[Serv] Truncated packet data.\n");
b->Used = tbytes - idx;
if (b->Used > 0)
memmove(b->RData, &b->RData[idx], b->Used);
break;
}
bool verified = false;
const u16 cnt = *(u16*)(&b->RData[idx]) / sizeof(u16);
for (u16 i = 1; i <= cnt; ++i)
{
if (i != cnt)
sum += *(u16*)(&b->RData[idx + (i*sizeof(u16))]);
else
verified = (sum == *(u16*)(&b->RData[idx + (i*sizeof(u16))]));
}
xpfAssert(verified);
*(u16*)b->WData = sum;
mMux->asyncSend(ep, b->WData, sizeof(u16), this);
idx += packetlen;
if (idx >= tbytes)
{
b->Used = 0;
break;
}
} // end of while (true)
mMux->asyncRecv(ep, &b->RData[b->Used], (u32)(2048 - b->Used), this);
}
}
void TestAsyncServer::SendCb(NetEndpoint::EError ec, NetEndpoint* ep, const c8* buf, u32 bytes)
{
xpfAssert(ec == NetEndpoint::EE_SUCCESS);
}
<file_sep>/build/gen_makefile.sh
#!/bin/sh
# cmake -DCMAKE_VERBOSE_MAKEFILE=on -DCMAKE_BUILD_TYPE=Release -G "Unix Makefiles" ../
cmake -G "Unix Makefiles" ../
<file_sep>/include/xpf/refcnt.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_REFCNT_HEADER_
#define _XPF_REFCNT_HEADER_
#include "platform.h"
namespace xpf {
// NOTE: Header-only impl.
/**
* A base class for objects whose life-cycle should be controlled by reference counting.
* RefCounted-derived objects born with ref count 1. Owners (except the one who new
* it) of such object should increase the reference count of it by calling ref(), and
* decrease the reference count by unref() after done using. Object with a reference
* count 0 will be deleted before the return of unref().
*/
class RefCounted
{
public:
RefCounted()
: mRefCount(1)
, mDebugName(0)
{
}
virtual ~RefCounted()
{
}
virtual s32 ref() const
{
return ++mRefCount;
}
virtual bool unref() const
{
xpfAssert( ( "Expecting a positive ref count.", mRefCount > 0 ));
if (0 == (--mRefCount))
{
delete this;
return true;
}
return false;
}
inline s32 getRefCount() const
{
return mRefCount;
}
inline const c8* getDebugName() const
{
return mDebugName;
}
protected:
// For derived class to associate a name for
// debugging purpose. Suggest to use a static
// immutable c-string since the life cycle of
// given string is not controlled by class.
void setDebugName(const c8* name)
{
mDebugName = name;
}
private:
mutable s32 mRefCount;
const c8* mDebugName;
};
/**
* A RefCounted-derived class with floating reference support.
* A floating reference means the object has been created with
* no owner. Whoever call ref() of this object at the first
* place owns this object (the ref count won't increase, instead
* the floating flag will be turn off).
*
* Ex: Class A creates a ref-counted object and than pass it to
* B and do unref() because A no more need to own the object.
*
* With RefCounted obj, the code will be:
* RefCounted *obj = new MyObject;
* B.adopt(obj); // B calls ref() on obj in adopt()
* obj->unref();
*
* With FloatingRefCounted obj, the code can be shorten to:
* B.adopt(new MyFloatingRefObject);
*/
class FloatingRefCounted : virtual public RefCounted
{
public:
FloatingRefCounted()
: mFloating(true)
{
}
virtual ~FloatingRefCounted()
{
}
virtual s32 ref() const
{
if ( xpfUnlikely(mFloating) )
{
mFloating = false;
return getRefCount();
}
return RefCounted::ref();
}
virtual bool unref() const
{
mFloating = false;
return RefCounted::unref();
}
inline bool isFloating() const
{
return mFloating;
}
inline void setFloating(bool f)
{
mFloating = f;
}
private:
mutable bool mFloating;
};
} // end of namespace xpf
#endif // _XPF_REFCNT_HEADER_<file_sep>/tests/base64/base64_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/base64.h>
#include <string.h>
#include <stdio.h>
// testcase from http://en.wikipedia.org/wiki/Base64
const char *plaintexts[] = {
"Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.",
"pleasure.",
"leasure.",
"easure.",
"asure.",
"sure.",
};
const char *codedtexts[] = {
"<KEY>
"cGxlYXN1cmUu",
"bGVhc3VyZS4=",
"ZWFzdXJlLg==",
"YXN1cmUu",
"c3VyZS4=",
};
using namespace xpf;
int main()
{
int testcases = sizeof(plaintexts) / sizeof(const char*);
// encoding test
for (int i = 0; i<testcases; ++i)
{
int olen = Base64::encode(plaintexts[i], 0, 0, 0);
xpfAssert(olen == 0);
int len = strlen(plaintexts[i]);
olen = Base64::encode(plaintexts[i], len, 0, 0);
xpfAssert(olen == strlen(codedtexts[i]));
char *buf = new char[olen + 1];
buf[olen] = '\0';
// ensure the actual output len hint is work.
int blen = 1;
int tlen = Base64::encode(plaintexts[i], len, buf, &blen);
xpfAssert((tlen == -1) && (blen == strlen(codedtexts[i])));
// ensure encoding is work.
blen = olen + 1;
tlen = Base64::encode(plaintexts[i], len, buf, &blen);
xpfAssert(blen == (tlen + 1)); // ensure blen is not touched when output buf is sufficient
xpfAssert(tlen == olen);
xpfAssert(strcmp(buf, codedtexts[i]) == 0);
delete[] buf;
}
// decoding test
for (int i = 0; i<testcases; ++i)
{
int olen = Base64::decode(codedtexts[i], 0, 0, 0);
xpfAssert(olen == 0);
int len = strlen(codedtexts[i]);
olen = Base64::decode(codedtexts[i], len, 0, 0);
xpfAssert(olen == strlen(plaintexts[i]));
char *buf = new char[olen + 1];
buf[olen] = '\0';
// ensure the actual output len hint is work.
int blen = 1;
int tlen = Base64::decode(codedtexts[i], len, buf, &blen);
xpfAssert((tlen == -1) && (blen == strlen(plaintexts[i])));
// ensure decoding is work.
blen = olen + 1;
tlen = Base64::decode(codedtexts[i], len, buf, &blen);
xpfAssert(blen == (tlen + 1)); // ensure blen is not touched when output buf is sufficient
xpfAssert(tlen == olen);
xpfAssert(strcmp(buf, plaintexts[i]) == 0);
printf("testcase %d: %s\n", i + 1, buf);
delete[] buf;
}
return 0;
}
<file_sep>/src/platform/tls_posix.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifdef _XPF_TLS_IMPL_INCLUDED_
#error Multiple TLS implementation files included
#else
#define _XPF_TLS_IMPL_INCLUDED_
#endif
#include <pthread.h>
namespace xpf {
struct TlsIndex
{
pthread_key_t Index;
};
vptr
TlsCreate()
{
pthread_key_t idx;
if (0 != pthread_key_create(&idx, 0))
{
xpfAssert(("Failed on pthread_key_create().", false));
return 0;
}
TlsIndex *index = new TlsIndex;
index->Index = idx;
return (vptr)index;
}
void
TlsDelete(vptr index)
{
xpfAssert(("Operate TlsDelete() with a null index.", (index != 0)));
if (index == 0)
return;
TlsIndex *idx = (TlsIndex*)index;
if (0 != pthread_key_delete(idx->Index))
{
xpfAssert(("Failed on pthread_key_delete().", false));
return;
}
delete idx;
}
vptr
TlsGet(vptr index)
{
xpfAssert(("Operate TlsGet() with a null index.", (index != 0)));
if (index == 0)
return 0;
TlsIndex *idx = (TlsIndex*)index;
return (vptr)pthread_getspecific(idx->Index);
}
void
TlsSet(vptr index, vptr data)
{
xpfAssert(("Operate TlsSet() with a null index.", (index != 0)));
if (index == 0)
return;
TlsIndex *idx = (TlsIndex*)index;
if (0 != pthread_setspecific(idx->Index, (void*)data))
{
xpfAssert(("Failed on pthread_setspecific().", false));
}
}
};<file_sep>/tests/network/main.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/platform.h>
#include <xpf/string.h>
#include "async_client.h"
#include "async_server.h"
#include "sync_client.h"
#include "sync_server.h"
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
int test_sync()
{
TestSyncServer *syncServ = new TestSyncServer;
printf("Sync Server started .\n");
syncServ->start();
xpf::Thread::sleep(100);
std::vector<TestSyncClient*> clients;
for (xpf::u32 i = 0; i < 20; ++i)
{
TestSyncClient *syncClient = new TestSyncClient(1000, 0);
clients.push_back(syncClient);
}
printf("Starting %lu sync clients ...\n", clients.size());
for (xpf::u32 i = 0; i < clients.size(); ++i)
{
clients[i]->start();
}
xpf::u32 errorcnt = 0;
while (!clients.empty())
{
for (xpf::u32 i = 0; i < clients.size(); ++i)
{
if (clients[i]->join(10))
{
xpf::u32 exitcode = clients[i]->getExitCode();
if (exitcode != 0)
errorcnt++;
delete clients[i];
clients[i] = clients.back();
clients.pop_back();
}
}
xpf::u32 remains = (xpf::u32)clients.size();
if ((remains != 0) && ((remains % 10) == 0))
{
printf("%u remaining sync clients ...\n", remains);
}
}
printf("All sync Clients have stopped. %u clients end up with error.\n", errorcnt);
printf("Sync Server stopping ...\n");
delete syncServ;
printf("Sync Server stopped .\n");
return 0;
}
int test_async()
{
TestAsyncServer *asyncServ = new TestAsyncServer(5);
TestAsyncClient *asyncClient = new TestAsyncClient(5);
asyncServ->start();
xpf::Thread::sleep(100);
asyncClient->start();
asyncClient->stop();
delete asyncClient;
asyncServ->stop();
delete asyncServ;
return 0;
}
int main(int argc, char *argv[])
{
srand((unsigned int)time(0));
if ((argc >= 2) && (xpf::string(argv[1]) == "async"))
{
printf("==== Running async test ====\n");
test_async();
}
else
{
printf("==== Running sync test ====\n");
test_sync();
}
return 0;
}
<file_sep>/src/netiomux.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/netiomux.h>
#include <xpf/string.h>
#include <xpf/lexicalcast.h>
#if defined(XPF_PLATFORM_WINDOWS)
# include "platform/netiomux_iocp.hpp"
#elif defined(XPF_PLATFORM_LINUX)
// Use epoll on Linux, Android hosts.
# include "platform/netiomux_epoll.hpp"
#elif defined(XPF_PLATFORM_BSD)
// Use kqueue on BSD-family hosts (both MacOSX and ios are included)
# include "platform/netiomux_kqueue.hpp"
#else
# error NetIoMux is not supported on current platform.
#endif
namespace xpf
{
NetIoMux::NetIoMux()
{
pImpl = new NetIoMuxImpl();
pDefaultMuxCallback = 0;
}
NetIoMux::~NetIoMux()
{
if (pImpl)
{
delete pImpl;
pImpl = 0;
}
}
void NetIoMux::enable(bool val)
{
pImpl->enable(val);
}
void NetIoMux::run()
{
pImpl->run();
}
NetIoMux::ERunningStaus NetIoMux::runOnce(u32 timeoutMs)
{
return pImpl->runOnce(timeoutMs);
}
void NetIoMux::asyncRecv(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
pImpl->asyncRecv(ep, buf, buflen, cb ? cb : pDefaultMuxCallback);
}
void NetIoMux::asyncRecvFrom(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
pImpl->asyncRecvFrom(ep, buf, buflen, cb ? cb : pDefaultMuxCallback);
}
void NetIoMux::asyncSend(NetEndpoint *ep, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
pImpl->asyncSend(ep, buf, buflen, cb ? cb : pDefaultMuxCallback);
}
void NetIoMux::asyncSendTo(NetEndpoint *ep, const NetEndpoint::Peer *peer, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
pImpl->asyncSendTo(ep, peer, buf, buflen, cb ? cb : pDefaultMuxCallback);
}
void NetIoMux::asyncAccept(NetEndpoint *ep, NetIoMuxCallback *cb)
{
pImpl->asyncAccept(ep, cb ? cb : pDefaultMuxCallback);
}
void NetIoMux::asyncConnect(NetEndpoint *ep, const c8 *host, const c8 *serviceOrPort, NetIoMuxCallback *cb)
{
pImpl->asyncConnect(ep, host, serviceOrPort, cb ? cb : pDefaultMuxCallback);
}
void NetIoMux::asyncConnect(NetEndpoint *ep, const c8 *host, u32 port, NetIoMuxCallback *cb)
{
string portStr = lexical_cast<c8>(port);
pImpl->asyncConnect(ep, host, portStr.c_str(), cb ? cb : pDefaultMuxCallback);
}
bool NetIoMux::join(NetEndpoint *ep)
{
return pImpl->join(ep);
}
bool NetIoMux::depart(NetEndpoint *ep)
{
return pImpl->depart(ep);
}
const char * NetIoMux::getMultiplexerType(EPlatformMultiplexer &epm)
{
return NetIoMuxImpl::getMultiplexerType(epm);
}
} // end of namespace xpf
<file_sep>/tests/coroutine/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(coroutine_test
coroutine_test.cpp
)
SET_PROPERTY(TARGET coroutine_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(coroutine_test xpf)
<file_sep>/tests/base64/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(base64_test
base64_test.cpp
)
SET_PROPERTY(TARGET base64_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(base64_test xpf)
<file_sep>/include/xpf/netendpoint.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_NETENDPOINT_HEADER_
#define _XPF_NETENDPOINT_HEADER_
#include "platform.h"
#define XPF_NETENDPOINT_MAXADDRLEN (128)
namespace xpf
{
class NetEndpointImpl;
class XPF_API NetEndpoint
{
public:
enum EStatus
{
ESTAT_INIT = 0,
ESTAT_LISTENING,
ESTAT_ACCEPTING,
ESTAT_CONNECTING,
ESTAT_CONNECTED,
ESTAT_CLOSING,
ESTAT_INVALID,
ESTAT_MAX,
ESTAT_UNKNOWN,
};
enum EError
{
EE_SUCCESS = 0,
EE_INVALID_OP,
EE_RECV,
EE_SEND,
EE_CONNECT,
EE_BIND,
EE_LISTEN,
EE_RESOLVE,
EE_ACCEPT,
EE_SHUTDOWN,
EE_WOULDBLOCK,
EE_MAX,
EE_UNKNOWN,
};
enum EShutdownDir
{
ESD_READ = 0,
ESD_WRITE,
ESD_BOTH,
};
struct Peer
{
c8 Data[XPF_NETENDPOINT_MAXADDRLEN];
s32 Length;
};
static const u32 ProtocolTCP = 0x1;
static const u32 ProtocolUDP = 0x2;
static const u32 ProtocolIPv4 = 0x100;
static const u32 ProtocolIPv6 = 0x200;
static NetEndpoint* create(u32 protocol);
static NetEndpoint* create(u32 protocol, const c8 *addr, const c8 *serviceOrPort, u32 *errorcode = 0, u32 backlog = 10);
static void release(NetEndpoint* ep);
static bool resolvePeer(u32 protocol, Peer &peer, const c8 * host, const c8 * serviceOrPort);
explicit NetEndpoint(u32 protocol);
virtual ~NetEndpoint();
// Outgoing endpoint only
bool connect(const c8 *addr, const c8 *serviceOrPort, u32 *errorcode = 0);
// Incoming endpoint only
bool listen (const c8 *addr, const c8 *serviceOrPort, u32 *errorcode = 0, u32 backlog = 10);
NetEndpoint* accept (u32 *errorcode = 0);
s32 recv ( c8 *buf, s32 len, u32 *errorcode = 0);
s32 recvFrom ( Peer *peer, c8 *buf, s32 len, u32 *errorcode = 0);
s32 send ( const c8 *buf, s32 len, u32 *errorcode = 0);
s32 sendTo ( const Peer *peer, const c8 *buf, s32 len, u32 *errorcode = 0);
void shutdown ( EShutdownDir dir, u32 *errorcode = 0);
void close ( );
EStatus getStatus() const;
const c8* getAddress() const;
u32 getPort() const;
u32 getProtocol() const;
s32 getSocket() const;
vptr getUserData() const;
vptr setUserData(vptr ud);
s32 getLastPlatformErrno() const;
void setLastPlatformErrno(s32 ec);
// TODO: getsockopt setsockopt
private:
static bool platformInit();
NetEndpoint();
NetEndpoint(u32 protocol, int socket, EStatus status);
// Non-copyable
NetEndpoint(const NetEndpoint& that) {}
NetEndpoint& operator = (const NetEndpoint& that) { return *this; }
void setStatus(EStatus status);
inline vptr getAsyncContext() const { return pAsyncContext; }
inline vptr setAsyncContext(vptr newdata) { vptr olddata = pAsyncContext; pAsyncContext = newdata; return olddata; }
NetEndpointImpl *pImpl;
vptr pAsyncContext;
vptr pUserData;
friend class NetIoMuxImpl;
};
}; // end of namespace xpf
#endif // _XPF_NETENDPOINT_HEADER_
<file_sep>/src/platform/coroutine_posix.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifdef _XPF_COROUTINE_IMPL_INCLUDED_
#error Multiple coroutine implementation files included
#else
#define _XPF_COROUTINE_IMPL_INCLUDED_
#endif
/*
* http://en.wikipedia.org/wiki/Setcontext
* Context-manipulating functions were introduced in POSIX.1-2001 standard
* but later marked as obsoleted and removed in POSIX.1-2004, POSIX.1-2008.
* However, there are no other way to implement fibers/coroutines/cooperative
* threads without them. So most UN*X platforms still support these functions.
*/
// MacOSX/iOS requires _XOPEN_SOURCE to be declared.
#ifdef __APPLE__
#define _XOPEN_SOURCE
#endif
#include <pthread.h>
#include <ucontext.h>
#include <map>
#include <utility>
#include <xpf/coroutine.h>
static bool _g_tls_inited = false;
static pthread_key_t _g_tls;
#define ENSURE_TLS_INIT \
if (!_g_tls_inited) {\
if (0 != pthread_key_create(&_g_tls, 0)) {\
xpfAssert(("Failed on pthread_key_create()", false)); \
}\
_g_tls_inited = true; \
}
#define FCSTKSZ (1048576)
namespace xpf
{
struct CoroutineSlot
{
ucontext_t Context;
void* Data;
void* StackBuffer;
size_t StackSize;
};
struct CoroutineManager
{
ucontext_t* MainContext;
ucontext_t* CurrentContext;
std::map<ucontext_t*, CoroutineSlot*> Slots;
};
vptr XPF_API InitThreadForCoroutines(vptr data)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
if (p)
{
// has been inited.
CoroutineManager *mgr = (CoroutineManager*)p;
return (vptr)mgr->MainContext;
}
CoroutineSlot *slot = new CoroutineSlot;
int ec = getcontext(&slot->Context);
if (ec != 0)
{
xpfAssert(("Failed on getcontext().", false));
delete slot;
return 0;
}
slot->Data = (void*)data;
slot->StackBuffer = 0;
slot->StackSize = 0;
CoroutineManager *mgr = new CoroutineManager;
mgr->MainContext = mgr->CurrentContext = &slot->Context;
mgr->Slots.insert(std::make_pair(&slot->Context, slot));
if (0 != pthread_setspecific(_g_tls, mgr))
{
xpfAssert(("Failed on pthread_setspecific().", false));
delete slot;
delete mgr;
return 0;
}
return (vptr)mgr->MainContext;
}
vptr XPF_API GetCurrentCoroutine()
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if (p)
{
CoroutineManager *mgr = (CoroutineManager*)p;
return (vptr)mgr->CurrentContext;
}
return 0;
}
vptr XPF_API GetCoroutineData()
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if (p)
{
CoroutineManager *mgr = (CoroutineManager*)p;
std::map<ucontext_t*, CoroutineSlot*>::iterator it = mgr->Slots.find(mgr->CurrentContext);
xpfAssert(("No matching slot for current context.", it != mgr->Slots.end()));
return (it != mgr->Slots.end()) ? (vptr)it->second->Data : 0;
}
return 0;
}
vptr XPF_API CreateCoroutine(u32 stackSize, CoroutineFunc body, vptr data)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if ((p == 0) || (body == 0))
return 0;
CoroutineManager *mgr = (CoroutineManager*)p;
CoroutineSlot *slot = new CoroutineSlot;
if (0 != getcontext(&slot->Context))
{
xpfAssert(("Failed on getcontext().", false));
delete slot;
return 0;
}
slot->Data = (void*)data;
// If stackSize is 0, use the default size FCSTKSZ.
slot->StackSize = (stackSize) ? stackSize : FCSTKSZ;
slot->StackBuffer = new char[slot->StackSize];
slot->Context.uc_stack.ss_sp = (char*) slot->StackBuffer;
slot->Context.uc_stack.ss_size = slot->StackSize;
slot->Context.uc_link = 0;
mgr->Slots.insert(std::make_pair(&slot->Context, slot));
// NOTE: Passing 64-bits pointer can causing porting issue.
// However, if the pointer is at the end of argument list, it should be fine.
makecontext(&slot->Context, (void(*)())(body), 1, slot->Data);
return (vptr)&slot->Context;
}
void XPF_API SwitchToCoroutine(vptr coroutine)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if ((p == 0) || (coroutine == 0) || (coroutine == GetCurrentCoroutine()))
return;
CoroutineManager *mgr = (CoroutineManager*)p;
// Ensure the target coroutine has been registered.
if (mgr->Slots.find((ucontext_t*)coroutine) == mgr->Slots.end())
{
xpfAssert(("Switching to an un-recognized coroutine.", false));
return;
}
ucontext_t *curctx = mgr->CurrentContext;
mgr->CurrentContext = (ucontext_t*)coroutine;
swapcontext(curctx, (ucontext_t*)coroutine);
// debug aserrt
xpfAssert(("Current context check after swapcontext() returns.", (mgr->CurrentContext == curctx)));
}
void XPF_API DeleteCoroutine(vptr coroutine)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if ((coroutine == 0) || (p == 0))
return;
CoroutineManager *mgr = (CoroutineManager*)p;
if ((coroutine != (vptr)mgr->CurrentContext) && (coroutine != (vptr)mgr->MainContext))
{
std::map<ucontext_t*, CoroutineSlot*>::iterator it =
mgr->Slots.find((ucontext_t*)coroutine);
if (it != mgr->Slots.end())
{
CoroutineSlot *slot = it->second;
delete[](char*)slot->StackBuffer;
delete slot;
mgr->Slots.erase(it);
}
}
else
{
// Full shutdown. Release everything and terminate current thread.
CoroutineSlot *currentSlot = 0;
for (std::map<ucontext_t*, CoroutineSlot*>::iterator it = mgr->Slots.begin();
it != mgr->Slots.end(); ++it)
{
// Delay the destuction of current context to the last.
if (it->first == mgr->CurrentContext)
{
currentSlot = it->second;
continue;
}
delete[](char*)it->second->StackBuffer;
delete it->second;
}
xpfAssert(("Unable to locate current context.", (currentSlot != 0)));
mgr->Slots.clear();
delete mgr; mgr = 0;
pthread_setspecific(_g_tls, 0);
// TODO: Does deleting current context causing any problem?
char *sb = (char*)currentSlot->StackBuffer;
delete currentSlot;
delete[] sb;
pthread_exit(0);
}
}
};
<file_sep>/src/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
FILE(GLOB EXPORTED_HEADER_FILES "${CMAKE_SOURCE_DIR}/include/xpf/*.h")
FILE(GLOB INTERNAL_HEADER_FILES "${CMAKE_SOURCE_DIR}/src/platform/*.hpp")
FILE(GLOB INTERNAL_SRC_FILES "${CMAKE_SOURCE_DIR}/src/*.cpp")
SOURCE_GROUP("Exported Headers" FILES ${EXPORTED_HEADER_FILES})
SOURCE_GROUP("Internal Headers" FILES ${INTERNAL_HEADER_FILES})
IF(NOT WIN32)
FIND_PACKAGE(Threads)
ENDIF(NOT WIN32)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
IF(WIN32)
ENABLE_LANGUAGE(ASM_MASM)
IF(CMAKE_CL_64)
ADD_CUSTOM_COMMAND(OUTPUT jump_x86_64_ms_pe_masm.obj COMMAND ${CMAKE_ASM_MASM_COMPILER} -c ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_x86_64_ms_pe_masm.asm DEPENDS ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_x86_64_ms_pe_masm.asm COMMENT "generate jump_x86_64_ms_pe_masm.obj" )
ADD_CUSTOM_COMMAND(OUTPUT make_x86_64_ms_pe_masm.obj COMMAND ${CMAKE_ASM_MASM_COMPILER} -c ${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_x86_64_ms_pe_masm.asm DEPENDS ${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_x86_64_ms_pe_masm.asm COMMENT "generate make_x86_64_ms_pe_masm.obj" )
SET(ASM_FILES jump_x86_64_ms_pe_masm.obj make_x86_64_ms_pe_masm.obj)
ELSE()
ADD_CUSTOM_COMMAND(OUTPUT jump_i386_ms_pe_masm.obj COMMAND ${CMAKE_ASM_MASM_COMPILER} -c ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_i386_ms_pe_masm.asm DEPENDS ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_i386_ms_pe_masm.asm COMMENT "generate jump_i386_ms_pe_masm.obj" )
ADD_CUSTOM_COMMAND(OUTPUT make_i386_ms_pe_masm.obj COMMAND ${CMAKE_ASM_MASM_COMPILER} -c ${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_i386_ms_pe_masm.asm DEPENDS ${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_i386_ms_pe_masm.asm COMMENT "generate make_i386_ms_pe_masm.obj" )
SET(ASM_FILES jump_i386_ms_pe_masm.obj make_i386_ms_pe_masm.obj)
ENDIF()
ELSEIF(APPLE)
ENABLE_LANGUAGE(ASM)
SET(ASM_FILES ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_x86_64_sysv_macho_gas.S
${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_x86_64_sysv_macho_gas.S)
ELSE()
ENABLE_LANGUAGE(ASM)
IF("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL x86_64)
SET(ASM_FILES ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_x86_64_sysv_elf_gas.S
${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_x86_64_sysv_elf_gas.S)
ELSEIF("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL amd64)
SET(ASM_FILES ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_x86_64_sysv_elf_gas.S
${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_x86_64_sysv_elf_gas.S)
ELSEIF("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL mips)
SET(ASM_FILES ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_mips32_o32_elf_gas.S
${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_mips32_o32_elf_gas.S)
ELSEIF("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL arm)
SET(ASM_FILES ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_arm_aapcs_elf_gas.S
${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_arm_aapcs_elf_gas.S)
ELSE()
SET(ASM_FILES ${CMAKE_SOURCE_DIR}/external/boost/context/asm/jump_i386_sysv_elf_gas.S
${CMAKE_SOURCE_DIR}/external/boost/context/asm/make_i386_sysv_elf_gas.S)
ENDIF()
ENDIF()
ADD_LIBRARY(xpf SHARED
${EXPORTED_HEADER_FILES}
${INTERNAL_HEADER_FILES}
${INTERNAL_SRC_FILES}
${ASM_FILES}
)
SET_PROPERTY(TARGET xpf PROPERTY ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/lib")
SET_PROPERTY(TARGET xpf PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
SET_PROPERTY(TARGET xpf PROPERTY LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
SET_PROPERTY(TARGET xpf PROPERTY DEFINE_SYMBOL XPF_BUILD_LIBRARY)
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
TARGET_LINK_LIBRARIES(xpf ${CMAKE_THREAD_LIBS_INIT} ws2_32)
ELSE(WIN32)
TARGET_LINK_LIBRARIES(xpf ${CMAKE_THREAD_LIBS_INIT})
ENDIF(WIN32)
ADD_LIBRARY(xpf_static STATIC
${EXPORTED_HEADER_FILES}
${INTERNAL_HEADER_FILES}
${INTERNAL_SRC_FILES}
${ASM_FILES}
)
SET_PROPERTY(TARGET xpf_static PROPERTY ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/lib")
SET_PROPERTY(TARGET xpf_static PROPERTY APPEND_STRING PROPERTY COMPILE_DEFINITIONS XPF_BUILD_STATIC_LIBRARY)
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
<file_sep>/tests/coroutine/coroutine_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/coroutine.h>
#include <iostream>
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
using namespace xpf;
vptr _g_mainroutine;
struct CustomData
{
int id;
bool done;
vptr routine;
};
#ifdef XPF_PLATFORM_WINDOWS
void __stdcall coroutine_body(vptr data)
#else
void coroutine_body(vptr data)
#endif
{
CustomData *d = (CustomData*)data;
std::cout << "Routine: " << d->id << ", step 1" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 2" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 3" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 4" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 5" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
//if (d->id == 5) DeleteCoroutine(d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 6" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 7" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 8" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 9" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
SwitchToCoroutine(_g_mainroutine);
std::cout << "Routine: " << d->id << ", step 10" << std::endl;
xpfAssert(data == GetCoroutineData());
xpfAssert(GetCurrentCoroutine() == d->routine);
d->done = true;
SwitchToCoroutine(_g_mainroutine);
//debug assert: should never reach here.
xpfAssert(("SHOULD NOT REACH HERE.", false));
}
#define NUM_ROUTINES (10)
int main(int argc, char *argv[])
{
#ifdef XPF_PLATFORM_WINDOWS
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
CustomData d[NUM_ROUTINES];
for (int i = 0; i<NUM_ROUTINES; ++i)
{
d[i].id = i + 1;
d[i].done = false;
d[i].routine = 0;
}
_g_mainroutine = InitThreadForCoroutines(0);
xpfAssert(_g_mainroutine != 0);
for (int i = 0; i<NUM_ROUTINES; ++i)
{
d[i].routine = CreateCoroutine(0, coroutine_body, (vptr)&d[i]);
xpfAssert(d[i].routine != 0);
}
while (true)
{
bool alldone = true;
for (int i = 0; i<NUM_ROUTINES; ++i)
{
if (d[i].done)
continue;
alldone = false;
SwitchToCoroutine(d[i].routine);
}
if (alldone)
break;
}
for (int i = 0; i<NUM_ROUTINES; ++i)
{
DeleteCoroutine(d[i].routine);
}
//if (_g_tls)
// pthread_key_delete(_g_tls);
return 0;
}
<file_sep>/src/platform/threadevent_posix.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/threadevent.h>
#ifdef _XPF_THREADEVENT_IMPL_INCLUDED_
#error Multiple ThreadEvent implementation files included
#else
#define _XPF_THREADEVENT_IMPL_INCLUDED_
#endif
#include <pthread.h>
#include <unistd.h>
#include <sys/time.h>
namespace xpf { namespace details {
class XpfThreadEvent
{
public:
explicit XpfThreadEvent(bool set /* = false */)
: m_set(false)
{
pthread_mutexattr_t mattr;
pthread_mutexattr_init(&mattr);
pthread_mutex_init(&m_lock, &mattr);
pthread_cond_init(&m_ready, NULL);
if (set)
this->set();
}
~XpfThreadEvent()
{
pthread_mutex_destroy(&m_lock);
pthread_cond_destroy(&m_ready);
}
inline void set()
{
pthread_mutex_lock(&m_lock);
m_set = true;
pthread_cond_signal(&m_ready);
pthread_mutex_unlock(&m_lock);
}
inline void reset()
{
pthread_mutex_lock(&m_lock);
m_set = false;
pthread_cond_destroy(&m_ready);
pthread_cond_init(&m_ready, NULL);
pthread_mutex_unlock(&m_lock);
}
inline bool wait(u32 timeoutMs /* = -1 */)
{
if (-1 == timeoutMs)
{
pthread_mutex_lock(&m_lock);
if (!m_set)
pthread_cond_wait(&m_ready, &m_lock);
pthread_mutex_unlock(&m_lock);
return true;
}
// Timed wait
bool ret = false;
if (m_set)
{
ret = true;
}
else
{
pthread_mutex_lock(&m_lock);
struct timeval tvnow, tvadv, tvres; // secs, microsecs (10^-6)
struct timespec ts; // secs, nanosecs (10^-9)
gettimeofday(&tvnow, NULL);
tvadv.tv_sec = (timeoutMs / 1000);
tvadv.tv_usec = (timeoutMs % 1000) * 1000;
timeradd(&tvnow, &tvadv, &tvres);
// convert timeval to timespec.
ts.tv_sec = tvres.tv_sec;
ts.tv_nsec = tvres.tv_usec * 1000;
if ( 0 == pthread_cond_timedwait(&m_ready, &m_lock, &ts) )
ret = true;
pthread_mutex_unlock(&m_lock);
}
return ret;
}
inline bool isSet()
{
return m_set;
}
private:
XpfThreadEvent(const XpfThreadEvent& that)
{
xpfAssert( ( "non-copyable object", false ) );
}
XpfThreadEvent& operator = (const XpfThreadEvent& that)
{
xpfAssert( ( "non-copyable object", false ) );
return *this;
}
pthread_cond_t m_ready;
pthread_mutex_t m_lock;
bool m_set;
};
};};
<file_sep>/include/xpf/lexicalcast.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_LEXICALCAST_HEADER_
#define _XPF_LEXICALCAST_HEADER_
#include "platform.h"
#include "string.h"
#include <cstdio>
#include <typeinfo>
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#pragma warning ( push )
#pragma warning ( disable : 4996 4800 )
#endif
namespace xpf {
/****
* Convert either value to string or string to value.
* Ex:
* wstring text = L"123.456";
* double v = lexical_cast<double>(text); // string to value
*
* string text2 = lexical_cast<c8>(v); // value to string
*
* Note:
* - All 4 string types are supported: c8, u16, u32, wchar_t.
* - Supported value types: bool, c8, u8, s16, u16, s32, u32, s64, u64, f32, f64.
* - Use libc to do the actual conversion, so might have porting issues.
*/
template < typename TargetType, typename SChar, typename SAlloc >
TargetType lexical_cast (const xpfstring< SChar, SAlloc >& src)
{
// ensure dealing with text in c8.
xpfstring<c8> srcText;
srcText = src.c_str();
if ((typeid(bool) == typeid(TargetType)) ||
(typeid(c8) == typeid(TargetType)) ||
(typeid(s16) == typeid(TargetType)) ||
(typeid(s32) == typeid(TargetType)) )
{
s32 buf;
std::sscanf(srcText.c_str(), "%d", &buf);
return (TargetType) buf;
}
else if ((typeid(u8) == typeid(TargetType)) ||
(typeid(u16) == typeid(TargetType)) ||
(typeid(u32) == typeid(TargetType)))
{
u32 buf;
std::sscanf(srcText.c_str(), "%u", &buf);
return (TargetType) buf;
}
else if (typeid(s64) == typeid(TargetType))
{
s64 buf;
std::sscanf(srcText.c_str(), "%lld", &buf);
return (TargetType) buf;
}
else if (typeid(u64) == typeid(TargetType))
{
u64 buf;
std::sscanf(srcText.c_str(), "%llu", &buf);
return (TargetType) buf;
}
else if (typeid(f32) == typeid(TargetType))
{
f32 buf;
std::sscanf(srcText.c_str(), "%f", &buf);
return (TargetType) buf;
}
else if (typeid(f64) == typeid(TargetType))
{
f64 buf;
std::sscanf(srcText.c_str(), "%lf", &buf);
return (TargetType) buf;
}
xpfAssert( ( "Unsupported casting target (String to numeric).", false ) ); // unsupported casting target
return TargetType(); // shoud never reach here.
}
template < typename TargetType, typename SChar >
TargetType lexical_cast (const SChar* src)
{
xpfstring<SChar> srcText = src;
return lexical_cast<TargetType>(srcText);
}
template < typename TargetType, typename ValueType >
xpfstring<TargetType> lexical_cast ( const ValueType& val )
{
xpfstring<TargetType> result;
if ((typeid(c8) == typeid(ValueType)) ||
(typeid(s16) == typeid(ValueType)) ||
(typeid(s32) == typeid(ValueType)) )
{
xpfstring<TargetType> format("%d");
result.printf(format.c_str(), (s32)val);
}
else if ((typeid(u8) == typeid(ValueType)) ||
(typeid(u16) == typeid(ValueType)) ||
(typeid(u32) == typeid(ValueType)))
{
xpfstring<TargetType> format("%u");
result.printf(format.c_str(), (u32)val);
}
else if (typeid(s64) == typeid(ValueType))
{
xpfstring<TargetType> format("%lld");
result.printf(format.c_str(), (s64)val);
}
else if (typeid(u64) == typeid(ValueType))
{
xpfstring<TargetType> format("%llu");
result.printf(format.c_str(), (u64)val);
}
else if (typeid(f32) == typeid(ValueType) ||
typeid(f64) == typeid(ValueType))
{
xpfstring<TargetType> format("%f");
result.printf(format.c_str(), val);
}
else if (typeid(bool) == typeid(ValueType))
{
result = (val)? "true" : "false";
}
else
{
xpfAssert( ( "Unsupported casting target (Numeric to string).", false ) );
}
return result;
}
}; // end of namespace xpf
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#pragma warning ( pop )
#endif
#endif // _XPF_LEXICALCAST_HEADER_
<file_sep>/tests/atomicops/atmoicops_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/thread.h>
#include <xpf/atomic.h>
#include <stdio.h>
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
using namespace xpf;
static int _g_hot = 0;
class MyThread : public Thread
{
public:
MyThread(int count, int step)
: mCount(count), mStep(step)
{
}
u32 run(u64 userdata)
{
while (mCount--)
{
// not thread-safe:
//_g_hot += mStep;
// thread-safe:
xpfAtomicAdd(&_g_hot, mStep);
}
return 0;
}
private:
int mCount;
const int mStep;
};
int main()
{
MyThread *threadVector[8] = {
new MyThread(10000, 1),
new MyThread(3334, 1),
new MyThread(10000, 2),
new MyThread(3333, 2),
new MyThread(5000, -2),
new MyThread(10000, -1),
new MyThread(10000, -1),
new MyThread(10000, -1),
};
for (u32 i=0; i<8; i++)
threadVector[i]->start();
printf("Test started.\n");
while(true)
{
Thread::sleep(1000);
bool quit = true;
for (u32 i=0; i<8; i++)
{
if (threadVector[i]->getStatus() != Thread::TRS_FINISHED)
{
quit = false;
break;
}
}
if (quit)
break;
}
printf("Test finished. Joining all threads ...\n");
for (u32 i=0; i<8; i++)
threadVector[i]->join();
printf("All threads joined ...\n");
for (u32 i=0; i<8; i++)
delete threadVector[i];
xpfAssert(_g_hot == 0);
printf("Test pass.\n");
return 0;
}
<file_sep>/include/xpf/netiomux.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_NETIOMUX_HEADER_
#define _XPF_NETIOMUX_HEADER_
#include "platform.h"
#include "netendpoint.h"
namespace xpf
{
class NetIoMuxImpl;
class NetIoMuxCallback;
class XPF_API NetIoMux
{
public:
enum EPlatformMultiplexer
{
EPM_IOCP = 0,
EPM_EPOLL,
EPM_KQUEUE,
EPM_MAX,
EPM_UNKNOWN,
};
enum ERunningStaus
{
ERS_NORMAL = 0,
ERS_TIMEOUT,
ERS_DISABLED,
};
enum EIoType
{
EIT_INVALID = 0,
EIT_RECV,
EIT_RECVFROM,
EIT_SEND,
EIT_SENDTO,
EIT_ACCEPT,
EIT_CONNECT,
};
NetIoMux();
virtual ~NetIoMux();
// life cycle
void enable(bool val = true);
inline void disable() { enable(false); }
// For worker threads.
void run();
ERunningStaus runOnce(u32 timeoutMs = 0xffffffff);
// For I/O control
void asyncRecv(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb = 0);
void asyncRecvFrom(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb = 0);
void asyncSend(NetEndpoint *ep, const c8 *buf, u32 buflen, NetIoMuxCallback *cb = 0);
void asyncSendTo(NetEndpoint *ep, const NetEndpoint::Peer *peer, const c8 *buf, u32 buflen, NetIoMuxCallback *cb = 0);
void asyncAccept(NetEndpoint *ep, NetIoMuxCallback *cb = 0);
void asyncConnect(NetEndpoint *ep, const c8 *host, const c8 *serviceOrPort, NetIoMuxCallback *cb = 0);
void asyncConnect(NetEndpoint *ep, const c8 *host, u32 port, NetIoMuxCallback *cb = 0); // A varient asyncConnect() which takes a numeric port number.
// Join/depart the endpoint to/from netiomux.
bool join(NetEndpoint *ep);
bool depart(NetEndpoint *ep);
// Default callback setter/getter
inline void setDefaultCallback(NetIoMuxCallback *cb) { pDefaultMuxCallback = cb; }
inline NetIoMuxCallback* getDefaultCallback() const { return pDefaultMuxCallback; }
static const char * getMultiplexerType(EPlatformMultiplexer &epm);
private:
// Non-copyable
NetIoMux(const NetIoMux& that) {}
NetIoMux& operator = (const NetIoMux& that) { return *this; }
NetIoMuxCallback *pDefaultMuxCallback;
NetIoMuxImpl *pImpl;
};
class NetIoMuxCallback
{
public:
virtual void onIoCompleted(NetIoMux::EIoType type, NetEndpoint::EError ec, NetEndpoint *sep, vptr tepOrPeer, const c8 *buf, u32 len) = 0;
};
}; // end of namespace xpf
#endif // _XPF_NETIOMUX_HEADER_
<file_sep>/tests/threading/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(threading_test
threading_test.cpp
)
SET_PROPERTY(TARGET threading_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(threading_test xpf)
<file_sep>/include/xpf/delegate_template.h
/******** Disclaimer
*
* The following code pieces are extracted from a third party open source project which
* I have no claim on.
*
* Project ACF:
* http://www.codeproject.com/Articles/11464/Yet-Another-C-style-Delegate-Class-in-Standard-C
* A non thread-safe, header only, delegate implementation.
*
********/
//-------------------------------------------------------------------------
//
// Copyright (C) 2004-2005 <NAME>
//
// Permission to copy, use, modify, sell and distribute this software is
// granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
// AcfDelegateTemplate.h
//
// Note: this header is a header template and must NOT have multiple-inclusion
// protection.
#define ACF_DELEGATE_TEMPLATE_PARAMS ACF_MAKE_PARAMS1(ACF_DELEGATE_NUM_ARGS, class T)
// class T0, class T1, class T2, ...
#define ACF_DELEGATE_TEMPLATE_ARGS ACF_MAKE_PARAMS1(ACF_DELEGATE_NUM_ARGS, T)
// T0, T1, T2, ...
#define ACF_DELEGATE_FUNCTION_PARAMS ACF_MAKE_PARAMS2(ACF_DELEGATE_NUM_ARGS, T, a)
// T0 a0, T1 a1, T2 a2, ...
#define ACF_DELEGATE_FUNCTION_ARGS ACF_MAKE_PARAMS1(ACF_DELEGATE_NUM_ARGS, a)
// a0, a1, a2, ...
// Comma if nonzero number of arguments
#if ACF_DELEGATE_NUM_ARGS == 0
#define ACF_DELEGATE_COMMA
#else
#define ACF_DELEGATE_COMMA ,
#endif
#ifdef __XPF_PATCHED__
namespace xpf {
#else
namespace Acf {
#endif
//-------------------------------------------------------------------------
// class Delegate<R (T1, T2, ..., TN)>
template <class R ACF_DELEGATE_COMMA ACF_DELEGATE_TEMPLATE_PARAMS>
class Delegate<R (ACF_DELEGATE_TEMPLATE_ARGS)>
{
// Declaractions
private:
class DelegateImplBase
{
// Fields
public:
DelegateImplBase* Previous; // singly-linked list
// Constructor/Destructor
protected:
DelegateImplBase() : Previous(NULL) { }
DelegateImplBase(const DelegateImplBase& other) : Previous(NULL) { }
public:
virtual ~DelegateImplBase() { }
// Methods
public:
virtual DelegateImplBase* Clone() const = 0;
virtual R Invoke(ACF_DELEGATE_FUNCTION_PARAMS) const = 0;
};
template <class TFunctor>
struct Invoker
{
static R Invoke(const TFunctor& f ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_PARAMS)
{
return (const_cast<TFunctor&>(f))(ACF_DELEGATE_FUNCTION_ARGS);
}
};
template <class TPtr, class TFunctionPtr>
struct Invoker<std::pair<TPtr, TFunctionPtr> >
{
static R Invoke(const std::pair<TPtr, TFunctionPtr>& mf ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_PARAMS)
{
return ((*mf.first).*mf.second)(ACF_DELEGATE_FUNCTION_ARGS);
}
};
template <class TFunctor>
class DelegateImpl : public DelegateImplBase
{
// Fields
public:
TFunctor Functor;
// Constructor
public:
DelegateImpl(const TFunctor& f) : Functor(f)
{
}
DelegateImpl(const DelegateImpl& other) : Functor(other.Functor)
{
}
// Methods
public:
virtual DelegateImplBase* Clone() const
{
return new DelegateImpl(*this);
}
virtual R Invoke(ACF_DELEGATE_FUNCTION_PARAMS) const
{
return Invoker<TFunctor>::Invoke(this->Functor ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_ARGS);
}
};
// Fields
private:
DelegateImplBase* _last;
// Constructor/Destructor
public:
Delegate()
{
this->_last = NULL;
}
template <class TFunctor>
Delegate(const TFunctor& f)
{
this->_last = NULL;
*this = f;
}
template<class TPtr, class TFunctionPtr>
Delegate(const TPtr& obj, const TFunctionPtr& mfp)
{
this->_last = NULL;
*this = std::make_pair(obj, mfp);
}
Delegate(const Delegate& d)
{
this->_last = NULL;
*this = d;
}
~Delegate()
{
Clear();
}
// Properties
public:
bool IsEmpty() const
{
return (this->_last == NULL);
}
bool IsMulticast() const
{
return (this->_last != NULL && this->_last->Previous != NULL);
}
// Static Methods
private:
static DelegateImplBase* CloneDelegateList(DelegateImplBase* list, /*out*/ DelegateImplBase** first)
{
DelegateImplBase* list2 = list;
DelegateImplBase* newList = NULL;
DelegateImplBase** pp = &newList;
DelegateImplBase* temp = NULL;
try
{
while (list2 != NULL)
{
temp = list2->Clone();
*pp = temp;
pp = &temp->Previous;
list2 = list2->Previous;
}
}
catch (...)
{
FreeDelegateList(newList);
throw;
}
if (first != NULL)
*first = temp;
return newList;
}
static void FreeDelegateList(DelegateImplBase* list)
{
DelegateImplBase* temp = NULL;
while (list != NULL)
{
temp = list->Previous;
delete list;
list = temp;
}
}
static void InvokeDelegateList(DelegateImplBase* list ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_PARAMS)
{
if (list != NULL)
{
if (list->Previous != NULL)
InvokeDelegateList(list->Previous ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_ARGS);
list->Invoke(ACF_DELEGATE_FUNCTION_ARGS);
}
}
// Methods
public:
template <class TFunctor>
void Add(const TFunctor& f)
{
DelegateImplBase* d = new DelegateImpl<TFunctor>(f);
d->Previous = this->_last;
this->_last = d;
}
template<class TPtr, class TFunctionPtr>
void Add(const TPtr& obj, const TFunctionPtr& mfp)
{
DelegateImplBase* d = new DelegateImpl<std::pair<TPtr, TFunctionPtr> >(std::make_pair(obj, mfp));
d->Previous = this->_last;
this->_last = d;
}
template <class TFunctor>
bool Remove(const TFunctor& f)
{
DelegateImplBase* d = this->_last;
DelegateImplBase** pp = &this->_last;
DelegateImpl<TFunctor>* impl = NULL;
while (d != NULL)
{
impl = dynamic_cast<DelegateImpl<TFunctor>*>(d);
if (impl != NULL && impl->Functor == f)
{
*pp = d->Previous;
delete impl;
return true;
}
pp = &d->Previous;
d = d->Previous;
}
return false;
}
template<class TPtr, class TFunctionPtr>
bool Remove(const TPtr& obj, const TFunctionPtr& mfp)
{
return Remove(std::make_pair(obj, mfp));
}
void Clear()
{
FreeDelegateList(this->_last);
this->_last = NULL;
}
private:
template <class TFunctor>
bool Equals(const TFunctor& f) const
{
if (this->_last == NULL || this->_last->Previous != NULL)
return false;
DelegateImpl<TFunctor>* impl =
dynamic_cast<DelegateImpl<TFunctor>*>(this->_last);
if (impl == NULL)
return false;
return (impl->Functor == f);
}
// Operators
public:
operator bool() const
{
return !IsEmpty();
}
bool operator!() const
{
return IsEmpty();
}
template <class TFunctor>
Delegate& operator=(const TFunctor& f)
{
DelegateImplBase* d = new DelegateImpl<TFunctor>(f);
FreeDelegateList(this->_last);
this->_last = d;
return *this;
}
Delegate& operator=(const Delegate& d)
{
if (this != &d)
{
DelegateImplBase* list = CloneDelegateList(d._last, NULL);
FreeDelegateList(this->_last);
this->_last = list;
}
return *this;
}
template <class TFunctor>
Delegate& operator+=(const TFunctor& f)
{
Add(f);
return *this;
}
template <class TFunctor>
friend Delegate operator+(const Delegate& d, const TFunctor& f)
{
return (Delegate(d) += f);
}
template <class TFunctor>
friend Delegate operator+(const TFunctor& f, const Delegate& d)
{
return (d + f);
}
template <class TFunctor>
Delegate& operator-=(const TFunctor& f)
{
Remove(f);
return *this;
}
template <class TFunctor>
Delegate operator-(const TFunctor& f) const
{
return (Delegate(*this) -= f);
}
template <class TFunctor>
friend bool operator==(const Delegate& d, const TFunctor& f)
{
return d.Equals(f);
}
template <class TFunctor>
friend bool operator==(const TFunctor& f, const Delegate& d)
{
return (d == f);
}
template <class TFunctor>
friend bool operator!=(const Delegate& d, const TFunctor& f)
{
return !(d == f);
}
template <class TFunctor>
friend bool operator!=(const TFunctor& f, const Delegate& d)
{
return (d != f);
}
R operator()(ACF_DELEGATE_FUNCTION_PARAMS) const
{
if (this->_last == NULL)
return _HandleInvalidCall<R>();
if (this->_last->Previous != NULL)
InvokeDelegateList(this->_last->Previous ACF_DELEGATE_COMMA ACF_DELEGATE_FUNCTION_ARGS);
return this->_last->Invoke(ACF_DELEGATE_FUNCTION_ARGS);
}
};
} // namespace Acf
#undef ACF_DELEGATE_TEMPLATE_PARAMS
#undef ACF_DELEGATE_TEMPLATE_ARGS
#undef ACF_DELEGATE_FUNCTION_PARAMS
#undef ACF_DELEGATE_FUNCTION_ARGS
#undef ACF_DELEGATE_COMMA
<file_sep>/include/xpf/fcontext.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_FCONTEXT_HEADER_
#define _XPF_FCONTEXT_HEADER_
#include "platform.h"
/* Fallback context functions for some platform lacking libc context supports (ex: Android). */
namespace xpf
{
typedef void* fcontext_t;
XPF_EXTERNC
vptr
jump_fcontext( fcontext_t * ofc, fcontext_t nfc,
vptr vp, bool preserve_fpu = true );
/*
* Input:
* sp: pointer to the stack space
* size: size of the stack space
* fn: entry point of the fiber/coroutine
*
* Return:
* An opaque pointer to the context (stored at
* the top of the stack space)
*
* Please note that depending of the architecture
* the stack grows either downwards or upwards.
* For most desktop PC, it grows upwards. So be
* sure to pass the *end* of allocated stack space
* rather than the head.
*/
XPF_EXTERNC
fcontext_t
make_fcontext( void * sp, vptr size, void (* fn)( vptr ) );
};
#endif // _XPF_FCONTEXT_HEADER_
<file_sep>/src/base64.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/base64.h>
static const char *chtab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int idxofch(char ch)
{
if ((ch >= 'A') && (ch <= 'Z'))
return (ch - 'A');
else if ((ch >= 'a') && (ch <= 'z'))
return (ch - 'a') + 26;
else if ((ch >= '0') && (ch <= '9'))
return (ch - '0') + 52;
else if (ch == '+')
return 62;
else if (ch == '/')
return 63;
else if (ch == '=')
return 0;
return -1;
}
namespace xpf
{
int Base64::encode(const char *input, int inputlen, char *output, int *outputlen)
{
if (inputlen < 0) return -1;
// Compute the encoded base64 string length
int enclen = ((inputlen + 2) / 3) * 4;
if (outputlen == 0 || output == 0)
{
if (outputlen) *outputlen = enclen;
return enclen;
}
// Check if the output buffer is large enough
int outlen = *outputlen;
if (outlen < enclen)
{
*outputlen = enclen;
return -1;
}
int outidx = 0;
int inidx = 0;
char temp = 0;
while (outidx < enclen)
{
char ch = input[inidx];
int mod = inidx % 3;
switch (mod)
{
case 0:
output[outidx++] = chtab[(ch >> 2) & 0x3f];
temp = ((ch & 0x03) << 4);
inidx++;
break;
case 1:
output[outidx++] = chtab[((ch >> 4) & 0x0f) | temp];
temp = ((ch & 0x0f) << 2);
inidx++;
break;
case 2:
output[outidx++] = chtab[((ch >> 6) & 0x03) | temp];
output[outidx++] = chtab[(ch & 0x3f)];
inidx++;
break;
}
// EOF check. Apply padding if necessary.
if ((inidx >= inputlen) && (mod != 2))
{
output[outidx++] = chtab[temp];
output[outidx++] = '=';
if (mod == 0)
output[outidx++] = '=';
}
}
return enclen;
}
int Base64::decode(const char *input, int inputlen, char *output, int *outputlen)
{
// The length of a valid base64 string should always be a multiplier of 4.
if ((inputlen < 0) || (inputlen % 4) != 0)
return -1;
int declen = (inputlen / 4) * 3;
if (inputlen >= 4)
{
if (input[inputlen - 1] == '=')
declen--;
if (input[inputlen - 2] == '=')
declen--;
}
if (outputlen == 0 || output == 0)
{
if (outputlen) *outputlen = declen;
return declen;
}
// Check if the output buffer is large enough
int outlen = *outputlen;
if (outlen < declen)
{
*outputlen = declen;
return -1;
}
int outidx = 0;
for (int inidx = 0; inidx < inputlen; inidx += 4)
{
int ch1 = idxofch(input[inidx]);
int ch2 = idxofch(input[inidx + 1]);
int ch3 = idxofch(input[inidx + 2]);
int ch4 = idxofch(input[inidx + 3]);
if ((ch1 == -1) || (ch2 == -1) || (ch3 == -1) || (ch4 == -1) || (input[inidx] == '=') || (input[inidx + 1] == '='))
return -1; // corrupted data
output[outidx++] = (ch1 << 2) | ((ch2 >> 4) & (0x03));
if (input[inidx + 2] == '=') break;
output[outidx++] = ((ch2 & 0x0f) << 4) | ((ch3 >> 2) & 0x0f);
if (input[inidx + 3] == '=') break;
output[outidx++] = ((ch3 & 0x03) << 6) | ch4;
}
return outidx;
}
}; // end of namespace xpf
<file_sep>/src/platform/coroutine_boost_fcontext.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifdef _XPF_COROUTINE_IMPL_INCLUDED_
# error Multiple coroutine implementation files included
#else
# define _XPF_COROUTINE_IMPL_INCLUDED_
#endif
#include <xpf/fcontext.h>
#include <xpf/coroutine.h>
/*
* The plain data structure of context object which
* the opaque fcontext_t pointer points to.
*/
#if defined(XPF_PLATFORM_CYGWIN)
# error Coroutine on CYGWIN platform has not yet verified.
#elif defined (XPF_PLATFORM_WINDOWS)
# if defined (XPF_CPU_X86)
# if defined (XPF_MODEL_64)
# include "fcontext_x86_64_win.hpp"
# else
# include "fcontext_i386_win.hpp"
# endif
# elif defined (XPF_CPU_ARM)
# include "fcontext_arm_win.hpp"
# else
# error Unsupported CPU-Arch on Windows platform.
# endif
#elif defined (XPF_PLATFORM_APPLE)
# if defined (XPF_PLATFORM_IOSSIM)
# include "fcontext_i386.hpp"
# elif defined (XPF_PLATFORM_IOS)
# include "fcontext_arm_mac.hpp"
# elif defined (XPF_MODEL_64)
# include "fcontext_x86_64.hpp"
# else
# include "fcontext_i386.hpp"
# endif
#else
# if defined (XPF_CPU_X86)
# if defined (XPF_MODEL_64)
# include "fcontext_x86_64.hpp"
# else
# include "fcontext_i386.hpp"
# endif
# elif defined (XPF_CPU_ARM)
# include "fcontext_arm.hpp"
# else
# error Unsupported CPU-Arch on UNIX platform.
# endif
#endif
#include <pthread.h>
#include <map>
#include <utility>
static bool _g_tls_inited = false;
static pthread_key_t _g_tls;
#define ENSURE_TLS_INIT \
if (!_g_tls_inited) {\
if (0 != pthread_key_create(&_g_tls, 0)) {\
xpfAssert(("Failed on pthread_key_create()", false)); \
}\
_g_tls_inited = true; \
}
#define FCSTKSZ (1048576)
namespace xpf
{
struct CoroutineSlot
{
fcontext_t Context;
void* Data;
void* StackBuffer;
vptr StackSize;
};
struct CoroutineManager
{
void* MainContext;
void* CurrentContext;
std::map<void*, CoroutineSlot*> Slots; // stack head as key, map to slot.
};
vptr XPF_API InitThreadForCoroutines(vptr data)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
if (p)
{
// has been inited.
CoroutineManager *mgr = (CoroutineManager*)p;
return (vptr)mgr->MainContext;
}
CoroutineSlot *slot = new CoroutineSlot;
slot->Context = 0; // not yet known until first jump_fcontext.
slot->Data = (void*)data;
slot->StackBuffer = (void*)0x42; // magic number for the main coroutine.
slot->StackSize = 0;
CoroutineManager *mgr = new CoroutineManager;
mgr->MainContext = mgr->CurrentContext = slot->StackBuffer;
mgr->Slots.insert(std::make_pair(slot->StackBuffer, slot));
if (0 != pthread_setspecific(_g_tls, mgr))
{
xpfAssert(("Failed on pthread_setspecific().", false));
delete slot;
delete mgr;
return 0;
}
return (vptr)mgr->MainContext;
}
vptr XPF_API GetCurrentCoroutine()
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if (p)
{
CoroutineManager *mgr = (CoroutineManager*)p;
return (vptr)mgr->CurrentContext;
}
return 0;
}
vptr XPF_API GetCoroutineData()
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if (p)
{
CoroutineManager *mgr = (CoroutineManager*)p;
std::map<void*, CoroutineSlot*>::iterator it = mgr->Slots.find(mgr->CurrentContext);
xpfAssert(("No matching slot for current context.", it != mgr->Slots.end()));
return (it != mgr->Slots.end()) ? (vptr)it->second->Data : 0;
}
return 0;
}
vptr XPF_API CreateCoroutine(u32 stackSize, CoroutineFunc body, vptr data)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if ((p == 0) || (body == 0))
return 0;
CoroutineManager *mgr = (CoroutineManager*)p;
CoroutineSlot *slot = new CoroutineSlot;
slot->Data = (void*)data;
// If stackSize is 0, use the default size FCSTKSZ.
slot->StackSize = (stackSize) ? stackSize : FCSTKSZ;
char *stkbuf = new char[slot->StackSize];
slot->StackBuffer = (void*)stkbuf;
slot->Context = make_fcontext(&stkbuf[slot->StackSize], slot->StackSize, body);
mgr->Slots.insert(std::make_pair(slot->StackBuffer, slot));
return (vptr)slot->StackBuffer;
}
void XPF_API SwitchToCoroutine(vptr coroutine)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if ((p == 0) || (coroutine == 0) || (coroutine == GetCurrentCoroutine()))
return;
CoroutineManager *mgr = (CoroutineManager*)p;
// Ensure the target coroutine has been registered.
std::map<void*, CoroutineSlot*>::iterator tit = mgr->Slots.find((void*)coroutine);
if (tit == mgr->Slots.end())
{
xpfAssert(("Switching to an un-recognized coroutine.", false));
return;
}
// Locate the record of current coroutine
std::map<void*, CoroutineSlot*>::iterator sit = mgr->Slots.find((void*)GetCurrentCoroutine());
if (sit == mgr->Slots.end())
{
xpfAssert(("Switching from an un-recognized coroutine.", false));
return;
}
mgr->CurrentContext = (void*)coroutine;
jump_fcontext(&sit->second->Context, tit->second->Context, (vptr)tit->second->Data);
// debug aserrt
xpfAssert(("Current context check after swapcontext() returns.", (mgr->CurrentContext == sit->second->StackBuffer)));
}
void XPF_API DeleteCoroutine(vptr coroutine)
{
ENSURE_TLS_INIT;
void* p = pthread_getspecific(_g_tls);
xpfAssert(("Calling coroutine functions from a normal thread.", (p != 0)));
if ((coroutine == 0) || (p == 0))
return;
CoroutineManager *mgr = (CoroutineManager*)p;
if ((coroutine != (vptr)mgr->CurrentContext) && (coroutine != (vptr)mgr->MainContext))
{ // Deleting a non-current and non-main coroutine.
std::map<void*, CoroutineSlot*>::iterator it =
mgr->Slots.find((void*)coroutine);
if (it != mgr->Slots.end())
{
CoroutineSlot *slot = it->second;
delete[](char*)slot->StackBuffer;
delete slot;
mgr->Slots.erase(it);
}
}
else
{ // Deleting on either the current or the main coroutine. Perform a
// full shutdown: Release everything and terminate current thread.
CoroutineSlot *currentSlot = 0;
for (std::map<void*, CoroutineSlot*>::iterator it = mgr->Slots.begin();
it != mgr->Slots.end(); ++it)
{
// Delay the destuction of current context to the last.
if (it->first == mgr->CurrentContext)
{
currentSlot = it->second;
continue;
}
char *sb = (char*)it->second->StackBuffer;
delete it->second;
if (0x42 != (vptr)sb)
delete[] sb;
}
xpfAssert(("Unable to locate current context.", (currentSlot != 0)));
mgr->Slots.clear();
delete mgr; mgr = 0;
pthread_setspecific(_g_tls, 0);
// TODO: Does deleting current context causing any problem?
char *sb = (char*)currentSlot->StackBuffer;
delete currentSlot;
if (0x42 != (vptr)sb)
delete[] sb;
pthread_exit(0);
}
}
};
<file_sep>/src/platform/netiomux_kqueue.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/netiomux.h>
#ifdef _XPF_NETIOMUX_IMPL_INCLUDED_
#error Multiple NetIoMux implementation files included
#else
#define _XPF_NETIOMUX_IMPL_INCLUDED_
#endif
#include "netiomux_syncfifo.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/event.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define MAX_EVENTS_AT_ONCE (128)
#define MAX_READY_LIST_LEN (10240)
#define ASYNC_OP_READ (0)
#define ASYNC_OP_WRITE (1)
namespace xpf
{
// host info for connect
struct ConnectHostInfo
{
ConnectHostInfo(const c8 *h, const c8 *s)
{
host = ::strdup(h);
service = ::strdup(s);
}
~ConnectHostInfo()
{
if (host) ::free(host);
if (service) ::free(service);
}
c8 *host;
c8 *service;
};
// data record per operation
struct Overlapped
{
Overlapped(NetEndpoint *ep, NetIoMux::EIoType iocode)
: iotype(iocode), sep(ep), tep(0), buffer(0), length(0)
, peer(0), cb(0), errorcode(0), provisioned(false) {}
NetIoMux::EIoType iotype;
NetEndpoint *sep;
NetEndpoint *tep;
c8 *buffer;
u32 length;
NetEndpoint::Peer *peer;
NetIoMuxCallback *cb;
int errorcode;
bool provisioned;
};
// data record per socket
struct AsyncContext
{
std::deque<Overlapped*> rdqueue; // queued read operations
std::deque<Overlapped*> wrqueue; // queued write operations
bool ready;
ThreadLock lock;
NetEndpoint *ep;
};
class NetIoMuxImpl
{
public:
NetIoMuxImpl()
: mEnable(true)
{
xpfSAssert(sizeof(socklen_t) == sizeof(s32));
mKqueue = kqueue();
xpfAssert(mKqueue != -1);
if (mKqueue == -1)
mEnable = false;
}
~NetIoMuxImpl()
{
enable(false);
if (mKqueue != -1)
close(mKqueue);
mKqueue = -1;
}
void enable(bool val)
{
mEnable = val;
}
void run()
{
while (mEnable)
{
if (NetIoMux::ERS_DISABLED == runOnce(10))
break;
}
}
NetIoMux::ERunningStaus runOnce(u32 timeoutMs)
{
bool consumeSome = false;
u32 pendingCnt = 0;
// Process the completion queue. Emit the completion event.
Overlapped *co = (Overlapped*) mCompletionList.pop_front(pendingCnt);
if (co)
{
consumeSome = true;
switch (co->iotype)
{
case NetIoMux::EIT_RECV:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, 0, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_RECV, co->sep, 0, co->buffer, 0);
break;
case NetIoMux::EIT_RECVFROM:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->peer, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_RECV, co->sep, 0, co->buffer, 0);
delete co->peer;
break;
case NetIoMux::EIT_SEND:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, 0, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SEND, co->sep, 0, co->buffer, 0);
break;
case NetIoMux::EIT_SENDTO:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, (vptr)co->peer, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->peer, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SEND, co->sep, (vptr)co->peer, co->buffer, 0);
delete co->peer;
break;
case NetIoMux::EIT_ACCEPT:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, 0, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->tep, 0, 0);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_ACCEPT, co->sep, 0, 0, 0);
delete co->peer;
break;
case NetIoMux::EIT_CONNECT:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, (co->peer == 0) ? NetEndpoint::EE_INVALID_OP : NetEndpoint::EE_RESOLVE, co->sep, 0, 0, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->peer, 0, 0);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_CONNECT, co->sep, 0, 0, 0);
delete co->peer;
break;
case NetIoMux::EIT_INVALID:
default:
xpfAssert(("Unrecognized iotype. Maybe a corrupted Overlapped.", false));
break;
}
delete co;
}
// Consume ready list:
// Pop the front socket out of list, and
// process all r/w operations until EWOULDBLOCK.
// Re-arm the socket if there are more pending
// operations.
NetEndpoint *ep = (NetEndpoint*) mReadyList.pop_front(pendingCnt);
do
{
if (!ep) break;
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
if (!ctx) break;
ScopedThreadLock ml(ctx->lock);
xpfAssert(("Expecting ready flag on for all ", ctx->ready));
ctx->ready = false;
while (!ctx->rdqueue.empty()) // process rqueue.
{
Overlapped *o = ctx->rdqueue.front();
if (!o) break;
consumeSome = true;
if (performIoLocked(ep, o))
ctx->rdqueue.pop_front();
else
break;
} // end of while (true)
while (!ctx->wrqueue.empty()) // process wrqueue
{
Overlapped *o = ctx->wrqueue.front();
if (!o) break;
consumeSome = true;
if (performIoLocked(ep, o))
ctx->wrqueue.pop_front();
else
break;
} // end of while (true)
struct kevent changes[2] = {0};
int changeCnt = 0;
if (!ctx->rdqueue.empty())
{
changes[changeCnt].filter = EVFILT_READ;
changes[changeCnt].flags = EV_ADD | EV_ONESHOT | EV_ENABLE;
changes[changeCnt].ident = ep->getSocket();
changes[changeCnt].udata = (void*) ep;
changeCnt++;
}
if (!ctx->wrqueue.empty())
{
changes[changeCnt].filter = EVFILT_WRITE;
changes[changeCnt].flags = EV_ADD | EV_ONESHOT | EV_ENABLE;
changes[changeCnt].ident = ep->getSocket();
changes[changeCnt].udata = (void*) ep;
changeCnt++;
}
if (changeCnt > 0)
{
int ec = kevent(mKqueue, changes, changeCnt, 0, 0, 0);
xpfAssert(ec != -1);
}
} while (0);
// Wait for more ready events.
// Will skip if the length of list is too large.
if (pendingCnt < MAX_READY_LIST_LEN)
{
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = (consumeSome) ? 0 : timeoutMs * 1000000;
struct kevent evts[MAX_EVENTS_AT_ONCE];
int nevts = kevent(mKqueue, 0, 0, evts, MAX_EVENTS_AT_ONCE, &ts);
xpfAssert(("Failed on calling kevent", nevts != -1));
if (0 == nevts)
{
return NetIoMux::ERS_TIMEOUT;
}
else if (nevts > 0)
{
for (int i=0; i<nevts; ++i)
{
short filter = evts[i].filter;
u_short flags = evts[i].flags;
NetEndpoint *ep = (NetEndpoint*) evts[i].udata;
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
ScopedThreadLock ml(ctx->lock);
xpfAssert(("Expecting non-ready ep in kqueue.", ctx->ready == false));
ctx->ready = false;
switch (filter)
{
case EVFILT_READ:
if (flags & EV_EOF)
{
for (std::deque<Overlapped*>::iterator it = ctx->rdqueue.begin();
it != ctx->rdqueue.end(); ++it)
{
Overlapped *o = (*it);
o->errorcode = ECONNABORTED;
mCompletionList.push_back((void*)o);
}
ctx->rdqueue.clear();
}
else
{
ctx->ready = true;
mReadyList.push_back((void*)ep);
}
break;
case EVFILT_WRITE:
if (flags & EV_EOF)
{
for (std::deque<Overlapped*>::iterator it = ctx->wrqueue.begin();
it != ctx->wrqueue.end(); ++it)
{
Overlapped *o = (*it);
o->errorcode = ECONNABORTED;
mCompletionList.push_back((void*)o);
}
ctx->wrqueue.clear();
}
else
{
ctx->ready = true;
mReadyList.push_back((void*)ep);
}
break;
default:
xpfAssert(("Unrecognizable kqueue evt filter.", false));
break;
} // end of switch(filter)
} // end of for (int i=0; i<nevts; ++i)
}
else
{
return NetIoMux::ERS_DISABLED;
}
}
return NetIoMux::ERS_NORMAL;
}
void asyncRecv(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_RECV);
o->buffer = buf;
o->length = buflen;
o->cb = cb;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_READ);
}
}
void asyncRecvFrom(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_RECVFROM);
o->buffer = buf;
o->length = buflen;
o->cb = cb;
o->peer = new NetEndpoint::Peer;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_READ);
}
}
void asyncSend(NetEndpoint *ep, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_SEND);
o->buffer = (c8*)buf;
o->length = buflen;
o->cb = cb;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_WRITE);
}
}
void asyncSendTo(NetEndpoint *ep, const NetEndpoint::Peer *peer, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_SENDTO);
o->buffer = (c8*)buf;
o->length = buflen;
o->cb = cb;
o->peer = new NetEndpoint::Peer(*peer); // clone
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_WRITE);
}
}
void asyncAccept(NetEndpoint *ep, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_ACCEPT);
o->cb = cb;
o->peer = new NetEndpoint::Peer;
o->peer->Length = XPF_NETENDPOINT_MAXADDRLEN;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_READ);
}
}
void asyncConnect(NetEndpoint *ep, const c8 *host, const c8 *serviceOrPort, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_CONNECT);
o->cb = cb;
o->buffer = (c8*) new ConnectHostInfo(host, serviceOrPort);
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_WRITE);
}
}
bool join(NetEndpoint *ep)
{
s32 sock = ep->getSocket();
// bundle with an async context
AsyncContext *ctx = new AsyncContext;
ctx->ready = false;
ctx->ep = ep;
ep->setAsyncContext((vptr)ctx);
// request the socket to be non-blocking
int flags = fcntl(sock, F_GETFL);
xpfAssert(flags != -1);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
return true;
}
bool depart(NetEndpoint *ep)
{
s32 sock = ep->getSocket();
// ensure the under lying fd removed from kqueue
struct kevent changes[2] = {0};
changes[0].ident = changes[1].ident = sock;
changes[0].flags = changes[1].flags = EV_DELETE;
changes[0].filter = EVFILT_READ;
changes[1].filter = EVFILT_WRITE;
int ec = kevent(mKqueue, changes, 2, 0, 0, 0);
xpfAssert((ec == 0 || errno == ENOENT));
if ((ec != 0) && (errno != ENOENT))
{
return false;
}
// delete the async context
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
xpfAssert(ctx != 0);
if (!ctx)
{
return false;
}
else
{
ctx->lock.lock();
if (ctx->ready)
{
mReadyList.erase((void*)ep); // Note: Acquire mReadyList's lock while holding ctx's lock.
}
delete ctx;
ep->setAsyncContext(0);
// since the whole context object has been deleted, there's no bother to call unlock.
}
// reset the socket to be blocking
int flags = fcntl(sock, F_GETFL);
xpfAssert(flags != -1);
fcntl(sock, F_SETFL, flags & (0 ^ O_NONBLOCK));
return (ec == 0);
}
static const char * getMultiplexerType(NetIoMux::EPlatformMultiplexer &epm)
{
epm = NetIoMux::EPM_KQUEUE;
return "kqueue";
}
private:
bool performIoLocked(NetEndpoint *ep, Overlapped *o) // require ep->ctx locked.
{
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx == 0)
return false;
bool complete = true;
switch (o->iotype)
{
case NetIoMux::EIT_RECV:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->errorcode = 0;
o->length = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::recv(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT);
if (bytes >= 0)
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
complete = false;
}
} while (0);
break;
case NetIoMux::EIT_RECVFROM:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::recvfrom(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT, (struct sockaddr*)o->peer->Data, (socklen_t*)&o->peer->Length);
if (bytes >= 0)
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
complete = false;
}
} while (0);
break;
case NetIoMux::EIT_ACCEPT:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_LISTENING == stat));
if (NetEndpoint::ESTAT_LISTENING != stat)
{
o->tep = 0;
o->length = 0;
o->buffer = 0;
break;
}
o->provisioned = true;
}
int peersock = ::accept(ep->getSocket(), (struct sockaddr*)o->peer->Data, (socklen_t*)&o->peer->Length);
if (peersock != -1)
{
o->errorcode = 0;
o->length = 0;
o->tep = new NetEndpoint(ep->getProtocol(), peersock, NetEndpoint::ESTAT_CONNECTED);
join(o->tep);
ep->setStatus(NetEndpoint::ESTAT_LISTENING);
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->tep = 0;
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
ep->setStatus(NetEndpoint::ESTAT_LISTENING);
}
else
{
complete = false;
ep->setStatus(NetEndpoint::ESTAT_ACCEPTING);
}
} while (0);
break;
case NetIoMux::EIT_SEND:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->errorcode = 0;
o->length = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::send(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT);
if (bytes >=0 )
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
complete = false;
}
} while (0);
break;
case NetIoMux::EIT_SENDTO:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->errorcode = 0;
o->length = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::sendto(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT,
(const struct sockaddr*)o->peer->Data, (socklen_t)o->peer->Length);
if (bytes >=0 )
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
complete = false;
}
} while (0);
break;
case NetIoMux::EIT_CONNECT:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", ((NetEndpoint::ESTAT_INIT == stat) && (o->buffer != 0))));
if ((NetEndpoint::ESTAT_INIT != stat) || (o->buffer == 0))
{
o->length = 0;
o->errorcode = 0;
o->peer = 0;
if (o->buffer)
{
ConnectHostInfo *chi = (ConnectHostInfo*)o->buffer;
delete chi;
o->buffer = 0;
}
break;
}
o->peer = new NetEndpoint::Peer;
// Note: resolving can be blockable.
ConnectHostInfo *chi = (ConnectHostInfo*)o->buffer;
bool resolved = NetEndpoint::resolvePeer(ep->getProtocol(), *o->peer, chi->host, chi->service);
delete chi;
if (!resolved)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
if (o->length == 0) // not yet called connect
{
int ec = ::connect(ep->getSocket(), (const struct sockaddr*)o->peer->Data, (socklen_t)o->peer->Length);
if (ec == 0)
{
o->length = 0;
o->errorcode = 0;
ep->setStatus(NetEndpoint::ESTAT_CONNECTED);
}
else if (errno != EINPROGRESS)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
ep->setStatus(NetEndpoint::ESTAT_INIT);
}
else
{
xpfAssert(o->length == 0);
ep->setStatus(NetEndpoint::ESTAT_CONNECTING);
o->length = 1; // mark a connect() call in progress.
complete = false;
}
}
else // a connect() was called and waiting for result.
{
int val = 0;
socklen_t valsize = sizeof(int);
int ec = ::getsockopt(ep->getSocket(), SOL_SOCKET, SO_ERROR, &val, &valsize);
xpfAssert(ec == 0);
if (ec == 0 && val == 0)
{
o->errorcode = 0;
o->length = 0;
ep->setStatus(NetEndpoint::ESTAT_CONNECTED);
}
else
{
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
delete o->peer;
o->peer = 0;
ep->setStatus(NetEndpoint::ESTAT_INIT);
}
}
} while (0);
break;
default:
xpfAssert(("Unexpected iotype.", false));
break;
} // end of switch (o->iotype)
if (complete)
mCompletionList.push_back(o);
return complete;
}
void appendAsyncOpLocked(NetEndpoint *ep, Overlapped *o, u8 mode) // require ep->ctx locked.
{
AsyncContext *ctx = (ep == 0)? 0 : (AsyncContext*)ep->getAsyncContext();
if (ctx == 0 || o == 0)
{
xpfAssert(false);
return;
}
switch (mode)
{
case ASYNC_OP_READ:
ctx->rdqueue.push_back(o);
break;
case ASYNC_OP_WRITE:
ctx->wrqueue.push_back(o);
break;
default:
xpfAssert(("Unexpected async op mode.",false));
break;
}
if (!ctx->ready)
{
ctx->ready = true;
mReadyList.push_back((void*)ep);
}
}
NetIoMuxSyncFifo mCompletionList; // fifo of Overlapped.
NetIoMuxSyncFifo mReadyList; // fifo of NetEndpoints.
bool mEnable;
int mKqueue;
}; // end of class NetIoMuxImpl (kqueue)
} // end of namespace xpf
<file_sep>/src/platform/tls_windows.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifdef _XPF_TLS_IMPL_INCLUDED_
#error Multiple TLS implementation files included
#else
#define _XPF_TLS_IMPL_INCLUDED_
#endif
#ifndef XPF_PLATFORM_WINDOWS
# error tls_windows.hpp shall not build on platforms other than Windows.
#endif
#include <Windows.h>
namespace xpf {
struct TlsIndex
{
DWORD Index;
};
vptr XPF_API
TlsCreate()
{
DWORD idx = TlsAlloc();
if (idx == TLS_OUT_OF_INDEXES)
{
DWORD errorcode = GetLastError();
xpfAssert(("Failed on TlsAlloc()", false));
return 0;
}
TlsIndex *ret = new TlsIndex;
ret->Index = idx;
return (vptr)ret;
}
void XPF_API
TlsDelete(vptr index)
{
xpfAssert(("Operate TlsDelete() with a null index.", (index != 0)));
if (index == 0)
return;
TlsIndex *idx = (TlsIndex*)index;
if (TlsFree(idx->Index) == 0)
{
DWORD errorcode = GetLastError();
xpfAssert(("Failed on TlsFree()", false));
}
delete idx;
}
vptr XPF_API
TlsGet(vptr index)
{
xpfAssert(("Operate TlsGet() with a null input.", (index != 0)));
if (index == 0)
return 0;
TlsIndex *idx = (TlsIndex*)index;
LPVOID data = TlsGetValue(idx->Index);
if (data == 0)
{
DWORD errorcode = GetLastError();
xpfAssert(("Failed on TlsGetValue()", (errorcode == ERROR_SUCCESS)));
}
return (vptr)data;
}
void XPF_API
TlsSet(vptr index, vptr data)
{
xpfAssert(("Operate TlsSet() with a null input.", (index != 0)));
if (index == 0)
return;
TlsIndex *idx = (TlsIndex*)index;
if (TlsSetValue(idx->Index, (LPVOID)data) == 0)
{
DWORD errorcode = GetLastError();
xpfAssert(("Failed on TlsSetValue()", false));
}
}
};
<file_sep>/src/getopt.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <xpf/getopt.h>
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#pragma warning ( push )
#pragma warning ( disable : 4996 4800 )
#endif
using namespace xpf;
// Instance of extern global variables
s32 xoptind;
s32 xoptopt;
s32 xopterr = 1;
s32 xoptreset;
c8 *xoptarg;
// A local-scope variable.
// Used for tracking parsing point within the same argument element.
static c8 *xoptcur;
static s32 xgetopt_impl(s32 argc, c8 * const argv[],
const c8 *optstring, const struct xoption *longopts,
s32 *longindex, bool only);
// Permute an argv array. So that all non-option element will be
// moved to the end of argv with respect to their original presenting order.
static void xgetopt_permute(s32 argc, c8 * const argv[],
const c8 *optstring, const struct xoption *longopts,
bool only)
{
// Tweak the optstring:
// 1. Remove any heading GNU flags ('+','-') at front of it (if any).
// 2. Insert a single '+' at the front.
c8 *pstr = 0;
if (optstring == 0)
{
pstr = strdup("+");
}
else
{
s32 len = (s32)strlen(optstring);
pstr = (c8*)malloc(len+2);
memset(pstr, 0, len+2);
while (((*optstring) == '+') || ((*optstring) == '-'))
optstring++;
pstr[0] = '+';
strcpy(&pstr[1], optstring);
}
// Clone longopts and tweak on flag and val.
struct xoption *x = 0;
if (longopts)
{
s32 cnt;
for (cnt=0; (longopts[cnt].name != 0) || (longopts[cnt].flag != 0) || (longopts[cnt].has_arg != 0) || (longopts[cnt].val != 0); ++cnt);
x = (struct xoption*) malloc(sizeof(struct xoption) * (cnt+1));
memset(x, 0, sizeof(struct xoption) * (cnt+1));
for (s32 i=0; i<cnt; ++i)
{
x[i].name = longopts[i].name;
x[i].has_arg = longopts[i].has_arg;
x[i].flag = 0;
x[i].val = 0x5299;
}
}
// A c8* buffer at most can hold all entries in argv.
c8 **nonopts = (c8**) malloc( sizeof(c8*) * argc );
s32 nonoptind = 0;
s32 old_xopterr = xopterr;
xopterr = 0;
xoptreset = 1;
bool stop = false;
while (!stop)
{
s32 code = xgetopt_impl(argc, argv, pstr, x, 0, only);
switch (code)
{
case -1:
if (xoptind < argc)
{
// Detach current element to nonopts buffer.
// Rotate all remaining elements forward.
nonopts[nonoptind++] = argv[xoptind];
char **pargs = (char**)argv;
for (s32 i=xoptind+1; i < argc; ++i)
pargs[i-1] = pargs[i];
argc--;
// Continue iteration on xoptind again.
xoptcur = 0;
continue;
}
else
{
stop = true;
// Append all element in nonopts at
// the end of argv.
c8 **pargs = (c8**)argv;
for (s32 i=0; i<nonoptind; ++i)
{
pargs[argc++] = nonopts[i];
}
}
break;
default:
break;
}
}
if (x)
free(x);
free(pstr);
free(nonopts);
xopterr = old_xopterr;
}
// A general getopt parser. Used for both short options and long options.
static s32 xgetopt_impl(s32 argc, c8 * const argv[],
const c8 *optstring, const struct xoption *longopts,
s32 *longindex, bool only)
{
// Determine the executable name. This is used when outputing
// stderr messages.
const c8 *progname = strrchr(argv[0], '/');
#ifdef _WIN32
if (!progname) progname = strrchr(argv[0], '\\');
#endif
if (progname)
progname++;
else
progname = argv[0];
if (optstring == 0)
optstring = "";
// BSD implementation provides a user controllable xoptreset flag.
// Set to be a non-zero value to ask getopt to clean up
// all internal state and thus perform a whole new parsing
// iteration.
if (xoptreset != 0)
{
xoptreset = 0;
xoptcur = 0;
xoptind = 0;
xoptarg = 0;
xoptopt = 0;
}
if (xoptind < 1)
xoptind = 1;
bool missingarg = false; // Whether a missing argument should return as ':' (true) or '?' (false).
bool permute = true; // Whether to perform content permuting: Permute the contents of the argument vector (argv)
// as it scans, so that eventually all the non-option arguments are at the end.
bool argofone = false; // Whether to handle each nonoption argv-element as if it were the argument of an option
// with character code 1.
//bool dashw = (0 != strstr(optstring, "W;")); // TODO: If 'W;' exists in optstring indicates '-W foo' will be treated as '--foo'.
// Parse the head of optstring for flags: "+-:"
for (const c8 *p = optstring; *p != '\0'; ++p)
{
if ((*p == '+') || (*p == '-'))
{
permute = false;
argofone = (*p == '-');
}
else if (*p == ':')
missingarg = true;
else
break;
optstring = p + 1;
}
xoptarg = 0;
if ((xoptind >= argc) || (0 == argv))
{
xoptind = argc;
if (permute)
xgetopt_permute(argc, argv, optstring, longopts, only);
return -1;
}
// Check whether xoptind has been changed since the last valid xgetopt_impl call.
// Reset xoptcur to NULL if does.
if (xoptcur)
{
bool inrange = false;
for (c8 * p = argv[xoptind]; *p != '\0'; ++p)
{
if (p != xoptcur) continue;
inrange = true;
break;
}
if (!inrange)
xoptcur = 0;
}
// Check the content of argv[xoptind], to see if it is:
// 1. Non-option argument (not start with '-')
// 2. A solely '-' or '--'
// 3. A option which starts with '-' or '--'
while (xoptind < argc)
{
// case 1
if (!xoptcur && (argv[xoptind][0] != '-'))
{
if (argofone)
{
xoptarg = argv[xoptind++];
return 1;
}
else if (permute)
{
xoptind++;
continue;
}
return -1;
}
// case 2
if (!xoptcur &&
((0 == strcmp("-", argv[xoptind])) ||
(0 == strcmp("--", argv[xoptind]))))
{
xoptind++;
break;
}
// case 3
const c8 *p = (argv[xoptind][1] == '-')? &argv[xoptind][2] : &argv[xoptind][1];
// matching long opts
do
{
if (!longopts || xoptcur || ((argv[xoptind][1] != '-') && !only))
break; // continue to match short opts ...
const c8 *r;
r = strchr(p, '=');
s32 plen = (r)? (s32)(r-p) : (s32)strlen(p);
const xoption *xo = 0;
s32 hitcnt = 0;
for (const xoption *x = longopts; ; ++x)
{
if (!x->name && !x->flag && !x->has_arg && !x->val) // terminating case: xoption == {0,0,0,0}
break;
if (!x->name)
continue;
// Long option names may be abbreviated if the abbreviation
// is unique or is an exact match for some defined option.
if (0 == strncmp(p, x->name, plen))
{
xo = x;
hitcnt++;
// is this an exact match?
if (plen == strlen(x->name))
{
hitcnt = 1;
break;
}
}
}
if (!xo) // unrecognized option
{
if (only)
break; // continue to match short opts..
if (xopterr)
fprintf(stderr, "%s: unrecognized option `%s\'\n", progname, argv[xoptind]);
xoptind++;
return '?';
}
else if (hitcnt > 1) // ambiguous
{
if (xopterr)
fprintf(stderr, "%s: option `%s\' is ambiguous\n", progname, argv[xoptind]);
xoptind++;
return '?';
}
if (longindex)
*longindex = (s32)(xo - longopts);
switch (xo->has_arg)
{
case xrequired_argument: // argument required
case xoptional_argument: // optional argument
{
bool valid = true;
s32 curind = xoptind++;
// Check whether the argument is provided as inline. i.e.: '--opt=argument'
const c8 *q = strchr(p, '=');
if (q) // Has inline argument.
{
xoptarg = (c8*)(q+1);
}
else if (xo->has_arg == xoptional_argument) // No inline argument implies no argument for 'xoptional_argument'
{
;
}
else if (xoptind < argc) // For xrequired_argument, use the next arg value if no inline argument present.
{
xoptarg = argv[xoptind++];
}
else // Missing argument.
{
valid = false;
}
if (valid)
{
if (xo->flag == 0)
return xo->val;
*xo->flag = xo->val;
return 0;
}
if (xopterr)
fprintf(stderr, "%s: option `%s\' requires an argument\n", progname, argv[curind]);
if (missingarg)
return ':';
}
return '?';
default: // no argument
xoptind++;
if (xo->flag == 0)
return xo->val;
*xo->flag = xo->val;
return 0;
}
} while (0);
// matching short opts ...
if (xoptcur)
p = xoptcur;
xoptarg = 0;
const c8 *d = strchr(optstring, *p);
if (d && ((0 == strncmp(d+1, "::", 2)) || (*(d+1) == ':')))
{
xoptind++;
xoptarg = 0;
xoptcur = 0;
const bool required = (*(d+2) != ':');
if (*(p+1) != '\0')
{
xoptarg = (c8*)(p+1);
}
else if ((xoptind < argc) && (required || (argv[xoptind][0] != '-')))
{
xoptarg = argv[xoptind];
xoptind++;
}
else if (required)
{
if (xopterr)
fprintf(stderr, "%s: option requires an argument -- \'%c\'\n", progname, *p);
xoptopt = *p;
return (missingarg)? ':': '?';
}
return *p;
}
if (*(p+1) != '\0')
{
xoptcur = (c8*)(p+1);
}
else
{
xoptind++;
xoptcur = 0;
}
if (!d)
{
xoptopt = *p;
if (!missingarg && xopterr)
fprintf(stderr, "%s: invalid option -- \'%c\'\n", progname, *p);
return '?';
}
return *p;
} // end of while (xoptind < argc)
if (permute)
xgetopt_permute(argc, argv, optstring, longopts, only);
return -1;
}
namespace xpf
{
s32 xgetopt(s32 argc, c8 * const argv[], const c8 *optstring)
{
return xgetopt_impl(argc, argv, optstring, 0, 0, false);
}
s32 xgetopt_long(s32 argc, c8 * const argv[], const c8 *optstring,
const struct xoption *longopts, s32 *longindex)
{
return xgetopt_impl(argc, argv, optstring, longopts, longindex, false);
}
s32 xgetopt_long_only(s32 argc, c8 * const argv[], const c8 *optstring,
const struct xoption *longopts, s32 *longindex)
{
return xgetopt_impl(argc, argv, optstring, longopts, longindex, true);
}
s32 xgetsubopt(c8 **optionp, c8 * const *tokens, c8 **valuep)
{
c8 *p = *optionp;
c8 *n = 0;
c8 *a = 0;
s32 ret = -1;
s32 nlen = 0;
bool stop = false;
for (n=p; !stop; ++n)
{
switch(*n)
{
case '=':
if (!a) a = n + 1;
break;
case ',':
case '\0':
*optionp = (*n == ',')? n+1 : n;
*n = '\0';
stop = true;
break;
default:
if (!a) nlen++;
break;
}
}
bool found = false;
for (s32 i=0; (nlen > 0) && (tokens[i] != NULL); ++i)
{
if (0 == strncmp(tokens[i], p, nlen))
{
found = true;
ret = i;
break;
}
}
*valuep = (found)? a: p;
return ret;
}
}; // end of namespace xpf
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#pragma warning ( pop )
#endif
<file_sep>/include/xpf/uuidv4.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_UUIDV4_HEADER_
#define _XPF_UUIDV4_HEADER_
#include "platform.h"
#include <string>
namespace xpf
{
class XPF_API Uuid
{
public:
/*
* Generate a version 4 (random) UUID.
* It utilizes the psuedo randomer of platform,
* so be sure to seed the randomer properly.
*/
static Uuid generate();
/*
* Return a nil/null UUID.
*/
static Uuid null();
/*
* Build an UUID object from raw octet (16 bytes).
*/
static Uuid fromOctet(u8* octet);
/*
* Build an UUID object from an null-terminated UUID string.
*/
static Uuid fromString(const c8* string);
Uuid(const Uuid& other);
virtual ~Uuid();
/*
* Return the length of octet, which should always be 16.
*/
u32 getLength() const;
/*
* Retrieve the raw data of the octet.
*/
u8* getOctet();
/*
* Get the readable UUID string of current octet.
*/
std::string asString();
bool operator< (const Uuid& other) const;
Uuid& operator= (const Uuid& other);
bool operator== (const Uuid& other) const;
protected:
/*
* Hide constructor. To construct an uuid, use Uuid::generate().
* Or use Uuid::null() to obtain a null uuid.
*/
Uuid();
private:
u8 mOctet[16];
};
};
#endif<file_sep>/src/platform/coroutine_windows.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifdef _XPF_COROUTINE_IMPL_INCLUDED_
#error Multiple coroutine implementation files included
#else
#define _XPF_COROUTINE_IMPL_INCLUDED_
#endif
#ifndef XPF_PLATFORM_WINDOWS
# error coroutine_windows.hpp shall not build on platforms other than Windows.
#endif
#include <Windows.h>
#include <xpf/coroutine.h>
namespace xpf
{
vptr XPF_API InitThreadForCoroutines(vptr data)
{
return (vptr)::ConvertThreadToFiber((LPVOID)data);
}
vptr XPF_API GetCurrentCoroutine()
{
return (vptr)::GetCurrentFiber();
}
vptr XPF_API GetCoroutineData()
{
return (vptr)::GetFiberData();
}
vptr XPF_API CreateCoroutine(u32 stackSize, CoroutineFunc body, vptr data)
{
return (vptr)::CreateFiber((SIZE_T)stackSize, (void( __stdcall *)(void*))body, (LPVOID)data);
}
void XPF_API SwitchToCoroutine(vptr coroutine)
{
::SwitchToFiber((LPVOID)coroutine);
}
void XPF_API DeleteCoroutine(vptr coroutine)
{
::DeleteFiber((LPVOID)coroutine);
}
};
<file_sep>/src/threadevent.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/platform.h>
// Currently only 2 threading models are supported: windows, posix.
#ifdef XPF_PLATFORM_WINDOWS
#include "platform/threadevent_windows.hpp"
#else
#include "platform/threadevent_posix.hpp"
#endif
namespace xpf {
ThreadEvent::ThreadEvent(bool set)
{
pImpl = (vptr) new details::XpfThreadEvent(set);
}
ThreadEvent::ThreadEvent(const ThreadEvent& that)
{
xpfAssert( ( "non-copyable", false ) ); // ThreadEvent is non-copyable
}
ThreadEvent::~ThreadEvent()
{
details::XpfThreadEvent *impl = (details::XpfThreadEvent*) pImpl;
delete impl;
pImpl = 0xfefefefe;
}
ThreadEvent& ThreadEvent::operator = (const ThreadEvent &that)
{
xpfAssert( ( "non-copyable", false ) ); // ThreadEvent is non-copyable
return *this;
}
void ThreadEvent::set()
{
details::XpfThreadEvent *impl = (details::XpfThreadEvent*) pImpl;
impl->set();
}
void ThreadEvent::reset()
{
details::XpfThreadEvent *impl = (details::XpfThreadEvent*) pImpl;
impl->reset();
}
bool ThreadEvent::wait(u32 timeoutMs)
{
details::XpfThreadEvent *impl = (details::XpfThreadEvent*) pImpl;
return impl->wait(timeoutMs);
}
bool ThreadEvent::isSet()
{
details::XpfThreadEvent *impl = (details::XpfThreadEvent*) pImpl;
return impl->isSet();
}
};
<file_sep>/src/threadlock.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/platform.h>
// Currently only 2 threading models are supported: windows, posix.
#ifdef XPF_PLATFORM_WINDOWS
#include "platform/threadlock_windows.hpp"
#else
#include "platform/threadlock_posix.hpp"
#endif
namespace xpf {
ThreadLock::ThreadLock()
{
pImpl = (vptr) new details::XpfThreadLock;
}
ThreadLock::ThreadLock(const ThreadLock& that)
{
xpfAssert( ( "non-copyable", false ) );
}
ThreadLock::~ThreadLock()
{
details::XpfThreadLock *impl = (details::XpfThreadLock*) pImpl;
delete impl;
pImpl = 0xfefefefe;
}
ThreadLock& ThreadLock::operator = (const ThreadLock& that)
{
xpfAssert( ( "non-copyable", false ) );
return *this;
}
void ThreadLock::lock()
{
details::XpfThreadLock *impl = (details::XpfThreadLock*) pImpl;
impl->lock();
}
bool ThreadLock::tryLock()
{
details::XpfThreadLock *impl = (details::XpfThreadLock*) pImpl;
return impl->tryLock();
}
bool ThreadLock::isLocked() const
{
details::XpfThreadLock *impl = (details::XpfThreadLock*) pImpl;
return impl->isLocked();
}
void ThreadLock::unlock()
{
details::XpfThreadLock *impl = (details::XpfThreadLock*) pImpl;
impl->unlock();
}
ThreadID ThreadLock::getOwner() const
{
details::XpfThreadLock *impl = (details::XpfThreadLock*) pImpl;
return impl->getOwner();
}
};
<file_sep>/include/xpf/tls.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_TLS_HEADER_
#define _XPF_TLS_HEADER_
#include "platform.h"
#include "threadlock.h"
#include <map>
// Compiler-specific TLS keyword
// http://en.wikipedia.org/wiki/Thread-local_storage
#ifdef XPF_COMPILER_SPECIFIED
# if defined(XPF_COMPILER_MSVC)
# define XPF_TLS __declspec(thread)
# else
# define XPF_TLS __thread
# endif
#endif
namespace xpf {
/*
* An abstraction of TLS support from native platforms.
* On Windows, it wraps TlsAlloc()/TlsFree()/TlsGetValue()/TlsSetValue().
* On POSIX platforms, it wraps pthread_key_create()/pthread_key_delete()/pthread_getspecific()/pthread_setspecific().
*/
// Returns an opaque value called index. Except 0 indicates an error occurred, do not make any
// assumption on the content of it.
// Use this index in subsequent calls to TlsDelete()/TlsGet()/TlsSet().
vptr XPF_API TlsCreate();
// Delete an index created by TlsCreate().
void XPF_API TlsDelete(vptr index);
// Retrieve the data associated with the index and the calling thread.
// After an index has been created, it is by default associated with 0
// for all threads.
vptr XPF_API TlsGet(vptr index);
// Associate the index with a custom data.
// This association is space-independent among threads.
void XPF_API TlsSet(vptr index, vptr data);
/*
* A standard STL map accompany with a thread lock.
* The key of the map is a thread ID, so that get()/put() calls made
* from each individual thread are guaranteed to be targeting on
* seperated storage space.
*
* One should generally use TlsCreate()/TlsDelete()/TlsGet()/TlsSet()
* instead of this TlsMap to implement TLS for better performance.
* TlsMap should be considered as a fallback mechanism on platforms
* which TlsXXX functions are not working properly. Or for special
* purpose.
*/
template < typename ValueType,
typename Compare = std::less<ValueType>,
typename Alloc = std::allocator< std::pair< xpf::ThreadID, ValueType> > >
class TlsMap
{
public:
typedef std::map< xpf::ThreadID, ValueType, Compare, Alloc > StorageMapType;
public:
TlsMap() {}
TlsMap(const TlsMap& other) { *this = other; }
~TlsMap() {}
TlsMap& operator=(const TlsMap& other)
{
ScopedThreadLock sl(mLock);
other.dump(mMap);
}
void dump(StorageMapType &outMap)
{
ScopedThreadLock sl(mLock);
outMap = mMap;
}
bool put(const ValueType& data, bool replace = false, ThreadID tid = 0)
{
ScopedThreadLock sl(mLock);
if (0 == tid)
{
tid = Thread::getThreadID();
}
if (replace)
{
mMap.erase(tid);
}
return mMap.insert( std::make_pair(tid, data) ).second;
}
bool get(ValueType& outData, ThreadID tid = 0)
{
ScopedThreadLock sl(mLock);
if (0 == tid)
{
tid = Thread::getThreadID();
}
typename StorageMapType::iterator it = mMap.find(tid);
if (it != mMap.end())
{
outData = it->second;
return true;
}
return false;
}
bool clear(ThreadID tid = 0)
{
ScopedThreadLock sl(mLock);
if (0 == tid)
{
tid = Thread::getThreadID();
}
return (mMap.erase(tid) > 0);
}
private:
ThreadLock mLock;
StorageMapType mMap;
};
}; // end of namespace xpf
#endif // _XPF_TLS_HEADER_
<file_sep>/tests/network/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(network_test
main.cpp
sync_server.cpp
sync_server.h
sync_client.cpp
sync_client.h
async_server.cpp
async_server.h
async_client.cpp
async_client.h
)
SET_PROPERTY(TARGET network_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(network_test xpf)
<file_sep>/src/platform/threadlock_windows.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/threadlock.h>
#ifdef _XPF_THREADLOCK_IMPL_INCLUDED_
#error Multiple ThreadLock implementation files included
#else
#define _XPF_THREADLOCK_IMPL_INCLUDED_
#endif
#ifndef XPF_PLATFORM_WINDOWS
# error threadlock_windows.hpp shall not build on platforms other than Windows.
#endif
#include <Windows.h>
namespace xpf { namespace details {
class XpfThreadLock
{
public:
XpfThreadLock()
: mOwner(Thread::INVALID_THREAD_ID)
{
::InitializeCriticalSection(&mMutex);
}
~XpfThreadLock()
{
::DeleteCriticalSection(&mMutex);
}
inline void lock()
{
::EnterCriticalSection(&mMutex);
mOwner = Thread::getThreadID();
}
inline bool tryLock()
{
BOOL ret = ::TryEnterCriticalSection(&mMutex);
if (TRUE == ret)
mOwner = Thread::getThreadID();
return (TRUE == ret)? true: false;
}
inline bool isLocked() const
{
return (mOwner != Thread::INVALID_THREAD_ID);
}
inline void unlock()
{
::LeaveCriticalSection(&mMutex);
mOwner = Thread::INVALID_THREAD_ID;
}
inline ThreadID getOwner() const
{
return mOwner;
}
private:
XpfThreadLock(const XpfThreadLock& that)
{
xpfAssert( ( "non-copyable object", false ) );
}
XpfThreadLock& operator = (const XpfThreadLock& that)
{
xpfAssert( ( "non-copyable object", false ) );
return *this;
}
ThreadID mOwner;
CRITICAL_SECTION mMutex;
};
};};<file_sep>/include/xpf/delegate.h
/******** Disclaimer
*
* The following code pieces are extracted from a third party open source project which
* I have no claim on.
*
* Project ACF:
* http://www.codeproject.com/Articles/11464/Yet-Another-C-style-Delegate-Class-in-Standard-C
* A non thread-safe, header only, delegate implementation.
*
********/
//-------------------------------------------------------------------------
//
// Copyright (C) 2004-2005 <NAME>
//
// Permission to copy, use, modify, sell and distribute this software is
// granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
//
// AcfDelegate.h
//
#ifndef __Acf_Delegate__
#define __Acf_Delegate__
#ifndef __XPF_PATCHED__
#define __XPF_PATCHED__
#endif
#include <stdexcept> // for std::logic_error
#include <utility> // for std::pair
#ifdef __XPF_PATCHED__
#include <string>
#define XCALLBACK(x) std::make_pair(this, &x)
#define XCALLBACK_(x, o) std::make_pair(o, &x)
#define XCALLBACK_STATIC(x) (&x)
#define XCALLBACK_FUNCTOR(x) (x)
#endif
// Macros for template metaprogramming
#define ACF_JOIN(a, b) ACF_DO_JOIN(a, b)
#define ACF_DO_JOIN(a, b) ACF_DO_JOIN2(a, b)
#define ACF_DO_JOIN2(a, b) a##b
#ifdef __XPF_PATCHED__
#define ACF_MAKE_PARAMS1_0(t)
#define ACF_MAKE_PARAMS1_1(t) t##1
#define ACF_MAKE_PARAMS1_2(t) t##1, t##2
#define ACF_MAKE_PARAMS1_3(t) t##1, t##2, t##3
#define ACF_MAKE_PARAMS1_4(t) t##1, t##2, t##3, t##4
#define ACF_MAKE_PARAMS1_5(t) t##1, t##2, t##3, t##4, t##5
#define ACF_MAKE_PARAMS1_6(t) t##1, t##2, t##3, t##4, t##5, t##6
#else
#define ACF_MAKE_PARAMS1_0(t)
#define ACF_MAKE_PARAMS1_1(t) t##1
#define ACF_MAKE_PARAMS1_2(t) t##1, ##t##2
#define ACF_MAKE_PARAMS1_3(t) t##1, ##t##2, ##t##3
#define ACF_MAKE_PARAMS1_4(t) t##1, ##t##2, ##t##3, ##t##4
#define ACF_MAKE_PARAMS1_5(t) t##1, ##t##2, ##t##3, ##t##4, ##t##5
#define ACF_MAKE_PARAMS1_6(t) t##1, ##t##2, ##t##3, ##t##4, ##t##5, ##t##6
#endif
#define ACF_MAKE_PARAMS2_0(t1, t2)
#define ACF_MAKE_PARAMS2_1(t1, t2) t1##1 t2##1
#define ACF_MAKE_PARAMS2_2(t1, t2) t1##1 t2##1, t1##2 t2##2
#define ACF_MAKE_PARAMS2_3(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3
#define ACF_MAKE_PARAMS2_4(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3, t1##4 t2##4
#define ACF_MAKE_PARAMS2_5(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3, t1##4 t2##4, t1##5 t2##5
#define ACF_MAKE_PARAMS2_6(t1, t2) t1##1 t2##1, t1##2 t2##2, t1##3 t2##3, t1##4 t2##4, t1##5 t2##5, t1##6 t2##6
#define ACF_MAKE_PARAMS1(n, t) ACF_JOIN(ACF_MAKE_PARAMS1_, n) (t)
#define ACF_MAKE_PARAMS2(n, t1, t2) ACF_JOIN(ACF_MAKE_PARAMS2_, n) (t1, t2)
#ifdef __XPF_PATCHED__
namespace xpf {
#else
namespace Acf {
#endif
class InvalidCallException : public std::logic_error
{
public:
InvalidCallException() : std::logic_error("An empty delegate is called")
{
}
};
#ifdef __XPF_PATCHED__
template <class T>
inline T _HandleInvalidCall()
{
throw InvalidCallException();
}
template <>
inline void _HandleInvalidCall<void>()
{
}
#else
template <class T>
inline static T _HandleInvalidCall()
{
throw InvalidCallException();
}
template <>
inline static void _HandleInvalidCall<void>()
{
}
#endif
template <class TSignature>
class Delegate; // no body
} // namespace Acf
// Specializations
#define ACF_DELEGATE_NUM_ARGS 0 // Delegate<R ()>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#define ACF_DELEGATE_NUM_ARGS 1 // Delegate<R (T1)>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#define ACF_DELEGATE_NUM_ARGS 2 // Delegate<R (T1, T2)>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#define ACF_DELEGATE_NUM_ARGS 3 // Delegate<R (T1, T2, T3)>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#define ACF_DELEGATE_NUM_ARGS 4 // Delegate<R (T1, T2, T3, T4)>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#define ACF_DELEGATE_NUM_ARGS 5 // Delegate<R (T1, T2, T3, T4, T5)>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#define ACF_DELEGATE_NUM_ARGS 6 // Delegate<R (T1, T2, T3, T4, T5, T6)>
#ifdef __XPF_PATCHED__
#include "delegate_template.h"
#else
#include "AcfDelegateTemplate.h"
#endif
#undef ACF_DELEGATE_NUM_ARGS
#undef __XPF_PATCHED__
#endif // #ifndef __Acf_Delegate__
<file_sep>/src/utfconv.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/utfconv.h>
namespace xpf {
namespace details {
enum EStatus { END_OF_STREAM = 0xFFFFFFFF, BAD_FORMAT = 0xFFFFFFFE, SUCCESS = 0, };
class IUcReader
{
public:
virtual ~IUcReader() {}
virtual u32 read() = 0;
};
class IUcWriter
{
public:
virtual ~IUcWriter() {}
virtual u32 write(u32 cp) = 0;
virtual u32 closure() = 0;
};
class Utf8Reader : public IUcReader
{
public:
Utf8Reader(u8 * buf, s32 cnt) : Current(buf), Remaining(cnt) {};
u32 read()
{
u32 codepoint = 0;
s32 sbcnt = 0;
if ((Remaining == 0) || (*Current == 0))
return END_OF_STREAM;
// Determine how many subsequent bytes for current code point.
u8 c = *Current;
if ((c & 0x80) == 0)
{
codepoint = c;
} else if ((c & 0xE0) == 0xC0) {
sbcnt = 1;
codepoint = (c & 0x1F);
} else if ((c & 0xF0) == 0xE0) {
sbcnt = 2;
codepoint = (c & 0x0F);
} else if ((c & 0xF8) == 0xF0) {
sbcnt = 3;
codepoint = (c & 0x07);
} else if ((c & 0xFC) == 0xF8) {
sbcnt = 4;
codepoint = (c & 0x03);
} else if ((c & 0xFE) == 0xFC) {
sbcnt = 5;
codepoint = (c & 0x01);
} else {
return BAD_FORMAT;
}
// Update remaining byte count.
// If current reading code point is truncated by remaining count,
// simply abort the reading and report EOS.
if (Remaining > 0)
{
if (Remaining < (sbcnt + 1))
return END_OF_STREAM;
else
Remaining -= (sbcnt + 1);
}
// utf-8 convertion
while (sbcnt--)
{
Current++;
if (((*Current) & 0xC0) == 0x80)
{
codepoint <<= 6;
codepoint |= ((*Current) & 0x3F);
} else {
return BAD_FORMAT;
}
}
Current++;
return codepoint;
}
private:
s32 Remaining;
u8* Current;
};
class Ucs2Reader : public IUcReader
{
public:
Ucs2Reader(u16 * buf, s32 cnt) : Current(buf), Remaining(cnt) {}
u32 read()
{
u32 codepoint = 0;
if ((Remaining == 0) || (*Current == 0))
return END_OF_STREAM;
u16 c = *Current;
if ((c >= 0xD800) && (c <= 0xDBFF))
{
if (Remaining > 0)
{
if (Remaining < 2)
return END_OF_STREAM;
else
Remaining -= 2;
}
// A lead surrogate
u16 t = *(++Current);
if ((t >= 0xDC00) && (t <= 0xDFFF))
{
codepoint = (c - 0xD800);
codepoint <<= 10;
codepoint |= (t - 0xDC00);
codepoint += 0x10000;
} else {
// A lead surrogate with no following trail surrogate.
return BAD_FORMAT;
}
}
else if ((c >= 0xDC00) && (c <= 0xDFFF))
{
// An orphan trail surrogate ...
return BAD_FORMAT;
}
else
{
if (Remaining > 0)
Remaining--;
codepoint = c;
}
Current++;
return codepoint;
}
private:
s32 Remaining;
u16* Current;
};
class Ucs4Reader : public IUcReader
{
public:
Ucs4Reader(u32 * buf, s32 cnt) : Current(buf), Remaining(cnt) {}
u32 read()
{
if ((Remaining == 0) || (*Current == 0))
return END_OF_STREAM;
if (Remaining > 0)
Remaining--;
return *(Current++);
}
private:
s32 Remaining;
u32* Current;
};
class Utf8Writer : public IUcWriter
{
public:
Utf8Writer(u8 * buf, s32 cnt) : Current(buf), Remaining(cnt) {}
u32 write(u32 cp)
{
if (Remaining == 0)
return END_OF_STREAM;
int sbcnt = 0;
if ( cp >= 0x4000000 )
{
sbcnt = 5;
} else if ( cp >= 0x200000 ) {
sbcnt = 4;
} else if ( cp >= 0x10000) {
sbcnt = 3;
} else if ( cp >= 0x800) {
sbcnt = 2;
} else if ( cp >= 0x80) {
sbcnt = 1;
}
if (Remaining > 0)
{
if (Remaining < (sbcnt + 1))
return END_OF_STREAM;
else
Remaining -= (sbcnt + 1);
}
for (int i=sbcnt; i>0; --i)
{
*(Current+i) = 0x80 | ((u8)(cp & 0x3F));
cp >>= 6;
}
switch (sbcnt)
{
default:
case 0:
*Current = (u8)(cp & 0xFF);
break;
case 1:
*Current = 0xC0 | (u8)(cp & 0x1F);
break;
case 2:
*Current = 0xE0 | (u8)(cp & 0x0F);
break;
case 3:
*Current = 0xF0 | (u8)(cp & 0x07);
break;
case 4:
*Current = 0xF8 | (u8)(cp & 0x03);
break;
case 5:
*Current = 0xFC | (u8)(cp & 0x01);
break;
}
Current += (sbcnt + 1);
return SUCCESS;
}
u32 closure()
{
if (Remaining != 0)
{
*Current = 0;
return SUCCESS;
}
return END_OF_STREAM;
}
private:
s32 Remaining;
u8* Current;
};
class Ucs2Writer : public IUcWriter
{
public:
Ucs2Writer(u16 * buf, s32 cnt) : Current(buf), Remaining(cnt) {}
u32 write(u32 cp)
{
if (Remaining == 0)
return END_OF_STREAM;
if (cp > 0x10FFFF)
{
// impossible code point value
}
else if (cp >= 0x10000)
{
if (Remaining > 0)
{
if (Remaining < 2)
return END_OF_STREAM;
else
Remaining -= 2;
}
cp -= 0x10000;
*(Current++) = ((u16)((cp & 0xFFC00)>>10)) + 0xD800;
*(Current++) = ((u16)(cp & 0x3FF)) + 0xDC00;
}
else
{
if (Remaining > 0)
Remaining--;
*(Current++) = (u16) cp;
}
return SUCCESS;
}
u32 closure()
{
if (Remaining != 0)
{
*Current = 0;
return SUCCESS;
}
return END_OF_STREAM;
}
private:
s32 Remaining;
u16* Current;
};
class Ucs4Writer : public IUcWriter
{
public:
Ucs4Writer(u32 * buf, s32 cnt) : Current(buf), Remaining(cnt) {}
u32 write(u32 cp)
{
if (Remaining == 0)
return END_OF_STREAM;
if (Remaining > 0)
Remaining--;
*(Current++) = cp;
return SUCCESS;
}
u32 closure()
{
if (Remaining != 0)
{
*Current = 0;
return SUCCESS;
}
return END_OF_STREAM;
}
private:
s32 Remaining;
u32* Current;
};
s32 utfConvInner( void * sbuf, void * dbuf, u32 scw, u32 dcw, s32 scnt, s32 dcnt )
{
if (((scw != 4) && (scw != 2) && (scw != 1)) ||
((dcw != 4) && (dcw != 2) && (dcw != 1)) )
return -1;
IUcReader *r = 0;
IUcWriter *w = 0;
// Select reader by the width of source char
switch (scw)
{
case 4:
r = new Ucs4Reader( (u32*) sbuf, scnt );
break;
case 2:
r = new Ucs2Reader( (u16*) sbuf, scnt );
break;
case 1:
r = new Utf8Reader( (u8*) sbuf, scnt );
break;
default:
break;
}
// Select writer by the width of destination char
switch (dcw)
{
case 4:
w = new Ucs4Writer( (u32*) dbuf, dcnt );
break;
case 2:
w = new Ucs2Writer( (u16*) dbuf, dcnt );
break;
case 1:
w = new Utf8Writer( (u8*) dbuf, dcnt );
break;
default:
break;
}
s32 cnt = 0;
while (true)
{
u32 cp = r->read();
if ((cp == END_OF_STREAM) || (cp == BAD_FORMAT))
{
w->closure();
break;
}
if ( SUCCESS != w->write(cp) )
break;
cnt++;
}
delete r;
delete w;
return cnt;
}
};
};
<file_sep>/tests/uuid/uuid_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/uuidv4.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string>
using namespace xpf;
int main(int argc, char *argv[])
{
srand((unsigned int)time(0));
Uuid id1 = Uuid::null();
Uuid id2 = Uuid::null();
xpfAssert(id1 == id2);
xpfAssert(id2.asString() == "00000000-0000-0000-0000-000000000000");
Uuid id3 = Uuid::fromString("00000000-0000-0000-0000-000000000000");
xpfAssert(id1 == id3);
id1 = Uuid::generate();
std::string v = id1.asString();
id2 = Uuid::fromString(v.c_str());
id3 = Uuid::fromOctet(id1.getOctet());
xpfAssert(id1 == id2);
xpfAssert(id2 == id3);
// Distribution test.
// Generate 200 uuids and check if all 122 possible bits are covered.
u8 coverage[16] = { 0, 0, 0, 0, 0, 0, 0xf0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0 };
for (u32 i = 0; i < 200; ++i)
{
Uuid u = Uuid::generate();
// check UUID v4 mark.
xpfAssert((u.getOctet()[6] & 0xf0) == 0x40);
xpfAssert((u.getOctet()[8] & 0xc0) == 0x80);
// commit bit coverage.
for (u32 j = 0; j < 16; ++j)
{
coverage[j] |= u.getOctet()[j];
}
}
// check coverage
for (u32 i = 0; i < 16; ++i)
{
xpfAssert(coverage[i] == 0xFF);
}
return 0;
}
<file_sep>/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
IF(NOT CMAKE_BUILD_TYPE)
SET(CMAKE_BUILD_TYPE "Debug")
# SET(CMAKE_BUILD_TYPE "Release")
ENDIF(NOT CMAKE_BUILD_TYPE)
IF ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
SET(BUILD_WITH_CLANG "1")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-value")
ELSEIF ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
SET(BUILD_WITH_GNU "1")
ELSEIF ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel")
SET(BUILD_WITH_ICC "1")
ELSEIF ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
SET(BUILD_WITH_MSVC "1")
ELSE()
MESSAGE("Un-recognizable compiler ID - ${CMAKE_CXX_COMPILER_ID}")
ENDIF()
IF(MSVC)
IF(DEFINED WIN32_MSVC_MT)
SET(CMAKE_C_FLAGS_DEBUG_INIT "/D_DEBUG /MTd /Zi /Ob0 /Od /RTC1")
SET(CMAKE_C_FLAGS_MINSIZEREL_INIT "/MT /O1 /Ob1 /D NDEBUG")
SET(CMAKE_C_FLAGS_RELEASE_INIT "/MT /O2 /Ob2 /D NDEBUG")
SET(CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "/MT /Zi /O2 /Ob1 /D NDEBUG")
SET(CMAKE_CXX_FLAGS_DEBUG_INIT "/D_DEBUG /MTd /Zi /Ob0 /Od /RTC1")
SET(CMAKE_CXX_FLAGS_MINSIZEREL_INIT "/MT /O1 /Ob1 /D NDEBUG")
SET(CMAKE_CXX_FLAGS_RELEASE_INIT "/MT /O2 /Ob2 /D NDEBUG")
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "/MT /Zi /O2 /Ob1 /D NDEBUG")
ENDIF(DEFINED WIN32_MSVC_MT)
ENDIF(MSVC)
ADD_SUBDIRECTORY("./src")
ADD_SUBDIRECTORY("./tests/threading")
ADD_SUBDIRECTORY("./tests/atomicops")
ADD_SUBDIRECTORY("./tests/string")
ADD_SUBDIRECTORY("./tests/delegate")
ADD_SUBDIRECTORY("./tests/allocators")
ADD_SUBDIRECTORY("./tests/network")
ADD_SUBDIRECTORY("./tests/base64")
ADD_SUBDIRECTORY("./tests/uuid")
ADD_SUBDIRECTORY("./tests/coroutine")
ADD_SUBDIRECTORY("./tests/fcontext")
<file_sep>/include/xpf/getopt.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_GETOPT_HEADER_
#define _XPF_GETOPT_HEADER_
#include "platform.h"
XPF_EXTERNC_BEGIN
extern XPF_API xpf::c8 *xoptarg;
extern XPF_API xpf::s32 xoptind;
extern XPF_API xpf::s32 xopterr;
extern XPF_API xpf::s32 xoptopt;
extern XPF_API xpf::s32 xoptreset;
XPF_EXTERNC_END
/*****
* This is a cross-platform implementation of legacy getopt related functions.
* Here provides 4 functions: xgetopt(), xgetopt_long(), xgetopt_long_only(),
* and xgetsubopt() which mimic almost the same functionality of both GNU
* and BSD's version of getopt(), getopt_long(), getopt_long_only, and
* getsubopt().
*
* Since there were some differences between GNU and BSD's getopt impl, xgetopt
* have to choose a side on those differences. Here list the behaviours:
*
* Argv permuting:
* GNU: By default would permute the argv so that all non-option argv eventually
* will be moved to the end of argv. User can disable permuting by specifying
* a '+' char in the optstring.
* BSD: No permuting.
* xgetopt: Follow GNU. Both '+' and '-' flags in the front of optstring can be recognized
* and should work properly.
*
* value of optopt:
* GNU: Set optopt only when either meet an undefined option, or detect on a missing
* argument.
* BSD: Always set it to be the option code which is currently examining at.
* xgetopt: Follow GNU.
*
* value of optarg:
* GNU: Reset to 0 at the start of every getopt() call.
* BSD: No reseting. It remains the same value until next write by getopt().
* xgetopt: Follow GNU.
*
* Reset state for parsing a new argc/argv set:
* GNU: Simply reset optind to be 1. However, it is impossible to reset parsing
* state when an internal short option parsing is taking place in argv[1].
* BSD: Use another global boolean 'optreset' for this purpose.
* xgetopt: Both behaviours are supported.
*
* -W special case:
* GNU: If "W;" is present in optstring, the "-W foo" in commandline will be
* treated as the long option "--foo".
* BSD: No mentioned in the man page but seems to support such usage.
* xgetopt: Do NOT support -W special case.
*/
namespace xpf
{
XPF_EXTERNC s32 XPF_API xgetopt(
s32 argc,
c8 * const argv[],
const c8 *optstr);
struct xoption
{
const c8 *name;
s32 has_arg;
s32 *flag;
s32 val;
};
#define xno_argument (0)
#define xrequired_argument (1)
#define xoptional_argument (2)
XPF_EXTERNC s32 XPF_API xgetopt_long(
s32 argc,
c8 * const argv[],
const c8 *optstring,
const struct xoption *longopts,
s32 *longindex);
XPF_EXTERNC s32 XPF_API xgetopt_long_only(
s32 argc,
c8 * const argv[],
const c8 *optstring,
const struct xoption *longopts,
s32 *longindex);
XPF_EXTERNC s32 XPF_API xgetsubopt(
c8 **optionp,
c8 * const *tokens,
c8 **valuep);
}; // end of namespace xpf
#endif
<file_sep>/tests/fcontext/fcontext_test.cpp
#include <iostream>
#include <xpf/fcontext.h>
xpf::fcontext_t fcm,fc1,fc2;
void f1(xpf::vptr p)
{
std::cout<<"f1: entered"<<std::endl;
std::cout<<"f1: call jump_fcontext( & fc1, fc2, 0)"<< std::endl;
xpf::jump_fcontext(&fc1,fc2,0);
std::cout<<"f1: return"<<std::endl;
xpf::jump_fcontext(&fc1,fcm,0);
}
void f2(xpf::vptr p)
{
std::cout<<"f2: entered"<<std::endl;
std::cout<<"f2: call jump_fcontext( & fc2, fc1, 0)"<<std::endl;
xpf::jump_fcontext(&fc2,fc1,0);
xpfAssert(false&&!"f2: never returns");
}
int main()
{
// Note: std::cout may refuse to work for a
// small stack size (ex: 8192).
std::size_t size(1024*1024); // Use 1mb
char* sp1 = new char[size];
char* sp2 = new char[size];
std::cout << "main: preparing fcontext..." << std::endl;
// Note: make_fcontext() uses the stack space (passed as
// the 1st param) as the native architecture does:
// it grows either from the top of the stack
// (downwards) or the bottom of the stack (upwards).
// For this testcase, we assume grows upwards.
fc1 = xpf::make_fcontext(&sp1[size], size, f1);
fc2 = xpf::make_fcontext(&sp2[size], size, f2);
std::cout<<"main: call jump_fcontext( & fcm, fc1, 0)"<<std::endl;
xpf::jump_fcontext(&fcm,fc1,0);
delete[] sp1;
delete[] sp2;
std::cout << "main: done" << std::endl;
return 0;
}
<file_sep>/tests/delegate/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(delegate_test
delegate.cpp
)
SET_PROPERTY(TARGET delegate_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
<file_sep>/tests/string/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(string_test
string_test.cpp
)
SET_PROPERTY(TARGET string_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(string_test xpf)
<file_sep>/src/platform/netiomux_epoll.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/netiomux.h>
#ifdef _XPF_NETIOMUX_IMPL_INCLUDED_
#error Multiple NetIoMux implementation files included
#else
#define _XPF_NETIOMUX_IMPL_INCLUDED_
#endif
#include "netiomux_syncfifo.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define MAX_EVENTS_AT_ONCE (128)
#define MAX_READY_LIST_LEN (10240)
#define ASYNC_OP_READ (0)
#define ASYNC_OP_WRITE (1)
namespace xpf
{
// host info for connect
struct ConnectHostInfo
{
ConnectHostInfo(const c8 *h, const c8 *s)
{
host = ::strdup(h);
service = ::strdup(s);
}
~ConnectHostInfo()
{
if (host) ::free(host);
if (service) ::free(service);
}
c8 *host;
c8 *service;
};
// data record per operation
struct Overlapped
{
Overlapped(NetEndpoint *ep, NetIoMux::EIoType iocode)
: iotype(iocode), sep(ep), tep(0), buffer(0), length(0)
, peer(0), cb(0), errorcode(0), provisioned(false) {}
NetIoMux::EIoType iotype;
NetEndpoint *sep;
NetEndpoint *tep;
c8 *buffer;
u32 length;
NetEndpoint::Peer *peer;
NetIoMuxCallback *cb;
int errorcode;
bool provisioned;
};
// data record per socket
struct AsyncContext
{
std::deque<Overlapped*> rdqueue; // queued read operations
std::deque<Overlapped*> wrqueue; // queued write operations
bool ready;
ThreadLock lock;
NetEndpoint *ep;
};
class NetIoMuxImpl
{
public:
NetIoMuxImpl()
: mEnable(true)
{
xpfSAssert(sizeof(socklen_t) == sizeof(s32));
mEpollfd = epoll_create1(0);
xpfAssert(mEpollfd != -1);
if (mEpollfd == -1)
mEnable = false;
}
~NetIoMuxImpl()
{
enable(false);
if (mEpollfd != -1)
close(mEpollfd);
mEpollfd = -1;
}
void enable(bool val)
{
mEnable = val;
}
void run()
{
while (mEnable)
{
if (NetIoMux::ERS_DISABLED == runOnce(10))
break;
}
}
NetIoMux::ERunningStaus runOnce(u32 timeoutMs)
{
bool consumeSome = false;
u32 pendingCnt = 0;
// Process the completion queue. Emit the completion event.
Overlapped *co = (Overlapped*) mCompletionList.pop_front(pendingCnt);
if (co)
{
consumeSome = true;
switch (co->iotype)
{
case NetIoMux::EIT_RECV:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, 0, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_RECV, co->sep, 0, co->buffer, 0);
break;
case NetIoMux::EIT_RECVFROM:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->peer, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_RECV, co->sep, 0, co->buffer, 0);
delete co->peer;
break;
case NetIoMux::EIT_SEND:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, 0, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SEND, co->sep, 0, co->buffer, 0);
break;
case NetIoMux::EIT_SENDTO:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, (vptr)co->peer, co->buffer, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->peer, co->buffer, co->length);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SEND, co->sep, (vptr)co->peer, co->buffer, 0);
delete co->peer;
break;
case NetIoMux::EIT_ACCEPT:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_INVALID_OP, co->sep, 0, 0, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->tep, 0, 0);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_ACCEPT, co->sep, 0, 0, 0);
delete co->peer;
break;
case NetIoMux::EIT_CONNECT:
if (!co->provisioned)
co->cb->onIoCompleted(co->iotype, (co->peer == 0)? NetEndpoint::EE_INVALID_OP : NetEndpoint::EE_RESOLVE, co->sep, 0, 0, 0);
else if (co->errorcode == 0)
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_SUCCESS, co->sep, (vptr)co->peer, 0, 0);
else
co->cb->onIoCompleted(co->iotype, NetEndpoint::EE_CONNECT, co->sep, 0, 0, 0);
delete co->peer;
break;
case NetIoMux::EIT_INVALID:
default:
xpfAssert(("Unrecognized iotype. Maybe a corrupted Overlapped.", false));
break;
}
delete co;
}
// Consume ready list:
// Pop the front socket out of list, and
// process all r/w operations until EWOULDBLOCK.
// Re-arm the socket if there are more pending
// operations.
NetEndpoint *ep = (NetEndpoint*) mReadyList.pop_front(pendingCnt);
do
{
if (!ep) break;
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
if (!ctx) break;
ScopedThreadLock ml(ctx->lock);
xpfAssert(("Expecting ready flag on for all ", ctx->ready));
ctx->ready = false;
while (!ctx->rdqueue.empty()) // process rqueue.
{
Overlapped *o = ctx->rdqueue.front();
if (!o) break;
consumeSome = true;
if (performIoLocked(ep, o))
ctx->rdqueue.pop_front();
else
break;
} // end of while (true)
while (!ctx->wrqueue.empty()) // process wrqueue
{
Overlapped *o = ctx->wrqueue.front();
if (!o) break;
consumeSome = true;
if (performIoLocked(ep, o))
ctx->wrqueue.pop_front();
else
break;
} // end of while (true)
bool rearm = false;
epoll_event evt;
evt.events = EPOLLET | EPOLLONESHOT;
evt.data.ptr = (void*) ep;
if (!ctx->rdqueue.empty()) { evt.events |= EPOLLIN; rearm = true; }
if (!ctx->wrqueue.empty()) { evt.events |= EPOLLOUT; rearm = true; }
if (rearm)
{
int ec = epoll_ctl(mEpollfd, EPOLL_CTL_MOD, ep->getSocket(), &evt);
if ((ec == -1) && (errno == ENOENT))
{
ec = epoll_ctl(mEpollfd, EPOLL_CTL_ADD, ep->getSocket(), &evt);
}
xpfAssert(ec == 0);
}
} while (0);
// epoll_wait for more ready events.
// Will skip if the length of list is too large.
if (pendingCnt < MAX_READY_LIST_LEN)
{
epoll_event evts[MAX_EVENTS_AT_ONCE];
int nevts = epoll_wait(mEpollfd, evts, MAX_EVENTS_AT_ONCE, (consumeSome)? 0 : timeoutMs);
xpfAssert(("Failed on calling epoll_wait", nevts != -1));
if (0 == nevts)
{
return NetIoMux::ERS_TIMEOUT;
}
else if (nevts > 0)
{
for (int i=0; i<nevts; ++i)
{
uint32_t events = evts[i].events;
NetEndpoint *ep = (NetEndpoint*) evts[i].data.ptr;
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
ScopedThreadLock ml(ctx->lock);
xpfAssert(("Expecting non-ready ep in epoll_wait.", ctx->ready == false));
ctx->ready = false;
if ((events & (EPOLLERR | EPOLLHUP)))
{
for (std::deque<Overlapped*>::iterator it = ctx->rdqueue.begin();
it != ctx->rdqueue.end(); ++it)
{
Overlapped *o = (*it);
o->errorcode = ECONNABORTED;
mCompletionList.push_back((void*)o);
}
for (std::deque<Overlapped*>::iterator it = ctx->wrqueue.begin();
it != ctx->wrqueue.end(); ++it)
{
Overlapped *o = (*it);
o->errorcode = ECONNABORTED;
mCompletionList.push_back((void*)o);
}
ctx->rdqueue.clear();
ctx->wrqueue.clear();
continue;
}
if (events & (EPOLLIN | EPOLLOUT))
{
xpfAssert(("Expecting non-ready ep in epoll_wait.", ctx->ready == false));
ctx->ready = true;
mReadyList.push_back((void*)ep);
}
} // end of for (int i=0; i<nevts; ++i)
}
else
{
return NetIoMux::ERS_DISABLED;
}
}
return NetIoMux::ERS_NORMAL;
}
void asyncRecv(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_RECV);
o->buffer = buf;
o->length = buflen;
o->cb = cb;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_READ);
}
}
void asyncRecvFrom(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_RECVFROM);
o->buffer = buf;
o->length = buflen;
o->cb = cb;
o->peer = new NetEndpoint::Peer;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_READ);
}
}
void asyncSend(NetEndpoint *ep, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_SEND);
o->buffer = (c8*)buf;
o->length = buflen;
o->cb = cb;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_WRITE);
}
}
void asyncSendTo(NetEndpoint *ep, const NetEndpoint::Peer *peer, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_SENDTO);
o->buffer = (c8*)buf;
o->length = buflen;
o->cb = cb;
o->peer = new NetEndpoint::Peer(*peer); // clone
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_WRITE);
}
}
void asyncAccept(NetEndpoint *ep, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_ACCEPT);
o->cb = cb;
o->peer = new NetEndpoint::Peer;
o->peer->Length = XPF_NETENDPOINT_MAXADDRLEN;
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_READ);
}
}
void asyncConnect(NetEndpoint *ep, const c8 *host, const c8 *serviceOrPort, NetIoMuxCallback *cb)
{
AsyncContext *ctx = (AsyncContext*)ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx)
{
Overlapped *o = new Overlapped(ep, NetIoMux::EIT_CONNECT);
o->cb = cb;
o->buffer = (c8*) new ConnectHostInfo(host, serviceOrPort);
ScopedThreadLock ml(ctx->lock);
appendAsyncOpLocked(ep, o, ASYNC_OP_WRITE);
}
}
bool join(NetEndpoint *ep)
{
s32 sock = ep->getSocket();
// bundle with an async context
AsyncContext *ctx = new AsyncContext;
ctx->ready = false;
ctx->ep = ep;
ep->setAsyncContext((vptr)ctx);
// request the socket to be non-blocking
int flags = fcntl(sock, F_GETFL);
xpfAssert(flags != -1);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
return true;
}
bool depart(NetEndpoint *ep)
{
s32 sock = ep->getSocket();
// remove given endpoint from epoll group
struct epoll_event dummy;
int ec = epoll_ctl(mEpollfd, EPOLL_CTL_DEL, sock, &dummy); // dummy is not used but cannot be NULL
xpfAssert((ec == 0 || errno == ENOENT));
if ((ec != 0) && (errno != ENOENT))
{
return false;
}
// delete the async context
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
xpfAssert(ctx != 0);
if (!ctx)
{
return false;
}
else
{
ctx->lock.lock();
if (ctx->ready)
{
mReadyList.erase((void*)ep); // Note: Acquire mReadyList's lock while holding ctx's lock.
}
delete ctx;
ep->setAsyncContext(0);
// since the whole context object has been deleted, there's no bother to call unlock.
}
// reset the socket to be blocking
int flags = fcntl(sock, F_GETFL);
xpfAssert(flags != -1);
fcntl(sock, F_SETFL, flags & (0 ^ O_NONBLOCK));
return (ec == 0);
}
static const char * getMultiplexerType(NetIoMux::EPlatformMultiplexer &epm)
{
epm = NetIoMux::EPM_EPOLL;
return "epoll";
}
private:
bool performIoLocked(NetEndpoint *ep, Overlapped *o) // require ep->ctx locked.
{
AsyncContext *ctx = (AsyncContext*) ep->getAsyncContext();
xpfAssert(ctx != 0);
if (ctx == 0)
return false;
bool completed = true;
switch (o->iotype)
{
case NetIoMux::EIT_RECV:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::recv(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT);
if (bytes >= 0)
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
completed = false;
}
} while (0);
break;
case NetIoMux::EIT_RECVFROM:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::recvfrom(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT, (struct sockaddr*)o->peer->Data, (socklen_t*)&o->peer->Length);
if (bytes >= 0)
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
completed = false;
}
} while (0);
break;
case NetIoMux::EIT_ACCEPT:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_LISTENING == stat));
if (NetEndpoint::ESTAT_LISTENING != stat)
{
o->tep = 0;
o->length = 0;
o->buffer = 0;
break;
}
o->provisioned = true;
}
int peersock = ::accept(ep->getSocket(), (struct sockaddr*)o->peer->Data, (socklen_t*)&o->peer->Length);
if (peersock != -1)
{
o->errorcode = 0;
o->length = 0;
o->tep = new NetEndpoint(ep->getProtocol(), peersock, NetEndpoint::ESTAT_CONNECTED);
join(o->tep);
ep->setStatus(NetEndpoint::ESTAT_LISTENING);
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->tep = 0;
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
ep->setStatus(NetEndpoint::ESTAT_LISTENING);
}
else
{
completed = false;
ep->setStatus(NetEndpoint::ESTAT_ACCEPTING);
}
} while (0);
break;
case NetIoMux::EIT_SEND:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::send(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT);
if (bytes >=0 )
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
completed = false;
}
} while (0);
break;
case NetIoMux::EIT_SENDTO:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == stat));
if (NetEndpoint::ESTAT_CONNECTED != stat)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
ssize_t bytes = ::sendto(ep->getSocket(), o->buffer, (size_t)o->length, MSG_DONTWAIT,
(const struct sockaddr*)o->peer->Data, (socklen_t)o->peer->Length);
if (bytes >=0 )
{
o->length = bytes;
o->errorcode = 0;
}
else if (errno != EWOULDBLOCK && errno != EAGAIN)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
}
else
{
completed = false;
}
} while (0);
break;
case NetIoMux::EIT_CONNECT:
do
{
if (false == o->provisioned)
{
const NetEndpoint::EStatus stat = ep->getStatus();
xpfAssert(("Invalid socket status.", ((NetEndpoint::ESTAT_INIT == stat) && (o->buffer != 0))));
if ((NetEndpoint::ESTAT_INIT != stat) || (o->buffer == 0))
{
o->length = 0;
o->errorcode = 0;
o->peer = 0;
if (o->buffer)
{
ConnectHostInfo *chi = (ConnectHostInfo*)o->buffer;
delete chi;
o->buffer = 0;
}
break;
}
o->peer = new NetEndpoint::Peer;
// Note: resolving can be blockable.
ConnectHostInfo *chi = (ConnectHostInfo*)o->buffer;
bool resolved = NetEndpoint::resolvePeer(ep->getProtocol(), *o->peer, chi->host, chi->service);
delete chi;
if (!resolved)
{
o->length = 0;
o->errorcode = 0;
break;
}
o->provisioned = true;
}
if (o->length == 0) // not yet called connect
{
int ec = ::connect(ep->getSocket(), (const struct sockaddr*)o->peer->Data, (socklen_t)o->peer->Length);
if (ec == 0)
{
o->length = 0;
o->errorcode = 0;
ep->setStatus(NetEndpoint::ESTAT_CONNECTED);
}
else if (errno != EINPROGRESS)
{
o->length = 0;
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
ep->setStatus(NetEndpoint::ESTAT_INIT);
}
else
{
xpfAssert(o->length == 0);
ep->setStatus(NetEndpoint::ESTAT_CONNECTING);
o->length = 1; // mark a connect() call in progress.
completed = false;
}
}
else // a connect() was called and waiting for result.
{
int val = 0;
socklen_t valsize = sizeof(int);
int ec = ::getsockopt(ep->getSocket(), SOL_SOCKET, SO_ERROR, &val, &valsize);
xpfAssert(ec == 0);
if (ec == 0 && val == 0)
{
o->errorcode = 0;
o->length = 0;
ep->setStatus(NetEndpoint::ESTAT_CONNECTED);
}
else
{
o->errorcode = errno;
ep->setLastPlatformErrno(errno);
delete o->peer;
o->peer = 0;
ep->setStatus(NetEndpoint::ESTAT_INIT);
}
}
} while (0);
break;
default:
xpfAssert(("Unexpected iotype.", false));
break;
} // end of switch (o->iotype)
if (completed)
mCompletionList.push_back(o);
return completed;
}
void appendAsyncOpLocked(NetEndpoint *ep, Overlapped *o, u8 mode) // require ep->ctx locked.
{
AsyncContext *ctx = (ep == 0)? 0 : (AsyncContext*)ep->getAsyncContext();
if (ctx == 0 || o == 0)
{
xpfAssert(false);
return;
}
switch (mode)
{
case ASYNC_OP_READ:
ctx->rdqueue.push_back(o);
break;
case ASYNC_OP_WRITE:
ctx->wrqueue.push_back(o);
break;
default:
xpfAssert(("Unexpected async op mode.",false));
break;
}
if (!ctx->ready)
{
ctx->ready = true;
mReadyList.push_back((void*)ep);
}
}
NetIoMuxSyncFifo mCompletionList; // fifo of Overlapped.
NetIoMuxSyncFifo mReadyList; // fifo of NetEndpoints.
bool mEnable;
int mEpollfd;
}; // end of class NetIoMuxImpl (epoll)
} // end of namespace xpf
<file_sep>/src/platform/netiomux_iocp.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/netiomux.h>
#include <xpf/string.h>
#include <xpf/lexicalcast.h>
#ifdef _XPF_NETIOMUX_IMPL_INCLUDED_
#error Multiple NetIoMux implementation files included
#else
#define _XPF_NETIOMUX_IMPL_INCLUDED_
#endif
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <Windows.h>
#include <Mswsock.h>
#include <string.h>
namespace xpf
{
#define IOMUX_OVERLAPPED_FIRED (0x1)
struct NetIoMuxOverlapped : public OVERLAPPED
{
WSABUF Buffer;
u32 IoType;
NetIoMuxCallback *Callback;
SOCKET AcceptingSocket;
NetEndpoint::Peer PeerData;
u32 Flags;
};
struct IocpAsyncContext
{
IocpAsyncContext()
: pAcceptEx(0), pConnectEx(0) {}
LPFN_ACCEPTEX pAcceptEx;
LPFN_CONNECTEX pConnectEx;
};
class NetIoMuxImpl
{
public:
NetIoMuxImpl()
: mhIocp(INVALID_HANDLE_VALUE)
, bEnable(true)
{
if (!NetEndpoint::platformInit())
return;
mhIocp = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
xpfAssert( ("Cannot create an empty IO completeion port.", NULL != mhIocp) );
}
~NetIoMuxImpl()
{
enable(false);
if (mhIocp != INVALID_HANDLE_VALUE)
{
CloseHandle(mhIocp);
mhIocp = INVALID_HANDLE_VALUE;
}
}
void enable(bool val)
{
bEnable = val;
}
void run()
{
while (bEnable)
{
if (NetIoMux::ERS_DISABLED == runOnce(10))
break;
}
}
NetIoMux::ERunningStaus runOnce(u32 timeoutMs)
{
DWORD bytes = 0;
ULONG_PTR key = 0;
NetIoMuxOverlapped *odata = 0;
BOOL ret = ::GetQueuedCompletionStatus(mhIocp, &bytes, &key, (LPOVERLAPPED*)&odata, timeoutMs);
if (FALSE == ret)
{
if ((odata == 0) && (GetLastError() != ERROR_ABANDONED_WAIT_0))
return NetIoMux::ERS_TIMEOUT;
return NetIoMux::ERS_DISABLED;
}
NetEndpoint *ep = (NetEndpoint*)key;
bool isCompletion = ((odata->Flags & IOMUX_OVERLAPPED_FIRED) != 0);
if (isCompletion) // Completion status from overlapped functions.
{
DWORD dummy; // not used.
ret = ::WSAGetOverlappedResult(ep->getSocket(), odata, &bytes, TRUE, &dummy);
}
NetEndpoint::EStatus st = ep->getStatus();
NetIoMuxCallback *cb = odata->Callback;
NetIoMux::EIoType iotype = (NetIoMux::EIoType)odata->IoType;
bool deleteOverlapped = true;
switch (iotype)
{
case NetIoMux::EIT_ACCEPT:
if (!isCompletion)
{
do
{
IocpAsyncContext *ctx = (IocpAsyncContext*)ep->getAsyncContext();
xpfAssert(("Unprovisioned netendpoint.", ctx != 0));
if (0 == ctx)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, 0, 0);
break;
}
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_LISTENING == st));
if (NetEndpoint::ESTAT_LISTENING != st)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, 0, 0);
break;
}
u32 proto = ep->getProtocol();
odata->AcceptingSocket = socket(
(proto & NetEndpoint::ProtocolIPv4) ? AF_INET : AF_INET6,
(proto & NetEndpoint::ProtocolTCP) ? SOCK_STREAM : SOCK_DGRAM,
(proto & NetEndpoint::ProtocolTCP) ? IPPROTO_TCP : IPPROTO_UDP
);
xpfAssert(("Unable to create socket for accepting peer", odata->AcceptingSocket != INVALID_SOCKET));
if (odata->AcceptingSocket == INVALID_SOCKET)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_ACCEPT, ep, 0, 0, 0);
break;
}
ep->setStatus(NetEndpoint::ESTAT_ACCEPTING);
resetOverlapped(odata);
odata->Flags |= IOMUX_OVERLAPPED_FIRED;
DWORD bytes = 0;
const int addrlen = (proto & NetEndpoint::ProtocolIPv4)
? sizeof(sockaddr_in) +16
: sizeof(sockaddr_in6)+16;
BOOL result = ctx->pAcceptEx(ep->getSocket(), odata->AcceptingSocket,
odata->PeerData.Data, 0, addrlen, addrlen, &bytes,
(LPWSAOVERLAPPED)odata);
if ((TRUE == result) || (ERROR_IO_PENDING == WSAGetLastError()))
{
deleteOverlapped = false;
}
else // error
{
ep->setStatus(NetEndpoint::ESTAT_LISTENING);
cb->onIoCompleted(iotype, NetEndpoint::EE_ACCEPT, ep, 0, 0, 0);
}
} while(0);
}
else
{
xpfAssert(NetEndpoint::ESTAT_ACCEPTING == st);
ep->setStatus(NetEndpoint::ESTAT_LISTENING);
if (ret == FALSE)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_ACCEPT, ep, 0, 0, 0);
}
else
{
int listeningSocket = ep->getSocket();
xpfAssert(("Expecting valid peer socket.", odata->AcceptingSocket != INVALID_SOCKET));
int ec = setsockopt(odata->AcceptingSocket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
(char *)&listeningSocket, sizeof(vptr)); // MSDN was wrong at the last parameter !! It should be the size of pointer.
xpfAssert(("Failed to update accepted context on newly connected socket.", ec == 0));
NetEndpoint *tep = new NetEndpoint(ep->getProtocol(), (int)odata->AcceptingSocket, NetEndpoint::ESTAT_CONNECTED);
join(tep);
cb->onIoCompleted(iotype, NetEndpoint::EE_SUCCESS, ep, (vptr)tep, 0, 0);
}
}
break;
case NetIoMux::EIT_CONNECT:
if (!isCompletion)
{
do
{
IocpAsyncContext *ctx = (IocpAsyncContext*)ep->getAsyncContext();
xpfAssert(("Unprovisioned netendpoint.", ctx != 0));
if (0 == ctx)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, 0, 0);
break;
}
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_INIT == st));
if (NetEndpoint::ESTAT_INIT != st)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, 0, 0);
break;
}
// NOTE: Address resolving can block.
NetEndpoint::Peer peer;
if (!NetEndpoint::resolvePeer(ep->getProtocol(), peer,
odata->Buffer.buf, &odata->Buffer.buf[960]))
{
cb->onIoCompleted(iotype, NetEndpoint::EE_RESOLVE, ep, 0, 0, 0);
::free(odata->Buffer.buf);
break;
}
::free(odata->Buffer.buf);
// NOTE: The socket provided to ConnectEx() must be bound already.
int ec = 0;
if (ep->getProtocol() & NetEndpoint::ProtocolIPv4)
{
sockaddr_in sa = { 0 };
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
ec = ::bind(ep->getSocket(), (const sockaddr*)&sa, sizeof(sockaddr_in));
}
else
{
sockaddr_in6 sa = { 0 };
sa.sin6_family = AF_INET6;
sa.sin6_addr = in6addr_any;
ec = ::bind(ep->getSocket(), (const sockaddr*)&sa, sizeof(sockaddr_in6));
}
if (0 != ec)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_BIND, ep, 0, 0, 0);
break;
}
ep->setStatus(NetEndpoint::ESTAT_CONNECTING);
resetOverlapped(odata);
odata->Flags |= IOMUX_OVERLAPPED_FIRED;
// After socket has ensured to be bound, we can finally calls ConnectEx.
BOOL result = ctx->pConnectEx(ep->getSocket(),
(const sockaddr*)peer.Data, peer.Length,
0, 0, 0, (LPWSAOVERLAPPED)odata);
if ((TRUE == result) || (ERROR_IO_PENDING == WSAGetLastError()))
{
deleteOverlapped = false;
}
else // error
{
ep->setStatus(NetEndpoint::ESTAT_INIT);
cb->onIoCompleted(iotype, NetEndpoint::EE_CONNECT, ep, 0, 0, 0);
}
} while(0);
}
else
{
xpfAssert(NetEndpoint::ESTAT_CONNECTING == st);
if (ret == FALSE)
{
ep->setStatus(NetEndpoint::ESTAT_INIT);
cb->onIoCompleted(iotype, NetEndpoint::EE_CONNECT, ep, 0, 0, 0);
}
else
{
ep->setStatus(NetEndpoint::ESTAT_CONNECTED);
int ec = setsockopt(ep->getSocket(), SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
xpfAssert(("Failed to update connected context on outgoing socket.", ec == 0));
cb->onIoCompleted(iotype, NetEndpoint::EE_SUCCESS, ep, 0, 0, 0);
}
}
break;
case NetIoMux::EIT_RECV:
if (!isCompletion)
{
do
{
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == st));
if (NetEndpoint::ESTAT_CONNECTED != st)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, odata->Buffer.buf, 0);
break;
}
resetOverlapped(odata);
odata->Flags |= IOMUX_OVERLAPPED_FIRED;
DWORD dummy = 0; // currently not used.
int ec = WSARecv(ep->getSocket(), &odata->Buffer, 1, 0, &dummy,
(LPWSAOVERLAPPED)odata, 0);
if ((0 == ec) || (ERROR_IO_PENDING == WSAGetLastError()))
{
deleteOverlapped = false;
}
else // error
{
cb->onIoCompleted(iotype, NetEndpoint::EE_RECV, ep, 0, odata->Buffer.buf, 0);
}
} while (0);
}
else
{
cb->onIoCompleted(iotype,
(ret) ? (NetEndpoint::EE_SUCCESS) : (NetEndpoint::EE_RECV),
ep, 0, odata->Buffer.buf, bytes);
}
break;
case NetIoMux::EIT_RECVFROM:
if (!isCompletion)
{
do
{
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == st));
if (NetEndpoint::ESTAT_CONNECTED != st)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, odata->Buffer.buf, 0);
break;
}
resetOverlapped(odata);
odata->Flags |= IOMUX_OVERLAPPED_FIRED;
DWORD flags = 0;
int ec = WSARecvFrom(ep->getSocket(), &odata->Buffer, 1, 0, &flags,
(sockaddr*)odata->PeerData.Data, &odata->PeerData.Length,
(LPWSAOVERLAPPED)odata, 0);
if ((0 == ec) || (ERROR_IO_PENDING == WSAGetLastError()))
{
deleteOverlapped = false;
}
else // error
{
cb->onIoCompleted(iotype, NetEndpoint::EE_RECV, ep, 0, odata->Buffer.buf, 0);
}
} while (0);
}
else
{
cb->onIoCompleted(iotype,
(ret) ? (NetEndpoint::EE_SUCCESS) : (NetEndpoint::EE_RECV),
ep, (vptr)&odata->PeerData, odata->Buffer.buf, bytes);
}
break;
case NetIoMux::EIT_SEND:
if (!isCompletion)
{
do
{
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == st));
if (NetEndpoint::ESTAT_CONNECTED != st)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep, 0, odata->Buffer.buf, 0);
break;
}
resetOverlapped(odata);
odata->Flags |= IOMUX_OVERLAPPED_FIRED;
int ec = WSASend(ep->getSocket(), &odata->Buffer, 1, 0, 0,
(LPWSAOVERLAPPED)odata, 0);
if ((0 == ec) || (ERROR_IO_PENDING == WSAGetLastError()))
{
deleteOverlapped = false;
}
else // error
{
cb->onIoCompleted(iotype, NetEndpoint::EE_SEND, ep, 0, odata->Buffer.buf, 0);
}
} while (0);
}
else
{
cb->onIoCompleted(iotype,
(ret) ? (NetEndpoint::EE_SUCCESS) : (NetEndpoint::EE_SEND),
ep, 0, odata->Buffer.buf, bytes);
}
break;
case NetIoMux::EIT_SENDTO:
if (!isCompletion)
{
do
{
xpfAssert(("Invalid socket status.", NetEndpoint::ESTAT_CONNECTED == st));
if (NetEndpoint::ESTAT_CONNECTED != st)
{
cb->onIoCompleted(iotype, NetEndpoint::EE_INVALID_OP, ep,
(vptr)&odata->PeerData, odata->Buffer.buf, 0);
break;
}
resetOverlapped(odata);
odata->Flags |= IOMUX_OVERLAPPED_FIRED;
const u32 proto = ep->getProtocol();
int ec = WSASendTo(ep->getSocket(), &odata->Buffer, 1, 0, 0,
(const sockaddr*)odata->PeerData.Data, odata->PeerData.Length,
(LPWSAOVERLAPPED)odata, 0);
if ((0 == ec) || (ERROR_IO_PENDING == WSAGetLastError()))
{
deleteOverlapped = false;
}
else // error
{
cb->onIoCompleted(iotype, NetEndpoint::EE_SEND, ep,
(vptr)&odata->PeerData, odata->Buffer.buf, 0);
}
} while (0);
}
else
{
cb->onIoCompleted(iotype,
(ret) ? (NetEndpoint::EE_SUCCESS) : (NetEndpoint::EE_SEND),
ep, (vptr)&odata->PeerData, odata->Buffer.buf, bytes);
}
break;
default:
xpfAssert(("Unrecognized EIoType.", false));
break;
}
if (deleteOverlapped)
recycleOverlapped(odata);
return NetIoMux::ERS_NORMAL;
}
void asyncRecv(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
NetIoMuxOverlapped *odata = obtainOverlapped();
odata->Buffer.buf = buf;
odata->Buffer.len = buflen;
odata->IoType = NetIoMux::EIT_RECV;
odata->Callback = cb;
BOOL ret = ::PostQueuedCompletionStatus(mhIocp, 0, (ULONG_PTR)ep, (LPOVERLAPPED)odata);
xpfAssert(("Failed on PostQueuedCompletionStatus()", ret != FALSE));
}
void asyncRecvFrom(NetEndpoint *ep, c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
NetIoMuxOverlapped *odata = obtainOverlapped();
odata->Buffer.buf = buf;
odata->Buffer.len = buflen;
odata->IoType = NetIoMux::EIT_RECVFROM;
odata->Callback = cb;
odata->PeerData.Length = XPF_NETENDPOINT_MAXADDRLEN;
BOOL ret = ::PostQueuedCompletionStatus(mhIocp, 0, (ULONG_PTR)ep, (LPOVERLAPPED)odata);
xpfAssert(("Failed on PostQueuedCompletionStatus()", ret != FALSE));
}
void asyncSend(NetEndpoint *ep, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
NetIoMuxOverlapped *odata = obtainOverlapped();
odata->Buffer.buf = (c8*)buf;
odata->Buffer.len = buflen;
odata->IoType = NetIoMux::EIT_SEND;
odata->Callback = cb;
BOOL ret = ::PostQueuedCompletionStatus(mhIocp, 0, (ULONG_PTR)ep, (LPOVERLAPPED)odata);
xpfAssert(("Failed on PostQueuedCompletionStatus()", ret != FALSE));
}
void asyncSendTo(NetEndpoint *ep, const NetEndpoint::Peer *peer, const c8 *buf, u32 buflen, NetIoMuxCallback *cb)
{
NetIoMuxOverlapped *odata = obtainOverlapped();
odata->Buffer.buf = (c8*)buf;
odata->Buffer.len = buflen;
odata->IoType = NetIoMux::EIT_SENDTO;
odata->Callback = cb;
odata->PeerData.Length = peer->Length;
::memcpy(odata->PeerData.Data, peer->Data, peer->Length);
BOOL ret = ::PostQueuedCompletionStatus(mhIocp, 0, (ULONG_PTR)ep, (LPOVERLAPPED)odata);
xpfAssert(("Failed on PostQueuedCompletionStatus()", ret != FALSE));
}
void asyncAccept(NetEndpoint *ep, NetIoMuxCallback *cb)
{
IocpAsyncContext *ctx = (IocpAsyncContext*)ep->getAsyncContext();
xpfAssert(("Unprovisioned netendpoint.", ctx != 0));
if (0 == ctx)
return;
if (xpfUnlikely(ctx->pAcceptEx == 0))
{
GUID GuidAcceptEx = WSAID_ACCEPTEX;
DWORD dwBytes = 0;
int ec = WSAIoctl(ep->getSocket(), SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidAcceptEx, sizeof (GuidAcceptEx),
&ctx->pAcceptEx, sizeof (ctx->pAcceptEx),
&dwBytes, NULL, NULL);
xpfAssert(("Unable to retrieve AcceptEx func ptr.", ec != SOCKET_ERROR));
if (ec == SOCKET_ERROR)
return;
}
NetIoMuxOverlapped *odata = obtainOverlapped();
odata->IoType = NetIoMux::EIT_ACCEPT;
odata->Callback = cb;
BOOL ret = ::PostQueuedCompletionStatus(mhIocp, 0, (ULONG_PTR)ep, (LPOVERLAPPED)odata);
xpfAssert(("Failed on PostQueuedCompletionStatus()", ret != FALSE));
}
void asyncConnect(NetEndpoint *ep, const c8 *host, const c8 *serviceOrPort, NetIoMuxCallback *cb)
{
IocpAsyncContext *ctx = (IocpAsyncContext*)ep->getAsyncContext();
xpfAssert(("Unprovisioned netendpoint.", ctx != 0));
if (0 == ctx)
return;
if (xpfUnlikely(ctx->pConnectEx == 0))
{
GUID GuidConnectEx = WSAID_CONNECTEX;
DWORD dwBytes = 0;
int ec = WSAIoctl(ep->getSocket(), SIO_GET_EXTENSION_FUNCTION_POINTER,
&GuidConnectEx, sizeof (GuidConnectEx),
&ctx->pConnectEx, sizeof (ctx->pConnectEx),
&dwBytes, NULL, NULL);
xpfAssert(("Unable to retrieve ConnectEx func ptr.", ec != SOCKET_ERROR));
if (ec == SOCKET_ERROR)
return;
}
NetIoMuxOverlapped *odata = obtainOverlapped();
odata->IoType = NetIoMux::EIT_CONNECT;
odata->Callback = cb;
odata->Buffer.buf = (CHAR*) ::malloc(1024); // 960 for 'host', 64 for 'serviceOrPort'
odata->Buffer.len = 1024;
::strncpy_s(odata->Buffer.buf, 1024, host, 960);
odata->Buffer.buf[960 - 1] = '\0';
::strncpy_s(&odata->Buffer.buf[960], 64, serviceOrPort, 64);
odata->Buffer.buf[1024 - 1] = '\0';
BOOL ret = ::PostQueuedCompletionStatus(mhIocp, 0, (ULONG_PTR)ep, (LPOVERLAPPED)odata);
xpfAssert(("Failed on PostQueuedCompletionStatus()", ret != FALSE));
}
bool join(NetEndpoint *ep)
{
bool joined = false;
if (ep->getAsyncContext() == 0)
{
HANDLE h = CreateIoCompletionPort((HANDLE)ep->getSocket(), mhIocp, (ULONG_PTR)ep, 0);
xpfAssert(("Unable to join a netendpoint to mux.", h != NULL));
if (h == NULL)
return false;
ep->setAsyncContext((vptr) new IocpAsyncContext);
joined = true;
}
return joined;
}
bool depart(NetEndpoint *ep)
{
IocpAsyncContext *ctx = (IocpAsyncContext*)((ep) ? ep->getAsyncContext() : 0);
if (ctx)
{
delete ctx;
ep->close();
return true;
}
return false;
}
NetIoMuxOverlapped* obtainOverlapped()
{
// TODO: Pool management
NetIoMuxOverlapped* ret = new NetIoMuxOverlapped;
::memset(ret, 0, sizeof(NetIoMuxOverlapped));
return ret;
}
void recycleOverlapped(NetIoMuxOverlapped *data)
{
delete data;
}
void resetOverlapped(NetIoMuxOverlapped *data)
{
// Reset the first part of NetIoMuxOverlapped (the legacy OVERLAPPED content) to be all 0.
::memset(data, 0, sizeof(OVERLAPPED));
}
static const char * getMultiplexerType(NetIoMux::EPlatformMultiplexer &epm)
{
epm = NetIoMux::EPM_IOCP;
return "iocp";
}
private:
HANDLE mhIocp;
bool bEnable;
}; // end of class NetIoMuxImpl (IOCP)
} // end of namespace xpf<file_sep>/tests/network/async_server.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_TEST_ASYNC_SERVER_HDR_
#define _XPF_TEST_ASYNC_SERVER_HDR_
#include <xpf/platform.h>
#include <xpf/netiomux.h>
#include <xpf/thread.h>
#include <vector>
class WorkerThread : public xpf::Thread
{
public:
explicit WorkerThread(xpf::NetIoMux *mux);
virtual ~WorkerThread();
xpf::u32 run(xpf::u64 udata);
private:
xpf::NetIoMux *mMux;
};
class TestAsyncServer : public xpf::NetIoMuxCallback
{
public:
struct Buffer
{
xpf::c8 RData[2048];
xpf::c8 WData[16];
xpf::u16 Used;
};
explicit TestAsyncServer(xpf::u32 threadNum);
virtual ~TestAsyncServer();
void start();
void stop();
// async callbacks (** multi-thread accessing)
void onIoCompleted(xpf::NetIoMux::EIoType type, xpf::NetEndpoint::EError ec, xpf::NetEndpoint *sep, xpf::vptr tepOrPeer, const xpf::c8 *buf, xpf::u32 len);
void AcceptCb(xpf::NetEndpoint::EError ec, xpf::NetEndpoint* listeningEp, xpf::NetEndpoint* acceptedEp);
void RecvCb(xpf::NetEndpoint::EError ec, xpf::NetEndpoint* ep, const xpf::c8* buf, xpf::u32 bytes);
void SendCb(xpf::NetEndpoint::EError ec, xpf::NetEndpoint* ep, const xpf::c8* buf, xpf::u32 bytes);
private:
std::vector<WorkerThread*> mThreads;
std::vector<xpf::NetEndpoint*> mClients;
xpf::NetIoMux *mMux;
xpf::NetEndpoint *mListeningEp;
};
#endif // _XPF_TEST_ASYNC_SERVER_HDR_<file_sep>/src/netendpoint.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/netendpoint.h>
#include <xpf/string.h>
#include <xpf/lexicalcast.h>
#include <cstring>
#if defined(XPF_PLATFORM_WINDOWS)
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <Windows.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#endif
#ifndef INVALID_SOCKET
#define INVALID_SOCKET (-1)
#endif
namespace xpf
{
class NetEndpointImpl
{
public:
explicit NetEndpointImpl(u32 protocol)
: Protocol(protocol)
{
reset();
if (!platformInit())
{
#ifdef XPF_PLATFORM_WINDOWS
Errno = WSANOTINITIALISED;
#endif
return;
}
Status = NetEndpoint::ESTAT_INIT;
// Decide detail socket parameters.
int family = AF_UNSPEC;
int type = 0;
int proto = 0;
if (protocol & NetEndpoint::ProtocolIPv4)
family = AF_INET;
else if (protocol & NetEndpoint::ProtocolIPv6)
family = AF_INET6;
xpfAssert( ("Invalid procotol specified.", AF_UNSPEC != family) );
if ( AF_UNSPEC == family )
{
Status = NetEndpoint::ESTAT_INVALID;
return;
}
if (protocol & NetEndpoint::ProtocolTCP)
{
type = SOCK_STREAM;
proto = IPPROTO_TCP;
}
else if (protocol & NetEndpoint::ProtocolUDP)
{
type = SOCK_DGRAM;
proto = IPPROTO_UDP;
}
xpfAssert( ("Invalid procotol specified.", ((type != 0) && (proto != 0))) );
if (type == 0 || proto == 0)
{
Status = NetEndpoint::ESTAT_INVALID;
return;
}
Socket = ::socket(family, type, proto);
if (INVALID_SOCKET == Socket)
{
saveLastError();
Status = NetEndpoint::ESTAT_INVALID;
}
}
NetEndpointImpl(u32 protocol, int socket, NetEndpoint::EStatus status = NetEndpoint::ESTAT_CONNECTED)
: Protocol(protocol)
{
reset();
Status = status;
Socket = socket;
SockInfo.Length = XPF_NETENDPOINT_MAXADDRLEN;
int ec = ::getsockname(socket, (struct sockaddr*)SockInfo.Data, (socklen_t*)&SockInfo.Length);
xpfAssert( ("Valid socket provisioning.", (ec == 0) && (SockInfo.Length < XPF_NETENDPOINT_MAXADDRLEN)) );
if (ec == 0)
{
c8 servbuf[128];
ec = ::getnameinfo((struct sockaddr*)SockInfo.Data, (socklen_t) SockInfo.Length,
Address, XPF_NETENDPOINT_MAXADDRLEN, servbuf, 128,
NI_NUMERICHOST | NI_NUMERICSERV);
if (ec == 0)
{
Port = lexical_cast<u32, c8>(&servbuf[0]);
return;
}
}
// abnormal case.
saveLastError();
close();
}
~NetEndpointImpl()
{
close();
}
bool connect(const c8 *addr, const c8 *serviceOrPort, u32 *errorcode)
{
bool ret = false;
if (0 == addr)
addr = "localhost";
xpfAssert(("Stale endpoint.", NetEndpoint::ESTAT_INIT == Status));
if ((0 == serviceOrPort) || (NetEndpoint::ESTAT_INIT != Status))
{
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_INVALID_OP;
return false;
}
NetEndpoint::Peer peer;
if (!NetEndpoint::resolvePeer(Protocol, peer, addr, serviceOrPort))
{
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_RESOLVE;
return false;
}
xpfAssert( ("Expecting valid results from getaddrinfo().",
(peer.Length > 0) && (peer.Length <= XPF_NETENDPOINT_MAXADDRLEN)));
do
{
// Always use the 1st record in results.
int ec = ::connect(Socket, (const sockaddr*)peer.Data, peer.Length);
if (0 != ec)
{
saveLastError();
break;
}
std::memcpy(SockInfo.Data, peer.Data, peer.Length);
SockInfo.Length = peer.Length;
ret = true;
Status = NetEndpoint::ESTAT_CONNECTED;
c8 servbuf[128];
ec = ::getnameinfo((const sockaddr*)peer.Data, peer.Length, Address, XPF_NETENDPOINT_MAXADDRLEN,
servbuf, 128, NI_NUMERICHOST | NI_NUMERICSERV);
if (0 != ec)
{
saveLastError();
xpfAssert( ("Expecting getnameinfo succeed after connect.", false) );
for (int i=0; i<XPF_NETENDPOINT_MAXADDRLEN; ++i)
{
Address[i] = addr[i];
if (addr[i] == '\0')
break;
}
Port = 0;
}
else
{
Port = lexical_cast<u32, c8>(&servbuf[0]);
}
} while (0);
if (errorcode)
*errorcode = (ret)? (u32)NetEndpoint::EE_SUCCESS : (u32)NetEndpoint::EE_CONNECT;
return ret;
}
// TCP: do bind() and listen(). UDP: do bind().
bool listen (const c8 *addr, const c8 *serviceOrPort, u32 *errorcode, u32 backlog)
{
bool ret = false;
xpfAssert(("Stale endpoint.", NetEndpoint::ESTAT_INIT == Status));
if ((NetEndpoint::ESTAT_INIT != Status) || (0 == serviceOrPort))
{
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_INVALID_OP;
return false;
}
// perform getaddrinfo() to prepare proper sockaddr data.
struct addrinfo hint = {0};
struct addrinfo *results;
hint.ai_family = (Protocol & NetEndpoint::ProtocolIPv6)? AF_INET6 : AF_INET;
hint.ai_socktype = (Protocol & NetEndpoint::ProtocolTCP)? SOCK_STREAM : SOCK_DGRAM;
hint.ai_protocol = (Protocol & NetEndpoint::ProtocolTCP)? IPPROTO_TCP : IPPROTO_UDP;
hint.ai_flags = 0;
if (0 == addr)
hint.ai_flags |= AI_PASSIVE;
if (AF_INET6 == hint.ai_family)
hint.ai_flags |= AI_V4MAPPED;
int ec = ::getaddrinfo(addr, serviceOrPort, &hint, &results);
if (0 != ec)
{
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_RESOLVE;
saveLastError();
return false;
}
xpfAssert( ("Expecting valid results from getaddrinfo().",
(results != 0) && (results->ai_addrlen > 0) && (results->ai_addrlen <= XPF_NETENDPOINT_MAXADDRLEN)) );
do
{
ec = ::bind(Socket, results->ai_addr, results->ai_addrlen);
if (0 != ec)
{
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_BIND;
saveLastError();
break;
}
// for TCP endpoint, need to do listen().
if ( (Protocol & NetEndpoint::ProtocolTCP) != 0 )
{
ec = ::listen(Socket, backlog);
if (0 != ec)
{
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_LISTEN;
Status = NetEndpoint::ESTAT_INVALID;
saveLastError();
break;
}
}
std::memcpy(SockInfo.Data, results->ai_addr, results->ai_addrlen);
SockInfo.Length = (s32) results->ai_addrlen;
c8 servbuf[128];
ec = ::getnameinfo((const sockaddr*)results->ai_addr, results->ai_addrlen, Address, XPF_NETENDPOINT_MAXADDRLEN,
servbuf, 128, NI_NUMERICHOST | NI_NUMERICSERV);
if (0 != ec)
{
saveLastError();
xpfAssert( ("Expecting getnameinfo succeed after listen.", false) );
for (int i=0; i<XPF_NETENDPOINT_MAXADDRLEN; ++i)
{
Address[i] = addr[i];
if (addr[i] == '\0')
break;
}
Port = 0;
}
else
{
Port = lexical_cast<u32, c8>(&servbuf[0]);
}
Status = NetEndpoint::ESTAT_LISTENING;
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_SUCCESS;
ret = true;
} while (0);
freeaddrinfo(results);
return ret;
}
// TCP only.
NetEndpointImpl* accept (u32 *errorcode)
{
bool isTcp = ( (Protocol & NetEndpoint::ProtocolTCP) != 0 );
xpfAssert( ("Expecting TCP endpoint.", isTcp) );
xpfAssert(("Not a listening endpoint.", Status == NetEndpoint::ESTAT_LISTENING));
if (!isTcp || (Status != NetEndpoint::ESTAT_LISTENING))
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_INVALID_OP;
return 0;
}
int acceptedSocket = ::accept(Socket, 0, 0);
if (acceptedSocket == INVALID_SOCKET)
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_ACCEPT;
saveLastError();
return 0;
}
NetEndpointImpl *peer = new NetEndpointImpl(Protocol, acceptedSocket);
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SUCCESS;
return peer;
}
// TCP and UDP
s32 recv (c8 *buf, s32 len, u32 *errorcode)
{
bool isTcp = ((Protocol & NetEndpoint::ProtocolTCP) != 0);
if (isTcp)
{
xpfAssert(("Not a connected TCP endpoint.", Status == NetEndpoint::ESTAT_CONNECTED));
}
else
{
xpfAssert(("Not a listening UDP endpoint.", Status == NetEndpoint::ESTAT_LISTENING));
}
if ((isTcp && (Status != NetEndpoint::ESTAT_CONNECTED)) ||
(!isTcp && (Status != NetEndpoint::ESTAT_LISTENING)))
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_INVALID_OP;
return 0;
}
s32 cnt = ::recv(Socket, buf, len, 0);
if (cnt < 0)
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_RECV;
saveLastError();
return 0;
}
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SUCCESS;
return cnt;
}
// UDP only
s32 recvFrom (NetEndpoint::Peer *peer, c8 *buf, s32 len, u32 *errorcode)
{
bool isUdp = ((Protocol & NetEndpoint::ProtocolUDP) != 0);
xpfAssert( ("Expecting a valid peer.", peer != 0) );
xpfAssert( ("Expecting an UDP endpoint.", isUdp) );
xpfAssert(("Neither a connected nor a listening endpoint.", (Status == NetEndpoint::ESTAT_CONNECTED || Status == NetEndpoint::ESTAT_LISTENING)));
if (!isUdp || !peer || ((Status != NetEndpoint::ESTAT_CONNECTED) && (Status != NetEndpoint::ESTAT_LISTENING)))
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_INVALID_OP;
return 0;
}
peer->Length = XPF_NETENDPOINT_MAXADDRLEN;
s32 cnt = ::recvfrom(Socket, buf, len, 0, (struct sockaddr*)&peer->Data[0], (socklen_t*)&peer->Length);
if (cnt < 0)
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_RECV;
saveLastError();
return 0;
}
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SUCCESS;
return cnt;
}
// TCP and UDP
s32 send (const c8 *buf, s32 len, u32 *errorcode)
{
xpfAssert(("Not a connected endpoint.", Status == NetEndpoint::ESTAT_CONNECTED));
if (Status != NetEndpoint::ESTAT_CONNECTED)
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_INVALID_OP;
return 0;
}
s32 cnt = ::send(Socket, buf, len, 0);
if (cnt < 0)
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SEND;
saveLastError();
return 0;
}
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SUCCESS;
return cnt;
}
// UDP only
s32 sendTo (const NetEndpoint::Peer *peer, const c8 *buf, s32 len, u32 *errorcode)
{
const bool isUdp = ((Protocol & NetEndpoint::ProtocolUDP) != 0);
xpfAssert( ("Expecting a valid peer.", peer != 0) );
xpfAssert( ("Expecting an UDP endpoint.", isUdp) );
xpfAssert( ("Not a connected endpoint.", Status == NetEndpoint::ESTAT_CONNECTED) );
if (!isUdp || !peer || (Status != NetEndpoint::ESTAT_CONNECTED))
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_INVALID_OP;
return 0;
}
s32 cnt = ::sendto(Socket, buf, len, 0, (const struct sockaddr*)&peer->Data[0], peer->Length);
if (cnt < 0)
{
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SEND;
saveLastError();
return 0;
}
if (errorcode)
*errorcode = (u32) NetEndpoint::EE_SUCCESS;
return cnt;
}
void shutdown(NetEndpoint::EShutdownDir dir, u32 *errorcode)
{
s32 shutdownFlag = 0;
switch (dir)
{
#ifdef XPF_PLATFORM_WINDOWS
case NetEndpoint::ESD_READ:
shutdownFlag = SD_RECEIVE;
break;
case NetEndpoint::ESD_WRITE:
shutdownFlag = SD_SEND;
break;
case NetEndpoint::ESD_BOTH:
shutdownFlag = SD_BOTH;
break;
#else
case NetEndpoint::ESD_READ:
shutdownFlag = SHUT_RD;
break;
case NetEndpoint::ESD_WRITE:
shutdownFlag = SHUT_WR;
break;
case NetEndpoint::ESD_BOTH:
shutdownFlag = SHUT_RDWR;
break;
#endif
default:
xpfAssert( ("Invalid shutdown flag.", false) );
if (errorcode)
*errorcode = (u32)NetEndpoint::EE_INVALID_OP;
return;
}
s32 ec = ::shutdown(Socket, shutdownFlag);
if (ec != 0)
saveLastError();
if (errorcode)
*errorcode = (0 == ec) ? (u32)NetEndpoint::EE_SUCCESS : (u32) NetEndpoint::EE_SHUTDOWN;
}
void close ()
{
Status = NetEndpoint::ESTAT_CLOSING;
if (Socket != INVALID_SOCKET)
{
shutdown(NetEndpoint::ESD_BOTH, 0);
#ifdef XPF_PLATFORM_WINDOWS
::closesocket(Socket);
#else
::close(Socket);
#endif
}
reset();
}
void reset()
{
Port = 0;
Status = NetEndpoint::ESTAT_INVALID;
Socket = INVALID_SOCKET;
Errno = 0;
SockInfo.Length = 0;
for (int i=0; i<XPF_NETENDPOINT_MAXADDRLEN; ++i)
{
Address[i] = 0;
SockInfo.Data[i] = 0;
}
}
void saveLastError()
{
#ifdef XPF_PLATFORM_WINDOWS
Errno = WSAGetLastError();
#else
Errno = errno;
#endif
}
static bool platformInit()
{
#if defined(XPF_PLATFORM_WINDOWS)
static bool initialized = false;
// Do WSAStartup if never did before.
if (!initialized)
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
if (0 == ::WSAStartup(wVersionRequested, &wsaData))
{
initialized = true;
}
else
{
xpfAssert( ("WSAStartup failed.", false) );
}
} // end of if (!initialized)
return initialized;
#else
return true;
#endif
}
c8 Address[XPF_NETENDPOINT_MAXADDRLEN]; // Always in numeric form.
NetEndpoint::Peer SockInfo;
u32 Port;
const u32 Protocol;
NetEndpoint::EStatus Status;
s32 Socket;
s32 Errno;
}; // end of struct NetEndpointImpl
//============------------- NetEndpoint Impl. ------------======================//
NetEndpoint::NetEndpoint()
: pImpl(0)
, pAsyncContext(0)
, pUserData(0)
{
}
NetEndpoint::NetEndpoint(u32 protocol)
: pAsyncContext(0)
, pUserData(0)
{
pImpl = new NetEndpointImpl(protocol);
}
NetEndpoint::NetEndpoint(u32 protocol, int socket, NetEndpoint::EStatus status)
: pAsyncContext(0)
, pUserData(0)
{
pImpl = new NetEndpointImpl(protocol, socket, status);
}
NetEndpoint::~NetEndpoint()
{
if (pImpl != 0)
{
delete pImpl;
pImpl = 0;
}
}
NetEndpoint* NetEndpoint::create(u32 protocol)
{
return new NetEndpoint(protocol);
}
NetEndpoint* NetEndpoint::create(u32 protocol, const c8 *addr, const c8 *serviceOrPort, u32 *errorcode, u32 backlog)
{
NetEndpoint *ret = new NetEndpoint(protocol);
if (!ret || !ret->listen(addr, serviceOrPort, errorcode, backlog))
{
delete ret;
return 0;
}
return ret;
}
void NetEndpoint::release(NetEndpoint *ep)
{
delete ep;
}
bool NetEndpoint::resolvePeer(u32 protocol, NetEndpoint::Peer &peer, const c8 * host, const c8 * serviceOrPort)
{
struct addrinfo hint = { 0 };
struct addrinfo *results;
hint.ai_family = (protocol & NetEndpoint::ProtocolIPv6) ? AF_INET6 : AF_INET;
hint.ai_socktype = (protocol & NetEndpoint::ProtocolTCP) ? SOCK_STREAM : SOCK_DGRAM;
hint.ai_protocol = (protocol & NetEndpoint::ProtocolTCP) ? IPPROTO_TCP : IPPROTO_UDP;
hint.ai_flags = (AF_INET6 == hint.ai_family) ? AI_V4MAPPED : 0;
int ec = ::getaddrinfo(host, serviceOrPort, &hint, &results);
if (0 != ec)
{
return false;
}
std::memcpy(peer.Data, results->ai_addr, results->ai_addrlen);
peer.Length = (s32)results->ai_addrlen;
::freeaddrinfo(results);
return true;
}
bool NetEndpoint::platformInit()
{
return NetEndpointImpl::platformInit();
}
bool NetEndpoint::connect(const c8 *addr, const c8 *serviceOrPort, u32 *errorcode)
{
return pImpl->connect(addr, serviceOrPort, errorcode);
}
bool NetEndpoint::listen (const c8 *addr, const c8 *serviceOrPort, u32 *errorcode, u32 backlog)
{
return pImpl->listen(addr, serviceOrPort, errorcode, backlog);
}
NetEndpoint* NetEndpoint::accept (u32 *errorcode)
{
NetEndpointImpl *peerDetail = pImpl->accept(errorcode);
if (peerDetail == 0)
{
return 0;
}
NetEndpoint *peer = new NetEndpoint;
peer->pImpl = peerDetail;
return peer;
}
s32 NetEndpoint::recv ( c8 *buf, s32 len, u32 *errorcode )
{
return pImpl->recv(buf, len, errorcode);
}
s32 NetEndpoint::recvFrom ( Peer *peer, c8 *buf, s32 len, u32 *errorcode )
{
return pImpl->recvFrom(peer, buf, len, errorcode);
}
s32 NetEndpoint::send ( const c8 *buf, s32 len, u32 *errorcode )
{
return pImpl->send(buf, len, errorcode);
}
s32 NetEndpoint::sendTo ( const Peer *peer, const c8 *buf, s32 len, u32 *errorcode )
{
return pImpl->sendTo(peer, buf, len, errorcode);
}
void NetEndpoint::shutdown(NetEndpoint::EShutdownDir dir, u32 *errorcode)
{
return pImpl->shutdown(dir, errorcode);
}
void NetEndpoint::close ()
{
pImpl->close();
}
NetEndpoint::EStatus NetEndpoint::getStatus() const
{
return pImpl->Status;
}
void NetEndpoint::setStatus(NetEndpoint::EStatus status)
{
pImpl->Status = status;
}
const c8* NetEndpoint::getAddress() const
{
return pImpl->Address;
}
u32 NetEndpoint::getPort() const
{
return pImpl->Port;
}
u32 NetEndpoint::getProtocol() const
{
return pImpl->Protocol;
}
int NetEndpoint::getSocket() const
{
return pImpl->Socket;
}
vptr NetEndpoint::getUserData() const
{
return pUserData;
}
vptr NetEndpoint::setUserData(vptr ud)
{
vptr olddata = pUserData;
pUserData = ud;
return olddata;
}
s32 NetEndpoint::getLastPlatformErrno() const
{
return pImpl->Errno;
}
void NetEndpoint::setLastPlatformErrno(s32 ec)
{
pImpl->Errno = ec;
}
}; // end of namespace xpf
<file_sep>/src/platform/fcontext_sparc.hpp
// Copyright <NAME> 2012
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_CTX_DETAIL_FCONTEXT_SPARC_H
#define BOOST_CTX_DETAIL_FCONTEXT_SPARC_H
#include <xpf/platform.h>
namespace xpf {
namespace detail {
extern "C" {
// if defined(_LP64) we are compiling for sparc64, otherwise it is 32 bit
// sparc.
struct stack_t
{
void* sp;
vptr size;
stack_t() :
sp( 0), size( 0)
{}
};
struct fp_t
{
#ifdef _LP64
u64 fp_freg[32];
u64 fp_fprs, fp_fsr;
#else
u64 fp_freg[16];
u32 fp_fsr;
#endif
fp_t() :
fp_freg(),
#ifdef _LP64
fp_fprs(),
#endif
fp_fsr()
{}
}
#ifdef _LP64
__attribute__((__aligned__(64))) // allow VIS instructions to be used
#endif
;
struct fcontext_t
{
fp_t fc_fp; // fpu stuff first, for easier alignement
#ifdef _LP64
u64
#else
u32
#endif
fc_greg[8];
stack_t fc_stack;
fcontext_t() :
fc_fp(),
fc_greg(),
fc_stack()
{}
};
}
}}
#endif // BOOST_CTX_DETAIL_FCONTEXT_SPARC_H
<file_sep>/tests/network/async_client.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include "async_client.h"
#include "async_server.h"
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#define NUM_ENPOINTS (16)
using namespace xpf;
TestAsyncClient::TestAsyncClient(u32 threadNum)
{
mMux = new NetIoMux();
xpfAssert(threadNum > 0);
for (u32 i = 0; i < threadNum; ++i)
{
mThreads.push_back(new WorkerThread(mMux));
}
for (u32 i = 0; i < NUM_ENPOINTS; ++i)
{
Client *c = new Client;
c->Checksum = 0;
c->Count = 0;
NetEndpoint *ep = NetEndpoint::create(NetEndpoint::ProtocolIPv4 | NetEndpoint::ProtocolTCP);
mMux->join(ep);
ep->setUserData((vptr)c);
mClients[i] = ep;
}
}
TestAsyncClient::~TestAsyncClient()
{
stop();
for (u32 i = 0; i < NUM_ENPOINTS; ++i)
{
Client *c = (Client*)mClients[i]->getUserData();
delete mClients[i];
delete c;
mClients[i] = 0;
}
delete mMux;
mMux = 0;
}
void TestAsyncClient::start()
{
printf("[Client] Starting worker threads ...\n");
for (u32 i = 0; i < mThreads.size(); ++i)
mThreads[i]->start();
for (u32 i = 0; i < NUM_ENPOINTS; ++i)
{
mMux->asyncConnect(mClients[i], "localhost", 50123, this);
}
}
void TestAsyncClient::stop()
{
if (mThreads.empty())
return;
while (true)
{
u32 i = 0;
u32 errcnt = 0;
u32 donecnt = 0;
for (; i < NUM_ENPOINTS; ++i)
{
Client *c = (Client*)mClients[i]->getUserData();
if (c->Count >= 9999)
errcnt++;
else if (c->Count <= 1000)
donecnt += c->Count;
}
if (donecnt == NUM_ENPOINTS * 1000)
{
printf("[Client] All jobs done.\n");
for (u32 j=0; j<NUM_ENPOINTS; ++j)
printf("[Client] job count: [%u] %u.\n", j, ((Client*)mClients[j]->getUserData())->Count);
break;
}
else
{
printf("[Client] waiting (%u / 16000)...\n", donecnt);
Thread::sleep(1000);
}
}
mMux->disable();
printf("[Client] Joining async client worker threads ...\n");
while (!mThreads.empty())
{
for (u32 i = 0; i < mThreads.size(); ++i)
{
bool joined = mThreads[i]->join();
if (joined)
{
delete mThreads[i];
mThreads[i] = mThreads.back();
mThreads.pop_back();
}
}
}
printf("[Client] All worker threads of async client have been joined.\n");
}
void TestAsyncClient::onIoCompleted(
NetIoMux::EIoType type,
NetEndpoint::EError ec,
NetEndpoint *sep,
vptr tepOrPeer,
const c8 *buf,
u32 len)
{
switch (type)
{
case NetIoMux::EIT_CONNECT:
ConnectCb(ec, sep);
break;
case NetIoMux::EIT_RECV:
RecvCb(ec, sep, buf, len);
break;
case NetIoMux::EIT_SEND:
SendCb(ec, sep, buf, len);
break;
default:
xpfAssert(("Unexpected NetIoMux::EIoType.", false));
break;
}
}
void TestAsyncClient::RecvCb(u32 ec, NetEndpoint* ep, const c8* buf, u32 bytes)
{
Client *c = (Client*)ep->getUserData();
if (ec == NetEndpoint::EE_SUCCESS)
{
if (bytes == 0)
{
printf("[Client] end of data.\n");
ep->close();
c->Count = 9999;
return;
}
xpfAssert(bytes == 2);
xpfAssert((*(u16*)c->RData) == c->Checksum);
c->Count++;
if (c->Count >= 1000)
{
printf("[Client] Client job completed.\n");
ep->close();
}
else
{
sendTestData(ep);
}
}
else
{
printf("[Client] Failed on recving.\n");
ep->close();
c->Count = 9999;
}
}
void TestAsyncClient::SendCb(u32 ec, NetEndpoint* ep, const c8* buf, u32 bytes)
{
Client *c = (Client*)ep->getUserData();
if (ec == NetEndpoint::EE_SUCCESS)
{
if (bytes == 0)
{
printf("[Client] truncated sending.\n");
ep->close();
c->Count = 9999;
return;
}
mMux->asyncRecv(ep, c->RData, 2, this);
}
else
{
printf("[Client] Failed on sending.\n");
ep->close();
c->Count = 9999;
}
}
void TestAsyncClient::ConnectCb(u32 ec, NetEndpoint* ep)
{
if (ec == NetEndpoint::EE_SUCCESS)
{
printf("[Client] Connected.\n");
sendTestData(ep);
}
else
{
printf("[Client] Failed on connecting.\n");
ep->close();
Client *c = (Client*)ep->getUserData();
c->Count = 9999;
}
}
void TestAsyncClient::sendTestData(NetEndpoint* ep)
{
Client *c = (Client*)ep->getUserData();
u16 datalen = (rand() % 1022) + 1; // 1 ~ 1022
u16 sum = 0;
for (u16 i = 1; i <= datalen; ++i)
{
const u16 data = (u16)(rand() % 65536);
*(u16*)(&c->WData[i * sizeof(u16)]) = data;
sum += data;
}
*(u16*)(&c->WData[(datalen + 1) * sizeof(u16)]) = sum;
*(u16*)(c->WData) = (datalen + 1) * sizeof(u16);
const s32 tlen = (s32)((datalen + 2) * sizeof(u16));
xpfAssert(tlen <= 2048);
//s32 bytes = mEndpoint->send(mBuf, tlen, &ec);
c->Checksum = sum;
mMux->asyncSend(ep, c->WData, tlen, this);
}
<file_sep>/src/thread.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/platform.h>
// Currently only 2 threading models are supported: windows, posix.
#ifdef XPF_PLATFORM_WINDOWS
#include "platform/thread_windows.hpp"
#else
#include "platform/thread_posix.hpp"
#endif
namespace xpf {
void Thread::sleep(u32 durationMs)
{
details::XpfThread::sleep(durationMs);
}
void Thread::yield()
{
details::XpfThread::yield();
}
ThreadID Thread::getThreadID()
{
return details::XpfThread::getThreadID();
}
//=================================================
Thread::Thread()
{
pImpl = (vptr) new details::XpfThread(this);
}
Thread::Thread(const Thread& that)
{
xpfAssert( ( "non-copyable", false ) );
}
Thread::~Thread()
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
delete impl;
pImpl = 0xfefefefe;
}
Thread& Thread::operator = (const Thread& that)
{
xpfAssert( ( "non-copyable", false ) );
return *this;
}
void Thread::start()
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
impl->start();
}
bool Thread::join(u32 timeoutMs)
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
return impl->join(timeoutMs);
}
Thread::RunningStatus Thread::getStatus() const
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
return impl->getStatus();
}
void Thread::setExitCode(u32 code)
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
impl->setExitCode(code);
}
u32 Thread::getExitCode() const
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
return impl->getExitCode();
}
u64 Thread::getData() const
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
return impl->getData();
}
void Thread::setData(u64 data)
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
impl->setData(data);
}
ThreadID Thread::getID() const
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
return impl->getID();
}
void Thread::requestAbort()
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
impl->requestAbort();
}
bool Thread::isAborting() const
{
details::XpfThread * impl = (details::XpfThread*) pImpl;
return impl->isAborting();
}
};
<file_sep>/include/xpf/string.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_STRING_HEADER_
#define _XPF_STRING_HEADER_
#include "platform.h"
#include <string>
#include <cstdio>
#include <stdarg.h>
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#pragma warning ( push )
#pragma warning ( disable : 4996 )
#endif
// NOTE: Header-only impl.
namespace xpf {
template < typename T, typename TAlloc = std::allocator<T> >
class xpfstring : public std::basic_string< T, std::char_traits<T>, TAlloc >
{
public:
typedef std::basic_string< T, std::char_traits<T>, TAlloc > base_type;
// Type definitions available from std::basic_string :
// value_type : type of T
// pointer : type of T*
// const_pointer : type of const T*
// reference : type of T&
// const_reference: type of const T&
// allocator_type : type of TAlloc
public:
explicit xpfstring (const TAlloc& alloc = TAlloc())
: base_type(alloc)
{
}
xpfstring (const base_type& str)
: base_type(str)
{
}
xpfstring (const xpfstring<T, TAlloc>& str)
: base_type(str)
{
}
xpfstring (const base_type& str, typename base_type::size_type pos, typename base_type::size_type len = base_type::npos, const TAlloc& alloc = TAlloc())
: base_type(str, pos, len, alloc)
{
}
xpfstring (const T* s, const TAlloc& alloc = TAlloc())
: base_type(s, alloc)
{
}
xpfstring (const T* s, typename base_type::size_type n, const TAlloc& alloc = TAlloc())
: base_type(s, n, alloc)
{
}
xpfstring (typename base_type::size_type n, T c, const TAlloc& alloc = TAlloc())
: base_type(n, c, alloc)
{
}
template <typename InputIterator>
xpfstring (InputIterator first, InputIterator last, const TAlloc& alloc = TAlloc())
: base_type(first, last, alloc)
{
}
explicit xpfstring (f64 val)
: base_type()
{
c8 buf[128];
std::sprintf(buf, "%0.6f", val);
*this = buf;
}
explicit xpfstring (s32 val)
: base_type()
{
bool negative = false;
if (val < 0)
{
val = 0 - val;
negative = true;
}
c8 tmpbuf[16]={0};
u32 idx = 15;
if (0 == val)
{
tmpbuf[14] = '0';
*this = &tmpbuf[14];
return;
}
while(val && idx)
{
--idx;
tmpbuf[idx] = (c8)('0' + (val % 10));
val /= 10;
}
if (negative)
{
--idx;
tmpbuf[idx] = '-';
}
*this = &tmpbuf[idx];
}
explicit xpfstring (u32 val)
: base_type()
{
c8 tmpbuf[16]={0};
u32 idx = 15;
if (0 == val)
{
tmpbuf[14] = '0';
*this = &tmpbuf[14];
return;
}
while(val && idx)
{
--idx;
tmpbuf[idx] = (c8)('0' + (val % 10));
val /= 10;
}
*this = &tmpbuf[idx];
}
explicit xpfstring (s64 val)
: base_type()
{
bool negative = false;
if (val < 0)
{
val = 0 - val;
negative = true;
}
c8 tmpbuf[32]={0};
u32 idx = 31;
if (0 == val)
{
tmpbuf[30] = '0';
*this = &tmpbuf[30];
return;
}
while(val && idx)
{
--idx;
tmpbuf[idx] = (c8)('0' + (val % 10));
val /= 10;
}
if (negative)
{
--idx;
tmpbuf[idx] = '-';
}
*this = &tmpbuf[idx];
}
explicit xpfstring (u64 val)
: base_type()
{
c8 tmpbuf[32]={0};
u32 idx = 31;
if (0 == val)
{
tmpbuf[30] = '0';
*this = &tmpbuf[30];
return;
}
while(val && idx)
{
--idx;
tmpbuf[idx] = (c8)('0' + (val % 10));
val /= 10;
}
*this = &tmpbuf[idx];
}
template <typename B>
xpfstring (const B* const c)
: base_type()
{
*this = c;
}
xpfstring<T, TAlloc>& operator= (const base_type& str)
{
base_type::operator=(str);
return *this;
}
xpfstring<T, TAlloc>& operator= (const xpfstring<T, TAlloc>& str)
{
base_type::operator=(str);
return *this;
}
xpfstring<T, TAlloc>& operator= (const T* s)
{
base_type::operator=(s);
return *this;
}
xpfstring<T, TAlloc>& operator= (T c)
{
base_type::operator=(c);
return *this;
}
template <typename B>
xpfstring<T, TAlloc>& operator=(const B* const c)
{
if (!c)
{
base_type::clear();
return *this;
}
if ((void*)c == (void*)base_type::c_str())
return *this;
u32 len = 0;
const B* p = c;
for (; *p != T(); ++p, ++len);
for (u32 l = 0; l<len; ++l)
base_type::append(1, (T)c[l]);
return *this;
}
xpfstring<T,TAlloc> make_lower() const
{
xpfstring<T,TAlloc> result;
for( typename base_type::const_iterator it = base_type::begin(); it != base_type::end(); ++it )
{
T ch = *it;
c8 ch8 = (c8)ch;
const c8 diff = 'a' - 'A';
if ((ch8 >= 'A') && (ch8 <='Z'))
result.append(1, (T)(ch8 + diff));
else
result.append(1, ch);
}
return result;
}
xpfstring<T,TAlloc> make_upper() const
{
xpfstring<T,TAlloc> result;
for( typename base_type::const_iterator it = base_type::begin(); it != base_type::end(); ++it )
{
T ch = *it;
c8 ch8 = (c8)ch;
const c8 diff = 'a' - 'A';
if ((ch8 >= 'a') && (ch8 <='z'))
result.append(1, (T)(ch8 - diff));
else
result.append(1, ch);
}
return result;
}
// Note: Not efficient for large string.
// May throw exceptions for bad pos/len.
bool equals_ignore_case( const base_type& other, s32 pos = 0, s32 len = -1) const
{
if (pos < 0)
return false;
typename base_type::size_type upos = (typename base_type::size_type)pos;
typename base_type::size_type ulen = (len < 0)? other.size(): (typename base_type::size_type)len;
xpfstring<T,TAlloc> str1 = this->make_lower();
xpfstring<T,TAlloc> str2 = xpfstring<T,TAlloc>(other).make_lower();
return (0 == str1.compare(upos, ulen, str2));
}
// return the trimmed string (remove the given characters at the begin and end of string)
xpfstring<T,TAlloc> trim(const xpfstring<T,TAlloc>& whitespace = " \t\n\r") const
{
typename base_type::size_type begin = base_type::find_first_not_of(whitespace);
if (begin == base_type::npos)
return xpfstring<T,TAlloc>();
typename base_type::size_type end = base_type::find_last_not_of(whitespace);
if (end < begin)
return xpfstring<T,TAlloc>();
return base_type::substr(begin, (end - begin + 1));
}
// TODO: ignoreEmptyTokens is not working.
template <typename Container>
u32 split(Container& ret, const base_type& delimiter, bool ignoreEmptyTokens=true, bool keepSeparators=false) const
{
if (delimiter.empty())
return 0;
typename base_type::size_type oldSize = ret.size();
u32 lastpos = 0;
bool lastWasSeparator = false;
for (u32 i=0; i<base_type::size(); ++i)
{
bool foundSeparator = false;
for (u32 j=0; j<delimiter.size(); ++j)
{
if (base_type::at(i) == delimiter[j])
{
if ((!ignoreEmptyTokens || ((i - lastpos) != 0)) &&
!lastWasSeparator)
ret.push_back(xpfstring<T,TAlloc>(&base_type::c_str()[lastpos], i - lastpos));
foundSeparator = true;
lastpos = (keepSeparators ? i : i + 1);
break;
}
}
lastWasSeparator = foundSeparator;
}
if ((base_type::size() - 1) > lastpos)
ret.push_back(xpfstring<T,TAlloc>(&base_type::c_str()[lastpos], (base_type::size() - 1) - lastpos));
return ret.size() - oldSize;
}
/* A nearly full implementation of standard printf() -
* http://www.cplusplus.com/reference/cstdio/printf/
* with few small tweaks:
* Specifiers:
* Supported: 'diuoxXfcsp%'
* Fallback: 'FeEgGaA' fallback to be 'f'
* Not supported: 'n' (neither does libc on linux)
* Length sub-specifiers:
* Supported: 'hh', 'h', 'l', 'll'
* Ignored: 'j', 'z', 't', 'L' (just ignored, using them won't cause any error)
* Tweak: Specifier 'c' and 's' will not take hint from length sub-specifier
* for the type of character. It just use the template parameter type T of
* this class. Which means you can use %c/%s for both char and wchar_t
* version (instead of %c/%s for char and %lc/%ls for wchar_t, which is
* required by the printf() of libc, yuck!!).
* Flags, Width, Percision:
* Fully supported.
*/
u32 printf(const T* format, ...)
{
va_list ap;
va_start(ap, format);
base_type::clear();
enum
{
ST_TEXT = 0,
ST_FLAGS,
ST_WIDTH,
ST_PERCISION,
ST_SUBSPEC,
ST_SPEC,
};
enum
{
FLAG_LEFTJUSTIFY = 0x1,
FLAG_FORCESIGN = 0x2,
FLAG_BLANKSIGN = 0x4,
FLAG_PREFIXSUFFIX = 0x8,
FLAG_LEFTPADZERO = 0x10,
FLAG_WIDTH_SPECIFIED = 0x100,
FLAG_WIDTH_PARAM = 0x200,
FLAG_PERCISION_SPECIFIED = 0x400,
FLAG_PERCISION_PARAM = 0x800,
FLAG_FMT_LONG = 0x1000,
FLAG_FMT_LONGLONG = 0x2000,
FLAG_FMT_HALF = 0x4000,
FLAG_FMT_HALFHALF = 0x8000,
};
const char *hextable = "0123456789abcdef";
int state = ST_TEXT;
int width = 0;
int percision = 0;
unsigned short flag = 0;
for (const T* p = format; *p != T(); ++p)
{
char c = (char)(*p);
switch (state)
{
case ST_TEXT:
if ('%' == c)
{
width = percision = 0;
flag = 0;
state = ST_FLAGS;
}
else
{
base_type::append(1, *p);
}
break;
case ST_FLAGS:
switch (c)
{
case '-':
flag |= FLAG_LEFTJUSTIFY; break;
case '+':
flag |= FLAG_FORCESIGN; flag &= (~FLAG_BLANKSIGN); break;
case ' ':
flag |= FLAG_BLANKSIGN; flag &= (~FLAG_FORCESIGN); break;
case '#':
flag |= FLAG_PREFIXSUFFIX; break;
case '0':
flag |= FLAG_LEFTPADZERO; break;
default:
p--; state = ST_WIDTH; break;
}
break;
case ST_WIDTH:
if ((c >= '0') && (c <= '9'))
{
flag |= FLAG_WIDTH_SPECIFIED;
if (width < 0) width = 0;
width = width * 10 + (c - '0');
}
else if (c == '*')
{
flag |= FLAG_WIDTH_SPECIFIED;
flag |= FLAG_WIDTH_PARAM;
}
else if (c == '.')
{
flag |= FLAG_PERCISION_SPECIFIED;
state=ST_PERCISION;
}
else
{
p--; state = ST_SUBSPEC;
}
break;
case ST_PERCISION:
if ((c >= '0') && (c <= '9'))
{
if (percision < 0) percision = 0;
percision = percision * 10 + (c - '0');
}
else if (c == '*')
{
flag |= FLAG_PERCISION_PARAM;
}
else
{
p--; state = ST_SUBSPEC;
}
break;
case ST_SUBSPEC:
// http://www.cplusplus.com/reference/cstdio/printf/
// The sub-specifiers we're currently support is 'll', 'l', 'h', and 'hh', others are ignored.
switch(c)
{
case 'l':
if (*(p+1) == 'l')
{
flag |= FLAG_FMT_LONGLONG;
p++;
}
else
{
flag |= FLAG_FMT_LONG;
}
break;
case 'h':
if (*(p+1) == 'h')
{
flag |= FLAG_FMT_HALFHALF;
p++;
}
else
{
flag |= FLAG_FMT_HALF;
}
break;
case 'j':
case 'z':
case 't':
case 'L':
// not yet implement
break;
default:
p--;
state = ST_SPEC;
break;
}
break;
case ST_SPEC:
switch(c)
{
// Handy macro to conditionally load width and percision arguments from va_args
#define _READ_PARAMS \
if (flag & FLAG_WIDTH_PARAM)\
width = va_arg(ap, int);\
if (flag & FLAG_PERCISION_PARAM) \
percision = va_arg(ap, int);
case 'c':
{
// Note: For specifier 'c', we ignore any sub-specifier (i.e., 'l', 'h', etc.).
// Instead using %lc for wchar_t (required for standard libc), usage of %c is also allowed.
_READ_PARAMS;
int prepad = 0;
int postpad = 0;
if (width > 1)
{
if (flag & FLAG_LEFTJUSTIFY)
postpad = width - 1;
else
prepad = width - 1;
}
if (prepad > 0)
base_type::append(prepad, (T)' ');
// per C99 standard: char, short will be promoted to int when passing through '...'
// http://www.gnu.org/software/libc/manual/html_node/Argument-Macros.html#Argument-Macros
int v = va_arg(ap, int);
if (v != 0) // never append internal null
base_type::append(1, (T)v);
if (postpad > 0)
base_type::append(postpad, (T)' ');
}
state = ST_TEXT;
break;
case '%':
{
_READ_PARAMS;
base_type::append(1, (T)'%');
state = ST_TEXT;
}
break;
case 'p':
// Keep FLAG_WIDTH_PARAM and FLAG_PERCISION_PARAM but clear all other flag bits to 0.
// Add FLAG_WIDTH_SPECIFIED, and FLAG_PREFIXSUFFIX.
flag = (flag & (FLAG_WIDTH_SPECIFIED | FLAG_WIDTH_PARAM | FLAG_PERCISION_SPECIFIED | FLAG_PERCISION_PARAM)) | FLAG_PERCISION_SPECIFIED | FLAG_PREFIXSUFFIX;
if (percision < 8)
percision = 8;
if (sizeof(void*) > 4) // FIXME: better way to detect whether the host use a 64-bit pointer type?
{
if (percision < 16)
percision = 16;
flag |= FLAG_FMT_LONGLONG;
}
// fall-through ...
c = 'x';
case 'F': // all these specifiers are modeled as 'f'
case 'g':
case 'G':
case 'e':
case 'E':
case 'A':
case 'a':
if (c != 'x')
c = 'f';
// fall-through ...
case 'f':
case 'x':
case 'X':
case 'o':
case 'd':
case 'i':
case 'u':
{
_READ_PARAMS;
const bool isSigned = ((c == 'd') || (c == 'i'));
const bool isHex = ((c == 'x') || (c == 'X'));
const bool isOct = (c == 'o');
const bool isFloat = (c == 'f');
// Read param from va_arg with the type hint by sub-specifier.
// Apply necessary convertion. (i.e. to hex, to oct, or to integer)
xpfstring<T,TAlloc> valstr;
if (flag & FLAG_FMT_LONGLONG) // deal with 8-bytes value.
{
if (isSigned) // Signed 8-bytes integer
{
valstr = xpfstring<T,TAlloc>((long long)va_arg(ap, long long));
}
else if (isHex) // Unsigned 8-bytes hex.
{
unsigned long long v = va_arg(ap, unsigned long long);
bool leadingZero = true;
for (int i=0; i<16; ++i)
{
const T digit = (T)hextable[(v >> (64 - (4*(i+1)))) & 0xF];
if (leadingZero && digit == (T)'0')
continue;
leadingZero = false;
valstr.append(1, digit);
}
if (valstr.empty())
valstr.append(1, (T)'0');
if ('X' == c )
valstr = valstr.make_upper();
}
else if (isOct) // Unsigned 8-bytes oct.
{
unsigned long long v = va_arg(ap, unsigned long long);
bool leadingZero = true;
for (int i=0; i<22; ++i)
{
const T digit = (T)hextable[(v >> (66 - (3*(i+1)))) & 0x7];
if (leadingZero && digit == (T)'0')
continue;
leadingZero = false;
valstr.append(1, digit);
}
if (valstr.empty())
valstr.append(1, (T)'0');
}
else // Unsigned 8-bytes integer
{
valstr = xpfstring<T,TAlloc>((unsigned long long)va_arg(ap, unsigned long long));
}
}
else // deal with 4-bytes value. (char, short, etc. will be prompted to be 4 bytes)
{
if (isFloat) // 4-bytes double/float
{
double v = va_arg(ap, double);
valstr = xpfstring<T,TAlloc>(v);
}
else if (isSigned) // Signed 4-bytes integer
{
int v = (int)va_arg(ap, int);
// Shrink to valid value width according to sub-specifiers
if (flag & FLAG_FMT_HALF)
v &= 0xFFFF;
else if (flag & FLAG_FMT_HALFHALF)
v &= 0xFF;
valstr = xpfstring<T,TAlloc>(v);
}
else // Unsigned 4-bytes integer/hex/oct
{
unsigned int v = (unsigned int)va_arg(ap, unsigned int);
// Shrink to valid value width according to sub-specifiers
if (flag & FLAG_FMT_HALF)
v &= 0xFFFF;
else if (flag & FLAG_FMT_HALFHALF)
v &= 0xFF;
if (isHex) // Deal with 4-bytes hex
{
bool leadingZero = true;
for (int i=0; i<8; ++i)
{
const T digit = (T)hextable[(v >> (32 - (4*(i+1)))) & 0xF];
if (leadingZero && digit == (T)'0')
continue;
leadingZero = false;
valstr.append(1, digit);
}
if (valstr.empty())
valstr.append(1, (T)'0');
if ('X' == c )
valstr = valstr.make_upper();
}
else if (isOct) // Deal with 4-bytes oct
{
bool leadingZero = true;
for (int i=0; i<11; ++i)
{
const T digit = (T)hextable[(v >> (33 - (3*(i+1)))) & 0x7];
if (leadingZero && digit == (T)'0')
continue;
leadingZero = false;
valstr.append(1, digit);
}
if (valstr.empty())
valstr.append(1, (T)'0');
}
else // Unsigned 4-bytes integer
{
valstr = xpfstring<T,TAlloc>(v);
}
}
}
const bool neg = (valstr[0] == (T)'-');
// Neither width specified nor percision, the simplest case.
if (!(flag & (FLAG_WIDTH_SPECIFIED | FLAG_PERCISION_SPECIFIED)))
{
if (isSigned || isFloat)
{
if ((flag & FLAG_FORCESIGN) && !neg)
base_type::append(1, (T)'+');
if ((flag & FLAG_BLANKSIGN) && !neg)
base_type::append(1, (T)' ');
if (isFloat && (flag & FLAG_PREFIXSUFFIX))
{
if (valstr.find_first_of((T)'.') == base_type::npos)
valstr.append(1, (T)'.');
}
}
if ((isHex || isOct) && (flag & FLAG_PREFIXSUFFIX))
{
if (!((valstr[0]==(T)'0') && (valstr[1]==(T)0)))
{
base_type::append(1, (T)'0');
if (c != 'o')
base_type::append(1, (T)c); // append either 'x' or 'X'
}
}
base_type::append(valstr);
}
else
{
if (flag & (FLAG_PERCISION_SPECIFIED | FLAG_LEFTJUSTIFY))
{
// FLAG_LEFTPADZERO will be ignored when either FLAG_PERCISION_SPECIFIED or FLAG_LEFTJUSTIFY present
flag &= (~FLAG_LEFTPADZERO);
}
xpfstring<T,TAlloc> prefix;
if (isSigned || isFloat)
{
if (neg)
prefix = "-";
else if (flag & FLAG_FORCESIGN)
prefix = "+";
else if (flag & FLAG_BLANKSIGN)
prefix = " ";
}
else if ((isHex || isOct) && (flag & FLAG_PREFIXSUFFIX))
{
prefix = "0";
if (isHex)
prefix.append(1, (T)c);
}
if (flag & FLAG_PERCISION_SPECIFIED)
{
do
{
// Per spec: If percision is 0, do not output any digit when val is also 0.
if (!isFloat && (percision == 0) && (valstr[0]==(T)'0') && (valstr[1]==(T)0))
{
valstr = "";
if (isSigned)
{
// Note: both msvc and gcc still output sign (either '+' or ' ') for such case.
if (flag & FLAG_FORCESIGN)
valstr = "+";
else if (flag & FLAG_BLANKSIGN)
valstr = " ";
}
break;
}
if (neg)
valstr = valstr.substr(1);
if (isFloat) // trim or pad for float values
{
size_t idx = valstr.find_first_of((T)'.');
int padcnt = 0;
if (idx == base_type::npos) // no '.' in content, only possible to pad
{
if ((percision > 0) || (flag & FLAG_PREFIXSUFFIX))
{
valstr.append(1, (T)'.');
padcnt = percision;
}
}
else // trim or pad
{
// trim
int restcnt = (int)valstr.size() - (int)idx - 1;
if (restcnt > percision)
{
// if percision is 0, only show tailing '.' if FLAG_PREFIXSUFFIX has been set.
if ((percision == 0) && !(flag & FLAG_PREFIXSUFFIX))
valstr = valstr.substr(0, (int)idx);
else
valstr = valstr.substr(0, (int)idx + percision + 1);
}
else
padcnt = percision - restcnt;
}
if (padcnt > 0)
valstr.append(padcnt, (T)'0');
valstr = prefix + valstr;
}
else // integer based values
{
// compute padding count
const int cnt = (percision > (int)valstr.size())? (percision - (int)valstr.size()): 0;
if (cnt > 0)
{
xpfstring<T,TAlloc> padding;
padding.append(cnt, (T)'0');
valstr = prefix + padding + valstr;
}
else
valstr = prefix + valstr;
}
} while (0);
// layout in given width
const int cnt = (width > (int)valstr.size())? (width - (int)valstr.size()): 0;
if (flag & FLAG_LEFTJUSTIFY)
{
base_type::append(valstr);
if (cnt > 0)
base_type::append(cnt, (T)' ');
}
else
{
if (cnt > 0)
base_type::append(cnt, (T)' ');
base_type::append(valstr);
}
}
else // width specified but no percision
{
if (neg)
valstr = valstr.substr(1);
// Per spec: float values has a default percision of 6
// However, the irrString constructor of the version
// which takes a double param already guarantee this.
const int fulllen = (int)(prefix.size() + valstr.size());
const int padlen = (width > fulllen)? (width - fulllen): 0;
if (flag & FLAG_LEFTJUSTIFY)
{
base_type::append(prefix);
base_type::append(valstr);
if (padlen > 0)
base_type::append(padlen, (T)' ');
}
else if (flag & FLAG_LEFTPADZERO)
{
base_type::append(prefix);
if (padlen > 0)
base_type::append(padlen, (T)'0');
base_type::append(valstr);
}
else
{
if (padlen > 0)
base_type::append(padlen, (T)' ');
base_type::append(prefix);
base_type::append(valstr);
}
}
}
}
state = ST_TEXT;
break;
case 's':
{
_READ_PARAMS;
T* v = va_arg(ap, T*);
// Neither width specified nor percision, the simplest case.
if (!(flag & (FLAG_WIDTH_SPECIFIED | FLAG_PERCISION_SPECIFIED)))
{
int cnt = 0;
for (T* vp = v; *vp != T(); ++vp, ++cnt);
if (cnt > 0)
base_type::append(v, cnt);
}
else
{
// look for the string length (must not exceeds percision, if present)
int cnt = 0;
for (T* vp = v; *vp != T(); ++vp, ++cnt)
{
if ((flag & FLAG_PERCISION_SPECIFIED) && (cnt >= percision))
{
cnt = percision; break;
}
}
int pad = ((flag & FLAG_WIDTH_SPECIFIED) && (width > cnt))? (width - cnt): 0;
if (flag & FLAG_LEFTJUSTIFY)
{
base_type::append(v, cnt);
if (pad > 0)
base_type::append(pad, (T)' ');
}
else
{
if (pad > 0)
base_type::append(pad, (T)' ');
base_type::append(v, cnt);
}
}
}
state = ST_TEXT;
break;
default:
state = ST_TEXT;
break;
}
break;
default:
state = ST_TEXT;
break;
}
#undef _READ_PARAMS
}
va_end(ap);
return (u32)base_type::size();
}
// simple hash algorithm referenced from xerces-c project.
inline u32 hash(const u32 modulus = 10993UL, const s32 len = -1, const s32 offset = 0) const
{
u32 ulen = (len < 0)? base_type::size(): (u32)len;
u32 uoff = (offset < 0)? 0: (u32)offset;
if (uoff + ulen > base_type::size())
return 0;
const T* curCh = base_type::c_str() + uoff;
u32 hashVal = (u32)(*curCh++);
for (u32 i=0; i<ulen; ++i)
hashVal = (hashVal * 38) + (hashVal >> 24) + (u32)(*curCh++);
return hashVal % modulus;
}
bool begin_with( const xpfstring<T,TAlloc>& str, bool ignoreCase = false ) const
{
if (base_type::size() < str.size())
return false;
xpfstring<T, TAlloc> snip = substr(0, str.size());
if (ignoreCase)
{
return snip.equals_ignore_case(str);
}
return (snip == str);
}
bool end_with( const xpfstring<T,TAlloc>& str, bool ignoreCase = false ) const
{
if (base_type::size() < str.size())
return false;
xpfstring<T, TAlloc> snip = substr( base_type::size() - str.size(), str.size() );
if (ignoreCase)
{
return snip.equals_ignore_case(str);
}
return (snip == str);
}
};
typedef xpfstring< c8> string;
typedef xpfstring<u16> u16string;
typedef xpfstring<u32> u32string;
typedef xpfstring<wchar_t> wstring;
}; // end of namespace xpf
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#pragma warning ( pop )
#endif
#endif // _XPF_STRING_HEADER_
<file_sep>/tests/delegate/delegate.cpp
// NOTE: Test case available from http://www.codeproject.com/Articles/11464/Yet-Another-C-style-Delegate-Class-in-Standard-C
// Delegate.cpp : Defines the entry point for the console application.
//
#define CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#ifdef _MSC_VER
#include <crtdbg.h>
#endif // #ifdef _MSC_VER
#include <xpf/delegate.h>
using namespace xpf;
static void H(const char* s)
{
printf(" Static function invoked by %s\n", s);
}
class MyObject
{
public:
int count;
MyObject(int n) : count(n) { }
void G(const char* s)
{
printf(" Member function invoked by %s\n", s);
this->count++;
}
};
class MyFunctor
{
public:
void operator()(const char* s)
{
printf(" Functor invoked by %s\n", s);
}
};
int main(int argc, char* argv[])
{
#ifdef _MSC_VER
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif // #ifdef _MSC_VER
// Create an empty delegate
printf("Invoking delegate a0:\n");
Delegate<void ()> a0;
a0();
printf("\n");
// Create delegate a that references a static function:
Delegate<void (const char*)> a(&H);
assert(a == &H);
printf("Invoking delegate a:\n");
a("a");
printf("\n");
// Create delegate b that references an instance function:
MyObject myObj(0);
Delegate<void (const char*)> b(&myObj, &MyObject::G);
assert(b == std::make_pair(&myObj, &MyObject::G));
printf("Invoking delegate b:\n");
b("b");
assert(myObj.count == 1);
printf("\n");
// Create delegate c that references a function object:
MyFunctor myFunctor;
Delegate<void (const char*)> c(myFunctor);
printf("Invoking delegate c:\n");
c("c");
printf("\n");
// Add an instance function and a functor to delegate a
a += std::make_pair(&myObj, &MyObject::G);
a += MyFunctor();
printf("Invoking delegate a:\n");
a("a");
assert(myObj.count == 2);
printf("\n");
// Remove the static function from delegate a
a -= &H;
printf("Invoking delegate a:\n");
a("a");
assert(myObj.count == 3);
printf("\n");
// Create delegate d from a
Delegate<void (const char*)> d(a);
// Add delegate b to delegate d
d += Delegate<void (const char*)>(&H);
printf("Invoking delegate d:\n");
d("d");
assert(myObj.count == 4);
printf("\n\nDone\n");
return 0;
}
<file_sep>/tests/allocators/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(allocator_test
allocator_test.cpp
)
SET_PROPERTY(TARGET allocator_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(allocator_test xpf)
<file_sep>/include/xpf/utfconv.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_UTFCONV_HEADER_
#define _XPF_UTFCONV_HEADER_
#include "platform.h"
#include "string.h"
namespace xpf
{
// Functions defined in 'details' namespace should be only used internally by xpf.
// For utf conversions, use xpf::utfCon() instead.
namespace details
{
s32 XPF_API utfConvInner( void * sbuf, void * dbuf, u32 scw, u32 dcw, s32 scnt, s32 dcnt );
};
/***********************************************
* Convert unicode strings between utf-8, ucs-2 (utf-16), and ucs-4 (utf-32).
*
* Template arguments:
* SrcType: Character type of source string.
* DstType: Character type of destination string.
* Function arguments:
* srcBuf: Pointer pointed to a string buffer of SrcType.
* dstBuf: Pointer pointed to a string buffer of DstType.
* srcCount: Number of SrcType items in srcBuf to be converted.
* If -1 is given, it assumes the source string is null-terminated.
* dstCount: Max number of DstType items in dstBuf can hold.
* If -1 is given, it assumes the dstBuf is large enough to hold all conversion result.
* Return value:
* Return negative number if one of SrcType and DstType is not supported.
* Return >=0 indicates how many code point have been converted.
* utfConv() will try to append a null in the end of dstBuf if possible.
*
* Example:
* xpf::c8 utfString[] = {0xe6, 0xff, 0xff, 0xe6, 0xb8, 0xac, 0xff, 0xa9, 0xa6, 0x0};
* wchar_t wString[100];
*
* int count = xpf::utfConv<xpf::c8, wchar_t>(utfString, wString);
*
*****/
template < typename SrcType, typename DstType >
s32 utfConv( SrcType * srcBuf, DstType * dstBuf, s32 srcCount = -1, s32 dstCount = -1 )
{
return details::utfConvInner( (void*)srcBuf, (void*)dstBuf, sizeof(SrcType), sizeof(DstType), srcCount, dstCount );
}
// Coverter operates on xpf::string level.
// Note that the result string is always associated with the standard heap allocator.
template < typename S, typename SAlloc >
xpfstring<c8> to_utf8(const xpfstring<S, SAlloc>& src)
{
xpfstring<c8> result;
if (!src.empty())
{
const u32 blen = src.size()*8 + 1;
c8 * buf = new c8[blen];
if (utfConv(src.c_str(), buf, src.size(), blen) > 0)
result = buf;
delete[] buf;
}
return result;
}
template < typename S, typename SAlloc >
xpfstring<u16> to_ucs2(const xpfstring<S, SAlloc>& src)
{
xpfstring<u16> result;
if (!src.empty())
{
const u32 blen = src.size()*8 + 1;
u16 * buf = new u16[blen];
if (utfConv(src.c_str(), buf, src.size(), blen) > 0)
result = buf;
delete[] buf;
}
return result;
}
template < typename S, typename SAlloc >
xpfstring<u32> to_ucs4(const xpfstring<S, SAlloc>& src)
{
xpfstring<u32> result;
if (!src.empty())
{
const u32 blen = src.size()*8 + 1;
u32 * buf = new u32[blen];
if (utfConv(src.c_str(), buf, src.size(), blen) > 0)
result = buf;
delete[] buf;
}
return result;
}
template < typename S, typename SAlloc >
xpfstring<wchar_t> to_wchar(const xpfstring<S, SAlloc>& src)
{
xpfstring<wchar_t> result;
if (!src.empty())
{
const u32 blen = src.size()*8 + 1;
wchar_t * buf = new wchar_t[blen];
if (utfConv(src.c_str(), buf, src.size(), blen) > 0)
result = buf;
delete[] buf;
}
return result;
}
}; // end of namespace xpf
#endif // _XPF_UTFCONV_HEADER_
<file_sep>/tests/allocators/allocator_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/allocators.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <deque>
#ifdef XPF_PLATFORM_WINDOWS
#include <Windows.h>
#else
#include <sys/time.h>
#endif
using namespace xpf;
class StopWatch
{
public:
StopWatch()
{
#ifdef XPF_PLATFORM_WINDOWS
QueryPerformanceFrequency(&Freq);
QueryPerformanceCounter(&Counter);
#else
gettimeofday(&Time, NULL);
#endif
}
u32 click() // return in ms
{
#ifdef XPF_PLATFORM_WINDOWS
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
double ret = (double)(c.QuadPart - Counter.QuadPart) / (double)Freq.QuadPart;
Counter = c;
return (u32)(ret * 1000);
#else
struct timeval t, s;
gettimeofday(&t, NULL);
timersub(&t, &Time, &s);
Time = t;
return (u32)((s.tv_sec * 1000) + (s.tv_usec / 1000));
#endif
}
private:
#ifdef XPF_PLATFORM_WINDOWS
LARGE_INTEGER Freq;
LARGE_INTEGER Counter;
#else
struct timeval Time;
#endif
};
struct MemObj
{
MemObj(void * p, u32 s)
: pattern(0), ptr(p), size(s) {}
void provision(u32 pt)
{
pattern = pt;
u32 cnt = size/sizeof(u32) - 2;
u32 *ppp = (u32*)ptr;
xpfAssert((*ppp != 0x52995299) || (*(ppp+1) != 0x99259925));
*ppp = 0x52995299; ppp++;
*ppp = 0x99259925; ppp++;
while(cnt--)
{
*ppp = pattern;
ppp++;
}
}
bool validate()
{
u32 *ppp = (u32*)ptr;
if (*ppp != 0x52995299)
return false;
*ppp = 0;
ppp++;
if (*ppp != 0x99259925)
return false;
*ppp = 0;
ppp++;
u32 cnt = size/sizeof(u32) - 2;
while(cnt--)
{
if ((*ppp) != pattern)
return false;
}
return true;
}
u32 size;
u32 pattern;
void* ptr;
};
struct Bank
{
Bank(u32 s, u32 n)
: size(s)
, number(n)
{}
u32 size;
u32 number;
std::deque<MemObj> objs;
};
bool _g_log = true;
bool _g_memop = true;
//128mb
#define POOLSIZE (1 << 27)
bool test(bool sysalloc = false)
{
BuddyAllocator *pool = (sysalloc) ? 0 : BuddyAllocator::instance();
Bank profile[] =
{
Bank((1<<24), 2), // 16mb * 2 = 32mb
Bank((1<<23), 4), // 8mb * 4 = 32mb
Bank((1<<21), 16), // 2mb *16 = 32mb
Bank((1<<12), 2048), // 4kb *2048 = 8mb
Bank((1<<7), (1<<16)), // 128b * 2^16 = 8mb
Bank(0,0),
};
int probs[] = { 2, 6, 22, 2070, 67606, 0 };
int randomCnt = 0;
int opCnt = 1000;
bool op = true; // true: alloc, false: dealloc
int totalCnt = 100000;
int falseOp = 0;
int falseAlloc = 0;
u32 liveBytes = 0;
u32 liveObjs = 0;
while (totalCnt--)
{
bool alloc = false;
if (opCnt > 0)
{
opCnt--;
alloc = op;
}
else
{
alloc = ((rand() & 0x1) == 0x1);
randomCnt++;
if (randomCnt >= 1000)
{
if (_g_log) printf("Enqueue 500 allocs after 1000 random ops.\n");
op = true;
opCnt = 500;
randomCnt = 0;
}
}
int p = (rand() % 67606);
int i = 0;
for (; probs[i] !=0; ++i)
{
if (p<probs[i])
break;
}
Bank& b = profile[i];
if (alloc)
{
if (b.number == 0)
{
if (_g_log) printf("Alloc: MemObj of size %u run out of quota.\n", b.size);
falseOp++;
}
else
{
void * ptr = (sysalloc)? malloc(b.size): pool->alloc(b.size);
if (NULL == ptr)
{
if (_g_log) printf("Alloc: MemoryPool failed to allocate MemObj of size %u. (liveBytes = %u, liveObjs = %u).\n", b.size, liveBytes, liveObjs);
op = false;
opCnt = 2000;
randomCnt = 0;
falseAlloc++;
}
else
{
b.number--;
b.objs.push_back(MemObj(ptr, b.size));
u32 pt = (u32)rand();
if (_g_memop)
b.objs.back().provision(pt);
liveObjs++;
liveBytes += b.size;
}
}
}
else // dealloc
{
if (b.objs.empty())
{
if (_g_log) printf("Dealloc: No more live MemObj of size %u.\n", b.size);
falseOp++;
}
else
{
MemObj &obj = b.objs.front();
if (_g_memop)
{
if (!obj.validate())
return false;
}
bool useDealloc = (rand()%2 > 0);
if (sysalloc)
{
free(obj.ptr);
}
else
{
if (useDealloc)
pool->dealloc(obj.ptr, obj.size);
else
pool->free(obj.ptr);
}
b.objs.pop_front();
b.number++;
liveObjs--;
liveBytes -= b.size;
}
}
if (_g_log && (totalCnt%1000 == 0))
{
printf("Test: liveBytes = %u, liveObjs = %u, falseOp = %u, falseAlloc = %u\n", liveBytes, liveObjs, falseOp, falseAlloc);
}
} // while (totalCnt--)
printf("Test: liveBytes = %u, liveObjs = %u, falseOp = %u, falseAlloc = %u\n", liveBytes, liveObjs, falseOp, falseAlloc);
// free all objs and make sure the top-most block can be allocated
if (_g_log)
{
for(int i=0; ; ++i)
{
Bank& b = profile[i];
if ((b.size == 0) && (b.number == 0))
break;
while(!b.objs.empty())
{
liveObjs--;
liveBytes -= b.size;
pool->free(b.objs.front().ptr);
//pool->dealloc(b.objs.front().ptr, b.size);
b.objs.pop_front();
}
}
xpfAssert((liveObjs == 0) && (liveBytes == 0));
#ifdef XPF_ALLOCATORS_ENABLE_TRACE
u32 usedBytes, highPeak;
pool->trace(usedBytes, highPeak, true);
xpfAssert( ("UsedBytes shall be 0", usedBytes == 0) );
printf("HighPeakBytes = %u bytes\n", highPeak);
#endif
void * p = pool->alloc(POOLSIZE);
if (!p)
return false;
pool->free(p);
}
return true;
}
int main()
{
unsigned int seed = (unsigned int)time(NULL);
srand(seed);
printf("\n==== SanityTest ====\n");
u32 size = BuddyAllocator::create(POOLSIZE);
xpfAssert(0 != size);
bool ret = test();
xpfAssert(ret);
// std::allocator compatibility
{
std::deque<int, Allocator<int, AllocInstOf<BuddyAllocator> > > verifyingDeque;
int i=0;
for (; i<20000; i++)
{
verifyingDeque.push_back(i);
}
i=0;
while (!verifyingDeque.empty())
{
xpfAssert( ( "std::allocator compatibility", i == verifyingDeque.front() ) );
i++;
verifyingDeque.pop_front();
}
}
BuddyAllocator::destory();
LinearAllocator::create(1024);
LinearAllocator *stack = LinearAllocator::instance();
xpfAssert((stack != 0) && (stack->capacity() == 1024) && (stack->available() == 1016));
void *ptrs[5];
for (u32 i=0; i<5; i++)
{
ptrs[i] = stack->alloc(32);
xpfAssert(ptrs[i] != 0);
for (u32 j=0; j<8; ++j)
{
*((int*)ptrs[i] + j) = 0xababbadc;
}
}
xpfAssert((stack->used() == 200) && (stack->available() == 816));
for (u32 i=0; i<5; i++)
{
for (u32 j=0; j<8; ++j)
{
xpfAssert(*((int*)ptrs[i] + j) == 0xababbadc);
}
stack->free(ptrs[i]);
if (i == 4)
{
u32 u = stack->used();
xpfAssert(stack->used() == 0);
}
else
{
xpfAssert(stack->used() == 200);
}
}
for (u32 i=0; i<5; i++)
{
ptrs[i] = stack->alloc(32);
xpfAssert(ptrs[i] != 0);
for (u32 j=0; j<8; ++j)
{
*((int*)ptrs[i] + j) = 0xababbadc;
}
}
xpfAssert((stack->used() == 200) && (stack->available() == 816));
stack->free(ptrs[3]);
xpfAssert(stack->used() == 200);
stack->free(ptrs[4]);
xpfAssert(stack->used() == 120);
ptrs[3] = stack->alloc(192);
xpfAssert(stack->used() == 320);
ptrs[4] = stack->alloc(2000);
xpfAssert(stack->used() == 320);
xpfAssert(ptrs[4] == 0);
stack->free(ptrs[1]);
stack->free(ptrs[2]);
stack->free(ptrs[3]);
xpfAssert(stack->used() == 40);
xpfAssert(stack->hwm() == 320);
stack->reset();
xpfAssert((stack->used() == 0) && (stack->hwm() == 0));
LinearAllocator::destory();
// done sanity test.
_g_log = false;
while (true)
{
printf("\n==== Benchmark (%s memop) ====\n", (_g_memop)? "with": "without");
size = BuddyAllocator::create(POOLSIZE);
xpfAssert(0 != size);
srand(seed);
StopWatch sw;
test();
u32 timeCost1 = sw.click();
printf("Time cost of buddy = %u ms\n", timeCost1);
BuddyAllocator::destory();
srand(seed);
sw.click();
test(true);
u32 timeCost2 = sw.click();
printf("Time cost of sysalloc = %u ms\n", timeCost2);
if (timeCost2 > timeCost1)
{
printf("Improved: %f%%\n", (double)(timeCost2 - timeCost1)*100.00/(double)timeCost2);
}
else
{
printf("Worse than sysalloc.\n");
}
if (_g_memop)
_g_memop = false;
else
break;
}
return 0;
}
<file_sep>/include/xpf/allocators.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_ALLOCATORS_HEADER_
#define _XPF_ALLOCATORS_HEADER_
#include "platform.h"
#include <memory>
#include <cstddef>
namespace xpf {
//============---------- BuddyAllocator -----------================//
struct BuddyAllocatorDetails;
class XPF_API BuddyAllocator
{
public:
/*****
* Create a buddy-algorithm based memory allocator in slot of 'slotId'
* which preallocates a memory bulk of size 'size'. The 'size' shall
* be power of 2 or it will be promoted to be one (nearest but not
* less than). The promoted size value should neither less than 2^4
* (16 bytes) nor larger than 2^31 (2 Gb). Later calls of
* BuddyAllocator::instance() with the same 'slotId' returns the
* pointer to this global memory pool instance. One should call
* BuddyAllocator::destroy() with the same 'slotId' after done using
* to release the entire memory bulk.
*
* 'slotId' should be a unsigned short integer ranged from 0 to 255.
*
* Returns the promoted memory bulk size. Or 0 on error.
*/
static u32 create( u32 size, u16 slotId = 0 );
/*****
* Delete the BuddyAllocator instance in slot of 'slotId'
* if ever created.
*/
static void destory(u16 slotId = 0);
/*****
* Return the pointer to the BuddyAllocator instance in given slot.
* Make sure the BuddyAllocator::create() has been called
* on the same slot otherwise it returns 0 (NULL).
*/
static BuddyAllocator* instance(u16 slotId = 0);
public:
explicit BuddyAllocator(u32 size);
~BuddyAllocator();
// Returns the maximum capacity in bytes.
u32 capacity () const;
// Return the maximum allocatable space in bytes.
u32 available () const;
// Return the used (allocated) space in bytes.
u32 used() const;
// Return the high water mark in bytes since last reset
u32 hwm() const;
// Return the high water mark in bytes and reset its value.
u32 reset();
// Allocate a memory chunk which is at least 'bytes' long.
// Our implementation guarantees the returned pointer is
// 16-bytes aligned.
void* alloc ( u32 size );
// Free up a memory chunk which is previously allocated by this allocator.
void dealloc ( void *p, u32 size );
// dealloc() without size hint
void free ( void *p );
// Extend or shrink the allocated block size.
// May move the memory block to a new location and returns the new address.
// The content of the memory block is preserved up to the lesser of the new and old sizes.
void* realloc ( void *p, u32 size );
// Allocate for an array of 'num' elements, each of length 'size' bytes.
// All allocated memory bytes are initialized to 0.
void* calloc ( u32 num, u32 size );
private:
// non-copyable
BuddyAllocator(const BuddyAllocator& other) {}
BuddyAllocator& operator = (const BuddyAllocator& other) { return *this; }
BuddyAllocatorDetails *mDetails;
}; // end of class BuddyAllocator
//============---------- BuddyAllocator -----------================//
//============---------- LinearAllocator -----------================//
struct LinearAllocatorDetails;
class XPF_API LinearAllocator
{
// NOTE: Expose the same interface as BuddyAllocator.
public:
static u32 create( u32 size, u16 slotId = 0 );
static void destory(u16 slotId = 0);
static LinearAllocator* instance(u16 slotId = 0);
explicit LinearAllocator(u32 size);
~LinearAllocator();
u32 capacity () const;
u32 available () const;
u32 used() const;
u32 hwm() const;
// Return current hwm and reset both hwm and stack pointer.
u32 reset();
void* alloc ( u32 size );
void dealloc ( void *p, u32 size );
void free ( void *p );
void* realloc ( void *p, u32 size );
void* calloc ( u32 num, u32 size );
private:
// non-copyable
LinearAllocator(const LinearAllocator& other) {}
LinearAllocator& operator = (const LinearAllocator& other) { return *this; }
LinearAllocatorDetails *mDetails;
}; // end of class LinearAllocator
//============---------- LinearAllocator -----------================//
//============---------- STL allocator compatible -----------================//
// A wrapper to wrap both LinearAllocator and BuddyAllocator with a
// specific slot index to a dedicated type for STL-compatible allocator.
template < typename ALLOCATOR, u16 SLOT = 0 >
class AllocInstOf
{
public:
typedef ALLOCATOR ALLOCATOR_TYPE;
static ALLOCATOR* get()
{
return ALLOCATOR::instance(SLOT);
}
};
// ALLOC_GETTER can be any type meet the following requirements:
// 1. Has a public typedef named 'ALLOCATOR_TYPE' refer to
// the actual allocator type which has 3 required APIs:
// a. void* alloc ( u32 size );
// b. void dealloc ( void *p, u32 size );
// c. u32 capacity () const;
// 2. Has a public static API declared as:
// static ALLOCATOR* get();
// to return the proper allocator instance.
template < typename T , typename ALLOC_GETTER >
class Allocator
{
public:
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
typedef u32 size_type;
typedef ptrdiff_t difference_type;
template < typename U >
struct rebind { typedef Allocator<U, ALLOC_GETTER> other; };
public:
Allocator ()
{
mPool = ALLOC_GETTER::get();
}
Allocator ( const Allocator& other )
{
mPool = other.mPool;
}
template < typename U >
Allocator ( const Allocator<U, ALLOC_GETTER>& other )
{
mPool = other.mPool;
}
~Allocator ()
{
mPool = 0;
}
Allocator& operator = ( const Allocator& other )
{
// DO NOT exchange mPool
}
template < typename U >
Allocator& operator = (const Allocator<U, ALLOC_GETTER>& other)
{
// DO NOT exchange mPool
}
pointer address ( reference x ) const
{
return &x;
}
const_pointer address ( const_reference x ) const
{
return &x;
}
pointer allocate ( size_type n, void* hint = 0 )
{
xpfAssert( ( "Null mPool.", mPool != 0 ) );
pointer ptr = (pointer) mPool->alloc(n * sizeof(value_type));
if (NULL == ptr)
throw std::bad_alloc();
return ptr;
}
void deallocate ( pointer p, size_type n )
{
xpfAssert( ( "Null mPool.", mPool != 0 ) );
mPool->dealloc( (void*) p, n * sizeof(value_type) );
}
size_type max_size() const
{
xpfAssert( ( "Null mPool.", mPool != 0 ) );
return (mPool->capacity() / sizeof(value_type));
}
// Call the c'tor to construct object using the storage space passed in.
void construct ( pointer p, const_reference val )
{
new ((void*)p) value_type (val);
}
// Call the d'tor but not release the storage.
void destroy (pointer p)
{
p->~value_type();
}
public:
typename ALLOC_GETTER::ALLOCATOR_TYPE* mPool; // weak reference to an existing allocator instance.
}; // end of class Allocator
}; // end of namespace xpf
#endif // _XPF_ALLOCATORS_HEADER_
<file_sep>/tests/threading/threading_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/thread.h>
#include <xpf/tls.h>
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <time.h>
using namespace xpf;
TlsMap<u64> _g_tlsmap;
vptr _g_tlsdata;
struct MyHot
{
ThreadLock lock;
int sum;
} _g_hot;
class MyThread : public Thread
{
public:
MyThread() : tid(Thread::INVALID_THREAD_ID) {}
~MyThread() { printf("Thread [%llu] terminated.\n", tid); }
u32 run(u64 userdata)
{
if (Thread::INVALID_THREAD_ID == tid)
{
tid = Thread::getThreadID();
TlsSet(_g_tlsdata, (vptr)&tid);
}
u64 sec = userdata;
u64 cnt = sec * 1000;
while (cnt--)
{
ScopedThreadLock ml(_g_hot.lock);
_g_hot.sum += 1;
}
while (sec--)
{
// Verify TLS
vptr data = TlsGet(_g_tlsdata);
xpfAssert((*((ThreadID*)data)) == tid);
printf("Thread [%llu]: Remaining %llu seconds. \n", tid, sec);
Thread::sleep(1000);
_g_tlsmap.put(userdata, true);
TlsSet(_g_tlsdata, (vptr)&tid);
}
vptr data = TlsGet(_g_tlsdata);
xpfAssert((*((ThreadID*)data)) == tid);
return (u32)tid;
}
private:
ThreadID tid;
};
int main()
{
#ifdef XPF_PLATFORM_WINDOWS
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
::srand((unsigned int)::time(NULL));
_g_hot.sum = 0;
_g_tlsdata = TlsCreate();
xpfAssert(_g_tlsdata != 0);
std::vector<Thread*> ta;
u64 expectingCnt = 0;
for (int i=0; i<30; ++i)
{
ta.push_back(new MyThread);
u64 udata = (u64)(rand()%30+ 1);
ta.back()->setData(udata);
expectingCnt += (udata)*1000;
}
for (unsigned int i=0; i<ta.size(); ++i)
{
xpfAssert(ta[i]->getStatus() == Thread::TRS_READY);
ta[i]->start();
}
while(ta.size() > 0)
{
u32 i;
bool joinedAny = false;
for (i=0; i<ta.size(); ++i)
{
if (ta[i]->join(0))
{
u64 udata;
xpfAssert(ta[i]->getStatus() == Thread::TRS_JOINED);
xpfAssert((u32)ta[i]->getID() == ta[i]->getExitCode());
xpfAssert(_g_tlsmap.get(udata, ta[i]->getID()));
xpfAssert((ta[i]->getData() == udata));
delete ta[i];
ta[i] = ta[ta.size()-1];
ta.pop_back();
i--;
joinedAny = true;
break;
}
}
if (!joinedAny)
Thread::sleep(1000);
}
xpfAssert(("Expecting matched sum.", _g_hot.sum == expectingCnt));
TlsDelete(_g_tlsdata);
return 0;
}
<file_sep>/include/xpf/coroutine.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_COROUTINE_HEADER_
#define _XPF_COROUTINE_HEADER_
#include "platform.h"
namespace xpf
{
/*****
* API to create and manipulating coroutines (or fibers).
* Coroutine are like thread: both have individual execution
* context and stack. However, unlike threads, context-switching
* among coroutines should be performed manually by themselves.
*
* One who ever uses fibers on Windows should find this API model
* seems to be familiar. They shares the same idea of usage.
* On POSIX platforms, these function are implemented by getcontext(),
* makecontext(), and swapcontext().
*
* General usage:
* 1. A thread shall calls InitThreadForCoroutines() to install
* a coroutine manager in TLS before making other coroutine
* API calls. Caller of InitThreadForCoroutines() becomes
* the main coroutine.
* 2. The thread is then able to use CreateCoroutine() to
* create one or more subcoroutines. These subcoroutines
* will not run until SwitchToCoroutine() has been called.
* 3. Whenever a coroutine returns from its coroutine body
* or calls DeleteCoroutine() to delete itself, it
* terminates the current thread.
* 4. When a subcoroutine has finished its job, it shall call
* SwitchToCoroutine() to switch back to either: one of other
* unfinished subcoroutines, or the main coroutine.
* 5. The main coroutine shall implement a mechanism to call
* DeleteCoroutine() properly on those subcoroutines who have
* done their jobs.
*/
/*
* Function prototype of the coroutine body.
* The input argument is used as a userdata dedicated
* for this coroutine. The coroutine can call
* GetCoroutineData() to retrieve this userdata anywhere
* while it is running.
*/
#if !defined(XPF_COROUTINE_USE_FCONTEXT) && defined(XPF_PLATFORM_WINDOWS)
typedef void (__stdcall *CoroutineFunc) (vptr);
#else
typedef void (*CoroutineFunc) (vptr);
#endif
/*
* Must call before making any other coroutine API.
* Install a coroutine manager in cuurent thread's
* local storage (TLS). The input argument is used
* as userdata for the main coroutine.
*/
vptr XPF_API InitThreadForCoroutines(vptr data);
/*
* Return the current running coroutine.
* Can be either main or one of created subcoroutines.
*/
vptr XPF_API GetCurrentCoroutine();
/*
* Return the userdata associated for
* the current running coroutine.
*/
vptr XPF_API GetCoroutineData();
/*
* Create a subcoroutine. Given a 'stackSize' as 0
* to use the platform default value.
*/
vptr XPF_API CreateCoroutine(u32 stackSize, CoroutineFunc body, vptr data);
/*
* Manually perform a context switching to the target
* coroutine. After done, calling coroutine stops
* running and the target coroutine resumes from
* either: 1) start of its coroutine body, or 2)
* the last point it calls SwitchToCoroutine().
*
* Self-switching can casue undefined behaviour
* and hence should be avoided.
*/
void XPF_API SwitchToCoroutine(vptr coroutine);
/*
* Stop and delete a coroutine.
* Self-deleting or deleting the main coroutine
* can terminate current thread.
*/
void XPF_API DeleteCoroutine(vptr coroutine);
}
#endif
<file_sep>/src/platform/threadevent_windows.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/threadevent.h>
#ifdef _XPF_THREADEVENT_IMPL_INCLUDED_
#error Multiple ThreadEvent implementation files included
#else
#define _XPF_THREADEVENT_IMPL_INCLUDED_
#endif
#ifndef XPF_PLATFORM_WINDOWS
# error threadevent_windows.hpp shall not build on platforms other than Windows.
#endif
#include <Windows.h>
namespace xpf { namespace details {
class XpfThreadEvent
{
public:
explicit XpfThreadEvent(bool set /* = false */)
{
mEvent = ::CreateEvent(NULL, TRUE, (set)? TRUE: FALSE, NULL);
}
~XpfThreadEvent()
{
::CloseHandle(mEvent);
}
inline void XpfThreadEvent::set()
{
::SetEvent(mEvent);
}
inline void XpfThreadEvent::reset()
{
::ResetEvent(mEvent);
}
inline bool XpfThreadEvent::wait(u32 timeoutMs /* = -1L */)
{
// -1L (0xFFFFFFFF) happens to be the INFINITE on windows.
return (WAIT_OBJECT_0 == ::WaitForSingleObject(mEvent, timeoutMs));
}
inline bool XpfThreadEvent::isSet()
{
return wait(0);
}
private:
XpfThreadEvent(const XpfThreadEvent& that)
{
xpfAssert( ( "non-copyable object", false ) );
}
XpfThreadEvent& operator = (const XpfThreadEvent& that)
{
xpfAssert( ( "non-copyable object", false ) );
return *this;
}
::HANDLE mEvent;
};
};};<file_sep>/tests/string/string_test.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/utfconv.h>
#include <xpf/lexicalcast.h>
#include <stdio.h>
#include <vector>
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
using namespace xpf;
int main()
{
#ifdef XPF_PLATFORM_WINDOWS
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
wstring str1 = L"The elements of the C language library are also included as a subset of the C++ Standard library. \x6b50\x7279\x514b\x651c\x624b\x5de8\x5320\x96fb\x8166\x9996\x5ea6\x63a8\x51fa\x004d\x006f\x006c\x0064\x0066\x006c\x006f\x0077\x8a8d\x8b49\x0020\x0020\x63d0\x5347\x81fa\x7063\x0049\x0043\x0054\x7522\x696d\x7af6\x722d\x529b";
// apply a chain of conversions ...
u32string str2 = to_ucs4(str1);
string str3 = to_utf8(str2);
u16string str4 = to_ucs2(str3);
string str5 = to_utf8(str4);
wstring str6 = to_wchar(str5);
// check if the final output is identical to the original string
xpfAssert((str3 == str5));
xpfAssert((str6 == str1));
xpfAssert((str3.hash() == str5.hash()));
xpfAssert((str6.hash() == str1.hash()));
xpfAssert((str3.hash() != str1.hash()));
// test the printf function
float fval = 12345.625f;
double dval = 54321.5725;
const char* format = "abc %f %s %%(%c) test %f @#$^& %%(%X) haha";
const char* str = "%%%ddd%%%";
const char ch = '%';
const char* validOutput = "abc 12345.625000 %%%ddd%%% %(%) test 54321.572500 @#$^& %(FEE1DEAD) haha";
{
string utf8fmt = format;
string utf8str = str;
string utf8vo = validOutput;
c8 utf8ch = (c8)ch;
string buf;
buf.printf(utf8fmt.c_str(), fval, utf8str.c_str(), utf8ch, dval, 0xfee1dead);
xpfAssert((buf == utf8vo));
xpfAssert((buf.hash() == utf8vo.hash()));
xpfAssert((buf.hash() != utf8fmt.hash()));
}
{
u16string u16fmt = format;
u16string u16str = str;
u16string u16vo = validOutput;
u16 u16ch = (u16)ch;
u16string buf;
buf.printf(u16fmt.c_str(), fval, u16str.c_str(), u16ch, dval, 0xfee1dead);
xpfAssert((buf == u16vo));
xpfAssert((buf.hash() == u16vo.hash()));
xpfAssert((buf.hash() != u16fmt.hash()));
}
{
u32string u32fmt = format;
u32string u32str = str;
u32string u32vo = validOutput;
u32 u32ch = (u32)ch;
u32string buf;
buf.printf(u32fmt.c_str(), fval, u32str.c_str(), u32ch, dval, 0xfee1dead);
xpfAssert((buf == u32vo));
xpfAssert((buf.hash() == u32vo.hash()));
xpfAssert((buf.hash() != u32fmt.hash()));
}
{
wstring wfmt = format;
wstring wstr = str;
wstring wvo = validOutput;
wchar_t wch = (wchar_t)ch;
wstring buf;
buf.printf(wfmt.c_str(), fval, wstr.c_str(), wch, dval, 0xfee1dead);
xpfAssert((buf == wvo));
xpfAssert((buf.hash() == wvo.hash()));
xpfAssert((buf.hash() != wfmt.hash()));
}
// test split
{
string buf = validOutput;
std::vector< xpf::string > c;
u32 cnt = buf.split(c, " %");
xpfAssert((cnt == 10));
}
// lexical cast
{
double v = xpf::lexical_cast<double>(L"0.546");
xpfAssert((v > 0.545) && (v < 0.547));
}
{
wstring aaa = xpf::lexical_cast<wchar_t>(false);
xpfAssert(aaa == L"false");
}
// printf - width/percision test
{
string buf;
buf.printf("%% %c %c %-10.5s %*.*s %.2f %03d %+03d %#.0f %#o %#05X %%",
'C', 0, "0123456789", 10, 5, "987654321", 0.12345f, 15, 1518, 2.0f, 8, 255);
xpfAssert(buf == "% C 01234 98765 0.12 015 +1518 2. 010 0X0FF %");
}
printf("string test pass.\n");
return 0;
}
<file_sep>/README.md
libxpf
======
A light-wight, cross-platform infrastructure library to help software developing.
License: zlib
Planned target arch:
* x86/x64
* arm
* mips
Planned target platforms:
* windows
* mac
* linux
* bsd
* ios
* android
Contributions from 3rd-party:
- Acf Delegate
> http://www.codeproject.com/Articles/11464/Yet-Another-C-style-Delegate-Class-in-Standard-C
<file_sep>/tests/uuid/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(uuid_test
uuid_test.cpp
)
SET_PROPERTY(TARGET uuid_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(uuid_test xpf)
<file_sep>/src/platform/fcontext_x86_64_win.hpp
// Copyright <NAME> 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_CONTEXT_DETAIL_FCONTEXT_X86_64_H
#define BOOST_CONTEXT_DETAIL_FCONTEXT_X86_64_H
#include <xpf/platform.h>
#if defined(XPF_COMPILER_MSVC)
#pragma warning(push)
#pragma warning(disable:4351)
#endif
namespace xpf {
namespace detail {
extern "C" {
struct stack_t
{
void* sp;
vptr size;
void* limit;
stack_t() :
sp( 0), size( 0), limit( 0)
{}
};
struct fcontext_t
{
u64 fc_greg[10];
stack_t fc_stack;
void* fc_local_storage;
u64 fc_fp[24];
u64 fc_dealloc;
fcontext_t() :
fc_greg(),
fc_stack(),
fc_local_storage( 0),
fc_fp(),
fc_dealloc()
{}
};
}
}}
#if defined(XPF_COMPILER_MSVC)
#pragma warning(pop)
#endif
#endif // BOOST_CONTEXT_DETAIL_FCONTEXT_X86_64_H
<file_sep>/include/xpf/platform.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_PLATFORM_HEADER_
#define _XPF_PLATFORM_HEADER_
#include "assert.h"
#include "compiler.h"
//==========----------==========//
/*
* Detecting host platform via pre-defined compiler macros.
* http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system
*/
// Cygwin-POSIX
#if !defined(XPF_PLATFORM_SPECIFIED) && (defined(__CYGWIN__) || defined(__CYGWIN32__))
# define XPF_PLATFORM_CYGWIN 1
# define XPF_PLATFORM_SPECIFIED 1
#endif
// Windows-CE
#if !defined(XPF_PLATFORM_SPECIFIED) && defined(_WIN32_WCE)
# define XPF_PLATFORM_WINDOWS 1
# define XPF_PLATFORM_WINCE 1
# define XPF_PLATFORM_SPECIFIED 1
#endif
// Windows-desktop
#if !defined(XPF_PLATFORM_SPECIFIED) && defined(_WIN32)
# define XPF_PLATFORM_WINDOWS 1
# if defined(__MINGW32__) || defined(__MINGW64__)
# define XPF_PLATFORM_MINGW
# endif
# define XPF_PLATFORM_SPECIFIED 1
#endif
// x86-MaxOS and IOS
#if !defined(XPF_PLATFORM_SPECIFIED) && defined(__APPLE__) && defined(__MACH__)
# include <TargetConditionals.h>
# if TARGET_IPHONE_SIMULATOR == 1
# define XPF_PLATFORM_IOSSIM 1
# elif TARGET_OS_IPHONE == 1
# define XPF_PLATFORM_IOS 1
# elif TARGET_OS_MAC == 1
# define XPF_PLATFORM_MAC 1
# else
# error This is an un-supported mac platform.
# endif
# define XPF_PLATFORM_APPLE 1
# define XPF_PLATFORM_BSD 1
# define XPF_PLATFORM_SPECIFIED 1
#endif
// BSD-family
#if !defined(XPF_PLATFORM_SPECIFIED) && (defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__))
# define XPF_PLATFORM_BSD 1
# if defined(__DragonFly__)
# define XPF_PLATFORM_DRAGONFLY 1
# elif defined(__FreeBSD__)
# define XPF_PLATFORM_FREEBSD 1
# elif defined(__NetBSD__)
# define XPF_PLATFORM_NETBSD 1
# elif defined(__OpenBSD__)
# define XPF_PLATFORM_OPENBSD 1
# endif
# define XPF_PLATFORM_SPECIFIED 1
#endif
// Linux/Android
#if !defined(XPF_PLATFORM_SPECIFIED) && defined(__unix__) && defined(__linux__)
# if defined(__ANDROID__)
# define XPF_PLATFORM_ANDROID 1
# endif
# define XPF_PLATFORM_LINUX 1
# define XPF_PLATFORM_SPECIFIED 1
#endif
// Solaris
#if !defined(XPF_PLATFORM_SPECIFIED) && defined(__sun) && defined(__SVR4)
# define XPF_PLATFORM_SOLARIS 1
# define XPF_PLATFORM_SPECIFIED 1
#endif
//==========----------==========//
/*
* Determines address-model
*/
#ifndef XPF_MODEL_SPECIFIED
// Currently only x86/x86_64/arm are supported.
#if defined(XPF_PLATFORM_WINDOWS)
# define XPF_CPU_X86 1
# if defined(_WIN64)
# define XPF_MODEL_64 1
# define XPF_X86_64 1
# else
# define XPF_MODEL_32 1
# define XPF_X86_32 1
# endif
#else
# if defined(__arm__)
# define XPF_CPU_ARM 1
# if defined(__aarch64__)
# define XPF_MODEL_64 1
# define XPF_ARM_64 1
# else
# define XPF_MODEL_32 1
# define XPF_ARM_32 1
# endif
# elif defined(__x86_64) || defined(__amd64) || defined(__amd64__)
# define XPF_CPU_X86 1
# define XPF_MODEL_64 1
# define XPF_X86_64 1
# elif defined(__i386__) || defined(__i386) || defined(__i686__) || defined(__i686)
# define XPF_CPU_X86 1
# define XPF_MODEL_32 1
# define XPF_X86_32 1
# else
# error Un-supported arch type.
# endif
#endif
#endif // XPF_MODEL_SPECIFIED
//==========----------==========//
// Data types
namespace xpf {
typedef unsigned char u8;
typedef char c8;
typedef unsigned short u16;
typedef short s16;
typedef unsigned int u32;
typedef int s32;
typedef unsigned long long u64;
typedef long long s64;
typedef float f32;
typedef double f64;
#if defined(XPF_MODEL_32)
typedef u32 vptr;
#elif defined(XPF_MODEL_64)
typedef u64 vptr;
#else
# error Can not determine pointer data type due to unknown address-model.
#endif
} // end of namespace xpf {
#if defined(XPF_PLATFORM_WINDOWS) && defined(XPF_COMPILER_MSVC)
#define WCHAR_LEN 2
#else
#define WCHAR_LEN 4
#endif
// Double confirm the width of all types at compile time.
xpfSAssert(1==(sizeof(xpf::u8)));
xpfSAssert(1==(sizeof(xpf::c8)));
xpfSAssert(2==(sizeof(xpf::u16)));
xpfSAssert(2==(sizeof(xpf::s16)));
xpfSAssert(4==(sizeof(xpf::u32)));
xpfSAssert(4==(sizeof(xpf::s32)));
xpfSAssert(4==(sizeof(xpf::f32)));
xpfSAssert(8==(sizeof(xpf::u64)));
xpfSAssert(8==(sizeof(xpf::s64)));
xpfSAssert(8==(sizeof(xpf::f64)));
#if defined(XPF_MODEL_32)
xpfSAssert(4==(sizeof(xpf::vptr)));
#elif defined(XPF_MODEL_64)
xpfSAssert(8==(sizeof(xpf::vptr)));
#else
# error Can not determine pointer data type due to unknown address-model.
#endif
#if WCHAR_LEN == 2
xpfSAssert(2==(sizeof(wchar_t)));
#elif WCHAR_LEN == 4
xpfSAssert(4==(sizeof(wchar_t)));
#else
# error Unsupported wchar length.
#endif
//==========----------==========//
// XPF_COROUTINE_USE_FCONTEXT controls whether xpf should use fcontext from
// boost project to replace native context functions provided by platform.
//
// Theoretically fcontext should work on all POSIX platforms (with pthread).
// For now, it is only enabled on Android platform simply because there are no
// native context functions on it. To enable fcontext on other POSIX platforms,
// remove the ifdef statement to force XPF_COROUTINE_USE_FCONTEXT to be defined.
#if !defined(XPF_COROUTINE_USE_FCONTEXT) && defined(XPF_PLATFORM_ANDROID)
# define XPF_COROUTINE_USE_FCONTEXT 1
#endif
#endif // _XPF_PLATFORM_HEADER_
<file_sep>/src/uuidv4.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/platform.h>
#include <xpf/uuidv4.h>
#include <string.h>
#include <stdlib.h>
namespace xpf
{
Uuid Uuid::generate()
{
// A valid UUID v4 Layout:
// xxxxxxxx-xxxx-4xxx-Nxxx-xxxxxxxxxxxx, where N
// could be 8,9,A,B.
// Each rand() returns a 32-bits randome value
// varies from 0 to RAND_MAX. Here we assume
// RAND_MAX is 32767, which stands on most popular
// platforms. By this assumption, we get only 15
// random bits at each rand() call.
Uuid u;
// Fill u.mOctet with 8 random value.
for (u32 i = 0; i < 8; ++i)
{
u16 r = (u16)rand();
u.mOctet[i * 2] = r >> 8;
u.mOctet[i * 2 + 1] = r & 0xFF;
}
// By the assumption of RAND_MAX is 32767,
// the most significant bit of those 8 random values
// should all be 0. Here we get another random value
// and use its bit to pad those 'holes'.
u16 r = (u16)rand();
u.mOctet[0] |= ((r & 0x1) << 7);
u.mOctet[2] |= ((r & 0x2) << 6);
u.mOctet[4] |= ((r & 0x4) << 5);
u.mOctet[6] = ((u.mOctet[6] & 0x0F) | 0x40);
u.mOctet[8] = ((u.mOctet[8] & 0x3F) | 0x80);
u.mOctet[10] |= ((r & 0x8) << 4);
u.mOctet[12] |= ((r & 0x10) << 3);
u.mOctet[14] |= ((r & 0x20) << 2);
return u;
}
Uuid Uuid::null()
{
return Uuid();
}
Uuid Uuid::fromOctet(u8* octet)
{
Uuid u;
::memcpy(u.mOctet, octet, 16);
return u;
}
Uuid Uuid::fromString(const c8* string)
{
Uuid u;
u8 cnt = 0;
u8 w = 0xff;
for (const c8 *p = string; (*p != '\0') && (cnt < 16); p++)
{
u8 v = (u8)*p;
if ((v >= '0') && (v <= '9'))
v -= '0';
else if ((v >= 'a') && (v <= 'f'))
v = 10 + (v - 'a');
else if ((v >= 'A') && (v <= 'F'))
v = 10 + (v - 'A');
else
continue;
if (w == 0xff)
{
w = v;
continue;
}
u.mOctet[cnt++] = (w << 4) | v;
w = 0xff;
}
return u;
}
Uuid::Uuid()
{
::memset(mOctet, 0, 16);
}
Uuid::Uuid(const Uuid& other)
{
this->operator=(other);
}
Uuid::~Uuid()
{
}
u32 Uuid::getLength() const
{
return 16;
}
u8* Uuid::getOctet()
{
return mOctet;
}
std::string Uuid::asString()
{
static const c8 *map = "0123456789abcdef";
std::string str;
for (u32 i = 0; i<16; ++i)
{
u8 c = mOctet[i];
str.append(1, map[c >> 4]);
str.append(1, map[c & 0xF]);
if ((i == 3) || (i == 5) || (i == 7) || (i == 9))
str.append(1, '-');
}
return str;
}
bool Uuid::operator< (const Uuid& other) const
{
for (int i = 0; i<4; ++i)
{
if ((*(unsigned int*)&mOctet[i * 4]) <
(*(unsigned int*)&other.mOctet[i * 4]))
return true;
}
return false;
}
Uuid& Uuid::operator= (const Uuid& other)
{
::memcpy(mOctet, other.mOctet, 16);
return *this;
}
bool Uuid::operator== (const Uuid& other) const
{
for (int i = 0; i<4; ++i)
{
if ((*(unsigned int*)&mOctet[i * 4]) !=
(*(unsigned int*)&other.mOctet[i * 4]))
return false;
}
return true;
}
};
<file_sep>/src/allocators.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/allocators.h>
#include <stdlib.h>
#include <string.h>
#define MINSIZE_POWOF2 (4)
#define MAXSIZE_POWOF2 (31)
#define INVALID_VALUE (0xFFFFFFFF)
#define MAXSLOT (256)
namespace xpf {
//============---------- BuddyAllocator -----------================//
static BuddyAllocator* _global_pool_instances[MAXSLOT] = { 0 };
/****************************************************************************
* An implementation of Buddy memory allocation algorithm
* http://en.wikipedia.org/wiki/Buddy_memory_allocation
****************************************************************************/
struct BuddyAllocatorDetails
{
private:
struct FreeBlockRecord;
// The element type used for the linked-list of free blocks.
// Since we store this data structure inside each of free block,
// it is crucial to make sure that sizeof(FreeBlockRecord) is
// always smaller then the smallest-possible block size
// (1 << MINSIZE_POWOF2 bytes).
struct FreeBlockRecord
{
FreeBlockRecord *Prev;
FreeBlockRecord *Next;
};
public:
explicit BuddyAllocatorDetails(u32 size)
: TierNum(1)
, Capacity(1 << MINSIZE_POWOF2)
, UsedBytes(0)
, HWMBytes(0)
{
// This is a static assertion which makes sure the size
// of FreeBlockRecord is always less or equal to the smallest
// possible block size.
// If compiler nag anything about this line, the assumption
// probably doesn't hold. Which is fatal to our implementation.
xpfSAssert((sizeof(FreeBlockRecord) <= (1<<MINSIZE_POWOF2)));
const u32 maxSize = (1 << MAXSIZE_POWOF2);
while ( xpfLikely (Capacity < size) )
{
Capacity <<= 1;
++TierNum;
if ( xpfUnlikely (maxSize == Capacity) )
break;
}
FlagsLen = (1 << ((TierNum <= 3) ? 0 : (TierNum - 3))); // about 1/64 size of Capacity.
Chunk = (char*) ::malloc(sizeof(char) * Capacity);
Flags = (char*) ::malloc(sizeof(char) * FlagsLen);
FreeChainHead = (FreeBlockRecord**) ::malloc(sizeof(FreeBlockRecord*) * TierNum);
::memset(Flags, 0, sizeof(char) * FlagsLen);
::memset(FreeChainHead, 0, sizeof(FreeBlockRecord*) * TierNum);
// make sure the top-most tier places its only block in its free chain.
setBlockInUse(0, 0, true);
recycle(0, 0);
}
~BuddyAllocatorDetails()
{
::free(Chunk);
::free(Flags);
::free(FreeChainHead);
}
void* alloc ( const u32 size )
{
const u32 tier = tierOf(size);
if ( xpfUnlikely(INVALID_VALUE == tier) )
return NULL;
const u32 blockId = obtain(tier);
if ( xpfUnlikely (INVALID_VALUE == blockId) )
return NULL;
const u32 bsize = blockSizeOf(tier);
UsedBytes += bsize;
if (UsedBytes > HWMBytes)
HWMBytes = UsedBytes;
return (void*)(Chunk + (blockId * bsize));
}
// Return the allocated block with size hint.
void dealloc ( void *p, const u32 size )
{
const u32 tier = tierOf(size);
xpfAssert( ( "Expecting a valid tier index." , tier != INVALID_VALUE ) );
if ( xpfUnlikely(INVALID_VALUE == tier) )
return;
const u32 blockId = blockIdOf(tier, p);
xpfAssert( ( "Expecting a valid blockId." , blockId != INVALID_VALUE ) );
if ( xpfLikely ( blockId != INVALID_VALUE ) )
{
recycle(tier, blockId);
UsedBytes -= blockSizeOf(tier);
}
}
// dealloc() without size hint.
void free ( void *p )
{
u32 tier, blockId;
bool located = locateBlockInUse(p, tier, blockId);
xpfAssert( ( "Expecting a managed pointer.", located ) );
if (located)
{
recycle(tier, blockId);
UsedBytes -= blockSizeOf(tier);
}
}
// Change the size of allocated block pointed by p.
// May move the memory block to a new location (whose addr will be returned).
// The content of the memory block is preserved up to the lesser of the new and old sizes.
// Return NULL on error, in which case the memory content will not be touched.
void* realloc ( void *p, const u32 size )
{
// forwarding cases
if ( xpfUnlikely ( NULL == p ) )
{
return alloc(size);
}
if ( xpfUnlikely ( 0 == size ) )
{
free(p);
return NULL;
}
u32 tier, blockId;
if (locateBlockInUse(p, tier, blockId))
{
const u32 blockSize = blockSizeOf(tier);
// boundary cases
if ((0 == tier) && (size > blockSize))
return 0;
if (((TierNum-1) == tier) && (size <= blockSize))
return p;
// The new size is large than the current block size,
// promote to a bigger block.
if (size > blockSize)
{
void * b = alloc(size);
if (NULL != b)
{
::memcpy(b, p, blockSize);
dealloc(p, blockSize);
}
return b;
}
// The new size is less-or-equal to half of the current
// block size, demote to a smaller block.
if (size <= (blockSize >> 1))
{
void * b = alloc(size);
if (NULL != b)
{
::memcpy(b, p, size);
dealloc(p, blockSize);
}
return b;
}
// Current block is still suitable for the new size, so nothing changes.
return p;
}
return 0;
}
inline u32 capacity() const { return Capacity; }
inline u32 usedBytes() const { return UsedBytes; }
inline u32 hwmBytes(bool reset = false) { u32 ret = HWMBytes; if (reset) HWMBytes = 0; return ret; }
u32 available() const
{
for (u32 t=0; t<TierNum; ++t)
{
if (NULL != FreeChainHead[t])
{
return blockSizeOf(t);
}
}
return 0;
}
private:
u32 obtain( const u32 tier )
{
// 1. Check if there is any free block available in given tier,
// return one of them if does.
FreeBlockRecord *fbr = FreeChainHead[tier];
if (NULL != fbr)
{
const u32 blockSize = blockSizeOf(tier);
const u32 blockId = ((u32)((char*)fbr - Chunk))/blockSize;
FreeChainHead[tier] = fbr->Next;
if (fbr->Next)
{
fbr->Next->Prev = NULL;
}
setBlockInUse(tier, blockId, true);
return blockId;
}
// 2. Ask the upper tier to split one of its free block to two smaller
// blocks to join given tier. Return one of them for use and push
// another in the free block chain of current tier.
const u32 upperBlockId = (tier > 0)? obtain(tier-1) : INVALID_VALUE;
if (INVALID_VALUE != upperBlockId)
{
const u32 blockId1 = (upperBlockId << 1);
const u32 blockId2 = blockId1 + 1;
setBlockInUse(tier, blockId1, true);
setBlockInUse(tier, blockId2, true);
recycle(tier, blockId2);
return blockId1;
}
// 3. No available free block, returns INVALID_VALUE.
return INVALID_VALUE;
}
void recycle( const u32 tier, const u32 blockId)
{
// 1. Validate the in-use bit of given block.
xpfAssert( ( "Expecting a in-using blockId.", isBlockInUse(tier, blockId) == true ) );
setBlockInUse(tier, blockId, false);
// 2. Check the status of its buddy block.
const u32 buddyBlockId = buddyIdOf(blockId);
const u32 blockSize = blockSizeOf(tier);
if ((0 == tier) || (isBlockInUse(tier, buddyBlockId)))
{
// 2a. The buddy block is currently in-use, so we just
// clear the in-use bit of the recycling block and
// push it to the free block chain of current tier.
// Setup FreeBlockRecord and push to free chain
FreeBlockRecord * fbr = (FreeBlockRecord*)(Chunk + (blockSize * (blockId + 1)) - sizeof(FreeBlockRecord));
if (FreeChainHead[tier])
{
FreeChainHead[tier]->Prev = fbr;
}
fbr->Next = FreeChainHead[tier];
fbr->Prev = NULL;
FreeChainHead[tier] = fbr;
}
else
{
// 2b. The buddy block is also free, remove buddy block
// from the free block chain and return these 2 blocks
// back to upper tier.
FreeBlockRecord * fbr = (FreeBlockRecord*)(Chunk + (blockSize * (buddyBlockId + 1)) - sizeof(FreeBlockRecord));
if (fbr->Prev)
{
fbr->Prev->Next = fbr->Next;
}
if (fbr->Next)
{
fbr->Next->Prev = fbr->Prev;
}
if (fbr == FreeChainHead[tier])
{
FreeChainHead[tier] = (fbr->Prev)? fbr->Prev: fbr->Next;
}
recycle(tier-1, (blockId >> 1));
}
}
inline bool isValidPtr ( void *p ) const
{
xpfAssert( ( "Expecting a managed pointer (>= bulk start).", (char*)p >= Chunk ) );
if ( xpfUnlikely ((char*)p < Chunk) )
return false;
const u32 offset = (u32)((char*)p - Chunk);
xpfAssert( ( "Expecting a managed pointer ( < bulk length).", offset < Capacity ) );
if ( xpfUnlikely (offset >= Capacity) )
return false;
// Check if it aligns to minimal block size.
const bool aligned = (offset == (offset & (0xFFFFFFFF << MINSIZE_POWOF2)));
xpfAssert( ( "Expecting an aligned pointer.", aligned ) );
return aligned;
}
// Input: A pointer to an allocated block and its tier index.
// Return: A pointer to its buddy block on the same tier. Or NULL on error.
inline void* buddyAddrOf ( const u32 tier, void *p )
{
if ( xpfUnlikely (isValidPtr(p)) )
return NULL;
const u32 offset = (u32)((char*)p - Chunk);
return (void*)(Chunk + (offset ^ blockSizeOf(tier)));
}
// Input: Block id of any tier.
// Return: The block id of its buddy on the same tier.
inline u32 buddyIdOf ( const u32 blockId ) const
{
return (blockId ^ 0x1);
}
// Input: A pointer to an allocated block and its tier index.
// Return: The block id of the input block on that tier. Or INVALID_VALUE on error.
inline u32 blockIdOf ( const u32 tier, void *p ) const
{
const bool valid = isValidPtr(p);
xpfAssert( ( "Expecting a valid pointer.", valid ) );
if ( xpfUnlikely (!valid) )
return INVALID_VALUE;
// Check if p aligns to the block size of given tier.
const u32 offset = (u32)((char*)p - Chunk);
const u32 mask = (0xFFFFFFFF << (MINSIZE_POWOF2 + TierNum - tier - 1));
const bool aligned = (offset == (offset & mask));
xpfAssert( ( "Expecting an aligned pointer.", aligned ) );
if ( xpfUnlikely (!aligned) )
return INVALID_VALUE;
return (offset / blockSizeOf(tier));
}
// Return the block size of given tier.
inline u32 blockSizeOf ( const u32 tier ) const
{
xpfAssert( ( "Expecting a valid tier index.", tier < TierNum ) );
return (1 << (MINSIZE_POWOF2 + TierNum - tier - 1));
}
// Input: Block size.
// Return: The index of tier which deals with such block size.
inline u32 tierOf ( const u32 size ) const
{
u32 s = (1 << MINSIZE_POWOF2);
s32 t = TierNum - 1;
while (t >= 0)
{
if (size <= s)
return (u32)t;
s <<= 1;
t--;
}
return INVALID_VALUE;
}
inline bool isBlockInUse (const u32 tier, const u32 blockId) const
{
xpfAssert( ( "Expecting a valid tier index.", tier < TierNum ) );
const u32 idx = (1 << tier) + blockId;
const u32 offset = (idx >> 3);
const char mask = (1 << (idx & 0x7));
return (0 != (Flags[offset] & mask));
}
inline void setBlockInUse (const u32 tier, const u32 blockId, bool val)
{
xpfAssert( ( "Expecting a valid tier index.", tier < TierNum ) );
const u32 idx = (1 << tier) + blockId;
const u32 offset = (idx >> 3);
const char mask = (1 << (idx & 0x7));
if (val)
{
Flags[offset] |= mask;
}
else
{
Flags[offset] &= (mask ^ 0xFF);
}
}
// Try to find out the blockId and tier index of a in-use block
// based on given pointer. Return true if found one with its tier
// index and block id stored in outTier and outBlockId. Return false
// on error.
bool locateBlockInUse ( void *p, u32& outTier, u32& outBlockId ) const
{
bool ret = false;
u32 t = TierNum;
do
{
--t;
const u32 blockId = blockIdOf(t, p);
xpfAssert( ( "Expecting a valid blockId.", blockId != INVALID_VALUE ) );
if (INVALID_VALUE == blockId)
break;
if (isBlockInUse(t, blockId))
{
outTier = t;
outBlockId = blockId;
ret = true;
break;
}
} while (0 != t);
return ret;
}
u32 Capacity;
char* Chunk;
u32 FlagsLen;
char* Flags;
u32 TierNum;
FreeBlockRecord** FreeChainHead;
u32 UsedBytes;
u32 HWMBytes;
};
// *****************************************************************************
BuddyAllocator::BuddyAllocator(u32 size)
: mDetails(new BuddyAllocatorDetails(size))
{
}
BuddyAllocator::~BuddyAllocator()
{
if (mDetails)
{
delete mDetails;
mDetails = (BuddyAllocatorDetails*)0xfefefefe;
}
}
u32 BuddyAllocator::capacity() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->capacity();
}
u32 BuddyAllocator::available() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->available();
}
u32 BuddyAllocator::used() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->usedBytes();
}
u32 BuddyAllocator::hwm() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->hwmBytes();
}
u32 BuddyAllocator::reset()
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->hwmBytes(true);
}
void* BuddyAllocator::alloc(u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->alloc(size);
}
void BuddyAllocator::dealloc(void *p, u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
mDetails->dealloc(p, size);
}
void BuddyAllocator::free(void *p)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
mDetails->free(p);
}
void* BuddyAllocator::realloc(void *p, u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->realloc(p, size);
}
void* BuddyAllocator::calloc(u32 num, u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
const u32 length = num * size;
void *ptr = mDetails->alloc(length);
if ( xpfLikely(NULL != ptr) )
{
::memset(ptr, 0, length);
}
return ptr;
}
//===========----- BuddyAllocator static members ------==============//
u32 BuddyAllocator::create(u32 size, u16 slotId)
{
if ( xpfUnlikely(slotId >= MAXSLOT) )
return 0;
destory(slotId);
_global_pool_instances[slotId] = new BuddyAllocator(size);
xpfAssert( ( "Unable to create memory bulk.", _global_pool_instances[slotId] != 0 ) );
return (_global_pool_instances[slotId])? _global_pool_instances[slotId]->capacity() : 0;
}
void BuddyAllocator::destory(u16 slotId)
{
if ( xpfUnlikely(slotId >= MAXSLOT) )
return;
if ( xpfLikely (_global_pool_instances[slotId] != 0) )
{
delete _global_pool_instances[slotId];
_global_pool_instances[slotId] = 0;
}
}
BuddyAllocator* BuddyAllocator::instance(u16 slotId)
{
return (xpfUnlikely(slotId >= MAXSLOT))? NULL: _global_pool_instances[slotId];
}
//============---------- BuddyAllocator -----------================//
//============---------- LinearAllocator -----------================//
static LinearAllocator* _global_stack_instances[MAXSLOT] = { 0 };
/****************************************************************************
* An allocator implementation which shares similiar idea from obstack project.
* https://github.com/cleeus/obstack
****************************************************************************/
struct LinearAllocatorDetails
{
struct FreeCellRecord
{
u32 PrevOffset;
u32 CRC;
};
char *Chunk;
u32 Current;
u32 Previous;
u32 Capacity;
u32 HWMBytes;
};
LinearAllocator::LinearAllocator(u32 size)
{
// This assumption shall always true for current implementation.
xpfSAssert( MAXSIZE_POWOF2 <= 31);
if ( size < (1 << MINSIZE_POWOF2) )
{
size = (1 << MINSIZE_POWOF2);
}
else if ( size > (1 << MAXSIZE_POWOF2) )
{
size = (1 << MAXSIZE_POWOF2);
}
else if ( xpfUnlikely(0 != (size & 0x7)) )
{
// Upgrade size if it is not a multiply of 8.
size = (((size >> 3) + 1) << 3);
}
mDetails = new LinearAllocatorDetails;
mDetails->Chunk = (char*) ::malloc(size);
mDetails->Current = 0;
mDetails->Previous = 0;
mDetails->Capacity = size;
mDetails->HWMBytes = 0;
}
LinearAllocator::~LinearAllocator()
{
if (mDetails)
{
::free(mDetails->Chunk);
delete mDetails;
mDetails = (LinearAllocatorDetails*)0xfefefefe;
}
}
u32 LinearAllocator::capacity() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->Capacity;
}
u32 LinearAllocator::available() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
const u32 size = mDetails->Capacity - mDetails->Current;
if (size < sizeof(LinearAllocatorDetails::FreeCellRecord))
return 0;
return size - sizeof(LinearAllocatorDetails::FreeCellRecord);
}
u32 LinearAllocator::used() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->Current;
}
u32 LinearAllocator::hwm() const
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
return mDetails->HWMBytes;
}
u32 LinearAllocator::reset()
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
u32 ret = mDetails->HWMBytes;
mDetails->Current = mDetails->Previous = mDetails->HWMBytes = 0;
return ret;
}
void* LinearAllocator::alloc(u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
// Every allocation has an internal space overhead of
// sizeof(MemoryStackDetails::FreeCellRecord) (8 bytes).
size += sizeof(LinearAllocatorDetails::FreeCellRecord);
// Upgrade the size if it is not a multiply of 8.
// This can make sure every pointer we return is 8-bytes aligned.
if ( 0 != (size & 0x7) )
{
size = (((size >> 3) + 1) << 3);
}
if (size > available())
return NULL;
xpfAssert( ("Expecting Current < Capacity", mDetails->Current < mDetails->Capacity) );
if ( xpfLikely(mDetails->Current < mDetails->Capacity) )
{
LinearAllocatorDetails::FreeCellRecord *rec =
(LinearAllocatorDetails::FreeCellRecord*)(mDetails->Chunk + mDetails->Current);
rec->PrevOffset = mDetails->Previous;
rec->CRC = rec->PrevOffset ^ 0x5FEE1299; // as checksum of prev.
mDetails->Previous = mDetails->Current;
// This implies the first bit of rec->PrevOffset is not used and
// can be used as a flag indicates the chunk has been freed or not.
xpfAssert( ("Expecting PrevOffset < (1<<MAXSIZE_POWOF2)", rec->PrevOffset < (1<<MAXSIZE_POWOF2)) );
char *ret = mDetails->Chunk + mDetails->Current + sizeof(LinearAllocatorDetails::FreeCellRecord);
mDetails->Current += size;
if ( mDetails->Current > mDetails->HWMBytes )
mDetails->HWMBytes = mDetails->Current;
return (void*)ret;
}
return NULL;
}
void LinearAllocator::dealloc(void *p, u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
XPF_NOTUSED(size);
free(p);
}
void LinearAllocator::free(void *p)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
char *cell = (char*)p - sizeof(LinearAllocatorDetails::FreeCellRecord);
xpfAssert( ( "Expecting managed pointer.", ( (cell >= mDetails->Chunk) && (cell < mDetails->Chunk + mDetails->Capacity) ) ) );
if ( xpfLikely( (cell >= mDetails->Chunk) && (cell < mDetails->Chunk + mDetails->Capacity) ) )
{
// Check if data corrupted.
LinearAllocatorDetails::FreeCellRecord *rec = (LinearAllocatorDetails::FreeCellRecord*)cell;
xpfAssert( ("Checksum matched (data corrupted)", ((rec->PrevOffset & 0x7FFFFFFF) ^ 0x5FEE1299) == rec->CRC ) );
xpfAssert( ("In-using cell", (0 == (rec->PrevOffset & 0x80000000))) );
// Mark this cell as freed
rec->PrevOffset |= 0x80000000;
// For cells who are not at the top of the stack,
// just return here.
if ( mDetails->Previous != (cell - mDetails->Chunk) )
return;
// For the top-most cell, we need to apply a rollback sequence
// to adjust both mDetails->Current and mDetails->Previous to fit
// the next top-most cell which is still alive.
while (true)
{
mDetails->Current = (u32)((char*)rec - mDetails->Chunk);
// Quit the loop if hit the bottom of stack (all cells have been freed).
if ( xpfUnlikely ( 0 == mDetails->Current ) )
{
mDetails->Previous = 0;
break;
}
// Locate and verify the FreeCellRecord of previous cell.
rec = (LinearAllocatorDetails::FreeCellRecord*)(mDetails->Chunk + mDetails->Previous);
xpfAssert( ("Checksum matched (data corrupted)", ((rec->PrevOffset & 0x7FFFFFFF) ^ 0x5FEE1299) == rec->CRC ) );
mDetails->Previous = (rec->PrevOffset & 0x7FFFFFFF);
// Quit the loop whenever we meet an alive cell.
if ( 0 == (rec->PrevOffset & 0x80000000) )
break;
} // end of while (true)
}
}
void* LinearAllocator::realloc(void *p, u32 size)
{
// NOTE: Using of realloc() of MemoryStack is highly
// discouraged.
// It always allocates a new cell with given
// 'size' and copy the content pointed by 'p' to
// newly allocated cell.
// This means it could be very space-expensive.
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
if ( 0 == size )
return NULL;
void *ptr = alloc(size);
if ( xpfLikely ( NULL != ptr) )
{
if ( NULL != p )
{
::memcpy(ptr, p, size);
free(p);
}
}
return ptr;
}
void* LinearAllocator::calloc(u32 num, u32 size)
{
xpfAssert( ( "Null mDetails.", mDetails != 0 ) );
const u32 length = num * size;
void *ptr = alloc(length);
if ( xpfLikely(NULL != ptr) )
{
::memset(ptr, 0, length);
}
return ptr;
}
//===========----- LinearAllocator static members ------==============//
u32 LinearAllocator::create(u32 size, u16 slotId)
{
if ( xpfUnlikely(slotId >= MAXSLOT) )
return 0;
destory(slotId);
_global_stack_instances[slotId] = new LinearAllocator(size);
xpfAssert( ( "Unable to create memory bulk.", _global_stack_instances[slotId] != 0 ) );
return (_global_stack_instances[slotId])? _global_stack_instances[slotId]->capacity() : 0;
}
void LinearAllocator::destory(u16 slotId)
{
if ( xpfUnlikely(slotId >= MAXSLOT) )
return;
if ( xpfLikely (_global_stack_instances[slotId] != 0) )
{
delete _global_stack_instances[slotId];
_global_stack_instances[slotId] = 0;
}
}
LinearAllocator* LinearAllocator::instance(u16 slotId)
{
return (xpfUnlikely(slotId >= MAXSLOT))? NULL: _global_stack_instances[slotId];
}
//============---------- LinearAllocator -----------================//
}; // end of namespace xpf
<file_sep>/tests/network/sync_server.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include "sync_server.h"
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <set>
#include <stdio.h>
#include <string.h>
using namespace xpf;
std::set<TestSyncServer*> _g_server_conns;
TestSyncServer::TestSyncServer()
: mEndpoint(0)
, mBuf(0), mBufUsed(0)
, mAccepting(true)
{
u32 ec = 0;
mEndpoint = NetEndpoint::create(NetEndpoint::ProtocolIPv4 | NetEndpoint::ProtocolTCP, "localhost", "50123", &ec);
xpfAssert(("Failed on creating server endpoint.", mEndpoint != 0));
}
TestSyncServer::TestSyncServer(NetEndpoint *ep)
: mEndpoint(ep), mBufUsed(0)
, mAccepting(false)
{
mBuf = new c8[2048];
}
TestSyncServer::~TestSyncServer()
{
if (mAccepting)
{
printf("Free up all connected conns (%lu)...\n", _g_server_conns.size());
for (std::set<TestSyncServer*>::iterator it = _g_server_conns.begin();
it != _g_server_conns.end(); ++it)
{
delete (*it);
}
printf("All connected conns freed.\n");
_g_server_conns.clear();
}
if (mEndpoint)
{
mEndpoint->close();
join();
NetEndpoint::release(mEndpoint);
mEndpoint = 0;
}
delete[] mBuf;
}
u32 TestSyncServer::run(u64 udata)
{
u32 ec = 0;
if (mAccepting)
{
while (true)
{
NetEndpoint *ep = mEndpoint->accept(&ec);
if (!ep)
return 1;
TestSyncServer *s = new TestSyncServer(ep);
_g_server_conns.insert(s);
s->start();
}
return 0;
}
while (true)
{
// fill buf
const s32 available = (s32)(2048 - mBufUsed);
s32 bytes = mEndpoint->recv(mBuf + mBufUsed, available, &ec);
if (bytes == 0)
{
mBufUsed = 0;
break;
}
const u16 tbytes = bytes + mBufUsed;
// consume packet
u16 idx = 0;
while (true)
{
u16 sum = 0;
u16 packetlen = *(u16*)(&mBuf[idx]) + sizeof(u16);
xpfAssert(packetlen <= 2048);
if (idx + packetlen > tbytes)
{
printf("Truncated packet data.\n");
mBufUsed = tbytes - idx;
if (mBufUsed > 0)
memmove(mBuf, &mBuf[idx], mBufUsed);
break;
}
bool verified = false;
const u16 cnt = *(u16*)(&mBuf[idx]) / sizeof(u16);
for (u16 i = 1; i <= cnt; ++i)
{
if (i != cnt)
sum += *(u16*)(&mBuf[idx+(i*sizeof(u16))]);
else
verified = (sum == *(u16*)(&mBuf[idx + (i*sizeof(u16))]));
}
xpfAssert(verified);
if (!verified)
{
return 1;
}
else
{
bytes = mEndpoint->send((const c8*)&sum, sizeof(u16), &ec);
xpfAssert(bytes == sizeof(u16));
}
idx += packetlen;
if (idx >= tbytes)
{
mBufUsed = 0;
break;
}
}
}
return 0;
}
<file_sep>/src/platform/thread_posix.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/thread.h>
#include <xpf/threadevent.h>
#ifdef _XPF_THREAD_IMPL_INCLUDED_
#error Multiple Thread implementation files included
#else
#define _XPF_THREAD_IMPL_INCLUDED_
#endif
#include <pthread.h>
#include <unistd.h>
#include <sys/time.h>
namespace xpf { namespace details {
class XpfThread
{
public:
explicit XpfThread(Thread * host)
: mExitCode(0)
, mUserData(0)
, mID(Thread::INVALID_THREAD_ID)
, mStartEvent(new ThreadEvent(false))
, mFinishEvent(new ThreadEvent(false))
, mStatus(Thread::TRS_READY)
, mAborting(false)
, mHost(host)
{
pthread_create(&mThreadHandle, NULL, XpfThread::exec, this);
}
virtual ~XpfThread()
{
switch (mStatus)
{
case Thread::TRS_READY:
case Thread::TRS_RUNNING:
mAborting = true;
// fall through
case Thread::TRS_FINISHED:
join(-1);
break;
case Thread::TRS_JOINED:
default:
break;
}
delete mStartEvent;
mStartEvent = (ThreadEvent*) 0xfefefefe;
delete mFinishEvent;
mFinishEvent = (ThreadEvent*) 0xfefefefe;
}
inline void start()
{
mStatus = Thread::TRS_RUNNING;
mStartEvent->set();
}
inline bool join(u32 timeoutMs /*= -1*/)
{
if (mStatus == Thread::TRS_JOINED)
return true;
if ((mStatus != Thread::TRS_READY) &&
((-1 == timeoutMs) || (mFinishEvent->wait(timeoutMs))))
{
pthread_join(mThreadHandle, NULL);
pthread_detach(mThreadHandle);
mThreadHandle = 0;
mStatus = Thread::TRS_JOINED;
return true;
}
return false;
}
inline Thread::RunningStatus getStatus() const
{
return mStatus;
}
inline void setExitCode(u32 code)
{
mExitCode = code;
}
inline u32 getExitCode() const
{
return mExitCode;
}
inline u64 getData() const
{
return mUserData;
}
inline void setData(u64 data)
{
mUserData = data;
}
inline ThreadID getID() const
{
return mID;
}
inline void requestAbort()
{
mAborting = true;
}
inline bool isAborting() const
{
return mAborting;
}
static void sleep(u32 durationMs)
{
usleep(durationMs * 1000);
}
static void yield()
{
usleep(1000);
}
static ThreadID getThreadID()
{
return (ThreadID) pthread_self();
}
// ====
static void* exec (void* param)
{
XpfThread *thread = (XpfThread*) param;
thread->mID = XpfThread::getThreadID();
thread->mStartEvent->wait();
if (!thread->mAborting)
{
thread->mExitCode = thread->mHost->run(thread->getData());
thread->mFinishEvent->set();
thread->mStatus = Thread::TRS_FINISHED;
}
return (void*) (vptr) thread->mExitCode;
}
private:
XpfThread(const XpfThread& that)
{
xpfAssert( ( "non-copyable object", false ) );
}
XpfThread& operator = (const XpfThread& that)
{
xpfAssert( ( "non-copyable object", false ) );
return *this;
}
pthread_t mThreadHandle;
u32 mExitCode;
u64 mUserData;
Thread::RunningStatus mStatus;
ThreadEvent *mStartEvent;
ThreadEvent *mFinishEvent;
Thread *mHost;
ThreadID mID;
bool mAborting;
};
};};
<file_sep>/tests/network/async_client.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_TEST_ASYNC_CLIENT_HDR_
#define _XPF_TEST_ASYNC_CLIENT_HDR_
#include <xpf/platform.h>
#include <xpf/netiomux.h>
#include <xpf/thread.h>
#include <vector>
class WorkerThread;
class TestAsyncClient : public xpf::NetIoMuxCallback
{
public:
struct Client
{
xpf::u16 Checksum;
xpf::u16 Count;
xpf::c8 RData[2];
xpf::c8 WData[2048];
};
explicit TestAsyncClient(xpf::u32 threadNum);
virtual ~TestAsyncClient();
void start();
void stop();
// async callbacks (** multi-thread accessing)
void onIoCompleted(xpf::NetIoMux::EIoType type, xpf::NetEndpoint::EError ec, xpf::NetEndpoint *sep, xpf::vptr tepOrPeer, const xpf::c8 *buf, xpf::u32 len);
void RecvCb(xpf::u32 ec, xpf::NetEndpoint* ep, const xpf::c8* buf, xpf::u32 bytes);
void SendCb(xpf::u32 ec, xpf::NetEndpoint* ep, const xpf::c8* buf, xpf::u32 bytes);
void ConnectCb(xpf::u32 ec, xpf::NetEndpoint* ep);
private:
void sendTestData(xpf::NetEndpoint* connectedEp);
std::vector<WorkerThread*> mThreads;
xpf::NetEndpoint* mClients[16];
xpf::NetIoMux *mMux;
};
#endif // _XPF_TEST_ASYNC_CLIENT_HDR_<file_sep>/tests/fcontext/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include")
ADD_EXECUTABLE(fcontext_test
fcontext_test.cpp
)
SET_PROPERTY(TARGET fcontext_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(fcontext_test xpf)
<file_sep>/tests/atomicops/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(libxpf)
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/include" )
ADD_EXECUTABLE(atmoicops_test
atmoicops_test.cpp
)
SET_PROPERTY(TARGET atmoicops_test PROPERTY RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/build/bin")
IF(WIN32)
ADD_DEFINITIONS(-DUNICODE -D_UNICODE)
ENDIF(WIN32)
TARGET_LINK_LIBRARIES(atmoicops_test xpf)
<file_sep>/include/xpf/thread.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_THREAD_HEADER_
#define _XPF_THREAD_HEADER_
#include "platform.h"
namespace xpf {
typedef u64 ThreadID;
class XPF_API Thread
{
public:
static const ThreadID INVALID_THREAD_ID = -1LL;
enum RunningStatus
{
TRS_READY = 0, // Created but not yet started.
TRS_RUNNING, // Started but not yet finished.
TRS_FINISHED, // Finished (returned from run()).
TRS_JOINED, // Finished and joined.
};
public:
Thread();
virtual ~Thread();
/* Causes the caller thread to sleep for the given interval of time (given in milliseconds). */
static void sleep(u32 durationMs);
/* Causes the calling Thread to yield execution time. */
static void yield();
/* Return the caller thread id */
static ThreadID getThreadID();
/* Every thread is created as suspended until its start() is called from other thread. */
void start();
/*
* Block the caller thread and wait for the given interval of time trying to join this thread.
* If timeoutMs is -1L (or 0xFFFFFFFF) then it blocks forever until this thread has finished.
* Return true if this thread has finished and joined, return false on timeout (and this thread is still running).
*/
bool join(u32 timeoutMs = -1L);
/*
* This is the thread body which will be called after this thread
* has started. User must provide their customized body via overriding.
* userdata can be set via setData().
* The return value will be set to be exit code.
*
* NOTE: One could hint thread to abort current job and leave asap by
*
*/
virtual u32 run(u64 userdata) = 0;
/* Return true if this thread has been started. */
RunningStatus getStatus() const;
/* getter / setter of exit code */
void setExitCode(u32 code);
u32 getExitCode() const;
/* getter / setter of user data */
u64 getData() const;
void setData(u64 data);
/* Get the identifier of this thread */
ThreadID getID() const;
/*
* Hint the thread body to abort and return asap.
* The detail reaction depends on the derived impl of run().
*/
void requestAbort();
protected:
/*
* Whether an abort request has been issued.
* All derived run() implementation should check
* it as frequent as possible and perform
* aborting if requested.
*/
bool isAborting() const;
private:
// Non-copyable
Thread(const Thread& that);
Thread& operator = (const Thread& that);
vptr pImpl;
};
} // end of namespace xpf
#endif // _XPF_THREAD_HEADER_
<file_sep>/tests/network/sync_client.cpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include "sync_client.h"
#ifdef XPF_PLATFORM_WINDOWS
// http://msdn.microsoft.com/en-us/library/vstudio/x98tx3cf.aspx
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <stdlib.h>
#include <stdio.h>
using namespace xpf;
TestSyncClient::TestSyncClient(u16 times, u32 latencyMs)
: mEndpoint(0)
, mPingPongTimes(times)
, mPingPongLatencyMs(latencyMs)
{
mBuf = new c8[2048];
}
TestSyncClient::~TestSyncClient()
{
if (mEndpoint)
{
mEndpoint->close();
join();
NetEndpoint::release(mEndpoint);
mEndpoint = 0;
}
delete[] mBuf;
}
u32 TestSyncClient::run(u64 udata)
{
mEndpoint = NetEndpoint::create(NetEndpoint::ProtocolTCP | NetEndpoint::ProtocolIPv4);
xpfAssert(mEndpoint != 0);
bool ret = false;
u32 ec = 0;
ret = mEndpoint->connect("localhost", "50123", &ec);
if (!ret)
{
printf("Failed on connecting .\n");
return 1;
}
for (u16 cnt = 0; cnt < mPingPongTimes; cnt++)
{
u16 datalen = (rand() % 1022) + 1; // 1 ~ 1022
u16 sum = 0;
for (u16 i = 1; i <= datalen; ++i)
{
const u16 data = (u16)(rand() % 65536);
*(u16*)(&mBuf[i * sizeof(u16)]) = data;
sum += data;
}
*(u16*)(&mBuf[(datalen + 1) * sizeof(u16)]) = sum;
*(u16*)(mBuf) = (datalen + 1) * sizeof(u16);
s32 tlen = (s32)((datalen + 2) * sizeof(u16));
s32 bytes = mEndpoint->send(mBuf, tlen, &ec);
xpfAssert(bytes == tlen);
//printf("TestSyncClient send out %u bytes of data.\n", bytes);
// waiting for response
bytes = mEndpoint->recv(mBuf, 2, &ec);
xpfAssert(bytes == 2);
xpfAssert(*(u16*)mBuf == sum);
if (mPingPongLatencyMs > 0)
sleep(mPingPongLatencyMs);
}
return 0;
}
<file_sep>/include/xpf/base64.h
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#ifndef _XPF_BASE64_HEADER_
#define _XPF_BASE64_HEADER_
#include "platform.h"
namespace xpf
{
class XPF_API Base64
{
public:
/**
* Encode a bulk of memory buffer to a base64 encoded ASCII string.
*
* Input Parameters:
* input - Pointer to the input buffer. Must NOT be NULL.
* inputlen - Length of input buffer. Must >= 0.
* output - Pointer to the output buffer to hold the encoded string.
* If either output or outputlen is 0, the encode() simply
* computes the output length required and returns.
* outputlen - Length of output buffer. If its value is smaller than
* required (except for 0, see above), encode() returns
* -1 and fill the required length in *outputlen.
* Return Value:
* -1 to indicate an error. Otherwise it is the length of the encoded
* string.
*/
static int encode(const char *input, int inputlen, char *output, int *outputlen);
/**
* Decode a base64 encoded ASCII string to original data.
*
* Input Parameters:
* input - Pointer to the input buffer. Must NOT be NULL.
* inputlen - Length of input buffer. Must >= 0.
* output - Pointer to the output buffer to hold the decoded data.
* If either output or outputlen is 0, the decode() simply
* computes the output length required and returns.
* outputlen - Length of output buffer. If its value is smaller than
* required (except for 0, see above), decode() returns
* -1 and fill the required length in *outputlen.
* Return Value:
* -1 to indicate an error. Otherwise it is the length of the decoded
* data.
*/
static int decode(const char *input, int inputlen, char *output, int *outputlen);
};
}; // end of namespace xpf
#endif // _XPF_BASE64_HEADER_<file_sep>/src/platform/thread_windows.hpp
/*******************************************************************************
* Copyright (c) 2013 <EMAIL>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
********************************************************************************/
#include <xpf/thread.h>
#include <xpf/threadevent.h>
#ifdef _XPF_THREAD_IMPL_INCLUDED_
#error Multiple Thread implementation files included
#else
#define _XPF_THREAD_IMPL_INCLUDED_
#endif
#ifndef XPF_PLATFORM_WINDOWS
# error thread_windows.hpp shall not build on platforms other than Windows.
#endif
#include <Windows.h>
#include <process.h>
namespace xpf { namespace details {
class XpfThread
{
public:
explicit XpfThread(Thread * host)
: mExitCode(0)
, mUserData(0)
, mID(Thread::INVALID_THREAD_ID)
, mStatus(Thread::TRS_READY)
, mAborting(false)
, mHost(host)
{
u32 tid;
mThreadHandle = (HANDLE*) ::_beginthreadex(0, 0, XpfThread::exec, this, CREATE_SUSPENDED, &tid);
mID = tid;
}
virtual ~XpfThread()
{
switch (mStatus)
{
case Thread::TRS_READY:
case Thread::TRS_RUNNING:
mAborting = true;
// fall through
case Thread::TRS_FINISHED:
join(0xFFFFFFFF);
break;
case Thread::TRS_JOINED:
default:
break;
}
}
inline void start()
{
mStatus = Thread::TRS_RUNNING;
::ResumeThread(mThreadHandle);
}
inline bool join(u32 timeoutMs /*= -1L*/)
{
if (mStatus == Thread::TRS_JOINED)
return true;
if ((mStatus != Thread::TRS_READY) &&
(WAIT_OBJECT_0 == ::WaitForSingleObject(mThreadHandle, timeoutMs)))
{
// Windows guarantees a _endthreadex() will be called after
// the thread routine returns.
// However, _endthreadex() does not call CloseHandle() on the
// thread handler.
mStatus = Thread::TRS_JOINED;
if ((HANDLE)Thread::INVALID_THREAD_ID != mThreadHandle)
{
::CloseHandle(mThreadHandle);
mThreadHandle = (HANDLE)Thread::INVALID_THREAD_ID;
}
return true;
}
return false;
}
inline Thread::RunningStatus getStatus() const
{
return mStatus;
}
inline void setExitCode(u32 code)
{
mExitCode = code;
}
inline u32 getExitCode() const
{
return mExitCode;
}
inline u64 getData() const
{
return mUserData;
}
inline void setData(u64 data)
{
mUserData = data;
}
inline ThreadID getID() const
{
return mID;
}
inline void requestAbort()
{
mAborting = true;
}
inline bool isAborting() const
{
return mAborting;
}
static void sleep(u32 durationMs)
{
::Sleep(durationMs);
}
static void yield()
{
::Sleep(1);
}
static ThreadID getThreadID()
{
return (ThreadID) ::GetCurrentThreadId();
}
// ====
static unsigned int WINAPI exec (void * param)
{
XpfThread *thread = (XpfThread*)param;
if (!thread->mAborting)
{
thread->mExitCode = thread->mHost->run(thread->getData());
thread->mStatus = Thread::TRS_FINISHED;
}
return thread->mExitCode;
}
private:
XpfThread(const XpfThread& that)
{
xpfAssert( ( "non-copyable object", false ) );
}
XpfThread& operator = (const XpfThread& that)
{
xpfAssert( ( "non-copyable object", false ) );
return *this;
}
HANDLE mThreadHandle;
ThreadID mID;
u32 mExitCode;
u64 mUserData;
Thread *mHost;
Thread::RunningStatus mStatus;
bool mAborting;
};
};}; | d90ae4c1e6e74839640c0dfc74c7d1b7e2ef88df | [
"CMake",
"Markdown",
"C",
"C++",
"Shell"
] | 75 | C++ | matthklo/libxpf | f58137582803ac04d94994d35ccafb604ce6de84 | 350704b1859771bcf06c24490e29baa1210892dc |
refs/heads/master | <repo_name>D-Poschel/PolyCheckRNN<file_sep>/test.py
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 17:32:29 2017
@author: Daniel
"""
import praw
import csv
import re
reddit = praw.Reddit(client_id='YcfxGiBKgBL_TA',
client_secret='<KEY>',
password='',
user_agent='testscript by /u/',
username='')
with open('Conservative.csv','w') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_NONE, escapechar = ' ')
for comment in reddit.subreddit('Conservative').stream.comments():
csvdata = [re.sub('[,\n]', '', comment.body),'1']
spamwriter.writerow(csvdata) | 79da610f884d152039b814ddbf1c8519aa119d93 | [
"Python"
] | 1 | Python | D-Poschel/PolyCheckRNN | 8398798cccb09fc69bb19b78fa09c03e04226822 | 2c991bafe8e3939fd4a52f77b680a33144e5608e |
refs/heads/main | <repo_name>keithliu03/COMP7051_PONG<file_sep>/README.md
# COMP7051_PONG
3D Pong game made in Unity
Controls:
Keyboard: S and W / Up Arrow and Down Arrow
Xbox Controller: Dpad Up and Down / Left Thumbstick Up and Down / Y and A button ( Only works in player vs player )
We only had 1 controller to use.
Note: much of the console code was used from this [tutorial video](https://www.youtube.com/watch?v=VzOEM-4A2OM).
Console commands:
<ul>
<li><code>change_background</code> - changes the background color to cyan</li>
<li><code>reset_score</code> - resets the scoreboard</li>
</ul>
Note: To enter the commands you must click out of the console.
<file_sep>/COMP7051Assignment1/Assets/ConsoleController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
// Note: most of the logic for the console was taken from: https://youtu.be/VzOEM-4A2OM
public class ConsoleController : MonoBehaviour
{
bool showConsole;
string input;
public static ConsoleCommand CHANGE_BACKGROUND;
public static ConsoleCommand RESET_SCORE;
public List<object> commandList;
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
showConsole = !showConsole;
}
if (Input.GetKeyDown(KeyCode.Return))
{
Debug.Log("Enter pressed");
if (showConsole)
{
HandleInput();
input = "";
}
}
}
private void Awake()
{
CHANGE_BACKGROUND = new ConsoleCommand("change_background", "Change the background colour of the game", "change_background", () => {
GameObject.Find("Background").GetComponent<Renderer>().material.color = Color.cyan;
});
RESET_SCORE = new ConsoleCommand("reset_score", "Reset the scoreboard", "reset_score", () => {
Score score = GetComponent(typeof(Score)) as Score;
score.leftScore = 0;
score.rightScore = 0;
});
commandList = new List<object>
{
CHANGE_BACKGROUND,
RESET_SCORE
};
}
private void OnGUI()
{
if (!showConsole) {return;}
float y = 0f;
GUI.Box(new Rect(0, y, Screen.width, 30), "");
GUI.backgroundColor = new Color(0, 0, 0, 0);
input = GUI.TextField(new Rect(10f, y + 5f, Screen.width - 20f, 20f), input);
}
private void HandleInput()
{
for (int i = 0; i < commandList.Count; i++)
{
ConsoleCommandBase commandBase = commandList[i] as ConsoleCommandBase;
if (input.Contains(commandBase.commandID))
{
if(commandList[i] as ConsoleCommand != null)
{
(commandList[i] as ConsoleCommand).Invoke();
}
}
}
}
}
<file_sep>/COMP7051Assignment1/Assets/PlayerController2.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController2 : MonoBehaviour
{
//create private internal references
private InputActions2 inputActions;
private InputAction movement;
private void Awake()
{
inputActions = new InputActions2();//create new InputActions
}
//called when script enabled
private void OnEnable()
{
movement = inputActions.Player.Movement;//get reference to movement action
movement.Enable();
}
//called when script disabled
private void OnDisable()
{
movement.Disable();
}
//called every physics update
private void FixedUpdate()
{
Vector2 v2 = movement.ReadValue<Vector2>();//extract 2d input data
Vector3 v3 = new Vector3(v2.x, 0, v2.y);//convert to 3d space
transform.Translate(v3);
//Debug.Log("Movement values " + v2);
if (transform.position.x < -35)
{
transform.position = new Vector3(-35f, 0, -40);
}
if (transform.position.x > 35)
{
transform.position = new Vector3(35f, 0, -40);
}
}
}
<file_sep>/COMP7051Assignment1/Assets/RightGoal.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class RightGoal : MonoBehaviour
{
public Score score;
void OnCollisionEnter(Collision col)
{
Ball ball = col.gameObject.GetComponent<Ball>();
if (ball != null)
{
ball.transform.position = new Vector3(0f, 1f, 0f);
ball.initialImpulse.x = Random.Range(10, 20);
ball.initialImpulse.z = Random.Range(10, 20);
Debug.Log("x = " + ball.initialImpulse.x);
Debug.Log("z = " + ball.initialImpulse.z);
ball.rb.velocity = ball.initialImpulse;
ball.rb.AddForce(ball.initialImpulse, ForceMode.Impulse);
score.leftScore++;
if (score.leftScore == 5)
{
SceneManager.LoadScene("GameOver");
}
}
}
}
<file_sep>/COMP7051Assignment1/Assets/ConsoleCommand.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConsoleCommandBase
{
private string _commandID;
private string _commandDescription;
private string _commandFormat;
public string commandID {get {return _commandID;}}
public string commandDescription {get {return _commandDescription;}}
public string commandFormat {get {return _commandFormat;}}
public ConsoleCommandBase(string id, string description, string format)
{
_commandID = id;
_commandDescription = description;
_commandFormat = format;
}
}
public class ConsoleCommand : ConsoleCommandBase
{
private Action command;
public ConsoleCommand(string id, string description, string format, Action command) : base (id, description, format)
{
this.command = command;
}
public void Invoke()
{
command.Invoke();
}
} | 6d8c56b8a5b324644feab48b88ff04b8b9c4dd96 | [
"Markdown",
"C#"
] | 5 | Markdown | keithliu03/COMP7051_PONG | ffb9c2a40758cd85994e11be9c6820e3948608c1 | c02e73754159e9b849fbb012de170c846ecc9bc6 |
refs/heads/master | <file_sep># StudentList
## Simple CRUD application made with Spring Boot and secured with Spring Security
- Spring Boot
- Spring Security
- Thymeleaf
- H2 database
- Bootstrap
Usage (with eclipse):
1.) Clone the project
2.) Eclipse: File -> Import -> Maven -> Existing Maven Projects
3.) Run
4.) Navigate to localhost:8080
or run this project by copy this command into your terminal :
`mvn clean spring-boot:run`
Username & password : `<PASSWORD>` or `user/user`
## Screen shot
Login User Page:

List User Page

Add New User Page

H2 Login Console

H2 Student Data
<file_sep>package com.hendisantika.student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.hendisantika.student.model.Student;
import com.hendisantika.student.repository.StudentRepository;
@SpringBootApplication
public class CrudbootApplication {
private static final Logger log = LoggerFactory.getLogger(CrudbootApplication.class);
public static void main(String[] args) {
SpringApplication.run(CrudbootApplication.class, args);
}
/**
* Save students to H2 DB for testing
*
* @param repository
* @return
*/
@Bean
public CommandLineRunner demo(StudentRepository repository) {
return (args) -> {
// save students
repository.save(new Student("Hendi", "Santika", "IT", "<EMAIL>"));
repository.save(new Student("Uzumaki", "Naruto", "IT", "<EMAIL>"));
repository.save(new Student("Hatake", "Kakashi", "IT", "<EMAIL>"));
repository.save(new Student("Sakura", "Haruno", "Nursery", "<EMAIL>"));
repository.save(new Student("Sasuke", "Uchiha", "Business", "<EMAIL>"));
};
}
}
| 5084fc9165878d2924ec909c634a4219e372a245 | [
"Markdown",
"Java"
] | 2 | Markdown | hendisantika/student-list-secure | da3a78b521659dc4976e3c924313601dcf2d38de | 7b96ee2c8117846e32f93a8440b43a25f7742495 |
refs/heads/master | <file_sep>from bs4 import BeautifulSoup
import requests
import sqlite3
c = sqlite3.connect('nyc.db')
# Create table
c.execute('''Drop TABLE communityBoards''')
c.execute('''CREATE TABLE communityBoards
(board text, area text, pop text, normedPop text, neighborhoods text)''')
r = requests.get('https://en.wikipedia.org/wiki/Neighborhoods_in_New_York_City')
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find("table")
data = []
for row in table.findAll("tr"):
dataRow = []
for i, col in enumerate(row.findAll("td")):
dataRow.append(col.find(text=True).encode('utf-8'))
print(len(dataRow))
if(len(dataRow)>=5):
c.execute("INSERT INTO communityBoards VALUES (?,?,?,?,?)", dataRow)
# print(data)
# Save (commit) the changes
c.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
c.close()
| 2b666154447702f2096ff5f7f90ded1bfa936108 | [
"Python"
] | 1 | Python | grutt/nycTables | 608b23b3af3e124fb9fec915ee805c1a34dc9fbf | 75e841fec7360170a89fd65a11917ca7ad69b1c3 |
refs/heads/master | <file_sep><?php
function sendNotification($token, $payload){
$url = "https://fcm.googleapis.com/fcm/send";
$fields = array(
'to' => $token, //"/topics/test",//$tokens,
'data' => $payload
);
$headers = array(
'Authorization:key=<KEY> <KEY>',
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
if($result === FALSE){
die('CURL FAILED '. curl_error($ch));
}
$info = curl_getinfo($ch);
curl_close($ch);
return array('result'=>$result,'status'=>$info['http_code']);
}
// $tokens = array("<KEY> <KEY>","<KEY>","<KEY>");
// $token = '<KEY>';
$token = '<KEY>';
$message = array(
'image' => "http://www.connectingmass.com/notification_test/monpura.jpg",
'notificationHeader' => 'Title Text',
'notificationText' => 'Body Text',
'resourceUrl' => 'http://google.com',
'notificationType' => 'SMALL'
);
$messageLarge = array(
'image' => "http://connectingmass.com/notification_test/jspromise.jpg",
'notificationHeader' => 'Title Text',
'notificationText' => 'Body Text',
'resourceUrl' => 'http://google.com',
'notificationType' => 'LARGE'
);
$messageLogout = array(
// 'image' => "http://connectingmass.com/notification_test/jspromise.jpg",
'notificationHeader' => 'New Login',
'notificationText' => 'Your account has been logged-in from another device',
'resourceUrl' => 'http://google.com',
'notificationType' => 'LOGOUT'
);
try{
$sendResponse = sendNotification($token,$messageLarge);
echo '<pre>';
print_r($sendResponse);
}catch(Exception $ex){
echo $ex->getMessage();
}<file_sep># Firebase-Cloud-Messaging-FCM-
Firebase Cloud Messaging (commonly referred to as FCM), formerly known as Google Cloud Messaging (GCM), is a cross-platform solution for messages and notifications for Android, iOS, and web applications, which currently can be used at no cost.
```
<?php
function sendNotification($token, $payload){
$url = "https://fcm.googleapis.com/fcm/send";
$fields = array(
'to' => $token, //"/topics/test",//$tokens,
'data' => $payload
);
$headers = array(
'Authorization:key=<KEY> <KEY>',
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
if($result === FALSE){
die('CURL FAILED '. curl_error($ch));
}
$info = curl_getinfo($ch);
curl_close($ch);
return array('result'=>$result,'status'=>$info['http_code']);
}
$message = array(
'image' => "http://www.connectingmass.com/notification_test/monpura.jpg",
'notificationHeader' => 'Title Text',
'notificationText' => 'Body Text',
'resourceUrl' => 'http://google.com',
'notificationType' => 'SMALL'
);
$messageLarge = array(
'image' => "http://connectingmass.com/notification_test/jspromise.jpg",
'notificationHeader' => 'Title Text',
'notificationText' => 'Body Text',
'resourceUrl' => 'http://google.com',
'notificationType' => 'LARGE'
);
$messageLogout = array(
// 'image' => "http://connectingmass.com/notification_test/jspromise.jpg",
'notificationHeader' => 'New Login',
'notificationText' => 'Your account has been logged-in from another device',
'resourceUrl' => 'http://google.com',
'notificationType' => 'LOGOUT'
);
try{
$sendResponse = sendNotification($token,$messageLarge);
echo '<pre>';
print_r($sendResponse);
}catch(Exception $ex){
echo $ex->getMessage();
}
?>
```
| 16085cbc7520f2d15c69730c0dee5488c2250f1c | [
"Markdown",
"PHP"
] | 2 | PHP | matiur1000/Firebase-Cloud-Messaging-FCM- | 552c61f8051318f9b454a5480c7c120fb2500b57 | 0cc6ad35ab89d275ac9263e36d515733fd57264c |
refs/heads/master | <file_sep># etch-a-sketch
Etch-A-Sketch made with JQuery for TOP.
<file_sep>function initializeMatrix(matrixSize) {
var cellSize = 1000 / matrixSize;
$('#container').empty(); // Removes any pre-existing cells
for (var i = 1; i <= matrixSize; i++) {
$('#container').append('<div class="cell clear-left"></div>'); // First cell clears at left
for (var j = 2; j <= matrixSize; j++) {
$('#container').append('<div class="cell"></div>');
}
}
$('.cell').width(cellSize);
$('.cell').height(cellSize);
$('.cell').mouseenter(function() { // Makes cells become painted when mouse enters to them
$(this).addClass('painted');
});
}
$(document).ready(function() {
initializeMatrix(16); // Initial matrix is 16x16
$('button#reset').click(function() {
$('.cell').removeClass('painted');
var newSize = prompt('What size do you want now?');
initializeMatrix(newSize);
});
});
| 452b477fc69aae00077ec2c637624b1028ddcc5d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mgiagante/etch-a-sketch | d1facb9397f2cc7a3c29bab236ff5f5f3af636e3 | 519092487082c9a338f503ee4c96768995372149 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
cd ~/.ubuntu && vagrant up && vagrant ssh
<file_sep>#!/usr/bin/env bash
mkdir ~/.omnios
# copy files needed by vm
cp -f ./mdb_v8_amd64.so ~/.omnios/v8.so
cp -f ./run-mdb.sh ~/.omnios
# temp copy vagrantfile
cp -f ./omnios-Vagrantfile ~/.np-temp/omnios-Vagrantfile
vagrant box add omnios http://omnios.omniti.com/media/omnios-latest.box
cd ~/.omnios
vagrant init -m omnios
cp -f ~/.np-temp/omnios-Vagrantfile ~/.omnios/Vagrantfile
<file_sep>#!/usr/bin/env bash
sudo apt-get update
sudo apt-get install -y libfontconfig
sudo apt-get install -y redis-server
sudo apt-get install -y vim
sudo apt-get install -y gdb
sudo apt-get install -y git
git config --global credential.helper 'cache --timeout=180000'
sudo timedatectl set-timezone America/New_York
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash
source ~/.bashrc
nvm install v5.7.0
nvm install v4.3.1
nvm use v4.3.1
sudo apt-get install -y nodejs-legacy
# vagrant stuff for profiling in solaris
cp $(which node) /vagrant/nodejs
<file_sep>#!/usr/bin/env bash
cd ~/.omnios && vagrant up && vagrant ssh
<file_sep>#!/usr/bin/env bash
cd ~/.ubuntu && vagrant halt
<file_sep>#!/usr/bin/env bash
./vagrant-setup.sh && ./ubuntu-setup.sh && ./ubuntu-start.sh
<file_sep>#!/usr/bin/env bash
brew cask install vagrant
vagrant plugin install vagrant-vbguest
mkdir ~/.np-temp
<file_sep>#!/usr/bin/env bash
mkdir ~/.ubuntu
# copy files needed by vm
cp -f ./ubuntu-setup-vm.sh ~/.ubuntu
# temp copy vagrantfile
cp -f ./ubuntu-Vagrantfile ~/.np-temp/ubuntu-Vagrantfile
vagrant box add ubuntu https://github.com/kraksoft/vagrant-box-ubuntu/releases/download/14.04/ubuntu-14.04-amd64.box
cd ~/.ubuntu
vagrant init -m ubuntu
cp -f ~/.np-temp/ubuntu-Vagrantfile ~/.ubuntu/Vagrantfile<file_sep>mdb ./nodejs ./core.core
| ea8ac255477aabae3630b6bd83710246b4bf6b8f | [
"Shell"
] | 9 | Shell | ICEDLEE337/node-profiling | bad32016e3f8f7499d5d67b5e0e8530ca4f1a052 | 893ee97a2e85e04ce8ead24b3420689f02da168d |
refs/heads/main | <repo_name>joeltonluz/todo-list-react<file_sep>/src/Components/AddArea/styles.ts
import styled from 'styled-components';
export const Container = styled.div`
display: flex;
align-items: center;
border: 1px solid #555;
border-radius: 15px;
padding: 10px;
margin: 20px 0;
.image {
margin-right: 5px;
}
input {
border: 0px;
background: transparent;
outline: 0;
color: #fff;
font-size: 18px;
flex: 1;
}
button {
background: transparent;
color: #000;
padding: 8px 16px;
border-radius: 8px;
cursor: pointer;
background-color: #FFA07A;
font-size: 16px;
font-weight: 700;
transition: filter 0.3s;
&:hover {
filter: brightness(0.8);
}
}
`; | 7264d48c47539f03d7e2fb38ba4156d6c33361a0 | [
"TypeScript"
] | 1 | TypeScript | joeltonluz/todo-list-react | 0e1ed956daa995f1d133d8efc8b96a6ca98f92d6 | 563a88135f8e17839e88936183077b767abb45f4 |
refs/heads/master | <file_sep>cmake_minimum_required(VERSION 2.8.3)
project(bag_tools)
find_package(catkin REQUIRED COMPONENTS rospy sensor_msgs)
catkin_package()<file_sep>#!/usr/bin/env python
###############################################################################
# Duckietown - Project Unicorn ETH
# Author: <NAME>
# Subscribe and store compressed image.
###############################################################################
import cv2
from cv_bridge import CvBridge, CvBridgeError
from os.path import isdir
import rospy
from sensor_msgs.msg import CompressedImage
class Main():
def __init__(self):
self.bridge = CvBridge()
topic = rospy.get_param("/imagemsg_to_png/img_topic")
rospy.Subscriber(topic, CompressedImage, self.callback)
self.i = 0
self.storage_path = rospy.get_param("/imagemsg_to_png/storage_dir")
if not isdir(self.storage_path):
raise OSError("Invalid storage path !")
rospy.spin()
def callback(self, data):
"""Store message data as png."""
try:
frame = self.bridge.compressed_imgmsg_to_cv2(data, "bgr8")
except CvBridgeError as e:
rospy.logfatal(e)
name = self.storage_path + "/" + str(self.i) + ".png"
cv2.imwrite(name, frame)
self.i += 1
if __name__ == '__main__':
rospy.init_node('converter_imagemsg_png', anonymous=True)
try:
Main()
except rospy.ROSInterruptException:
cv2.destroyAllWindows()
| b1ee261d3305e76192feba32fcc2fa7820bbbd61 | [
"Python",
"CMake"
] | 2 | CMake | duckietown-project-unicorn/bag_tools | 3b1c2179e8e77cc37e0fd85e7e1d83e8a2ae3a4a | 7c251b123eb5e551dd9e06e96085cf704191f8f4 |
refs/heads/master | <file_sep>import "./App.css";
import Paper from "@material-ui/core/Paper";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import FirstPage from "./components/FirstPage";
import BuyNextOne from "./components/BuyPage/BuyNextPageAll/BuyNextOne";
import BuyNextTwo from "./components/BuyPage/BuyNextPageAll/BuyNextTwo";
import BuyNextThree from "./components/BuyPage/BuyNextPageAll/BuyNextThree";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { getAllCountries } from "./redux/actions/CountryAction";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
overflow: "hidden",
padding: theme.spacing(0, 3),
alignItems: "center",
justifyContent: "center",
height: "100vh",
display: "flex",
},
paper: {
maxWidth: "50%",
padding: "30px",
},
}));
function App() {
const classes = useStyles();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getAllCountries());
}, []);
return (
<>
<Router>
<div className={classes.root}>
<Paper className={classes.paper}>
<Grid container wrap="nowrap" spacing={2}>
<Switch>
<Route exact path="/" component={FirstPage} />
<Route exact path="/buyPageOne" component={BuyNextOne} />
<Route exact path="/buyPageTwo" component={BuyNextTwo} />
<Route exact path="/buyPageThree" component={BuyNextThree} />
</Switch>
</Grid>
</Paper>
</div>
</Router>
</>
);
}
export default App;
<file_sep>import React from 'react'
const BuyNextThree = () => {
return (
<div>
<div>
<div></div>
<h5>
Transfers between banks are usually faster. If available give preference to your
local bank and the system will automatically find the best P2P for you.
</h5>
<h5>
{" "}
<a href="#">How long does it usually take?</a>{" "}
</h5>
</div>
</div>
);
}
export default BuyNextThree
<file_sep>import { Button } from '@material-ui/core';
import React, { useState } from 'react'
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import WAValidator from "wallet-address-validator";
import { getWalletAddress } from '../../../redux/actions/CountryAction';
const BuyNextTwo = () => {
const dispatch = useDispatch();
const [address, setAddress] = useState("");
let history = useHistory();
const isValid = () => {
const valid = WAValidator.validate(address, "BTC");
if (valid) {
const walletAddress = {
addressWallet: address,
};
dispatch(getWalletAddress(walletAddress));
alert("This is a valid address");
history.push("/buyPageThree");
} else {
alert("Address INVALID");
}
};
return (
<div className="container border my-5">
<div className="container p-5">
<p>wallet : 1KFzzGtDdnq5hrwxXGjwVnKzRbvf8WVxck </p>
<input
onBlur={(e) => setAddress(e.target.value)}
className="form-control mb-5"
type="text"
placeholder="Enter your BSC wallet address"
/>
<h4>You will receive your TAOA in this address</h4>
<h4 className="text-danger mt-5">
Pay close attention mistakes will make you loose all your assets and there is nothing we
can do to help
</h4>
</div>
<a href="https://testnet.binance.org/en/create" target="_blank" className="text-center">
<h4>Don't have a BSC wallet yet?</h4>
</a>
<div className="text-center py-5">
<Button style={{ width: "100%" }} variant="contained" color="secondary" onClick={isValid}>
Next
</Button>
</div>
</div>
);
}
export default BuyNextTwo
<file_sep>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
click_styles: {
textDecoration: "none",
},
text_center: {
textAlign: "center",
},
}));
const FirstPage = () => {
//call material styles
const classes = useStyles();
return (
<div>
<h1>Welcome To Our Finex Company</h1>
<div className={classes.text_center}>
<h4>
Buy Coins Finex...{" "}
<a href="/buyPageOne" className={classes.click_styles}>
Click here
</a>
</h4>
<h4>
Sell Coins Finex...{" "}
<a href="/sellNext1" className={classes.click_styles}>
Click here
</a>
</h4>
</div>
</div>
);
};
export default FirstPage;
| e6b9bee50d1b4642943c9a4b5b501cdbb3c2c030 | [
"JavaScript"
] | 4 | JavaScript | hannanuddin78/inax-gateway-with-material-uI | f673db79fa256cddace9acf22e781cb85e700b8d | 28f3dc34715d123672f336caddc67c54d0e826ad |
refs/heads/master | <repo_name>tf198/phpqueues<file_sep>/tests/FIFOTest.php
<?php
require_once "bootstrap.php";
class FIFOTest extends PHPUnit_Framework_TestCase {
const DATAFILE = 'data/test.fifo';
private $fifo;
function setUp() {
if(file_exists(self::DATAFILE)) unlink(self::DATAFILE);
$this->fifo = new ConcurrentFIFO(self::DATAFILE);
}
function tearDown() {
$this->fifo = null;
}
function testEnqueueDequeue() {
for($i=0; $i<10; $i++) {
$this->assertSame($i+1, $this->fifo->enqueue(str_repeat('a', $i+1)));
}
$this->assertFalse($this->fifo->is_empty());
for($i=0; $i<10; $i++) {
$this->assertSame(str_repeat('a', $i+1), $this->fifo->dequeue());
}
$this->assertTrue($this->fifo->is_empty());
$this->assertSame(null, $this->fifo->dequeue());
}
function testCount() {
for($i=0; $i<10; $i++) {
$this->fifo->enqueue(str_repeat('a', $i+1));
$this->assertSame($i+1, $this->fifo->count());
}
}
function testRandomAccess() {
$seq = array(1,0,1,1,0,1,0,1,1,0,0,1,0,1,0);
$queue = array();
foreach($seq as $key=>$op) {
if($op) {
$data = str_repeat('s', $key+1);
array_push($queue, $data);
$this->assertSame(count($queue), $this->fifo->enqueue($data));
} else {
$data = $this->fifo->dequeue();
$this->assertSame(array_shift($queue), $data);
}
}
$this->assertSame(count($queue), $this->fifo->count());
}
function testCompact() {
$this->fifo->enqueue('a');
$this->fifo->enqueue('aa');
$this->fifo->enqueue('aaa');
$this->fifo->dequeue();
$this->fifo->dequeue();
$index = $this->fifo->_read_index();
$this->fifo->_compact($index['start'], $index['end'], $index['len']);
$this->assertSame('aaa', $this->fifo->dequeue());
}
function testAutoCompaction() {
$data = str_repeat('a', 98); // 100 bytes per record
for($i=0; $i<100; $i++) $this->fifo->enqueue($data);
// with 4K compaction then 40 records are read before compaction
for($i=0; $i<40; $i++) $this->fifo->dequeue();
$this->assertEquals(array('start' => 4016, 'end' => 10016, 'len' => 60, 'checksum' => 10412), $this->fifo->_read_index());
// one more dequeue should trigger compaction
$this->fifo->dequeue();
$this->assertEquals(array('start' => 16, 'end' => 5916, 'len' => 59, 'checksum' => 5943), $this->fifo->_read_index());
// check that the pointers are still correct for appending
$this->fifo->enqueue('Hello World');
// remove the rest of the auto elements (there will be another compaction during this)
for($i=0; $i<59; $i++) $this->fifo->dequeue();
$this->assertSame('Hello World', $this->fifo->dequeue());
$this->assertEquals(null, $this->fifo->_read_index());
}
function testItems() {
for($i=0; $i<10; $i++) $this->fifo->enqueue('ITEM_' . $i);
$this->assertSame(10, count($this->fifo->items()));
$this->assertEquals(array('ITEM_8', 'ITEM_9'), $this->fifo->items(8));
$this->assertEquals(array('ITEM_4', 'ITEM_5', 'ITEM_6'), $this->fifo->items(4, 3));
$this->assertEquals(array('ITEM_8', 'ITEM_9'), $this->fifo->items(8, 12));
$this->assertEquals(array(), $this->fifo->items(23));
$this->fifo->clear();
$this->assertSame(array(), $this->fifo->items());
$this->assertSame(array(), $this->fifo->items(4));
$this->assertSame(array(), $this->fifo->items(4, 2));
}
}<file_sep>/README.md
# ConcurrentFIFO #
PHP file-based FIFO specifically designed for concurrent access - think IPC,
processing queues etc. Can do over 18K/s operations depending
on disk speed with guaranteed atomicicity. A single class with no library dependancies,
the only requirement is a file writable by all processes.
## Status ##
This should be considered alpha code - there is still more work to be done on recovery
from data corruption and pushing it to the load limit. As a simple task queue though it should be
pretty stable and usable (without any guarantees though!). Documentation is provided by looking at the
[source](https://github.com/tf198/phpqueues/blob/master/ConcurrentFIFO.php) - it is only one file with half
a dozen methods :-)
## Usage ##
Basic example is a user registration page that wants to send a welcome email to the new user.
```php
<?
require_once "ConcurrentFIFO.php";
$q = new ConcurrentFIFO('data/test.fifo');
$job = array('email' => '<EMAIL>', 'message' => 'Hello Bob');
$q->enqueue(json_encode($job)); // the queue only knows about strings
?>
```
You can then have a cron job that gets the jobs and processes them every X minutes:
```php
<?
require_once "ConcurrentFIFO.php";
$q = new ConcurrentFIFO('data/test.fifo');
while($data = $q->dequeue()) {
$job = json_decode($data, true); // as array instead of object
mail($job['email'], "Your registration", $job['message']);
}
```
or daemonise the process - with this you can run as many 'workers' required and the emails
will be sent as soon as possible:
```php
<?
require_once "ConcurrentFIFO.php";
$q = new ConcurrentFIFO('data/test.fifo');
while(true) {
$data = $q->bdequeue(0); // blocks until an item is available
$job = json_decode($data, true);
mail($job['email'], "Your registration", $job['message']);
}
```
## Implementation ##
Data is written sequencially to the file and the first item pointer is advanced
as items are dequeued. The file is truncated when all items have been dequeued and
compacted when the the wasted space is greater than 4K so the file should remain a
reasonable size as long as the number of dequeues > enqueues over time. There is a 2 byte
overhead for each item + a 16 byte header. Atomicity is provided through flock() and should
be cross-platform (more testing needed).
## Performance ##
### bench.php ###
The first version was able to get > 35K ops/s enqueue() and 20K ops/s dequeue() but without any fault tolerance. The new version
is more robust and manages around 19K ops/s for all operations which I think is a fair compromise (and on a par with pipelined Redis commands).
These figures are obviously with a single reader/writer so multiple accessors will share this 'bandwidth' plus a bit of overhead for obtaining the
locks. 19K ops/sec was recorded on my AMD Phenom II x6 3.20Ghz with a 7200 RPM Barracuda SATA drive and a queue size of 10,000 items - it reduces to
around 14K ops/sec with a queue size of 100,000 items but the queue is intended to be kept sparse anyway - if you get up to these sort of numbers
you dont have enough worker processes!
### examples/load_test.php ###
This starts multiple producer (job_creator.php) and consumer (job_worker.php) processes and allows you to watch the number of tasks processed in
a separate console with job_manager.php. I have run this up to 25 producers and 100 consumers on a single system with no deadlocks or process starvation
though the setup is fairly controlled and this could do with some more rigorous testing under heavy loads.
### TODO ###
* The data structure should be able to recover from crashes during enqueue()/dequeue() but the methods haven't been implemented yet.
* Provide a lightweight Redis wrapper so this can be used for prototyping.
* Should be simple to add a basic REST frontend so one machine can act as a messaging server for multiple systems
* Add magic number to start of datastructure
* Find the load limit where flock() times out and do something more constructive than die()
* See if we can use this structure to implement a persistent pub/sub model.
<file_sep>/ConcurrentFIFO.php
<?php
/**
* File-based FIFO specifically designed for concurrent access - think IPC,
* processing queues etc. Can do over 18K/s operations depending
* on disk speed with guaranteed atomicicity.
*
* Data is written sequencially to the file and the first item pointer is advanced
* as items are dequeued. The file is truncated when all items have been dequeued and
* compacted when the the wasted space is greater than 4K so the file should remain a
* reasonable size as long as the number of dequeues > enqueues over time.
*/
class ConcurrentFIFO {
/**
* Our file pointer
* @var resource
*/
private $fp, $filename;
const INDEX_FORMAT = 'V4';
const INDEX_UNPACK = 'Vstart/Vend/Vlen/Vchecksum';
const INDEX_SIZE = 16;
const LENGTH_FORMAT = 'v';
const LENGTH_SIZE = 2;
const BUFSIZ = 8192; // copy 8K chunks when compacting
const COMPACT_AT = 4096; // allow 4K before truncating
/**
* Poll frequency for blocking operations (in microseconds)
* @var int
*/
public $poll_frequency = 100000;
/**
* Open or create a new list
*
* @param string $filename path to file
* @throws Exception if the open fails for any reason
*/
function __construct($filename) {
touch($filename);
$this->fp = fopen($filename, 'rb+');
$this->filename = $filename;
if(!$this->fp) throw new Exception("Failed to open '{$filename}'");
}
/**
* Read the list index and validate the checksum.
* Returns an assoc array with the elements 'start', 'end', 'len' and 'checksum'
*
* @access private
* @return multitype:int
*/
function _read_index() {
fseek($this->fp, 0);
$buffer = fread($this->fp, self::INDEX_SIZE);
if(!$buffer) return null;
$data = unpack(self::INDEX_UNPACK, $buffer);
if(($data['start'] ^ $data['end'] ^ $data['len']) != $data['checksum']) throw new Exception("Index corrupt - rebuild required");
return $data;
}
/**
* Writes the list index including a checksum.
*
* @access private
* @param int $start first item pointer
* @param int $end end of data pointer
* @param int $len number of items
*/
function _write_index($start, $end, $len) {
$checksum = $start ^ $end ^ $len;
fseek($this->fp, 0);
fwrite($this->fp, pack(self::INDEX_FORMAT, $start, $end, $len, $checksum));
}
/**
* Read an integer from the datafile according to the format provided.
*
* @access private
* @param string $format one of the unpack() format strings
* @param int $size number of bytes the format string requires
* @return int
*/
function _read_int($format, $size) {
$buffer = fread($this->fp, $size);
if(!$buffer) return 0;
$u = unpack($format, $buffer);
return $u[1];
}
/**
* Get the first available from the queue, or null if the queue is empty
*
* @return string
*/
function dequeue() {
// need an exclusive lock
flock($this->fp, LOCK_EX) or die('Failed to get lock');
$index = $this->_read_index();
if($index) {
// read the length and get the data
fseek($this->fp, $index['start']);
$l = $this->_read_int(self::LENGTH_FORMAT, self::LENGTH_SIZE);
// TODO: should be able to recover from zero data length here
if(!$l) throw new Exception("Zero data length");
$data = fread($this->fp, $l);
$p = ftell($this->fp);
// check if there is any more data
if($p < $index['end']) {
if($p > self::COMPACT_AT) {
// compaction writes the new index
$this->_compact($p, $index['end'], $index['len'] - 1);
} else {
// just update the start pointer
$this->_write_index($p, $index['end'], $index['len'] - 1);
}
} else {
// can just truncate the whole file
ftruncate($this->fp, 0);
}
} else {
$data = null;
}
flock($this->fp, LOCK_UN);
return $data;
}
/**
* Add an item to the queue.
*
* @param unknown_type $data
* @throws Exception if there is no data to add
* @return int the number of items in the queue after this operation
*/
function enqueue($data) {
$data = (string) $data;
$c = strlen($data);
if($c == 0) throw new Exception("No data");
// get exclusive lock
flock($this->fp, LOCK_EX) or die('Failed to get lock');
// read and update the index
$index = $this->_read_index();
if(!$index) {
$index = array('start' => self::INDEX_SIZE, 'end' => self::INDEX_SIZE, 'len' => 0);
}
fseek($this->fp, $index['end']);
// write length followed by data
fwrite($this->fp, pack(self::LENGTH_FORMAT, $c), self::LENGTH_SIZE);
fwrite($this->fp, $data, $c);
$this->_write_index($index['start'], $index['end'] + $c + self::LENGTH_SIZE, $index['len'] + 1);
//echo "Wrote {$data} at {$index['end']}\n";
// release lock
flock($this->fp, LOCK_UN);
return $index['len'] + 1;
}
/**
* Check if the queue is empty.
* Note that calling dequeue() and checking for null is an atomic operation where as
* if (!$q->is_empty()) $data = $q->dequeue()
* is not!
* @return boolean
*/
function is_empty() {
flock($this->fp, LOCK_SH) or die('Failed to get lock');
$index = $this->_read_index();
flock($this->fp, LOCK_UN);
return ($index === null);
}
/**
* Get the number of items currently in the queue
*
* @return int
*/
function count() {
flock($this->fp, LOCK_SH) or die('Failed to get lock');
$index = $this->_read_index();
flock($this->fp, LOCK_UN);
return ($index === null) ? 0 : $index['len'];
}
/**
* Remove all elements from the queue.
* Actually just truncates the file.
*/
function clear() {
flock($this->fp, LOCK_EX) or die('Failed to get lock');
ftruncate($this->fp, 0);
flock($this->fp, LOCK_UN);
}
/**
* Delete the queue entirely.
* Note any further attempts to modify the queue will result in an exception.
*/
function delete() {
flock($this->fp, LOCK_EX) or die('Failed to get lock');
fclose($this->fp);
unlink($this->filename);
$this->fp = null;
}
/**
* Return an array of items from the queue. Does not modify the queue in any way.
*
* @param int $offset skip $offset items at the start
* @param int $count return up to $count items
* @return multitype:string
*/
function items($offset=0, $count=0) {
flock($this->fp, LOCK_SH) or die('Failed to get lock');
$index = $this->_read_index();
if(!$index) return array();
$result = array();
$p = $index['start'];
while($p < $index['end']) {
$l = $this->_read_int(self::LENGTH_FORMAT, self::LENGTH_SIZE);
if(!$l) break;
$data = fread($this->fp, $l);
$p += $l + self::LENGTH_SIZE;
assert($p == ftell($this->fp));
if($offset) {
$offset--;
} else {
$result[] = $data;
if($count) {
$count--;
if(!$count) break;
}
}
}
flock($this->fp, LOCK_UN);
return $result;
}
/**
* Compacts the data file by shifting the unprocessed items to the start of the datafile
* and truncating to the new length. This is currently an unprotected operation so
* if this crashes mid operation the the data will corrupt. The parameters are the current
* values from the index.
*
* @access private
* @todo protect this operation
* @param int $start current start pointer
* @param int $end current end pointer
* @param int $len number of items
*/
function _compact($start, $end, $len) {
// truncate start
$p_current = $start;
$p_new = self::INDEX_SIZE;
fseek($this->fp, $p_current);
while($buffer = fread($this->fp, self::BUFSIZ)) {
fseek($this->fp, $p_new);
$c = strlen($buffer);
//echo "Writing {$c} bytes from {$p_current} to {$p_new}\n";
fwrite($this->fp, $buffer, $c);
$p_current += $c;
$p_new += $c;
fseek($this->fp, $p_current);
}
ftruncate($this->fp, $p_new);
$this->_write_index(self::INDEX_SIZE, $end - $start + self::INDEX_SIZE, $len);
}
/**
* Pseudo blocking version of dequeue()
* Returns immediately if data is available, otherwise polls/sleeps
* every ConcurrentFIFO::$poll_frequency microseconds until data becomes available.
*
* @param int $timeout maximum time (in seconds) to block for, or zero for forever
* @return string data or null if timed out
*/
function bdequeue($timeout) {
$start = microtime(true);
while(true) {
$data = $this->dequeue();
if($data !== null) return $data;
usleep($this->poll_frequency);
if($timeout && (microtime(true) > $start + $timeout)) return null;
}
}
function __toString() {
return "<FIFO: {$this->filename}>";
}
}
<file_sep>/examples/job_creator.php
<?php
require "job_common.php";
$pid = getmypid();
echo "Creator {$pid} started\n";
$jobs = new ConcurrentFIFO(JOBS_IN);
$i=0;
while(file_exists(JOBS_LOCK)) {
$jobs->enqueue($pid . ":" . $i++);
usleep(rand(400000,00000));
}<file_sep>/examples/job_worker.php
<?php
require "job_common.php";
$pid = getmypid();
echo "Worker {$pid} started\n";
$input = new ConcurrentFIFO(JOBS_IN);
$output = new ConcurrentFIFO(JOBS_OUT);
$timeout = 5;
while(file_exists(JOBS_LOCK)) {
$data = $input->bdequeue($timeout);
if($data) {
usleep(rand(100000, 200000));
$output->enqueue("{$pid}:{$data}");
if($data == 'quit') break;
} else {
$output->enqueue("{$pid}:0");
}
}<file_sep>/tests/mp_func.php
<?php
define("MP_EXIT", 'exit.lock');
MultiProcess::$level = LOG_WARNING;
function mp_one() { return 1; }
function mp_hi($name) { return "Hello {$name}"; }
function mp_err() { throw new Exception("Test Exception"); }
function mp_big_hi($repeat=4000) {
return str_repeat("Hi", $repeat);
}
function mp_exit() {
if( file_exists(MP_EXIT)) {
unlink(MP_EXIT);
exit(1);
}
return "Exit okay";
}<file_sep>/tests/bootstrap.php
<?php
require_once dirname(__FILE__) . '/../ConcurrentFIFO.php';
if(!is_dir('data')) {
mkdir('data') or die('Failed to create data dir');
}<file_sep>/tests/DeferredTest.php
<?php
require_once dirname(__FILE__) . '/../Deferred.php';
class DeferredTest extends PHPUnit_Framework_TestCase {
function setUp() {
$this->stack = array();
}
function assertSequence($seq) {
$this->assertSame(implode('->', $this->stack), $seq);
}
function testFired() {
$d = new Deferred();
$d->addCallback(array($this, 'cb_none'));
$this->assertFalse($d->fired);
$d->callback(1);
$this->assertTrue($d->fired);
$this->assertSequence('cb_none[1]');
$this->assertSame($d->result, 1);
}
function testResults() {
$d = new Deferred();
$d->addCallback(array($this, 'cb_plus_1'));
$d->addCallback(array($this, 'cb_none'));
$d->addCallback(array($this, 'cb_times_2'));
$d->callback(5);
$this->assertSequence('cb_plus_1[5]->cb_none[6]->cb_times_2[6]');
$this->assertSame($d->result, 12);
}
function testErrbacks() {
$d = new Deferred();
$d->addErrback(array($this, 'eb_none'));
$d->addCallback(array($this, 'cb_err')); // Y
$d->addCallback(array($this, 'cb_none'));
$d->addErrback(array($this, 'eb_none')); // Y
$d->addCallback(array($this, 'cb_none'));
$d->addErrback(array($this, 'eb_err')); // Y
$d->addErrback(array($this, 'eb_none')); // Y
$d->addErrback(array($this, 'eb_okay')); // Y
$d->addErrback(array($this, 'eb_none'));
$d->addCallback(array($this, 'cb_plus_1')); // Y
$d->addErrback(array($this, 'eb_none'));
$d->callback(1);
$this->assertSequence('cb_err[1]->eb_none[a]->eb_err[a]->eb_none[b]->eb_okay[b]->cb_plus_1[42]');
$this->assertSame($d->result, 43);
}
function testAlreadyFired() {
$d = new Deferred();
$d->callback(1);
$d->addCallback(array($this, 'cb_plus_1'));
$this->assertSequence('cb_plus_1[1]');
$this->assertSame($d->result, 2);
}
function testConstructor() {
$d = new Deferred(1);
$this->assertTrue($d->fired);
$this->assertSame($d->result, 1);
$d = new Deferred(new Exception('a'));
$d->addErrback(array($this, 'eb_handled'));
$this->assertTrue($d->fired);
$this->assertSame($d->result, null);
}
function testFire() {
$d = new Deferred();
$d->callback(1);
try {
$d->callback(2);
$this->fail("Should have thrown an exception");
} catch(Exception $e) {
$this->assertSame($e->getMessage(), 'Deferred already fired');
}
$this->assertSame($d->result, 1);
}
function testErrback() {
$d = new Deferred();
$d->addCallback(array($this, 'cb_none'));
$d->addErrback(array($this, 'eb_handled'));
$d->errback('c');
$this->assertSequence('eb_handled[c]');
$this->assertSame($d->result, null);
}
function testLateErrback() {
$d = new Deferred(new Exception('Test exception'));
$d->addErrback(array($this, 'eb_handled'));
$this->assertSequence('eb_handled[Test exception]');
$this->assertSame($d->result, null);
unset($d);
}
function testBadCallback() {
$d = new Deferred();
try {
$d->addCallback(array($this, 'false'));
$d->fail("Should have thrown");
} catch(UnexpectedValueException $e) {
}
}
function testChaining() {
$d = new Deferred();
$d->addCallback(array($this, 'cb_none'))
->addErrback(array($this, 'eb_none'))
->addBoth(array($this, 'cb_none'))
->addCallback(array($this, 'cb_plus_1'));
$d->callback(3);
$this->assertSequence('cb_none[3]->cb_none[3]->cb_plus_1[3]');
$this->assertSame($d->result, 4);
}
function cb_none($r) {
$this->stack[] = "cb_none[{$r}]";
return $r;
}
function cb_plus_1($r) {
$this->stack[] = "cb_plus_1[{$r}]";
return $r + 1;
}
function cb_times_2($r) {
$this->stack[] = "cb_times_2[{$r}]";
return $r * 2;
}
function cb_err($r) {
$this->stack[] = "cb_err[{$r}]";
throw new Exception('a');
}
function eb_none($e) {
$this->stack[] = "eb_none[{$e->getMessage()}]";
return $e;
}
function eb_handled($e) {
$this->stack[] = "eb_handled[{$e->getMessage()}]";
}
function eb_okay($e) {
$this->stack[] = "eb_okay[{$e->getMessage()}]";
return 42;
}
function eb_err($e) {
$this->stack[] = "eb_err[{$e->getMessage()}]";
throw new Exception('b');
}
}<file_sep>/MultiProcess.php
<?php
require_once "Deferred.php";
require_once "ConcurrentFIFO.php";
define('MULTIPROCESS_PID', getmypid());
define('MP_WORKER_TIMEOUT', 10);
define('MP_DATA_DIR', 'data');
class Multiprocess {
public static $level = LOG_DEBUG;
static function log($message, $level=LOG_INFO) {
if( $level > self::$level ) return;
if(is_array($message)) {
$message = print_r($message, true);
}
fprintf(STDERR, "[%4d] %s\n", MULTIPROCESS_PID, $message);
}
static function format_callable($callable) {
$method = array_shift($callable);
return self::format_method($method, $callable);
}
static function format_method($method, $params) {
return sprintf("%s(%s)", print_r($method, true), self::format_params($params));
}
static function format_params($params) {
foreach($params as &$param) {
if(is_object($param)) {
$param = "<OBJ>";
} elseif(is_array($param)) {
$param = "<ARRAY>";
} else {
$param = var_export($param, true);
}
}
return implode(', ', $params);
}
}
class MultiProcessManager {
private $bootstrap;
private $num_workers;
private $queue = array();
private $allocated = array();
private $workers = array();
private $running;
function __construct($bootstrap, $workers=2, $allowable_errors=10, $data_dir=MP_DATA_DIR) {
if(!is_dir($data_dir) && !mkdir($data_dir)) {
throw new Exception("Failed to create data dir");
}
if(!is_writeable($data_dir)) {
throw new Exception("{$data_dir} is not writable");
}
$this->bootstrap = realpath($bootstrap);
if(!$this->bootstrap) throw new Exception("Cannot locate '{$bootstrap}'");
$this->manager_fifo = tempnam($data_dir, 'mp-');
Multiprocess::log("Manager FIFO: {$this->manager_fifo}");
// prevent eternal loops
$this->allowable_errors = $allowable_errors;
MultiProcess::log("Starting {$workers} workers");
for($i=0; $i<$workers; $i++) $this->add_worker();
}
function add_worker() {
$worker = new MultiProcessWorker($this->bootstrap, $this->manager_fifo);
$this->workers[$worker->id()] = $worker;
}
function defer($callable) {
$params = func_get_args();
$d = new Deferred();
$this->queue[] = array($params, $d);
return $d;
}
function shutdown() {
$this->running = false;
}
function process() {
$this->running = true;
MultiProcess::log("Starting to process jobs");
$recv_q = new ConcurrentFIFO($this->manager_fifo);
MultiProcess::log("Waiting for results on {$recv_q}", LOG_DEBUG);
// allow the reactor to set an exception to be thrown
$e = null;
while($this->running) {
foreach($this->workers as $wid=>$worker) {
$status = $worker->get_status();
// Check if worker is still alive
if($status['running']) {
// check if worker is idle
if(!isset($this->allocated[$wid])) {
// allocate a job if one is available
$job = array_shift($this->queue);
if($job) {
$printable = MultiProcess::format_callable($job[0]);
MultiProcess::log("Assiging {$printable} to worker {$wid}", LOG_DEBUG);
$this->allocated[$wid] = $job;
//MultiProcess::send($this->workers[$pid]->get_stdin() , $job[0]);
$worker->send($job[0]);
}
}
} else {
// worker has died for some reason
MultiProcess::log("Worker {$wid} died - RIP!", LOG_WARNING);
$this->allowable_errors--;
// if we lose too many processes there is probably a coding error
if($this->allowable_errors <= 0) {
MultiProcess::log("Too many errors, shutting down", LOG_ERR);
$this->running = false;
$e = new Exception("Too many errors");
continue;
}
$worker->close();
unset($this->workers[$wid]);
// requeue the job if required
if(isset($this->allocated[$wid])) {
array_unshift($this->queue, $this->allocated[$wid]);
unset($this->allocated[$wid]);
}
// start a new worker to take its place
$this->add_worker();
}
}
MultiProcess::log(count($this->allocated) . " workers busy", LOG_DEBUG);
// check for results
if($this->allocated) {
$data = $recv_q->bdequeue(60);
if($data) {
$result = unserialize($data);
#Multiprocess::log($result);
$wid = $result['worker_id'];
list($job, $d) = $this->allocated[$wid];
if($result['status'] == 'ok') {
$d->callback($result['result']);
} else {
$d->errback($result['exception']);
}
unset($this->allocated[$wid]);
}
} else {
if(!$this->queue) {
MultiProcess::log("No more work", LOG_DEBUG);
break;
}
}
}
MultiProcess::log("Shutting down");
// try and shut down everything cleanly
foreach($this->workers as $worker) {
$worker->close();
}
$recv_q->delete();
if($e) throw $e;
MultiProcess::log("Everything cleanly shutdown", LOG_DEBUG);
}
}
/**
* Process wrapper
* @author tris
*
*/
class MultiProcessWorker {
private $p;
private $send_q, $worker_id;
static $_next_id=0;
function __construct($bootstrap, $manager_fifo) {
$manager = MULTIPROCESS_PID;
$this->worker_id = self::$_next_id++;
$cmd = sprintf("php %s %s %s %d", __FILE__, escapeshellarg($bootstrap), escapeshellarg($manager_fifo), $this->worker_id);
$this->p = proc_open($cmd, array(), $streams);
if(!is_resource($this->p)) throw new Exception("Failed to open process: {$cmd}");
$this->send_q = new ConcurrentFIFO("{$manager_fifo}-{$this->worker_id}");
MultiProcess::log("Send queue for worker {$this->worker_id}: {$this->send_q}", LOG_DEBUG);
}
function get_status() {
return proc_get_status($this->p);
}
function id() {
return $this->worker_id;
}
function send($data) {
$data = serialize($data);
#MultiProcess::log("Sending data: {$data}");
$this->send_q->enqueue($data);
}
function close() {
$status = $this->get_status();
Multiprocess::log("Closing process {$status['pid']}");
$this->send_q->enqueue("SIG_QUIT");
$result = proc_close($this->p);
$this->send_q->delete();
return $result;
}
}
#### END OF CLASSES ###
// use this file as the dispatcher
if( __FILE__ != realpath($_SERVER['SCRIPT_FILENAME']) ) return;
if( $argc < 4 ) die("Not enough arguments\n");
$bootstrap = $argv[1];
$basepath = dirname($bootstrap);
set_include_path(get_include_path() . PATH_SEPARATOR . $basepath);
chdir($basepath);
require_once $bootstrap;
#MultiProcess::log("Loaded bootstrap: {$bootstrap}", LOG_DEBUG);
$manager_fifo = $argv[2];
$worker_id = $argv[3];
$jobs_q = new ConcurrentFIFO("{$manager_fifo}-{$worker_id}");
$results_q = new ConcurrentFIFO($manager_fifo);
#MultiProcess::log("Receive queue: {$jobs_q}", LOG_DEBUG);
#MultiProcess::log("Results queue: {$results_q}", LOG_DEBUG);
MultiProcess::log("Worker {$worker_id} ready for jobs");
while($data = $jobs_q->bdequeue(MP_WORKER_TIMEOUT)) {
#MultiProcess::log("Got data: {$data}");
if(!$data) {
MultiProcess::log("Worker {$worker_id} received no work in " . MP_WORKER_TIMEOUT . " seconds - quitting...", LOG_WARNING);
break;
}
if(substr($data, 0, 3) == 'SIG') {
MultiProcess::log("Worker {$worker_id} received {$data}", LOG_DEBUG);
switch(substr($data, 4)) {
case 'QUIT':
break 2;
default:
MultiProcess::log("Unknown signal!", LOG_WARNING);
}
}
$params = unserialize($data);
$callback = array_shift($params);
$result = array('child_pid' => MULTIPROCESS_PID, 'worker_id' => $worker_id);
MultiProcess::log(sprintf("Worker %d: %s", $worker_id, MultiProcess::format_method($callback, $params)), LOG_DEBUG);
// need to make sure nothing else writes to STDOUT
ob_start();
try {
$result['result'] = call_user_func_array($callback, $params);
$result['status'] = 'ok';
} catch(Exception $e) {
$result['status'] = 'failed';
$result['exception'] = $e;
}
MultiProcess::log("Result: {$result['status']}", LOG_DEBUG);
$data = ob_get_clean();
if($data) fwrite(STDERR, $data);
$results_q->enqueue(serialize($result));
}
MultiProcess::log("Worker {$worker_id} Finished", LOG_DEBUG);
<file_sep>/examples/job_common.php
<?php
define('JOBS_BASE', dirname(dirname(__FILE__)));
require_once JOBS_BASE . '/ConcurrentFIFO.php';
define('JOBS_IN', JOBS_BASE . '/data/jobs_in.fifo');
define('JOBS_OUT', JOBS_BASE . '/data/jobs_out.fifo');
define('JOBS_LOCK', JOBS_BASE . '/data/jobs.running');
touch(JOBS_LOCK);<file_sep>/Deferred.php
<?php
/**
* A blatent ripoff of twisted Deferred.
*/
class Deferred {
private $stack = array();
public $fired = false;
public $result = null;
/**
* Create a new deferred.
*
* If the $result parameter is passed then the deferred is considered to have
* already been fired, though callbacks/errbacks can still be added.
*
* @param string $result Optional starting result
*/
function __construct($result=null) {
if($result !== null) {
$this->result = $result;
$this->_fire();
}
}
function __destruct() {
if($this->result instanceof Exception) {
trigger_error("Deferred exception not handled: " . $this->result->getMessage());
}
}
/**
* Add a pair of callback/errbacks.
*/
function addCallbacks($callback, $errback, $callback_params=null, $errback_params=null) {
$this->stack[] = array($callback, $errback, $callback_params, $errback_params);
if($this->fired) $this->_fire();
return $this;
}
function addCallback($callback) {
if(!is_callable($callback)) throw new UnexpectedValueException("Callable required");
$params = array_slice(func_get_args(), 1);
return $this->addCallbacks($callback, null, $params);
}
function addErrback($errback) {
if(!is_callable($errback)) throw new UnexpectedValueException("Callable required");
$params = array_slice(func_get_args(), 1);
return $this->addCallbacks(null, $errback, null, $params);
}
function addBoth($callback) {
if(!is_callable($callback)) throw new UnexpectedValueException("Callable required");
$params = array_slice(func_get_args(), 1);
return $this->addCallbacks($callback, $callback, $params, $params);
}
function callback($result) {
if($this->fired) throw new Exception("Deferred already fired");
$this->result = $result;
$this->_fire();
}
function errback($e) {
if(!$e instanceof Exception) $e = new Exception($e);
$this->callback($e);
}
function succeeded() {
if(!$this->fired) throw new Exception("Deferred not fired");
return (! $this->result instanceof Exception);
}
private function _fire() {
$this->fired = true;
while($spec = array_shift($this->stack)) {
// select callback or errback
if($this->result instanceof Exception) {
$callable = $spec[1];
$params = $spec[3];
} else {
$callable = $spec[0];
$params = $spec[2];
}
// drop through to next if nothing set
if($callable === null) continue;
// execute and catch any exceptions
array_unshift($params, $this->result);
try {
$this->result = call_user_func_array($callable, $params);
} catch(Exception $e) {
$this->result = $e;
}
}
}
}
class DeferredList extends Deferred {
private $waiting = 0;
private $deferred_list = null;
function __construct($l) {
# setup counters
$this->deferred_list = $l;
$this->waiting = count($l);
# add a callback for each deferred that fires regardless
foreach($l as $d) $d->addBoth(array($this, '_finished'));
}
function _finished($result) {
$this->waiting--;
if($this->waiting == 0) {
$results = array();
foreach($this->deferred_list as $d) $results[] = array($d->succeeded(), $d->result);
$this->callback($results);
}
// TODO: Check this behaviour - should we just swallow exceptions?
// pass through the result
return $result;
}
}<file_sep>/bench.php
<?php
define('LOOP', 100000);
define('TEST_FIFO', 'test.fifo');
include "ConcurrentFIFO.php";
@unlink(TEST_FIFO);
$q = new ConcurrentFIFO(TEST_FIFO);
$start = microtime(true);
for($i=0; $i<LOOP; $i++) {
$q->enqueue('test_' . $i);
}
$ms = microtime(true) - $start;
printf("%30s %4d ms [%6d ops/s]\n", 'ENQUEUE', $ms * 1000, LOOP / $ms);
$start = microtime(true);
for($i=0; $i<LOOP; $i++) {
assert($q->dequeue() == 'test_' . $i);
}
$ms = microtime(true) - $start;
printf("%30s %4d ms [%6d ops/s]\n", 'DEQUEUE', $ms*1000, LOOP / $ms);
exit;
for($i=0; $i<LOOP; $i++) $q->append('test_' . $i);
$start = microtime(true);
for($i=LOOP-1; $i>=0; $i--) {
assert($q->pop() == 'test_' . $i);
}
$ms = microtime(true) - $start;
printf("%30s %4d ms [%6d ops/s]\n", 'POP', $ms*1000, LOOP / $ms);
<file_sep>/tests/RedisTest.php
<?php
require_once "bootstrap.php";
require_once dirname(__FILE__) . '/../RedisQueues.php';
class RedisTest extends PHPUnit_Framework_TestCase {
private $redis;
private $lists = array('list1', 'list2');
function setUp() {
foreach($this->lists as $list) {
$datafile = "data/{$list}.fifo";
if(file_exists($datafile)) unlink($datafile) or die("Failed to remove {$datafile}");
}
$this->redis = new RedisQueues('data');
}
function tearDown() {
$this->redis = null;
}
function testUsage() {
$this->assertSame(1, $this->redis->lpush('list1', 'test1'));
$this->assertSame(2, $this->redis->lpush('list1', 'test2'));
$this->assertSame(2, $this->redis->llen('list1'));
$this->assertSame(0, $this->redis->llen('list2'));
$this->assertSame('test1', $this->redis->rpop('list1'));
$this->assertSame('test2', $this->redis->rpoplpush('list1', 'list2'));
$this->assertSame('test2', $this->redis->rpop('list2'));
}
}
<file_sep>/tests/MultiProcessTest.php
<?php
require_once dirname(__FILE__) . '/../MultiProcess.php';
require_once "mp_func.php";
class MultiProcessTest extends PHPUnit_Framework_TestCase {
function setUp() {
MultiProcess::$level = LOG_WARNING;
}
function tearDown() {
MultiProcess::$level = LOG_INFO;
}
function testUsage() {
# do everything as one big test to avoid too many processes being created
$mp = new MultiProcessManager(dirname(__FILE__) . '/mp_func.php');
$l = array();
touch(MP_EXIT);
$this->assertTrue(file_exists(MP_EXIT));
$l[] = $mp->defer('mp_hi', 'Andy');
$l[] = $mp->defer('mp_hi', 'Bob');
$l[] = $mp->defer('mp_exit'); // fakes a process dying
$l[] = $mp->defer('mp_hi', 'Charlie');
$this->failure = $mp->defer('mp_err', 'Dave'); // throws an exception
$l[] = $this->failure;
$d = new DeferredList($l);
$d->addCallback(array($this, 'check_usage_results'));
# Swallow the exception
$this->failure->addErrback('pi');
$mp->process();
}
function testBigData() {
$mp = new MultiProcessManager(dirname(__FILE__) . '/mp_func.php');
$d = $mp->defer('mp_big_hi', 10000);
$d->addCallback(array($this, 'check_big_data_result'));
$mp->process();
}
function testCantFind() {
try {
$mp = new MultiProcessManager('nosuchfile.php');
$this->fail();
} catch(Exception $e) {
$this->assertSame($e->getMessage(), "Cannot locate 'nosuchfile.php'");
}
}
function check_big_data_result($result) {
$this->assertSame(strlen($result), 10000*2);
}
function check_usage_results($results) {
$this->assertSame(array_shift($results), array(true, "Hello Andy"));
$this->assertSame(array_shift($results), array(true, "Hello Bob"));
$this->assertSame(array_shift($results), array(true, "Exit okay"));
$this->assertSame(array_shift($results), array(true, "Hello Charlie"));
list($ok, $e) = array_shift($results);
$this->assertSame(false, $ok);
$this->assertSame($e->getMessage(), 'Test Exception');
$this->assertEmpty($results);
}
}<file_sep>/RedisQueues.php
<?php
require_once "ConcurrentFIFO.php";
/**
* Lightweight wrapper to emulate Redis behaviour using ConcurrentFIFO objects.
* Can be used to prototype for high IO systems.
*
* Currently implemented:
* LPUSH LPUSHX RPOP BRPOP RPOPLPUSH LLEN DEL EXISTS
*/
class RedisQueues {
private $dir;
private $mutex;
private $queues = array();
function __construct($dir) {
if(!is_dir($dir)) {
mkdir($dir);
}
$this->dir = $dir;
$this->mutex = fopen("{$this->dir}/redis.lock", 'w');
$this->mutex or die("Failed to open mutex");
}
function _get_filename($list) {
return sprintf("%s/%s.fifo", $this->dir, $list);
}
function _get_fifo($list, $create=true) {
if(!isset($this->queues[$list])) {
$datafile = $this->_get_filename($list);
if(!file_exists($datafile) && !$create) return null;
$this->queues[$list] = new ConcurrentFIFO($datafile);
}
return $this->queues[$list];
}
function exists($key) {
$list = $this->_get_fifo($key, false);
return ($list != null);
}
function del($key) {
$list = $this->_get_fifo($key);
$list->clear();
}
function llen($key) {
$list = $this->_get_fifo($key, false);
return ($list == null) ? 0 : $list->count();
}
function lpush($key, $value) {
$list = $this->_get_fifo($key);
return $list->enqueue($value);
}
function rpop($key) {
$list = $this->_get_fifo($key);
return $list->dequeue();
}
function brpop($key, $timeout) {
$list = $this->_get_fifo($key);
return $list->bdequeue($timeout);
}
function rpoplpush($source, $dest) {
flock($this->mutex, LOCK_EX) or die("Failed to get lock");
$data = $this->rpop($source);
if($data) $this->lpush($dest, $data);
flock($this->mutex, LOCK_UN);
return $data;
}
function lpushx($key, $value) {
$list = $this->_get_fifo($key, false);
if($list == null) return 0;
return $list->enqueue($value);
}
}
<file_sep>/examples/job_manager.php
<?php
require 'job_common.php';
$output = new ConcurrentFIFO(JOBS_OUT);
$workers = array();
$i=0;
while(file_exists(JOBS_LOCK)) {
while($data = $output->dequeue()) {
$parts = explode(':', $data);
$pid = $parts[0];
if(!isset($workers[$pid])) $workers[$pid] = array(0, 0);
if($parts[1]) {
$workers[$pid][0]++;
} else {
$workers[$pid][1]++;
}
}
sleep(2);
//if($i>=10) {
echo PHP_EOL . PHP_EOL;
foreach($workers as $worker=>$results) {
fprintf(STDERR, "%5d %5d [%3d timeouts]\n", $worker, $results[0], $results[1]);
}
clearstatcache();
fprintf(STDERR, "\nIN QUEUE : %d\n", filesize(JOBS_IN));
fprintf(STDERR, "OUT QUEUE: %d\n", filesize(JOBS_OUT));
$i=0;
//}
//$i++;
}<file_sep>/examples/load_test.php
<?
require "job_common.php";
define('WORKERS', 5);
define('CREATORS', 2);
$processes = array();
@unlink(JOBS_IN);
@unlink(JOBS_OUT);
$path = realpath(dirname(__FILE__));
for($i=0; $i<CREATORS; $i++) {
$processes[] = proc_open("php {$path}/job_creator.php", array(), $pipes);
}
for($i=0; $i<WORKERS; $i++) {
$processes[] = proc_open("php {$path}/job_worker.php", array(), $pipes);
}
sleep(1);
echo "\nRun job_manager.php to track output\n";
echo "Press ENTER to stop...";
fgets(STDIN);
echo "\n\nCleaning up...\n";
unlink(JOBS_LOCK); | bb10424e7874c4f24067cef906ad2eaf27ef9b0b | [
"Markdown",
"PHP"
] | 17 | PHP | tf198/phpqueues | f77f35d6011e8f49b14d3b23925dded8055a4b0b | 6b7f1253f101511fafc037d0eae25b0d2605085a |
refs/heads/master | <repo_name>darrylhodgins/TB6612FNG-Particle<file_sep>/firmware/tb6612fng-particle.cpp
#include "tb6612fng-particle.h"
/**
* Constructor if you're only using 1 channel of the TB6612FNG.
*/
Tb6612fng::Tb6612fng(int in1, int in2, int pwm) {
_numChannels = 1;
_pinStby = -1;
setupChannelPins(TB6612FNG_CHANNEL_A, in1, in2, pwm);
setPwmFrequency(0);
sleep();
}
/**
* Constructor if you're only using 1 channel of the TB6612FNG, with Standby control.
*/
Tb6612fng::Tb6612fng(int in1, int in2, int pwm, int stby) {
_numChannels = 1;
_pinStby = stby;
pinMode(_pinStby, OUTPUT);
setupChannelPins(TB6612FNG_CHANNEL_A, in1, in2, pwm);
setPwmFrequency(0);
sleep();
}
/**
* Constructor for both channels of the TB6612FNG without Standby control.
*/
Tb6612fng::Tb6612fng(int aIn1, int aIn2, int pwmA, int bIn1, int bIn2, int pwmB) {
_numChannels = 2;
_pinStby = -1;
setupChannelPins(TB6612FNG_CHANNEL_A, aIn1, aIn2, pwmA);
setupChannelPins(TB6612FNG_CHANNEL_B, bIn1, bIn2, pwmB);
setPwmFrequency(0); // Use default PWM frequency
sleep();
}
/**
* Constructor for both channels of the TB6612FNG with Standby control.
*/
Tb6612fng::Tb6612fng(int aIn1, int aIn2, int pwmA, int bIn1, int bIn2, int pwmB, int stby) {
_numChannels = 2;
_pinStby = stby;
pinMode(_pinStby, OUTPUT);
setupChannelPins(TB6612FNG_CHANNEL_A, aIn1, aIn2, pwmA);
setupChannelPins(TB6612FNG_CHANNEL_B, bIn1, bIn2, pwmB);
setPwmFrequency(0);
sleep();
}
/**
* Set PWM frequency for all motors. The PWM frequency must be the same
* for all pins in the same timer group. See the Particle documentation for more information.
* @param pwmFrequency PWM frequency in Hz. Accepts 1..65535Hz. Default is 500Hz.
*/
void Tb6612fng::setPwmFrequency(int pwmFrequency) {
for (int channel = 0; channel < _numChannels; channel++) {
setPwmFrequency(channel, pwmFrequency);
}
}
/**
* Set PWM frequency for a given motor channel. The PWM frequency must be the same
* for all pins in the same timer group. See the Particle documentation for more information.
* @param channel TB6612FNG_CHANNEL_A or TB6612FNG_CHANNEL_B
* @param pwmFrequency PWM frequency in Hz. Accepts 1..65535Hz. Default is 500Hz.
*/
void Tb6612fng::setPwmFrequency(int channel, int pwmFrequency) {
if (pwmFrequency < 1 || pwmFrequency > 65535) {
_pwmFrequency[channel] = 0;
} else {
_pwmFrequency[channel] = pwmFrequency;
}
}
/**
* Shuts down all motors. If STBY is connected, also puts chip in Standby mode.
*/
void Tb6612fng::sleep() {
if (_pinStby != -1) {
digitalWrite(_pinStby, LOW);
}
for (int channel = 0; channel < _numChannels; channel++) {
analogWrite(_pinPwm[channel], 0);
digitalWrite(_pinIn1[channel], LOW);
digitalWrite(_pinIn2[channel], LOW);
}
}
/**
* Configure the I/O direction for the pins on the given channel
* @param channel TB6612FNG_CHANNEL_A or TB6612FNG_CHANNEL_B
* @param in1 XIN1 pin number (where X is channel A or B)
* @param in2 XIN2 pin number
* @param pwm PWMX pin number
*/
void Tb6612fng::setupChannelPins(int channel, int in1, int in2, int pwm) {
_pinIn1[channel] = in1;
_pinIn2[channel] = in2;
_pinPwm[channel] = pwm;
pinMode(_pinIn1[channel], OUTPUT);
pinMode(_pinIn2[channel], OUTPUT);
pinMode(_pinPwm[channel], OUTPUT);
}
/**
* Set speed on all channels
* @param speed -255..255. Positive values cause forward rotation; negative values cause reverse. High-impedance at 0.
*/
void Tb6612fng::setSpeed(int speed) {
for (int channel = 0; channel < _numChannels; channel++) {
setSpeed(channel, speed);
}
}
/**
* Set speed on all channels
* @param channel TB6612FNG_CHANNEL_A or TB6612FNG_CHANNEL_B.
* @param speed -255..255. Positive values cause forward rotation; negative values cause reverse. High-impedance at 0.
*/
void Tb6612fng::setSpeed(int channel, int speed) {
if (speed != 0 && _pinStby != -1) {
digitalWrite(_pinStby, HIGH);
}
if (speed == 0) {
// TODO: allow configuration of short brake vs. high-impedance.
// For now, this just goes to high-impedance.
digitalWrite(_pinIn1[channel], LOW);
digitalWrite(_pinIn2[channel], LOW);
} else {
if (speed > 0) {
// forward
digitalWrite(_pinIn1[channel], HIGH);
digitalWrite(_pinIn2[channel], LOW);
} else {
// reverse
digitalWrite(_pinIn1[channel], LOW);
digitalWrite(_pinIn2[channel], HIGH);
}
if (_pwmFrequency[channel] > 0) {
analogWrite(_pinPwm[channel], abs(speed), _pwmFrequency[channel]);
} else {
analogWrite(_pinPwm[channel], abs(speed));
}
}
}
<file_sep>/README.md
# Library for TB6612FNG.
Totally untested at this point.
<file_sep>/firmware/tb6612fng-particle.h
#ifndef TB6612FNG_PARTICLE_H
#define TB6612FNG_PARTICLE_H
#include "application.h"
#define TB6612FNG_CHANNEL_A 0
#define TB6612FNG_CHANNEL_B 1
class Tb6612fng
{
public:
Tb6612fng(int in1, int in2, int pwm);
Tb6612fng(int in1, int in2, int pwm, int stby);
Tb6612fng(int aIn1, int aIn2, int pwmA, int bIn1, int bIn2, int pwmB);
Tb6612fng(int aIn1, int aIn2, int pwmA, int bIn1, int bIn2, int pwmB, int stby);
void setPwmFrequency(int pwmFrequency);
void setPwmFrequency(int channel, int pwmFrequency);
void sleep();
void setSpeed(int speed);
void setSpeed(int channel, int speed);
private:
void setupChannelPins(int channel, int in1, int in2, int pwm);
int _numChannels;
int _pinStby;
int _pinIn1[2];
int _pinIn2[2];
int _pinPwm[2];
int _pwmFrequency[2];
};
#endif
| f1d15889c0c553ad3f5dca890a15676ea7b235dd | [
"Markdown",
"C++"
] | 3 | C++ | darrylhodgins/TB6612FNG-Particle | bc0b7a640fd6a60321a8fbd03667e7ab748f5298 | d6658acbf5cfb0bcfdeb3804d1602bbcb1e245de |
refs/heads/main | <repo_name>SayHelloRoman/Professor<file_sep>/Professor/cogs/main.py
from dislash import *
from discord.ext import commands
from discord import Game
class mycog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_slash_command_error(self, ctx, ex):
raise ex
@commands.Cog.listener()
async def on_ready(self):
await self.bot.change_presence(activity=Game(name="github.com/SayHelloRoman/Professor"))
def setup(bot):
bot.add_cog(mycog(bot))<file_sep>/Professor/bot.py
import os
from discord import Intents
from discord.ext import commands
from dislash import slash_commands
bot = commands.Bot(command_prefix="!", intents=Intents.all())
slash = slash_commands.SlashClient(bot)
for file_name in os.listdir("./Professor/cogs"):
if file_name.endswith(".py"):
bot.load_extension(f"Professor.cogs.{file_name[:-3]}")
bot.run(os.environ.get('TOKEN'))<file_sep>/README.md

<p align="left">
<img src="https://img.shields.io/github/commit-activity/m/SayHelloRoman/Professor">
<img src="https://img.shields.io/github/stars/SayHelloRoman/Professor?style=social">
</p>
Профессор это бот для дискорд сервера [Сборище профессоров](https://discord.gg/xq5gQtW3BS)
Наш бот использует [Slash Command](https://blog.discord.com/slash-commands-are-here-8db0a385d9e6)
## Команды
- ``server_info`` - Отправить в embed сообщении информацию о сервере
- ``clear`` - Очистить чат
- ``ban`` - Забанить участника сервера
<file_sep>/Professor/cogs/ban.py
from dislash import *
from discord.ext import commands
from discord import Embed, Status
class Ban(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_commands.command(
name="ban",
description="ban member",
guild_ids=[753623970863120434],
options=[
Option("user", "user", Type.USER, required=True),
Option("reason", "reason ban", Type.STRING)
]
)
@commands.has_permissions(administrator=True)
async def ban(self, ctx):
user = ctx.get("user")
reason = ctx.get("reason", "Фейс пам чел ты в бане")
emb = Embed(title=f"{user} был забанен", color=0x0080ff)
await user.ban(reason=reason)
await ctx.send(embed=emb, delete_after=10)
def setup(bot):
bot.add_cog(Ban(bot))<file_sep>/Professor/cogs/server.py
from dislash import *
from discord.ext import commands
from discord import Embed, Status
class Server(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_commands.command(
name="server_info",
description="View server information",
guild_ids=[753623970863120434]
)
async def server_info(self, ctx):
emb = Embed(title=f"Информация о сервер {ctx.guild.name}", color=0x0080ff)
emb.set_thumbnail(url=ctx.guild.icon_url)
ok = [
{
"name": f"Владелец сервера:",
"value": ctx.guild.owner.mention
},
{
"name": f"Сервер создан:",
"value": f"{ctx.guild.created_at.strftime('%d.%m.%Y')}"
},
{
"name": "Количество эмодзи:",
"value": len(ctx.guild.emojis)
},
{
"name": "Количество бустов",
"value": ctx.guild.premium_subscription_count
},
{
"name": f"Количество участников {ctx.guild.member_count}:",
"value": "\n".join(
(
f"<:online:852663368418066473> Онлайн: {sum(i.status == Status.online for i in ctx.guild.members)}",
f"<:cpit:852665608751022090> Не активен: {sum(i.status == Status.idle for i in ctx.guild.members)}",
f"<:netrogay:852665562227802133> Не беспокоить: {sum(i.status == Status.dnd for i in ctx.guild.members)}",
f"<:offline:852665632302694401> Оффлайн: {sum(i.status == Status.offline for i in ctx.guild.members)}"
)
)
}
]
for i in ok:
emb.add_field(**i, inline=True)
await ctx.send(embed=emb)
def setup(bot):
bot.add_cog(Server(bot))<file_sep>/Professor/cogs/clear.py
from dislash import *
from discord.ext import commands
from discord import Embed, Status
class Clear(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_commands.command(
name="clear",
description="Clear chat",
guild_ids=[753623970863120434],
options=[
Option("amount", "Amount message", Type.INTEGER, required=True)
]
)
@commands.has_permissions(administrator=True)
async def clear(self, ctx):
amount = int(ctx.get("amount"))
emb = Embed(title=f"Удалено {amount} сообщений", color=0x0080ff)
await ctx.channel.purge(limit=amount)
await ctx.send(embed=emb, delete_after=10)
def setup(bot):
bot.add_cog(Clear(bot))<file_sep>/requirements.txt
discord.py==1.7.1
dislash.py==1.0.13 | 9b56c2d3518268af0d05fa70857767f75da8e37a | [
"Markdown",
"Python",
"Text"
] | 7 | Python | SayHelloRoman/Professor | 2df2b16edc27c7b42dee3781724dea7160c5a77a | 60cee5189c6c855803c54478192786731d544aff |
refs/heads/master | <file_sep>namespace UnitTest
{
#region << Using >>
using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Incoding.MSpecContrib;
using Machine.Specifications;
#endregion
////ncrunch: no coverage start
public class MSpecAssemblyContext : IAssemblyContext
{
#region IAssemblyContext Members
public void OnAssemblyStart()
{
var configure = Fluently
.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(ConfigurationManager.ConnectionStrings["Test"].ConnectionString)
.ShowSql())
.Mappings(configuration => configuration.FluentMappings.AddFromAssembly(typeof(Bootstrapper).Assembly));
PleasureForData.StartNhibernate(configure, true);
}
public void OnAssemblyComplete() { }
#endregion
}
////ncrunch: no coverage end
}<file_sep>#region << Using >>
using IncUI.App_Start;
using WebActivator;
#endregion
[assembly: PreApplicationStartMethod(
typeof(IncodingStart), "PreStart")]
namespace IncUI.App_Start
{
#region << Using >>
using IncUI.Controllers;
#endregion
public static class IncodingStart
{
public static void PreStart()
{
Bootstrapper.Start();
new DispatcherController(); // init routes
}
}
} | b453999e365dea931181320d73d85dc00b95ac6e | [
"C#"
] | 2 | C# | Incoding-Software/VSIX | e40b110521bcabb7bbaedd15c5f12ca7a1890bb1 | b061e71e3ca2684cdddca9268a07cff3b8e6b939 |
refs/heads/main | <file_sep># TencentOpenAPI
[TencentOpenAPI 3.5.5 pod化](https://wiki.connect.qq.com/sdk下载)
<file_sep>Pod::Spec.new do |s|
s.name = 'TencentOpenAPI_iOS_V3'
s.version = '3.5.5'
s.summary = 'TencentOpenAPI, why not pod'
s.homepage = 'https://github.com/fengyang0329/TencentOpenAPI'
s.license = 'MIT'
s.author = { 'longzh' => '<EMAIL>' }
s.source = { :git => 'https://github.com/fengyang0329/TencentOpenAPI.git', :tag => s.version.to_s }
s.frameworks = 'Security', 'CoreFoundation','MobileCoreServices','QuartzCore','SystemConfiguration', 'CoreGraphics', 'CoreTelephony', 'WebKit'
s.libraries = 'iconv', 'sqlite3', 'stdc++', 'z','z.1.1.3'
s.ios.deployment_target = '7.0'
s.resources = '*.bundle'
s.public_header_files = '*.framework/Headers/*.h'
s.source_files = '*.framework/Headers/*.{h}'
s.vendored_frameworks = '*.framework'
s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.requires_arc = true
end
| d924976f76d9e288cb97caf48196b684c38a9c8e | [
"Markdown",
"Ruby"
] | 2 | Markdown | fengyang0329/TencentOpenAPI | 1d54a68c0e903f3ad5fef2ff5ea33db12005d58b | 465519a4dd6e08564326ed89a5af932aff383144 |
refs/heads/master | <repo_name>drwilkins/1dviz<file_sep>/README.md
# 1dviz
Simple 1-dimensional data visualization for middle schoolers and up.
<file_sep>/app.R
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny);require(ggplot2);require(cowplot)
data(list=c("mtcars","iris","ToothGrowth"))
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("One Dimensional Data Visuals"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("df","Choose Dataset",c("Motor Trend Car Road Tests"="mtcars","Iris (Flower) Measurements"="iris","Vitamin C Effects on Tooth Growth"="ToothGrowth"),selected="mtcars"),
selectInput("vrbl","Choose Variable","",multiple=F),
checkboxGroupInput("plottype","Choose Plot Type",choices=c("Dot Plot"="dot","Box Plot"="box","Histogram"="hist" )), #,"Bar Plot"="bar"
tableOutput("stats")
),#end sidebarPanel
# Show a plot of the generated distribution
mainPanel(
fluidPage( fluidRow(
uiOutput("resizeG")),
fluidRow(
div(id='mydiv',class='simpleDiv',tags$br(),
tags$h4("First 6 lines of the dataset") ),#end div,
tableOutput("view")#,
)
)#end fluidPage
)#end mainPanel
)
)
# Define server logic required to draw a histogram
server <- function(input, output,session) {
DFinput<-reactive({
switch(input$df,"mtcars"=mtcars,"iris"=iris,"ToothGrowth"=ToothGrowth)
})
observe(updateSelectInput(session,"vrbl",choices=names(DFinput())) )
output$view<-renderTable(head(DFinput(),6))
output$stats<-renderTable({
values<-eval(parse(text=paste0("DFinput()$",input$vrbl)))
print(input$vrbl)
meanx<-mean(values,na.rm=T)
medianx<-median(values,na.rm=T)
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
modex<-Mode(values)
madx<-mean(abs(values-meanx),na.rm=T)
stats<-data.frame(Stat=c("Mean","Median","Mode","Mean Abs Dev"),Value=c(meanx,medianx,modex,madx))
return(stats)
})#End Stats
#------------------------
#Reactive value that will connect graph (G) & formatted graph (resizeG)
Ngrafs<-reactiveValues()
observe(Ngrafs$x<-length(input$plottype))
#observe(print(paste0("N=",Ngrafs$x)))
#------------------------
### Define main plot
output$G <- renderPlot({
# generate bins based on input$bins from ui.R
DF<-DFinput()
#basic graph template
g0<-ggplot()+theme_bw()+theme(axis.text=element_text(size=14),axis.title=element_text(face="bold",size=18))
grafs<-list()
#Dot Plot
if("dot"%in%input$plottype)
{
tmp<-g0+geom_dotplot(data=DF,aes_string(x=input$vrbl),dotsize=.8)+theme(axis.text.y=element_blank())
yrange<-ggplot_build(tmp)$layout$panel_params[[1]]$y.range
grafs$dot<-tmp+ylim(yrange)
}
# if(input$plottype=="bar")
# {
# G<-g0+geom_bar(data=DF,aes_string(x=input$vrbl))
# }
#Boxplot
if("box"%in% input$plottype)
{
grafs$box<-g0+geom_boxplot(data=DF,aes_string(x=1,y=input$vrbl))+coord_flip()+theme(axis.text.y=element_blank(),axis.title.y=element_blank())
}
#Histogram
if("hist" %in% input$plottype)
{
grafs$hist<-g0+geom_histogram(data=DF,aes_string(x=input$vrbl))
}
if(is.null(input$plottype)){
ggplot()+annotate("text",x=-1,y=1,label="Choose a plot type",size=12)+theme_nothing()
}else{
#print(paste0("N.grafs=",isolate(N.grafs)))
plot_grid(plotlist=grafs,align="v",ncol=1)#+coord_fixed(ratio=4/3)
}
})#end renderPlot
# #make outputplot scale the height based on # of graphs
# output$dynamicheight<-renderUI({
# plotOutput("G",height=200+200*output$plotheight)})
reactive(print(paste0("x=",N.grafs$x)))
output$resizeG<-renderUI({
#print(paste0("N.grafs=",isolate(N.grafs)))
x<-plotOutput("G",height=200+200*Ngrafs$x,width="auto")
return(x)
})
}#end serverside
# Run the application
shinyApp(ui = ui, server = server)
| 2dc3d1e12043dde2b1642aca1db82f3a23aaa33d | [
"Markdown",
"R"
] | 2 | Markdown | drwilkins/1dviz | 1d9144e26f6014ff8f58f117471c465067fc762f | dbf2df29485bf2029e3a0634c96688c373bd0ff5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.