branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>nirname/simple_tree<file_sep>/app/assets/javascripts/simple_tree.js
$(function() {
return $(document).on("click", ".simple-tree .expand", function(element) {
var parent;
parent = $(this).parent();
if (parent.hasClass("expand-closed")) {
parent.removeClass("expand-closed").addClass("expand-opened");
} else if (parent.hasClass("expand-opened")) {
parent.removeClass("expand-opened").addClass("expand-closed");
}
if ($(this).closest(".simple-tree").hasClass("simple-tree-bootstrap")) {
if (parent.hasClass("expand-closed")) {
return $(this).removeClass("icon-minus").addClass("icon-plus");
} else if (parent.hasClass("expand-opened")) {
return $(this).removeClass("icon-plus").addClass("icon-minus");
}
}
});
});
<file_sep>/app/assets/stylesheets/simple_tree.css
.simple-tree {
padding: 0px;
margin: 0px; }
.simple-tree .node {
list-style-type: none;
margin-left: 20px;
zoom: 1;
border-top: 1px dashed #a0a0a0;
background-image: url("simple_tree/vertical_line.png");
background-repeat: repeat-y;
background-position: left top; }
.simple-tree .node .node-action {
width: 20px;
height: 20px;
float: left; }
.simple-tree .node .node-content {
margin-left: 25px;
min-height: 20px;
line-height: 20px;
cursor: pointer; }
.simple-tree > .node:last-child, .simple-tree > .node.is-last {
background-image: url("simple_tree/half_vertical_line.png");
background-repeat: no-repeat;
background-position: left top; }
.simple-tree > .node {
padding: 0px;
margin: 0px; }
.simple-tree > .node:first-child, .simple-tree > .node.is-first {
border-top: medium none; }
.simple-tree .descendants {
padding: 0px;
margin: 0px; }
.simple-tree .descendants > .node:last-child, .simple-tree .descendants > .node.is-last {
background-image: url("simple_tree/half_vertical_line.png");
background-repeat: no-repeat;
background-position: left top; }
.simple-tree .expand-opened .expand {
background-image: url("simple_tree/mines_small.png");
background-repeat: no-repeat;
background-position: center center;
cursor: pointer; }
.simple-tree .expand-opened .descendants {
display: block; }
.simple-tree .expand-closed .expand {
background-image: url("simple_tree/plus_small.png");
background-repeat: no-repeat;
background-position: center center;
cursor: pointer; }
.simple-tree .expand-closed .descendants {
display: none; }
.simple-tree .expand-leaf .expand {
background-image: url("simple_tree/leaf_small.png");
background-repeat: no-repeat;
background-position: center center;
cursor: default; }
* html .simple-tree .node-content {
line-height: 20px; }
<file_sep>/simple_tree.gemspec
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "simple_tree/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "simple_tree"
s.version = SimpleTree::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/nirname/simple_tree.git"
s.summary = "SimpleTree html tree render"
s.description = "SimpleTree provides you styles and helpers for drawing html tree"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
#s.add_dependency "rails", "~> 4.0.0.beta1"
s.add_dependency "rails", "~>4.0"
s.add_dependency "jquery-rails", "~> 2.2.1"
#group :assets do
#s.add_dependency 'sass-rails', '~> 4.0.0.beta1'
#s.add_dependency 'coffee-rails', '~> 4.0.0.beta1'
#end
#s.add_development_dependency "sqlite3"
end
<file_sep>/test/dummy/app/views/tree/bootstrap.html.haml
%h1
Project hierarcy bootstrap style
(
= link_to("simple style", tree_simple_path)
)
.row-fluid
.span6
-# Use simple_tree and simple_node helpers
-# Look for source
= simple_tree class: "simple-tree-bootstrap" do
= draw_heirarcy
-# ... or you can just do it manually
-#= simple_tree do
-# = simple_node "app" do
-# = simple_node "assets" do
-# = simple_node "images"
-# = simple_node "javascripts" do
-# = simple_node "application.js"
-# = simple_node "tree.js"
-# = simple_node "stylesheets" do
-# = simple_node "application.css"
-# = simple_node "tree.css"
-# and so on ...
<file_sep>/test/dummy/config/routes.rb
Dummy::Application.routes.draw do
get "tree/simple" => "tree#simple"
get "tree/bootstrap" => "tree#bootstrap"
end
<file_sep>/README.md
# Simple Tree
This project rocks and uses MIT-LICENSE.
It contains simple javascripts, stylesheets and helpers for rendering expandable trees.
## Installation
Write in your Gemfile:
```ruby
gem "simple_tree", github: "nirname/simple_tree"
```
Add this string to your `application.css`
```css
/*
*= require simple_tree
*/
```
... and that one to your `application.js`
```js
//= require simple_tree/simple_tree
```
## Using
Now you can use the followin helpers inside your views:
* simple_tree
* simple_node
For example (using 'haml'):
```haml
= simple_tree do
= simple_node "First node" do
= simple_node "Sub-node"
= simple_node "Second node"
```
... produces html code that will be similar to the one below:
```html
<ul class="simple-tree ">
<li class="node expand-opened">
... First node ...
<ul class="descendants">
<li class="node expand-leaf">
... Sub-node ...
</li>
</ul>
</li>
<li class="node expand-leaf">
... Second node ...
</li>
</ul>
```
You can pass `:opened` option to node:
```haml
= simple_tree do
= simple_node "Opened node", opened: true do
= simple_node "Leaf 1"
= simple_node "Closed node" do
= simple_node "Leaf 2"
```
By default node is supposed to be closed.
## Customizing
### HTML options
You are able to pass additional HTML options to your tree and its' nodes by passing them as a hash to your helper's calls:
```haml
= simple_tree class: "my_simple_tree" do
= node "My node", "data-id" => 1
```
### Bootstrap
If you are using [`bootstrap`](https://github.com/twitter/bootstrap "Twitter Bootstrap on GitHub") (check your `Gemfile`):
```ruby
gem "twitter-bootstrap-rails"
```
... and want to see similar styled tree add this string to your `application.css`
```css
/*
*= require simple_tree_bootstrap
*/
```
... then add the `simple-tree-bootstrap` class as an option:
```haml
= simple_tree class: "simple-tree-bootstrap" do
```
#### Node buttons
You can add some buttons to nodes by passing html code to node content.
Use `.btn-tree` and `.btn-group-tree` classes with [`bootstrap`](https://github.com/twitter/bootstrap "Twitter Bootstrap on GitHub")
`.btn` and `.btn-group` classes to get pretty style inline buttons, fox example:
```haml
.btn.btn-tree
.btn-group.btn-group-tree
```
You can still combine it with different classes such as `.btn-primary` and so on.
## Interaction
It can be easily integrated with existing gems, such as sortable_tree, for example:
```haml
= simple_tree do
= just_tree @your_tree, render_module: YourTreeHelper %>
```
... where YourTreeHelper module might looks like:
```ruby
module YourTreeHelper
class Render
class << self
attr_accessor :h, :options
def render_node(h, options)
@h, @options = h, options
node_content = options[:node].name)
if options[:children].blank?
h.simple_node(node_content) # draw leaf
else
h.simple_node(node_content) do # draw node
h.raw options[:children]
end
end
end
end
end
end
```
<file_sep>/lib/simple_tree/view_helpers.rb
module SimpleTree
module ViewHelpers
def simple_tree(options = {}, &block)
if block_given?
block = capture &block
"<ul class='simple-tree #{ options[:class] }'>
#{ block }
</ul>".html_safe
else
""
end
end
def simple_node(content, options = {}, &block)
options = HashWithIndifferentAccess.new(options)
if block_given?
block_content = capture &block
descendatns = "
<ul class='descendants'>
#{ block_content }
</ul>"
if (options[:opened] == true)
css_expand_class = "expand-opened"
css_icon_class = "icon-minus"
else
css_expand_class = "expand-closed"
css_icon_class = "icon-plus"
end
else
css_expand_class = "expand-leaf"
css_icon_class = ""
end
"<li class='node #{ css_expand_class } #{ options[:class] }' #{ hash_to_html_options(options.except(:class)) }>
<div class='node-action expand #{ css_icon_class }'></div>
<div class='node-content'>
#{ content }
</div>
#{ descendatns }
</li>".html_safe
end
def hash_to_html_options(hash)
hash.map{ |p, v| "#{p.to_s}=\"#{v.to_s}\"" }.join(" ")
end
end
end
<file_sep>/lib/simple_tree.rb
require "simple_tree/view_helpers"
module SimpleTree
#def self.setup
# begin
# yield self
# end
#end
class Engine < Rails::Engine
# auto wire
initializer "simple_tree.initialize" do |app|
ActionView::Base.send :include, SimpleTree::ViewHelpers
end
end
# configure our plugin on boot
#initializer ".initialize" do |app|
# ActionView::Base.send :include, SimpleTree::ViewHelpers
#end
end
<file_sep>/test/dummy/app/helpers/tree_helper.rb
module TreeHelper
def draw_heirarcy(path = "")
raw(Dir[Rails.root.join(path).to_s + "/*"].sort.group_by{ |content| File.directory?(content) }.instance_eval{ |h| [h[true], h[false]] }.compact.flatten.map do |content|
name = Pathname.new(content).basename.to_s
title = link_to(name, "#") +
content_tag(:div, class: "btn btn-tree") do
content_tag(:i, nil, class: "icon-list")
end +
content_tag(:div, class: "btn btn-tree") do
content_tag(:i, nil, class: "icon-th")
end
if File.directory?(content)
simple_node title do
draw_heirarcy content
end
else
simple_node title
end
end.join)
end
end
<file_sep>/test/dummy/app/controllers/tree_controller.rb
class TreeController < ApplicationController
def simple
render layout: "simple"
end
def bootstrap
render layout: "bootstrap"
end
end
<file_sep>/app/assets/stylesheets/simple_tree_bootstrap.css
.simple-tree.simple-tree-bootstrap {
padding: 0px;
margin: 0px; }
.simple-tree.simple-tree-bootstrap .node {
list-style-type: none;
margin-left: 37px;
margin-top: 5px;
zoom: 1;
border-top: none;
background-image: url("simple_tree/vertical_line.png");
background-position: 6px top;
background-repeat: repeat-y; }
.simple-tree.simple-tree-bootstrap .node .node-action {
border: 1px solid #dddddd;
border-radius: 5px;
background-color: white;
width: 30px;
height: 30px;
float: left; }
.simple-tree.simple-tree-bootstrap .node .node-content {
border: 1px solid #dddddd;
border-radius: 5px;
padding-left: 10px;
margin-left: 37px;
height: 30px;
line-height: 30px;
cursor: pointer; }
.simple-tree.simple-tree-bootstrap .node .node-content .btn-tree {
padding: 4px;
width: 20px;
float: right;
margin-right: 5px; }
.simple-tree.simple-tree-bootstrap .node .node-content .btn-tree:first-child, .simple-tree.simple-tree-bootstrap .node .node-content .btn-tree:first-of-type, .simple-tree.simple-tree-bootstrap .node .node-content .btn-tree.is-first {
margin-right: 0; }
.simple-tree.simple-tree-bootstrap .node .node-content .btn-group-tree {
float: right; }
.simple-tree.simple-tree-bootstrap .node .node-content .btn-group-tree .btn {
padding: 4px;
width: 20px; }
.simple-tree.simple-tree-bootstrap > .node:last-child, .simple-tree.simple-tree-bootstrap > .node.is-last {
background-image: none; }
.simple-tree.simple-tree-bootstrap > .node {
margin-left: 0px; }
.simple-tree.simple-tree-bootstrap > .node:first-child, .simple-tree.simple-tree-bootstrap > .node.is-first {
margin-top: 0; }
.simple-tree.simple-tree-bootstrap .descendants {
padding: 0px;
margin: 0px; }
.simple-tree.simple-tree-bootstrap .descendants > .node:last-child, .simple-tree.simple-tree-bootstrap .descendants > .node.is-last {
background-image: none; }
.simple-tree.simple-tree-bootstrap .expand-opened .expand {
background-image: none;
text-align: center;
padding-top: 8px;
height: 22px;
cursor: pointer; }
.simple-tree.simple-tree-bootstrap .expand-opened .descendants {
display: block; }
.simple-tree.simple-tree-bootstrap .expand-closed .expand {
background-image: none;
text-align: center;
padding-top: 8px;
height: 22px;
cursor: pointer; }
.simple-tree.simple-tree-bootstrap .expand-closed .descendants {
display: none; }
.simple-tree.simple-tree-bootstrap .expand-leaf .expand {
background-image: url("simple_tree/dot.png");
background-position: center center;
background-repeat: no-repeat;
cursor: default; }
* html .simple-tree.simple-tree-bootstrap .node-content {
line-height: 30px; }
|
4638cd22b883b4c63b2b5b84f94453a582efe722
|
[
"Markdown",
"Ruby",
"JavaScript",
"Haml",
"CSS"
] | 11 |
Markdown
|
nirname/simple_tree
|
28be761b260a06ba3fb21abb5052b40f79bfcadc
|
9d428af7f4ecfa5d2ae1b20a67c2b3ed8f1018b2
|
refs/heads/master
|
<repo_name>darthzippy/Sky-Asylum-Web-page---Webby<file_sep>/TODO.mdown
# SKY ASLYUM WEB SITE - TODO #
## INDEX ##
***
## IN PRODUCTION ##
***
## MISSION ##
Remove mission tab completely (?)
Mission statement "Exploring truth through film" as tagline (in header?) - replace 'Making great movies so you don't have to'
Repurpose mission text to main page intro paragraph
Rename 'Mission' tab to 'The Truth' and rewrite mission statment there
***
## INMATES ##
***
## SERVICES ##
Narrative
Documentary
Events
VHS Transfers
[Web Design]
|
d53dff6ff7d77cace7710dae2112c9326859a65c
|
[
"Markdown"
] | 1 |
Markdown
|
darthzippy/Sky-Asylum-Web-page---Webby
|
b6e28fe4a0443e436ce697877711244962219166
|
38095f33fe1035ee6e374aad370cbb97a36ac6bd
|
refs/heads/master
|
<repo_name>Aubrie-StLouis/nctc<file_sep>/review/review.html
<!doctype html>
<html>
<head>
<title>North Country Tree Care VT</title>
<link rel="stylesheet" href="../css/normalize.css">
<link rel="stylesheet" href="../css/main-2.css">
<link href="https://fonts.googleapis.com/css?family=Cormorant+Garamond:400,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=EB+Garamond" rel="stylesheet">
</head>
<body>
<header id="home">
<div class="full-width">
<h1 id="nct">North Country Tree Care</h1>
</div>
<div class="full-width">
<nav>
<ul>
<li><a href="../index.html">Home</a></li>
<li><a href="../index.html#services">Services</a></li>
<li><a href="../about/about.html">About</a></li>
<li><a href="../review/review.html">Reviews</a></li>
<li><a href="../estimate/estimate.html">Request an Estimate</a></li>
<li><a href="../contact/contact.html">Contact</a></li>
</ul>
</nav>
</div>
</header>
<main>
<section id="reviews">
<div class="full-width">
<h2>Helping Customers for Over 30 Years</h2>
<h3>Hear what they have to say</h3>
</div>
<section id="collage">
<div class="full-width" id="two-reviews">
<div class="half-width" id="one">
<p>"Tracy- Thanks for all the hard work, the fair prices, and the good chats- GREAT STUFF!" -Mike</p>
</div>
<div class="half-width" id="two">
<p> "Dear Tracy, Enclosed is our check for Invoice #**** for tree work at the Landon Lake House. Thanks very much for your good work!" Sincerely yours, - <NAME></p>
</div>
</div>
<div class="full-width" id="three">
<p>"Thank you Tracy for the fine, very professional work you did on our property. We are glad you came in July, so we will have a month to enjoy the results! Best Regards to you + your helper." -<NAME>.</p>
</div>
<div class="full-width" id="thank-you">
<div class="half-width" id="four">
<p>"Thank you Tracy. Will seem good to not worry about that tree falling on our home this winter." Happy Holidays - Mike + Audrey Hearne</p>
</div>
<div class="half-width" id="five">
<p>Thanks very much, Tracy. I am glad these have been taken down out of harms way." Best Wishes - <NAME></p>
</div>
</div>
</section>
<div class="full-width" id="reviews-foot">
<div class="quarter-width">
<h4>Fully Insured</h4>
</div>
<div class="quarter-width">
<h4>802-533-2951</h4>
</div>
<div class="quarter-width">
<h4><a href="mailto:<EMAIL>"><EMAIL></a></h4>
</div>
<div class="quarter-width">
<h4><a href="#home">Back to Top</a></h4>
</div>
</div>
</section>
</main>
</body>
</html><file_sep>/css/main.css
/***** BASE STYLES *****/
body {
font-family: 'EB Garamond', serif;
background: linear-gradient(#ffffff, #005826, #01A935);
}
/****** GRID ******/
.full-width {
width: 1200px;
margin: 0 auto;
}
.half-width {
width: 600px;
float: left;
}
.third-width {
width: 400px;
float: left;
}
.quarter-width {
width: 300px;
float: left;
}
/***** HEADER *****/
header #nct {
font-family: 'Cormorant Garamond', serif;
font-size: 120px;
color: #005826;
padding: 20px, 0px,0px,0px;
margin-left: 100px;
margin-top: -10px;
text-decoration: underline;
}
header #care {
font-family: 'Cormorant Garamond', serif;
font-size: 120px;
color: #005826;
padding-top: -10px;
margin-top: -85px;
margin-left: 468px;
text-decoration: underline;
}
nav {
float: left;
padding: 0px 20px;
margin-left: -20px;
margin-top: -55px;
}
nav ul li {
display: inline-block;
}
nav ul li a {
text-transform: uppercase;
text-decoration: underline;
font-size: 28px;
color: #005826;
padding-left: 50px;
}
header #logo {
padding: 20px, auto;
margin-left: 360px;
margin-top: 10px;
}
header h3 {
font-size: 40px;
color: #005826;
}
/***** SERVICES *****/
#services h2 {
font-family: 'Cormorant Garamond', serif;
font-size: 70px;
text-decoration: underline;
padding: 20px;
margin-left: 370px;
margin-top: 30px;
color: #000000;
}
#srvc-list {
font-size: 26px;
color: #000000;
padding: auto;
margin-left: 55px;
margin-top: 10px;
}
#srvc-foot {
font-size: 26px;
color: #000000;
padding: auto;
margin-left: 75px;
}
#services a {
color:#000000;
}
/***** ABOUT *****/
#about h1 {
font-size: 70px;
font-family: 'Cormorant Garamond', serif;
color: #ffffff;
padding: 0px;
margin-left: 345px;
text-decoration: underline;
}
#about #selfie {
padding: 0px;
margin-left: 170px;
margin-top: 60px;
border: solid 10px #ffffff;
}
#about p {
font-size: 26px;
color: #ffffff;
}
#about-foot {
font-size: 26px;
color: #ffffff;
padding: auto;
margin-left: 90px;
}
#about a {
color: #ffffff;
}
/***** REVIEWS *****/
#reviews h2 {
font-family: 'Cormorant Garamond', serif;
text-decoration: underline;
font-size: 70px;
padding-top: 40px;
margin-left: 75px;
}
#reviews h3 {
font-family: 'Cormorant Garamond', serif;
font-size: 40px;
padding: 0px;
margin-left: 375px;
margin-top: 10px;
}
#two-reviews, #thank-you{
font-size: 30px;
margin-left: 190px;
}
#one, #two, #three, #five{
padding: 50px;
width: 450px;
}
#four {
font-size: 30px;
width: 700px;
}
#reviews-foot {
font-size: 26px;
padding: auto;
margin-left: 213px;
}
#reviews a {
color: #000000;
}
/***** ESTIMATES *****/
#estimates h2 {
font-family: 'Cormorant Garamond', serif;
text-decoration: underline;
font-size: 70px;
color: #ffffff;
padding: auto;
margin-left: 95px;
}
#estimates p {
font-size: 26px;
width: 300px;
background: #ffffff;
background-size: cover;
padding: auto;
margin-left: 425px;
text-align: center;
}
#estimates h3 {
font-size: 30px;
background: #ffffff;
background-size: cover;
margin-left: 525px;
width: 80px;
text-align: center;
}
#estimate-foot {
font-size: 26px;
color: #ffffff;
padding: auto;
margin-left: 213px;
}
#estimates a {
color: #ffffff;
}
/***** CONTACT *****/
#contact h2 {
font-size: 70px;
font-family: 'Cormorant Garamond', serif;
text-decoration: underline;
padding: auto;
margin-left: 425px;
color: #ffffff;
}
#contact h3 {
font-size: 30px;
display: inline-block;
padding: 30px;
margin-left: 150px;
color: #ffffff;
}
|
af9ad6bd37788e2a077a0da52ab0d53e60611a57
|
[
"HTML",
"CSS"
] | 2 |
HTML
|
Aubrie-StLouis/nctc
|
6e6914eeb20e733b2474ff387dabd328d9251cce
|
b7eea667f4c45481bc031782ac296a8d4671f664
|
refs/heads/develop
|
<file_sep>JSONEditor.defaults.editors.number = JSONEditor.defaults.editors.string.extend({
sanitize: function(value) {
return (value+"").replace(/[^0-9\.\-eE]/g,'');
},
getNumColumns: function() {
return 2;
},
getValue: function() {
return this.value*1;
}
});
<file_sep>.jse-modal{
background-color: white;
border: 1px solid black;
position: absolute;
z-index: 10;
box-shadow:3px 3px black;
}
.jse-disableHeader, .jse-disableLabel{
color: #ccc;
}
.jse-CheckboxLabel{
font-weight: normal;
}
.jse-Checkbox{
display:inline-block;
width:auto;
}
.jse-MultiCheckboxLabel{
display:block;
}
.jse-MultiCheckboxControl{
display: inline-block;
margin-right: 20px;
}
.jse-Switcher{
background-color:transparent;
display: inline-block;
height:auto;
width:auto;
font-style:italic;
font-weight:normal;
margin-bottom: 0;
margin-left: 5px;
padding:0 0 0 3px;
}
.jse-TextareaInput{
width:100%;
height:300px;
box-sizing:border-box;
}
.jse-IndentedPanel{
padding-left:10px;
margin-left:10px;
border-left:1px solid #ccc;
}
.jse-Tab{
border: 1px solid #ccc;
borderWidth: 1px 0 1px 1px;
textAlign: center;
lineHeight: 30px;
borderRadius: 5px;
borderBottomRightRadius: 0;
borderTopRightRadius: 0;
fontWeight: bold;
cursor: pointer;
}
.jse-TabActive{
opacity: 1;
background: white;
}
.jse-TabInActive{
opacity:0.5;
background: none;
}
.jse-BlockLink{
display: block;
}
.jse-Media{
width:100%;
}
.jse-{
}
.jse-{
}
<file_sep>// Base Foundation theme
JSONEditor.defaults.themes.foundation = JSONEditor.AbstractTheme.extend({
getChildEditorHolder: function() {
var el = document.createElement('div');
el.style.marginBottom = '15px';
return el;
},
getSelectInput: function(options) {
var el = this._super(options);
el.style.minWidth = 'none';
el.style.padding = '5px';
el.style.marginTop = '3px';
return el;
},
getSwitcher: function(options) {
var el = this._super(options);
el.style.paddingRight = '8px';
return el;
},
afterInputReady: function(input) {
if(this.closest(input,'.compact')) {
input.style.marginBottom = 0;
}
input.group = this.closest(input,'.form-control');
},
getFormInputLabel: function(text, required) {
var el = this._super(text);
el.style.display = 'inline-block';
if(required)el.className += " required";
return el;
},
getFormInputField: function(type) {
var el = this._super(type);
el.style.width = '100%';
el.style.marginBottom = type==='checkbox'? '0' : '12px';
return el;
},
getFormInputDescription: function(text) {
var el = document.createElement('p');
el.textContent = text;
el.style.marginTop = '-10px';
el.style.fontStyle = 'italic';
return el;
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'panel';
el.style.paddingBottom = 0;
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.display = 'inline-block';
el.style.marginLeft = '10px';
el.style.verticalAlign = 'middle';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'button-group';
return el;
},
getButton: function(text, icon, title) {
var el = this._super(text, icon, title);
el.className += ' small button';
return el;
},
addInputError: function(input,text) {
if(!input.group) return;
input.group.className += ' error';
if(!input.errmsg) {
input.insertAdjacentHTML('afterend','<small class="error"></small>');
input.errmsg = input.parentNode.getElementsByClassName('error')[0];
}
else {
input.errmsg.style.display = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.errmsg) return;
input.group.className = input.group.className.replace(/ error/g,'');
input.errmsg.style.display = 'none';
},
getProgressBar: function() {
var progressBar = document.createElement('div');
progressBar.className = 'progress';
var meter = document.createElement('span');
meter.className = 'meter';
meter.style.width = '0%';
progressBar.appendChild(meter);
return progressBar;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
progressBar.firstChild.style.width = progress + '%';
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
progressBar.firstChild.style.width = '100%';
}
});
// Foundation 3 Specific Theme
JSONEditor.defaults.themes.foundation3 = JSONEditor.defaults.themes.foundation.extend({
getHeaderButtonHolder: function() {
var el = this._super();
el.style.fontSize = '.6em';
return el;
},
getFormInputLabel: function(text, required) {
var el = this._super(text);
el.style.fontWeight = 'bold';
if(required)el.className += " required";
return el;
},
getTabHolder: function() {
var el = document.createElement('div');
el.className = 'row';
el.innerHTML = "<dl class='tabs vertical two columns'></dl><div class='tabs-content ten columns'></div>";
return el;
},
setGridColumnSize: function(el,size) {
var sizes = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve'];
el.className = 'columns '+sizes[size];
},
getTab: function(text) {
var el = document.createElement('dd');
var a = document.createElement('a');
a.setAttribute('href','#');
a.appendChild(text);
el.appendChild(a);
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
var el = document.createElement('div');
el.className = 'content active';
el.style.paddingLeft = '5px';
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s*active/g,'');
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
}
});
// Foundation 4 Specific Theme
JSONEditor.defaults.themes.foundation4 = JSONEditor.defaults.themes.foundation.extend({
getHeaderButtonHolder: function() {
var el = this._super();
el.style.fontSize = '.6em';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'columns large-'+size;
},
getFormInputDescription: function(text) {
var el = this._super(text);
el.style.fontSize = '.8rem';
return el;
},
getFormInputLabel: function(text, required) {
var el = this._super(text);
el.style.fontWeight = 'bold';
if(required)el.className += " required";
return el;
}
});
// Foundation 5 Specific Theme
JSONEditor.defaults.themes.foundation5 = JSONEditor.defaults.themes.foundation.extend({
getFormInputDescription: function(text) {
var el = this._super(text);
el.style.fontSize = '.8rem';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'columns medium-'+size;
},
getButton: function(text, icon, title) {
var el = this._super(text,icon,title);
el.className = el.className.replace(/\s*small/g,'') + ' tiny';
return el;
},
getTabHolder: function() {
var el = document.createElement('div');
el.innerHTML = "<dl class='tabs vertical'></dl><div class='tabs-content vertical'></div>";
return el;
},
getTab: function(text) {
var el = document.createElement('dd');
var a = document.createElement('a');
a.setAttribute('href','#');
a.appendChild(text);
el.appendChild(a);
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
var el = document.createElement('div');
el.className = 'content active';
el.style.paddingLeft = '5px';
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s*active/g,'');
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
}
});
JSONEditor.defaults.themes.foundation6 = JSONEditor.defaults.themes.foundation5.extend({
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'callout secondary';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'button-group tiny';
el.style.marginBottom = 0;
return el;
},
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.display = 'block';
return el;
},
getFormControl: function(label, input, description) {
var el = document.createElement('div');
el.className = 'form-control';
if(label) el.appendChild(label);
if(input.type === 'checkbox') {
label.insertBefore(input,label.firstChild);
}
else if (label) {
label.appendChild(input);
} else {
el.appendChild(input);
}
if(description) label.appendChild(description);
return el;
},
addInputError: function(input,text) {
if(!input.group) return;
input.group.className += ' error';
if(!input.errmsg) {
var errorEl = document.createElement('span');
errorEl.className = 'form-error is-visible';
input.group.getElementsByTagName('label')[0].appendChild(errorEl);
input.className = input.className + ' is-invalid-input';
input.errmsg = errorEl;
}
else {
input.errmsg.style.display = '';
input.className = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.errmsg) return;
input.className = input.className.replace(/ is-invalid-input/g,'');
if(input.errmsg.parentNode) {
input.errmsg.parentNode.removeChild(input.errmsg);
}
},
});
|
6f075ea3d7a0aa54e6a4cce7f3d22399fc494b6d
|
[
"CoffeeScript",
"JavaScript",
"CSS"
] | 3 |
CoffeeScript
|
azavea/json-editor
|
b44361273567fce38ae81f0f28700b334ad35a85
|
8e3a2884031732577aae6ccc4130ce6b21faf7be
|
refs/heads/master
|
<file_sep>var pascam = require('com.skypanther.picatsize');
var targetWidth = 1024;
var targetHeight = 800;
$.index.addEventListener('open', function () {
if (parseInt(Ti.Platform.version.split(".")[0]) >= 6 && !Ti.Media.hasCameraPermissions()) {
Ti.Media.requestCameraPermissions(function (e) {
if (e.success) {
console.log("Camera permission granted.");
} else {
alert("You have denied the app permission to take pictures. Clicking either button will crash the app.\n\nPlease update the permissions in the Settings app or uninstall and try again.");
}
});
}
});
function openCameraActivity(e) {
if (!Ti.Media.hasCameraPermissions()) {
alert('oopsie');
return;
}
var overlay = Ti.UI.createView({});
var clickBt = Ti.UI.createButton({
title: "click me",
bottom: 10,
right: 20
});
overlay.add(clickBt);
clickBt.addEventListener('click', function () {
pascam.takePicture();
});
var closeBt = Ti.UI.createButton({
title: "close me",
bottom: 10,
left: 20
});
overlay.add(closeBt);
closeBt.addEventListener('click', function () {
pascam.hideCamera();
});
pascam.showCamera({
overlay: overlay, //setting the overlay makes the module start PASCameraActivity
autohide: false, //according to the docs, autohide must be false for takePicture() to work
success: function (e) {
Ti.API.info('Our type was: ' + e.mediaType);
Ti.API.info("bytes: " + e.media.length);
Ti.API.info("height: " + e.media.height);
Ti.API.info("width: " + e.media.width);
Ti.API.info("apiName: " + e.media.apiName);
$.img.image = e.media;
console.log(e);
pascam.hideCamera();
},
error: function (e) {
Ti.API.info(JSON.stringify(e));
},
saveToPhotoGallery: false,
mediaTypes: [pascam.MEDIA_TYPE_PHOTO],
targetWidth: targetWidth,
targetHeight: targetHeight
});
}
function openNativeCamera(e) {
if (!Ti.Media.hasCameraPermissions()) {
alert('oopsie');
return;
}
pascam.showCamera({
showControls: true,
autohide: true,
success: function (e) {
Ti.API.info('Our type was: ' + e.mediaType);
Ti.API.info("bytes: " + e.media.length);
Ti.API.info("height: " + e.media.height);
Ti.API.info("width: " + e.media.width);
Ti.API.info("apiName: " + e.media.apiName);
console.log(e);
//resize the media blob "manually"
//scale based on the largest side of the picture (use Math.max() for scaling on the littlest side)
var scale = Math.min(targetWidth / e.media.width, targetHeight / e.media.height);
var blob = e.media.imageAsResized(e.media.width * scale, e.media.height * scale);
Ti.API.info("new size: " + blob.width + "x" + blob.height);
$.img.image = blob;
//blob can be saved to a file if needed
},
error: function (e) {
Ti.API.info(JSON.stringify(e));
},
saveToPhotoGallery: false,
mediaTypes: [pascam.MEDIA_TYPE_PHOTO],
targetWidth: targetWidth,
targetHeight: targetHeight
});
}
$.index.open();<file_sep>PicAtSize
===========================================
Note: Initial support for Titanium 6.0 Beta added.
PicAtSize is an Android module that lets you take a "_PIC_ture _AT_ a _SIZE_" you specify. By taking a photo smaller than the camera's native size, you create smaller files which are faster to upload, faster to process (resize, crop, rotate), and which create less memory-related issues. It was the memory issue that inspired this module.
Natively, Android supports the `camera.getParameters.setPictureSize()` method. But Titanium's Ti.Media module does not expose this functionality. This module makes that available for you to use.
A few notes:
* With this module, you must use a camera overlay or you'll get the native camera which has no size-specifying support.
* You will get a photo at the closest, next larger size supported by the device's camera. It may not, and probably won't match the exact size you specify. (Reportedly, some Android devices will not take any photo if you were to specify a size that the camera doesn't support.)
I want to send a huge thanks to @olivier_morandi who helped me get this module working. I was close, but could never have finished it without his help. Thanks!!!
## INSTALL THE MODULE
### Use GitTio
Use GitTio, as it will download, unzip, and install the module for you.
```shell
gittio install com.skypanther.picatsize
```
### Manually
Download the zip from the dist folder, unzip, place in your project's modules folder.
Register in the tiapp.xml:
```xml
<modules>
<module platform="android">com.skypanther.picatsize</module>
</modules>
```
## USING THE MODULE IN CODE
See the included sample app (in the example directory).
```javascript
// instantiate and specify your target size
var pascam = require('com.skypanther.picatsize');
var targetWidth = 1024;
var targetHeight = 800;
// create the necessary overlay
var overlay = Ti.UI.createView();
var clickBt = Ti.UI.createButton({
title: "Take Photo",
bottom: 10,
right: 20
});
overlay.add(clickBt);
clickBt.addEventListener('click', function() {
pascam.takePicture();
});
var closeBt = Ti.UI.createButton({
title: "Cancel",
bottom: 10,
left: 20
});
overlay.add(closeBt);
closeBt.addEventListener('click', function() {
pascam.hideCamera();
});
// show the camerapascam.showCamera({
overlay: overlay, // setting the overlay makes the module start PASCameraActivity
autohide: false, // autohide must be false for takePicture() to work
success: function (e) {
Ti.API.info("bytes: " + e.media.length);
Ti.API.info("height: " + e.media.height);
Ti.API.info("width: " + e.media.width);
pascam.hideCamera();
},
error: function (e) {
Ti.API.info(JSON.stringify(e));
},
saveToPhotoGallery: false,
mediaTypes: [pascam.MEDIA_TYPE_PHOTO],
targetWidth: targetWidth,
targetHeight: targetHeight
});
```
# License
Apache License, Version 2.0
<file_sep>titanium.platform=/Users/timpoulsen/Library/Application Support/Titanium/mobilesdk/osx/7.2.0.GA/android
android.platform=/Users/timpoulsen/android-sdk/platforms/android-27
google.apis=/Users/timpoulsen/android-sdk/add-ons/addon-google_apis-google-27
android.ndk=/Users/${user.name}/android-ndk-r10e
<file_sep># picatsize Module
## Description
PicAtSize is an Android module that lets you take a "_PIC_ture _AT_ a _SIZE_" you specify.
## How to use:
See the main README file and the example application for usage info.
## Author
@skypanther
## License
Apache License, Version 2.0
<file_sep>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package com.skypanther.picatsize;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.appcelerator.kroll.common.Log;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
public class PASCamera
{
private static final String TAG = "PASCamera";
private static Camera camera;
public PASCamera()
{
if (camera == null) {
Log.i(TAG, "Camera created.", Log.DEBUG_MODE);
camera = Camera.open();
}
}
public Camera getCamera()
{
return camera;
}
// add some fancy click noise here in the future
ShutterCallback shutterCallback = new ShutterCallback()
{
public void onShutter()
{
Log.i(TAG, "onShutter() called. Capturing image.", Log.DEBUG_MODE);
}
};
// need the callback but we don't want to do anything with this currently
PictureCallback rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.i(TAG, "Picture taken: raw picture available", Log.DEBUG_MODE);
}
};
PictureCallback jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
FileOutputStream outputStream = null;
try {
String photosPath = "/sdcard/CameraTest/photos/";
// create storage location for photos if it does not exist
File photosDirectory = new File(photosPath);
if(!(photosDirectory.exists())) {
photosDirectory.mkdirs();
}
// write photo to storage
outputStream = new FileOutputStream(String.format(photosPath + "%d.jpg", System.currentTimeMillis()));
outputStream.write(data);
outputStream.close();
// camera preview stops when a photo is actually taken, restart it
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
<file_sep>var pascam = require('com.skypanther.picatsize');
var targetWidth = 1024;
var targetHeight = 800;
function openCameraActivity(e) {
var overlay = Ti.UI.createView({
});
var clickBt = Ti.UI.createButton({
title: "click me",
bottom: 10,
right: 20
});
overlay.add(clickBt);
clickBt.addEventListener('click', function() {
pascam.takePicture();
});
var closeBt = Ti.UI.createButton({
title: "close me",
bottom: 10,
left: 20
});
overlay.add(closeBt);
closeBt.addEventListener('click', function() {
pascam.hideCamera();
});
pascam.showCamera({
overlay: overlay, //setting the overlay makes the module start PASCameraActivity
autohide: false, //according to the docs, autohide must be false for takePicture() to work
success: function (e) {
Ti.API.info('Our type was: ' + e.mediaType);
Ti.API.info("bytes: " + e.media.length);
Ti.API.info("height: " + e.media.height);
Ti.API.info("width: " + e.media.width);
Ti.API.info("apiName: " + e.media.apiName);
console.log(e);
pascam.hideCamera();
},
error: function (e) {
Ti.API.info(JSON.stringify(e));
},
saveToPhotoGallery: false,
mediaTypes: [pascam.MEDIA_TYPE_PHOTO],
targetWidth: targetWidth,
targetHeight: targetHeight
});
}
function openNativeCamera(e) {
var targetWidth = 1024;
var targetHeight = 800;
pascam.showCamera({
showControls: true,
autohide: true,
success: function (e) {
Ti.API.info('Our type was: ' + e.mediaType);
Ti.API.info("bytes: " + e.media.length);
Ti.API.info("height: " + e.media.height);
Ti.API.info("width: " + e.media.width);
Ti.API.info("apiName: " + e.media.apiName);
console.log(e);
//resize the media blob "manually"
//scale based on the largest side of the picture (use Math.max() for scaling on the littlest side)
var scale = Math.min(targetWidth / e.media.width, targetHeight / e.media.height);
var blob = e.media.imageAsResized(e.media.width * scale, e.media.height * scale);
Ti.API.info("new size: " + blob.width + "x" + blob.height);
//blob can be saved to a file if needed
},
error: function (e) {
Ti.API.info(JSON.stringify(e));
},
saveToPhotoGallery: false,
mediaTypes: [pascam.MEDIA_TYPE_PHOTO],
targetWidth: targetWidth,
targetHeight: targetHeight
});
}
$.index.open();
|
cdf6cd0f3da6d24e60f34aefc65153046ea49aec
|
[
"Java",
"Markdown",
"JavaScript",
"INI"
] | 6 |
Java
|
skypanther/picatsize
|
ac4f8e59dbccbb156a1c61e2a1ea98215da4be4a
|
e07f49e72b2237ad01a42d234f706d02f83f2943
|
refs/heads/master
|
<repo_name>omissis/convenient-immutability<file_sep>/test/ImmutableTraitTest.php
<?php
namespace ConvenientImmutability\Test;
use ConvenientImmutability\Test\Resources\Foo;
use ConvenientImmutability\Test\Resources\SubclassedFoo;
class ImmutableTraitTest extends \PHPUnit_Framework_TestCase
{
/**
* @return array
*/
public function objectProvider()
{
$foo = new Foo();
$unserializedFoo = unserialize(serialize($foo));
$fooWithCustomConstructor = new SubclassedFoo();
return [
[$foo],
[$unserializedFoo],
[$fooWithCustomConstructor]
];
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_allows_one_assignment_per_property(Foo $foo)
{
$foo->bar = 1;
$foo->baz = 2;
$this->assertSame(1, $foo->bar);
$this->assertSame(2, $foo->baz);
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_fails_when_a_property_gets_reassigned(Foo $foo)
{
$foo->bar = 1;
$this->assertSame(1, $foo->bar);
$this->setExpectedException(\LogicException::class);
$foo->bar = 2;
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_fails_to_assign_values_to_undefined_properties(Foo $foo)
{
$this->setExpectedException(\LogicException::class);
$foo->bang = 1;
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_fails_to_retrieve_values_from_undefined_properties(Foo $foo)
{
$this->setExpectedException(\LogicException::class);
$foo->bang;
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_returns_null_for_properties_that_have_no_assigned_value(Foo $foo)
{
$this->assertSame(null, $foo->bar);
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_returns_the_default_attribute_value_of_properties_that_have_no_assigned_value(Foo $foo)
{
$this->assertSame([], $foo->bazzes);
}
/**
* @test
* @dataProvider objectProvider
*/
public function it_should_have_the_same_values_after_deserialization(Foo $foo)
{
$foo->bar = 'bar';
$foo->baz = 1;
$foo->bazzes = [1, 2, 3, 4];
/** @var Foo $deSerialized */
$deSerialized = unserialize(serialize($foo));
$this->assertSame($foo->bar, $deSerialized->bar);
$this->assertSame($foo->baz, $deSerialized->baz);
$this->assertSame($foo->bazzes, $deSerialized->bazzes);
}
}
|
2b37c01888bfffcf0fdfce7996de354c8ded0104
|
[
"PHP"
] | 1 |
PHP
|
omissis/convenient-immutability
|
b49542881e5d865d5d8a5da11e5479c061d887bf
|
22365b828878db86c0111f414026c4f89cbebb61
|
refs/heads/master
|
<file_sep>First - npm install
Second - npm start
|
15a064d312f17811719b5d806fadc96abca626eb
|
[
"Markdown"
] | 1 |
Markdown
|
Drag731/React-list-of-film
|
1e162aba2092c863549d2c675fecb97700d3decd
|
907146f2bd1fb7fb082087bfbdc51a1d4417dcf8
|
refs/heads/master
|
<repo_name>gql-dal/greldal<file_sep>/src/__specs__/operation-presets/insertion.spec.ts
import { GraphQLSchema, subscribe, parse, graphql, GraphQLObjectType, GraphQLID, GraphQLList } from "graphql";
import Knex from "knex";
// @snippet:start mapSchema_insert_subscription:0
import { PubSub } from "graphql-subscriptions";
// @snippet:end
import { MappedDataSource } from "../../MappedDataSource";
import { setupUserSchema, insertFewUsers, mapUsersDataSource, teardownUserSchema } from "../helpers/setup-user-schema";
import { mapSchema, operationPresets, useDatabaseConnector, OperationTypes } from "../..";
import { setupKnex } from "../helpers/setup-knex";
import { getSubscriptionResults } from "../helpers/subscriptions";
import * as NotificationDispatcher from "../../NotificationDispatcher";
let knex: Knex;
jest.setTimeout(30000);
describe("Insert operation", () => {
let users: MappedDataSource, schema: GraphQLSchema;
// @snippet:start mapSchema_insert_subscription:1
const pubsub = new PubSub();
// @snippet:end
beforeAll(() => {
knex = setupKnex();
useDatabaseConnector(knex);
});
describe("Subscriptions", () => {
beforeAll(async () => {
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSource();
// @snippet:start mapSchema_insert_subscription:2
// Globally configure notification dispatcher
// once to specify how it should publish notifications
NotificationDispatcher.configure({
publish: (payload: NotificationDispatcher.MutationNotification) => {
pubsub.publish("MUTATIONS", payload);
},
});
/// let
schema = mapSchema([
operationPresets.findOneOperation(users),
operationPresets.insertOneOperation(users),
// We define a subscription operation
// which can listen to this channel
{
operationType: OperationTypes.Subscription,
name: "userInserted",
fieldConfig: {
type: GraphQLList(
new GraphQLObjectType({
name: "UserInsertionNotification",
fields: {
id: {
type: GraphQLID,
},
},
}),
),
resolve: (payload: NotificationDispatcher.MutationNotification) => payload.entities.User,
subscribe: () => pubsub.asyncIterator("MUTATIONS"),
},
},
]);
// @snippet:end
});
afterAll(async () => {
await teardownUserSchema(knex);
NotificationDispatcher.resetConfig();
});
test("Insertions are published as a mutation via configured publisher", async () => {
const subscriptionQuery = `
subscription {
userInserted {
id
}
}
`;
const subP = subscribe(schema, parse(subscriptionQuery)).then(getSubscriptionResults());
const graphQLResult = await graphql(
schema,
`
mutation {
insertOneUser(entity: { id: 999, name: "<NAME>" }) {
id
name
}
}
`,
);
const subscriptionResult = await subP;
expect(graphQLResult.data!.insertOneUser.id).toEqual(subscriptionResult[0].data!.userInserted[0].id);
expect(graphQLResult).toMatchSnapshot();
expect(subscriptionResult).toMatchSnapshot();
});
});
});
<file_sep>/src/utils/JoinBuilder.ts
import * as Knex from "knex";
import { AliasHierarchyVisitor } from "../AliasHierarchyVisitor";
import { JoinTypeId } from "../AssociationMapping";
/**
* Type of a join builder function
*
* The API exposed by this function is currently much less polymorphic compared to Knex join composition
* functions. All parameters are mandatory.
*
* @param tableName (Unaliased) name of table being joined (referred to as target table)
* @param column1 (Unaliased) name of column in source table
* @param operator Join operator (eg. =, <)
* @param column2 (Unaliased) name of column in target table
*/
type BuildJoin = (tableName: string, column1: string, operator: string, column2: string) => JoinBuilder;
/**
* A mediator to allow users to compose joins across data sources without having to deal with
* aliasing.
*
* Exposes a function for every join type supported by knex. For the signature of the function refer
* BuildJoin type.
*
* For example:
*
* Given a joinBuilder constructed in the context of users table, when used as below:
*
* ```
* joinBuilder
* .leftJoin('departments', 'department_id', '=', 'id')
* .leftJoin('purchases', 'id', '=', 'department_id')
* ```
*
* Will construct a join like:
*
* ```
* `users` AS `GQL_DAL_users_1`
* LEFT JOIN `departments` as `GQL_DAL_departments_2`
* LEFT JOIN `purchases` as `GQL_DAL_purchases_3`
* ```
*
* Note that the aliasing of tables is completely abstracted out from the consumer of join builder
*/
export type JoinBuilder = { [J in JoinTypeId]: BuildJoin } & {
aliasHierarchyVisitor: AliasHierarchyVisitor;
};
const joinTypes: JoinTypeId[] = [
"innerJoin",
"leftJoin",
"leftOuterJoin",
"rightJoin",
"rightOuterJoin",
"outerJoin",
"fullOuterJoin",
"crossJoin",
];
/**
* Convenience utility to construct a JoinBuilder instance
*
* @param queryBuilder Knex query builder
* @param aliasHierarchyVisitor
*/
export const createJoinBuilder = (
queryBuilder: Knex.QueryBuilder,
aliasHierarchyVisitor: AliasHierarchyVisitor,
): JoinBuilder => {
let result: any = {
queryBuilder,
aliasHierarchyVisitor: aliasHierarchyVisitor,
};
joinTypes.forEach((joinType: JoinTypeId) => {
const joinFn: BuildJoin = (joinTableName, joinedTableColName, joinOperator, parentTableColName) => {
const tableVisitor = aliasHierarchyVisitor.visit(joinTableName);
queryBuilder[joinType](
`${joinTableName} as ${tableVisitor.alias}`,
`${tableVisitor.alias}.${joinedTableColName}`,
joinOperator,
`${aliasHierarchyVisitor.alias}.${parentTableColName}`,
);
return createJoinBuilder(queryBuilder, tableVisitor);
};
result[joinType] = joinFn;
});
return result;
};
<file_sep>/src/graphql-type-mapper.ts
import { MappedDataSource } from "./MappedDataSource";
import _debug from "debug";
import * as types from "./utils/types";
import * as t from "io-ts";
import {
GraphQLObjectType,
GraphQLFieldConfigMap,
GraphQLInputObjectType,
GraphQLInputFieldConfigMap,
GraphQLString,
GraphQLFloat,
GraphQLList,
GraphQLBoolean,
GraphQLOutputType,
GraphQLScalarType,
GraphQLInputType,
GraphQLInt,
GraphQLType,
GraphQLUnionType,
} from "graphql";
import { transform, uniqueId, isArray, first, isNil, memoize, camelCase, upperFirst, constant } from "lodash";
import { MappedField } from "./MappedField";
import { Maybe, Predicate } from "./utils/util-types";
import { JSONType } from "./utils/json";
import { MaybeType } from "./utils/maybe";
import { GraphQLDate, GraphQLDateTime, GraphQLTime } from "graphql-iso-date";
const debug = _debug("greldal:graphql-type-mapper");
/**
* Utilities to create GraphQL type descriptors from various GRelDAL specific inputs
*/
/**
* GraphQL type representing information about current page in a paginated query
*/
export const pageInfoType = memoize(
() =>
new GraphQLObjectType({
name: "GRelDALPageInfo",
fields: {
prevCursor: {
type: GraphQLString,
},
nextCursor: {
type: GraphQLString,
},
totalCount: {
type: GraphQLInt,
},
},
}),
);
/**
* Derive default GraphQL output type for specified data source
*/
export const deriveDefaultOutputType = <TSrc extends MappedDataSource>(mappedDataSource: TSrc) =>
new GraphQLObjectType({
name: mappedDataSource.mappedName,
fields: () => mapOutputAssociationFields(mappedDataSource, mapOutputFields(mappedDataSource)),
});
/**
* Derive output type for a paginated query
*
* @param pageContainerName Name of page container type
* @param pageName Name of page type
* @param wrappedType GraphQL output type of the entity being queried
*/
export const derivePaginatedOutputType = (
pageContainerName: string,
pageName: string,
wrappedType: GraphQLOutputType,
) =>
new GraphQLObjectType({
name: pageContainerName,
fields: {
page: {
type: new GraphQLObjectType({
name: pageName,
fields: {
pageInfo: {
type: pageInfoType(),
},
entities: {
type: GraphQLList(wrappedType),
},
},
}),
args: {
cursor: { type: GraphQLString },
pageSize: { type: GraphQLInt },
},
},
},
});
/**
* Derive the default GraphQL input type for specified data source excluding associations
*/
export const deriveDefaultShallowInputType = <TSrc extends MappedDataSource>(mappedDataSource: TSrc) =>
new GraphQLInputObjectType({
name: `${mappedDataSource.mappedName}Input`,
fields: () => mapInputFields(mappedDataSource),
});
/**
* Derive the GraphQL Input type for union of fields from multiple specified data sources
*/
export const deriveDefaultShallowUnionInputType = <TSrc extends MappedDataSource>(mappedDataSources: TSrc[]) =>
new GraphQLInputObjectType({
name: `UnionOf${mappedDataSources.map(d => d.mappedName).join("And")}Input`,
fields: () => {
const result: GraphQLInputFieldConfigMap = {};
mappedDataSources.forEach(d => mapInputFields(d, result));
return result;
},
});
/**
* Derive the GraphQL output type for a data source including only the (primary and computed) fields and not the associations
*/
export const deriveDefaultShallowOutputType = <TSrc extends MappedDataSource>(mappedDataSource: TSrc) =>
new GraphQLObjectType({
name: `Shallow${mappedDataSource.mappedName}`,
fields: () => mapOutputFields(mappedDataSource),
});
export const deriveDefaultIdOutputType = <TSrc extends MappedDataSource>(source: TSrc) => {
const fields = source.primaryFields;
const predicate = (field: MappedField) => fields.indexOf(field) >= 0;
return new GraphQLObjectType({
name: `${source.mappedName}Id`,
fields: () => mapOutputFields(source, {}, predicate),
});
};
/**
* Build GraphQLInputFieldConfig dictionary from field definitions of a data source
*
* This is primarily useful for deriving GraphQL input type for a data source.
*/
export const mapInputFields = (
dataSource: MappedDataSource,
result: GraphQLInputFieldConfigMap = {},
): GraphQLInputFieldConfigMap =>
transform(
dataSource.fields,
(fields: GraphQLInputFieldConfigMap, field, name) => {
fields[name] = {
type: field.graphQLInputType,
description: field.description,
};
},
result,
);
/**
* Build GraphQLFieldConfig dictionary from field definitions of a data source.
*
* This is primarily useful for deriving GraphQL output type for a data source.
*/
export const mapOutputFields = (
dataSource: MappedDataSource,
result: GraphQLFieldConfigMap<any, any> = {},
predicate = (field: MappedField) => field.exposed,
): GraphQLFieldConfigMap<any, any> =>
transform(
dataSource.fields,
(fields: GraphQLFieldConfigMap<any, any>, field, name) => {
if (!predicate(field)) {
debug("Field failed predicate match:", name);
return;
}
debug("mapping output field from data source field: ", name, field);
fields[name] = {
type: field.graphQLOutputType,
description: field.description,
};
},
result,
);
/**
* Build GraphQLFieldConfig dictionary from association definitions of a data source.
*
* This is primarily useful for deriving GraphQL output type for a data source.
*/
export const mapOutputAssociationFields = (
dataSource: MappedDataSource,
result: GraphQLFieldConfigMap<any, any> = {},
) =>
transform(
dataSource.associations,
(fields: GraphQLFieldConfigMap<any, any>, association, name) => {
if (!association.exposed) {
debug("Association not exposed:", name);
return;
}
debug("mapping output field from association: ", name, association);
const outputType = association.target.defaultOutputType;
fields[name] = {
type: association.singular ? outputType : GraphQLList(outputType),
args: {
where: {
type: association.target.defaultShallowInputType,
},
},
description: association.description,
resolve: source =>
normalizeResultsForSingularity(source[name], association.singular, association.isPaginated),
};
},
result,
);
/**
* Check if one io-ts type is a refinement of another
*/
export const isOrRefinedFrom = (type: t.Type<any>) => (targetType: t.Type<any>): boolean => {
if (type === targetType) return true;
if (targetType instanceof t.RefinementType) return isOrRefinedFrom(type)(targetType.type);
return false;
};
/**
* For singular operations, unwraps first result if result set is a collection
* For non-singular operations, wraps result set into a collection (if not already)
*
* This utility liberates resolver authors from worrying about whether or not an operation is singular
* when returning the results.
*/
export function normalizeResultsForSingularity(result: any, singular: boolean, paginated: boolean) {
if (singular) {
if (isArray(result)) return first(result);
} else {
if (isNil(result)) return [];
if (paginated) {
if (!result.page) result.page = {};
if (!result.page.entities) result.page.entities = [];
if (!isArray(result.page.entities)) result.page.entities = [result.page.entities];
} else {
if (!isArray(result)) return [result];
}
}
return result;
}
<file_sep>/src/MappedSourceAwareOperation.ts
import { MappedDataSource } from "./MappedDataSource";
import { MappedOperation } from "./MappedOperation";
import { PaginationConfig } from "./PaginationConfig";
import { Maybe } from "./utils/util-types";
import { normalizeResultsForSingularity } from "./graphql-type-mapper";
import { SourceAwareOperationMapping } from "./SourceAwareOperationMapping";
import { GraphQLResolveInfo } from "graphql";
import { MaybePaginatedResolveInfoVisitor } from "./PaginatedResolveInfoVisitor";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
export abstract class MappedSourceAwareOperation<
TSrc extends MappedDataSource,
TArgs extends object
> extends MappedOperation<TArgs> {
constructor(public readonly mapping: SourceAwareOperationMapping<TSrc, TArgs>) {
super(mapping);
}
get supportsMultipleDataSources() {
return false;
}
get paginationConfig(): Maybe<PaginationConfig> {
return this.mapping.paginate;
}
normalizeResultsForSingularity(result: any) {
return normalizeResultsForSingularity(result, this.singular, !!this.paginationConfig);
}
async createResolverContext(
source: any,
args: TArgs,
context: any,
resolveInfo: GraphQLResolveInfo,
resolveInfoVisitor?: MaybePaginatedResolveInfoVisitor<any>,
): Promise<SourceAwareResolverContext<any, any, TArgs>> {
return SourceAwareResolverContext.create(
this,
{} as any,
source,
args,
context,
resolveInfo,
resolveInfoVisitor,
);
}
}
<file_sep>/src/ReverseMapper.ts
import _debug from "debug";
import { MappedDataSource } from "./MappedDataSource";
import { Dict } from "./utils/util-types";
import { StoreQueryParams, PrimaryRowMapper } from "./SingleSourceQueryOperationResolver";
import { memoize, pick, compact, groupBy, uniq } from "lodash";
import assert from "assert";
const debug = _debug("greldal:ReverseMapper");
export interface ReverseMapperTree {
readonly primaryRowMappers: PrimaryRowMapper[];
readonly relationMappers: Dict<ReverseMapperTree>;
}
/**
* Utility to reverse map flattened tabular resultset obtained from a database query to a hierarchy of entities
*/
export class ReverseMapper<T extends MappedDataSource> {
public tree: ReverseMapperTree = {
primaryRowMappers: [],
relationMappers: {},
};
constructor(private storeParams: StoreQueryParams<T>) {
this.populateReverseTree();
}
async reverseMap(rows: Dict[], shallow = false) {
debug("Reverse mapping rows:", rows);
const hierarchy = this.reverseMapQueryResults(rows, this.tree)!;
if (!shallow) {
const { secondaryMappers } = this.storeParams;
for (const { propertyPath, result, reverseAssociate } of secondaryMappers.preFetched) {
const parents = this.extractEntitiesAtPath(propertyPath.slice(0, -1), hierarchy);
reverseAssociate(parents, await result);
}
for (const { propertyPath, run, reverseAssociate } of secondaryMappers.postFetched) {
const parents = this.extractEntitiesAtPath(propertyPath.slice(0, -1), hierarchy);
reverseAssociate(parents, await run(parents));
}
}
debug("Reverse mapped hierarchy: %O", hierarchy);
return hierarchy;
}
private populateReverseTree() {
debug("Populating reverseTree using storeParams: %O", this.storeParams);
for (const primaryMapper of this.storeParams.primaryMappers) {
let curLevel = this.tree;
for (const tablePathLevel of primaryMapper.tablePath) {
curLevel.relationMappers[tablePathLevel] = curLevel.relationMappers[tablePathLevel] || {
primaryRowMappers: [],
relationMappers: {},
};
curLevel = curLevel.relationMappers[tablePathLevel];
}
curLevel.primaryRowMappers.push(primaryMapper);
}
debug("Reverse mapping tree: %O", this.tree);
}
private getImmediateColKeys(level: ReverseMapperTree) {
return uniq(compact(level.primaryRowMappers.map(rowMapper => rowMapper.columnAlias)));
}
private getAllDescendantColKeys: (reverseMapperTree: ReverseMapperTree) => string[] = memoize(
(level: ReverseMapperTree) => {
const keys: string[] = [];
keys.push(...this.getImmediateColKeys(level));
for (const r of Object.values(level.relationMappers)) {
keys.push(...this.getAllDescendantColKeys(r));
}
return keys;
},
);
private reverseMapQueryResults(rows: Dict[], level = this.tree) {
const list = rows.map(r => pick(r, this.getAllDescendantColKeys(level)));
if (list.length === 1 && compact(Object.values(list[0])).length === 0) {
return null;
}
const immediateColKeys = this.getImmediateColKeys(level);
debug("Column keys at current level:", immediateColKeys);
const grouping = groupBy(list, listItem => JSON.stringify(immediateColKeys.map(key => listItem[key])));
return Object.values(grouping).map(groupingItem => {
const entity: any = {};
const derivations: Array<() => void> = [];
for (const { field, columnAlias } of level.primaryRowMappers) {
assert(columnAlias || field.isComputed, "Expected columnAlias to be omitted only for computed field");
if (columnAlias) {
const rowValue = field.fromSource(groupingItem[0][columnAlias]);
entity[field.mappedName] = rowValue;
} else {
const rowValue = field.derive!(
pick(
entity,
field.dependencies.map(f => f.mappedName),
),
);
derivations.push(() => {
entity[field.mappedName] = rowValue;
});
}
}
for (const derivation of derivations) {
derivation();
}
for (const [relationName, nextLevel] of Object.entries(level.relationMappers)) {
debug("Traversing to next level:", relationName);
entity[relationName] = this.reverseMapQueryResults(groupingItem, nextLevel);
}
return entity;
});
}
private extractEntitiesAtPath(path: string[], hierarchy: any[]): any[] {
if (path.length === 0) {
return hierarchy;
}
const curPath = path[0];
const entities = hierarchy.map(e => e[curPath]);
return this.extractEntitiesAtPath(path.slice(1), entities);
}
}
<file_sep>/src/docs/pages/mapping-associations.md
import {NextPageLink} from "../components/Link";
import Link from "next/link";
import {CodeSnippet} from "../components/CodeSnippet";
# Mapping Queries over Associations
While data sources derived from a single tables are useful in themselves, in larger applications, you'd likely have data stored across multiple tables. After all, the ability to join tables and enforce constraints on connected tables is what makes relational databases so powerful.
GRelDAL makes it easy for you to take advantage of advanced features of relational databases, by providing APIs to link data sources through different loading strategies.
### Associations fetched through join queries
We can configure an association between multiple data sources to use a join.
<CodeSnippet name="mapAssociation_leftOuterJoin_default" />
So now, for a query like the following:
<CodeSnippet name="mapAssociation_leftOuterJoin_default_query" transform={(content) => content.trim().split('\n').slice(1, -1).join('\n') }/>
GRelDAL will join the `products` and `departments` table on the `department_id` and `id` columns.
You are not limited in how many tables you can join and how the joins should be performed. Even in case of multiple joins or recursive joins, GRelDAL can take care of reverse mapping the fetched data sets into the hierarchical format your client expects.
<CodeSnippet name="mapAssociation_multiJoin_custom" />
### Associations fetched through batch queries:
An alternative to joins is to side-load the operations on related data sources.
Note that in the below scenario, when we are fetching a department and related products, we are always making only two queries - irrespective of the number of departments or the number of products we have or how many of them end up in our result set. Both of these queries are batched, and once again we can fall back on GRelDAL do our reverse mapping for us.
<CodeSnippet name="mapAssociation_sideLoading" />
<NextPageLink>Stored Procedures</NextPageLink>
<file_sep>/src/docs/components/APIContainer.js
import React from "react";
import qs from "qs";
import { PageLayout } from "./PageLayout";
import APITree from "./APITree";
import APIBody from "./APIBody";
import { SectionHeader } from "./Sidebar";
import memoize from "lodash/memoize";
import hierarchy from "../../../api/api-hierarchy.json";
import { getAPIName, getAPICategory, findInHierarchy } from "../utils/api";
import { HierarchyContext } from "./HierarchyContext";
import NotificationBanner from "./NotificationBanner";
export default class APIContainer extends React.Component {
state = {
hierarchy,
active: null,
};
componentDidMount() {
this.syncFromLocation();
window.addEventListener("popstate", this.syncFromLocation);
}
componentWillUnmount() {
window.removeEventListener("popstate", this.syncFromLocation);
}
syncFromLocation = () => {
const search = location.search.slice(1);
if (!search) return;
this.setState({
active: qs.parse(search),
});
};
render() {
const { active, hierarchy } = this.state;
let activeCategory;
let rootEntity;
if (active && active.rootEntityName) {
const entityPath = active.rootEntityName.split(".");
for (const category of this.state.hierarchy) {
const node = findInHierarchy(category, entityPath);
if (node) {
activeCategory = category;
rootEntity = node.entity;
break;
}
}
}
return (
<PageLayout
sidebar={
<>
{hierarchy.map(h => (
<>
<SectionHeader>{h.name}</SectionHeader>
<APITree
hierarchy={h.children}
handleToggle={this.handleToggle}
handleClick={this.handleClick}
/>
</>
))}
</>
}
>
{activeCategory &&
activeCategory.banners.map(b => <NotificationBanner>{b.children}</NotificationBanner>)}
<HierarchyContext.Provider value={this.state.hierarchy}>
<APIBody
{...{
activeCategory,
rootEntity,
activeEntityName: active && active.entityName,
}}
/>
</HierarchyContext.Provider>
</PageLayout>
);
}
handleClick = memoize((name, entity) => event => {
if (!entity) return;
let rootEntity = entity;
while (rootEntity.parent) {
rootEntity = rootEntity.parent;
}
const active = {
apiCategory: getAPICategory(rootEntity),
rootEntityName: getAPIName(rootEntity),
entityName: getAPIName(entity),
};
this.setState({ active });
history.pushState(
null,
`GRelDAL Documentation | ${rootEntity.name} | ${entity.name}`,
`?${qs.stringify(active)}`,
);
event.stopPropagation();
event.preventDefault();
});
handleToggle = (node, toggled) => {
node.toggled = toggled;
this.setState({ hierarchy: this.state.hierarchy });
};
}
<file_sep>/src/__specs__/udf-invocation.spec.ts
import * as Knex from "knex";
import { setupKnex } from "./helpers/setup-knex";
import { useDatabaseConnector, types, operationPresets } from "..";
import { setupUserSchema, insertFewUsers, mapUsersDataSource, teardownUserSchema } from "./helpers/setup-user-schema";
import { GraphQLSchema, GraphQLFloat, graphql } from "graphql";
import { mapSchema } from "../MappedSchema";
import { mapArgs } from "../MappedArgs";
import { MappedDataSource } from "../MappedDataSource";
import { mapUserDefinedFunction } from "../universal";
let knex: Knex;
describe("UDF Invocation mapping", () => {
let schema: GraphQLSchema;
let users: MappedDataSource;
const db = process.env.DB;
if (db === "pg") {
beforeAll(async () => {
knex = setupKnex();
useDatabaseConnector(knex);
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSource();
// @snippet:start udf_example
await knex.raw(`
CREATE OR REPLACE FUNCTION get_sum(a numeric, b numeric)
RETURNS NUMERIC AS $$
BEGIN
RETURN a + b;
END; $$ language plpgsql;
`);
// @snippet:end
schema = mapSchema([
operationPresets.findOneOperation(users),
// @snippet:start udf_mapping
mapUserDefinedFunction({
name: {
stored: "get_sum",
mapped: "getSum",
},
args: mapArgs({
a: { type: types.number },
b: { type: types.number },
}),
returnType: GraphQLFloat,
deriveParams: ({ a, b }) => [
{
name: "a",
value: a,
argMode: "IN",
},
{
name: "b",
value: b,
argMode: "IN",
},
],
}),
// @snippet:end
]);
});
it("returns result of invocation of stored procedure", async () => {
// @snippet:start udf_mapping_usage
const graphQLResult = await graphql(
schema,
`
mutation {
getSum(a: 1, b: 2)
}
`,
);
// @snippet:end
expect(graphQLResult.data!.getSum).toEqual(3);
});
afterAll(async () => {
await teardownUserSchema(knex);
await knex.raw("drop function get_sum(numeric, numeric)");
});
} else {
test.todo("Stored procedures not yet supported for this database");
}
});
<file_sep>/src/utils/assertions.ts
import { failure } from "io-ts/lib/PathReporter";
import * as t from "io-ts";
import { getOrElse } from "fp-ts/lib/Either";
/**
* Validate if a value complies with a runtime-type.
*
* @private
* @param type Runtime type
* @param value Value to be validated
* @param specId Human friendly descriptor used in validation failure message
*/
export const assertType = <T>(type: t.Type<T>, value: any, specId: string) => {
return getOrElse<t.Errors, T>((errors: t.Errors) => {
throw new TypeError(`${specId} incorrectly specified:\n${failure(errors).join("\n")}`);
})(type.decode(value));
};
<file_sep>/src/MappedStoredProcInvocationOperation.ts
import * as Knex from "knex";
import { MappedOperation } from "./MappedOperation";
import { OperationResolver } from "./OperationResolver";
import { GraphQLFieldConfigArgumentMap } from "graphql";
import { ResolverContext } from "./ResolverContext";
import { assertConnectorConfigured, globalConnector } from "./utils/connector";
import { values, isString } from "lodash";
import { TypeGuard } from "./utils/util-types";
import { InvocationParam, InvocationMapping } from "./InvocationMapping";
import { MySQLStoredProcInvocationOperationResolver } from "./MySQLStoredProcInvocationOperationResolver";
import { PGStoredProcInvocationOperationResolver } from "./PGStoredProcInvocationOperationResolver";
import { OperationTypes } from "./universal";
import { operationType } from "./operation-types";
export class MappedStoredProcInvocationOperation<TArgs extends {}> extends MappedOperation<TArgs> {
constructor(public readonly mapping: InvocationMapping<TArgs>) {
super(mapping);
}
get operationType(): OperationTypes {
return operationType(this.mapping.type, OperationTypes.Mutation);
}
get defaultArgs(): GraphQLFieldConfigArgumentMap {
throw new Error("Args must be explicit specified when mapping stored procedures");
}
get type() {
return this.mapping.returnType;
}
get connector(): Knex {
return assertConnectorConfigured(this.mapping.connector || globalConnector);
}
get procedureName(): string {
return (isString as TypeGuard<string>)(this.mapping.name) ? this.mapping.name : this.mapping.name.stored;
}
deriveParams(args: TArgs): InvocationParam[] {
const { deriveParams } = this.mapping;
if (deriveParams) return deriveParams(args);
return values(args).map(value => ({
value,
argMode: "IN",
}));
}
deriveResult(output: any) {
const { deriveResult } = this.mapping;
if (deriveResult) return deriveResult(output);
return output;
}
defaultResolver<TResolved>(
ctx: ResolverContext<MappedStoredProcInvocationOperation<TArgs>, TArgs>,
): OperationResolver<any, TArgs, TResolved> {
switch (this.connector().client.dialect) {
case "mysql":
case "mysql2":
return new MySQLStoredProcInvocationOperationResolver<typeof ctx, TArgs, any>(ctx);
case "postgresql":
return new PGStoredProcInvocationOperationResolver<typeof ctx, TArgs, any>(ctx);
}
throw new Error("GRelDAL does not support stored procedures for this dialect");
}
}
export const mapStoredProcedure = <TArgs>(mapping: InvocationMapping<TArgs>) =>
new MappedStoredProcInvocationOperation(mapping);
<file_sep>/src/docs/pages/comparision-with-alternatives.md
# Comparision with Alternatives
GRelDAL is not the only solution in this space. While we provide brief notes below on why you might (or might not) want to use GRelDAL instead of some of the alternatives, please keep in mind that we (the maintainers of GRelDAL) don't have indepth experience in these solutions and we encourage you to conduct your own evaluation before picking a solution that is the right fit for your use cases.
## Why use GRelDAL instead of alternatives ?
- Unlike services like **Prisma** and **Hasura**, GRelDAL does not involve a separate managed backend service or an infrastructure component. You don't deploy GRelDAL as a service and interact with it. You also don't need to send across your data to some managed third party application. Instead, you simply use GRelDAL as a library and build your application around it. GRelDAL has no opinions on how you manage and scale your application, it is just another javascript library in your stack.
- Unlike solutions like **Hasura** & **Postgraphile**, GRelDAL is not tied to a single data store. You can use one of the many supported relational databases.
- Unlike **Prisma**, GRelDAL doesn't aim to provide just an alternative for your ORM. It aims to provide an alternative for both your ORM as well as your API builder. Through a single library you map your database layer to a GraphQL API that you expose to clients. The mapping layer is flexible enough to accomodate your business logic through custom resolvers, interceptors and virtual fields. No schema stitching is required - there is one single GraphQL API.
## When can the alternatives be better solutions ?
- GRelDAL currently isn't the ideal solution if the response payload of your requests is too large to fit into memory. The logic for transforming database query results into the shape requested by the GraphQL client assumes that the resolved dataset fits in memory.
- GRelDAL is slower than solutions like Postgraphile which do all the data transformations within the database before they get transmitted down the wire. We believe this is an acceptable compromise that enables us to integrate better with business logic written in javascript/typescript and support polyglot persistence.
- GRelDAL strives to be typesafe (if you use TypeScript) but it doesn't guarantee absense of runtime errors for database operations - solutions like Prisma and Hasura (written in Scala and Haskell respectively) may offer stronger guarantees by relying on the powerful type systems of these languages. We will continually strive for improvement around this, but we consider basing our solution on TypeScript to be a good decision for more cohesive & flexible integration with applications where business logic is implemented in javascript/typescript.
- GRelDAL doesn't handle scaling, migrations, database management for you. It is assumed that you are choosing GRelDAL because you want to retain control over database management aspects and have the requisite expertise.
---
If you maintain, use or are enthusiastic about one of the third party solutions mentioned, and find any inaccurancies in the notes above, please send a pull request to fix them.
<file_sep>/src/__specs__/operation-presets/update.spec.ts
import { GraphQLSchema, GraphQLList, subscribe, parse, graphql, GraphQLObjectType, GraphQLID } from "graphql";
import util from "util";
import Knex from "knex";
import { PubSub } from "graphql-subscriptions";
import { MappedDataSource } from "../../MappedDataSource";
import { setupUserSchema, insertFewUsers, mapUsersDataSource, teardownUserSchema } from "../helpers/setup-user-schema";
import { mapSchema, operationPresets, useDatabaseConnector, OperationTypes } from "../..";
import { setupKnex } from "../helpers/setup-knex";
import { getSubscriptionResults } from "../helpers/subscriptions";
import { MutationNotification } from "../../NotificationDispatcher";
import { NotificationDispatcher } from "../../universal";
let knex: Knex;
jest.setTimeout(30000);
describe("Update operation", () => {
let users: MappedDataSource, schema: GraphQLSchema;
const pubsub = new PubSub();
beforeAll(() => {
knex = setupKnex();
useDatabaseConnector(knex);
});
describe("Subscriptions", () => {
beforeAll(async () => {
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSource();
NotificationDispatcher.configure({
publish: (payload: MutationNotification) => {
pubsub.publish("MUTATIONS", payload);
},
});
schema = mapSchema([
operationPresets.findOneOperation(users),
operationPresets.updateOneOperation(users),
{
operationType: OperationTypes.Subscription,
name: "userUpdated",
fieldConfig: {
type: GraphQLList(
new GraphQLObjectType({
name: "UserUpdateNotification",
fields: {
id: {
type: GraphQLID,
},
},
}),
),
resolve: payload => payload.entities.User,
subscribe: () => pubsub.asyncIterator("MUTATIONS"),
},
},
]);
});
afterAll(async () => {
await teardownUserSchema(knex);
NotificationDispatcher.resetConfig();
});
test("Updates are published as a mutation via configured publisher", async () => {
const subscriptionQuery = `
subscription {
userUpdated {
id
}
}
`;
const subP = subscribe(schema, parse(subscriptionQuery)).then(getSubscriptionResults());
const graphQLResult = await graphql(
schema,
`
mutation {
updateOneUser(where: { id: 1 }, update: { name: "<NAME>" }) {
id
name
}
}
`,
);
const subscriptionResult = await subP;
expect(graphQLResult.data!.updateOneUser.id).toEqual(subscriptionResult[0].data!.userUpdated[0].id);
expect(graphQLResult).toMatchSnapshot();
expect(subscriptionResult).toMatchSnapshot();
});
});
});
<file_sep>/src/utils/conventional-naming.ts
import { MaybeMapped, TypeGuard } from "./util-types";
import { isString } from "util";
import { snakeCase, upperFirst, camelCase } from "lodash";
import { pluralize, singularize } from "inflection";
export const deriveStoredDataSourceName = (name: MaybeMapped<string>) =>
(isString as TypeGuard<string>)(name) ? snakeCase(pluralize(name)) : name.stored;
export const deriveMappedDataSourceName = (name: MaybeMapped<string>) =>
(isString as TypeGuard<string>)(name) ? upperFirst(camelCase(singularize(name))) : name.mapped;
export const deriveStoredFieldName = (name: MaybeMapped<string>) =>
(isString as TypeGuard<string>)(name) ? snakeCase(name) : name.stored;
export const deriveMappedFieldName = (name: MaybeMapped<string>) =>
(isString as TypeGuard<string>)(name) ? camelCase(singularize(name)) : name.mapped;
<file_sep>/src/generator/adapters/MySQLAdapter.ts
import { Adapter, TableLike, TableSchema, ForeignKeyInfo } from "./Adapter";
import { BaseAdapter } from "./BaseAdapter";
import { retrieveTables, getSchemaForTable } from "./information-schema-support";
import { get, isEmpty } from "lodash";
import assert from "assert";
import { TYPES_MAPPING } from "./types-mapping";
export class MySQLAdapter extends BaseAdapter implements Adapter {
async getTables(): Promise<TableLike[]> {
const dbname = get(this.connector, "client.config.connection.database");
assert(dbname, "database name could not be retrieved from connection configuration");
return retrieveTables(this.connector, table =>
table.where(function() {
this.where("table_schema", dbname);
}),
);
}
async getSchemaForTable(table: TableLike): Promise<TableSchema> {
const knex = this.connector;
const colInfo = await knex("information_schema.columns").where({
table_schema: table.schema,
table_name: table.name,
});
const columns = colInfo.map((c: any) => {
const typeMapping = c.DATA_TYPE && TYPES_MAPPING.find(t => c.DATA_TYPE.match(t.regexp));
return {
name: c.COLUMN_NAME,
isPrimary: false,
type: typeMapping && typeMapping.type,
};
});
const primaryKeyCols = await knex("information_schema.key_column_usage as kcu")
.leftJoin("information_schema.table_constraints as tc", function() {
this.on("kcu.constraint_name", "=", "tc.constraint_name")
.andOn("kcu.table_schema", "=", "tc.constraint_schema")
.andOn("kcu.table_name", "=", "tc.table_name");
})
.where("tc.table_name", table.name)
.where("tc.constraint_type", "PRIMARY KEY");
if (!isEmpty(primaryKeyCols)) {
for (const pkCol of primaryKeyCols) {
for (const col of columns) {
if (col.name === pkCol.COLUMN_NAME) col.isPrimary = true;
}
}
}
const fkInfo: any[] = await knex("information_schema.table_constraints as tc")
.innerJoin("information_schema.key_column_usage AS kcu", function() {
this.on("tc.constraint_name", "=", "kcu.constraint_name").andOn(
"tc.table_schema",
"=",
"kcu.table_schema",
);
})
.where("tc.constraint_type", "FOREIGN KEY")
.where("tc.table_name", table.name)
.select(
"tc.table_schema",
"tc.constraint_name",
"tc.table_name",
"kcu.column_name",
"kcu.referenced_table_schema AS foreign_table_schema",
"kcu.referenced_table_name AS foreign_table_name",
"kcu.referenced_column_name AS foreign_column_name",
);
const foreignKeys: ForeignKeyInfo[] = fkInfo.map(f => {
return {
associatedTable: {
name: f.foreign_table_name,
schema: f.foreign_table_schema,
type: "table",
},
associatorColumns: {
inSource: f.column_name,
inRelated: f.foreign_column_name,
},
};
});
return {
columns,
foreignKeys,
};
}
}
<file_sep>/src/docs/components/ContentSection.js
import React from "react";
import { renderMarkdown } from "../utils/markdown";
const initialContext = { level: 1 };
export const ContentHierarchyContext = React.createContext(initialContext);
export function ContentHierarchy(props) {
return (
<ContentHierarchyContext.Consumer>
{({ level } = initialContext) => {
const { root } = props;
if (!root) return null;
const Header = `h${level}`;
const title = root.title && <Header style={{lineHeight: '2rem'}}>{root.title}</Header>;
const content = root.content && <p>{renderMarkdown(root.content)}</p>;
return (
<>
{title}
{content}
{root.members && (
<div style={{ paddingLeft: "15px" }}>
{root.members.map(member => (
<ContentHierarchy root={member} />
))}
</div>
)}
</>
);
}}
</ContentHierarchyContext.Consumer>
);
}
<file_sep>/scripts/generate-docs.js
const $ = require("shelljs");
const glob = require("glob");
const fs = require("fs");
const path = require("path");
const spawnedENV = {
...process.env,
ASSET_PATH: "/greldal/",
NODE_ENV: "production",
};
if (
$.exec(`${path.join("node_modules", ".bin", "next")} build src/docs`, {
env: spawnedENV,
}).code !== 0
) {
$.echo("Failed to compile next.js site");
$.exit(1);
}
if (
$.exec(`${path.join("node_modules", ".bin", "next")} export src/docs -o docs`, {
env: spawnedENV,
}).code !== 0
) {
$.echo("Failed to export static site");
$.exit(1);
}
// Hack required because nextjs doesn't support configuring subdirectory root
glob.sync("./docs/**/index.html").forEach(filePath => {
const index = fs.readFileSync(filePath, { encoding: "utf8" });
const updated = index
.replace(/href="\/_next\//g, 'href="/greldal/_next/')
.replace(/src="\/_next\//g, 'src="/greldal/_next/');
fs.writeFileSync(filePath, updated, { encoding: "utf8" });
});
<file_sep>/src/__specs__/types.ts
import * as t from "io-ts";
import { ExtendsWitness } from "../utils/util-types";
import { MappedDataSource } from "../MappedDataSource";
import { DataSourceMapping } from "../DataSourceMapping";
import { MappedField } from "../MappedField";
import { FieldMapping, FieldMappingArgs } from "../FieldMapping";
import { AssociationMapping } from "../AssociationMapping";
export type _AssociationMappingWitness = ExtendsWitness<
AssociationMapping<any, any>,
AssociationMapping<MappedDataSource, MappedDataSource>
>;
export type MappedDataSourceWitness = ExtendsWitness<MappedDataSource<any>, MappedDataSource<DataSourceMapping>>;
export type MappedFieldWitness = ExtendsWitness<MappedField<any, any>, MappedField>;
export type FieldMappingArgsWitness = ExtendsWitness<FieldMappingArgs<any>, FieldMappingArgs<FieldMapping<any, any>>>;
export type FieldMappingWitness = ExtendsWitness<FieldMapping<any, any>, FieldMapping<t.Type<any>, {}>>;
<file_sep>/src/typings/fix-indents.d.ts
declare module "fix-indents" {
const fixIndents: (input: string) => string;
export default fixIndents;
}
<file_sep>/src/PaginatedResolveInfoVisitor.ts
import { MappedDataSource } from "./MappedDataSource";
import Maybe from "graphql/tsutils/Maybe";
import { ResolveInfoVisitor } from "./ResolveInfoVisitor";
import { ResolveTree, parseResolveInfo } from "graphql-parse-resolve-info";
import { GraphQLResolveInfo } from "graphql";
export class PaginatedResolveInfoVisitor<
TSrc extends MappedDataSource,
TParentVisitor extends Maybe<MaybePaginatedResolveInfoVisitor<any, any>> = any
> {
public parsedResolveInfo: ResolveTree;
constructor(
public originalResolveInfoRoot: GraphQLResolveInfo,
public rootSource: TSrc,
parsedResolveInfo?: ResolveTree,
public parentSource?: TParentVisitor,
) {
this.parsedResolveInfo =
parsedResolveInfo ||
//TODO: Remove any after version incompatibility with typings is resolved
(parseResolveInfo(originalResolveInfoRoot as any) as any);
}
visitPage(): ResolveInfoVisitor<TSrc, PaginatedResolveInfoVisitor<TSrc, TParentVisitor>> {
return new ResolveInfoVisitor(
this.originalResolveInfoRoot,
this.rootSource,
this.parsedResolveInfo.fieldsByTypeName[this.rootSource.pageContainerName].page.fieldsByTypeName[
this.rootSource.pageName
].entities,
this,
);
}
}
export type MaybePaginatedResolveInfoVisitor<
TSrc extends MappedDataSource,
TParentVisitor extends Maybe<MaybePaginatedResolveInfoVisitor<any, any>> = any
> = ResolveInfoVisitor<TSrc, TParentVisitor> | PaginatedResolveInfoVisitor<TSrc, TParentVisitor>;
<file_sep>/src/MultiSourceUnionQueryOperationResolver.ts
import * as Knex from "knex";
import { identity } from "lodash";
import { MappedMultiSourceUnionQueryOperation } from "./MappedMultiSourceUnionQueryOperation";
import { MappedDataSource } from "./MappedDataSource";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { Dict } from "./utils/util-types";
import { DataSourceTypes, MappedMultiSourceOperation } from "./MappedMultiSourceOperation";
import { StoreQueryParams, SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { ReverseMapper } from "./ReverseMapper";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
export type MultiStoreParams<
TOp extends MappedMultiSourceOperation<TSrc, TArgs>,
TSrc extends MappedDataSource,
TArgs extends {}
> = { [K in keyof DataSourceTypes<TOp, TSrc, TArgs>]: StoreQueryParams<DataSourceTypes<TOp, TSrc, TArgs>[K]> };
export class MultiSourceUnionQueryOperationResolver<
TCtx extends SourceAwareResolverContext<MappedMultiSourceUnionQueryOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc extends MappedDataSource,
TArgs extends {},
TResolved
> extends SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved> {
constructor(public resolverContext: TCtx) {
super(resolverContext);
}
get operation(): MappedMultiSourceUnionQueryOperation<TSrc, TArgs> {
return this.resolverContext.operation;
}
async resolve(): Promise<TResolved> {
let queryBuilder: Knex.QueryBuilder;
const aliasHierarchyVisitor = new AliasHierarchyVisitor();
aliasHierarchyVisitor.createAlias = identity;
const resolvers: Dict<SingleSourceQueryOperationResolver<
SourceAwareResolverContext<MappedSingleSourceQueryOperation<TSrc, TArgs>, TSrc, TArgs, any, any>,
TSrc,
any,
TArgs,
any
>> = {};
return this.wrapInTransaction(async () => {
for await (const { key, dataSource, dataSourceConfig } of this.resolverContext.operation.iterateDataSources<
SourceAwareResolverContext<MappedMultiSourceUnionQueryOperation<any, TArgs>, TSrc, TArgs, any, any>
>(this.resolverContext)) {
const { resolver: _oldResolver, ...mapping } = this.operation.mapping;
const deriveWhereParams: any = dataSourceConfig.deriveWhereParams;
const subVisitor = aliasHierarchyVisitor.visit(dataSource.storedName);
const operation = new MappedSingleSourceQueryOperation<typeof dataSource, TArgs>({
...mapping,
deriveWhereParams,
rootSource: dataSource,
});
const resolverContext = SourceAwareResolverContext.derive(
operation,
[{ dataSource }],
this.resolverContext.source,
this.resolverContext.args,
this.resolverContext.context,
this.resolverContext.resolveInfoRoot,
);
const resolver = new SingleSourceQueryOperationResolver<
typeof resolverContext,
TSrc,
typeof operation,
TArgs,
any
>(resolverContext);
resolver.isDelegated = true;
resolver.activeTransaction = this.activeTransaction;
resolver.aliasColumnsToTableScope = false;
resolvers[key] = resolver;
await resolver.resolveFields(
[],
subVisitor,
dataSource,
resolverContext.primaryResolveInfoVisitor,
this.operation.outputTypeName,
true,
);
}
const resolverEntries = Object.entries(resolvers);
for (const [key, resolver] of resolverEntries) {
const { rootSource } = resolver.operation;
const subVisitor = aliasHierarchyVisitor.visit(rootSource.storedName);
if (!queryBuilder) {
queryBuilder = rootSource.rootQueryBuilder(subVisitor).transacting(this.activeTransaction!);
this.applyStoreQueryParamsFrom(resolver, queryBuilder);
} else {
const _this = this;
queryBuilder[this.operation.mapping.unionMode](function() {
_this.applyStoreQueryParamsFrom(
resolver,
this.from(`${rootSource.storedName} as ${subVisitor.alias}`),
);
});
}
}
if (this.operation.singular) queryBuilder.limit(1);
const rows = await queryBuilder;
const reverseMapper = new ReverseMapper(
resolverEntries.reduce(
(
result,
[
,
{
storeParams: { columns, primaryMappers, secondaryMappers },
},
],
) => {
result.columns.push(...columns);
result.primaryMappers.push(...primaryMappers);
result.secondaryMappers.preFetched.push(...secondaryMappers.preFetched);
result.secondaryMappers.postFetched.push(...secondaryMappers.postFetched);
return result;
},
{
whereParams: {},
queryBuilder,
columns: [],
primaryMappers: [],
secondaryMappers: {
preFetched: [],
postFetched: [],
},
} as StoreQueryParams<TSrc>,
),
);
const entities: any = await reverseMapper.reverseMap(rows);
return entities;
});
}
private applyStoreQueryParamsFrom(
resolver: SingleSourceQueryOperationResolver<
SourceAwareResolverContext<MappedSingleSourceQueryOperation<TSrc, TArgs>, TSrc, TArgs, any, any>,
TSrc,
any,
TArgs,
any
>,
queryBuilder: Knex.QueryBuilder,
) {
resolver.resolverContext.operation
.interceptQueryByArgs(queryBuilder.where(resolver.storeParams.whereParams), resolver.args)
.columns(resolver.storeParams.columns);
}
}
<file_sep>/src/__specs__/MappedDataSource.spec.ts
import { mapDataSource } from "../MappedDataSource";
export const mapEmptyDataSource = (name: string) => mapDataSource({ name });
test("name mapping", () => {
const user = mapEmptyDataSource("User");
expect(user.storedName).toEqual("users");
expect(user.mappedName).toEqual("User");
const productDetails = mapEmptyDataSource("productDetails");
expect(productDetails.storedName).toEqual("product_details");
expect(productDetails.mappedName).toEqual("ProductDetail");
});
test("field mapping", () => {});
<file_sep>/src/docs/pages/mapping-operations.md
import {NextPageLink, Link} from "../components/Link";
import {CodeSnippet} from "../components/CodeSnippet";
# Mapping Operations
GRelDAL supports two types of GraphQL operations: [Queries and Mutations](https://graphql.org/learn/schema/#the-query-and-mutation-types).
Let us say we have following data source mapping:
<CodeSnippet name="mapDataSource_user_simple" />
Now we want to allow users to operate on this data source.
The most convenient way to make this happen is through one of pre-defined operation presets.
```ts
import { operationPresets } from "greldal";
const schema = mapSchema([operationPresets.query.findOneOperation(users)]);
```
A `findOne` operation allows us to query the users table like this:
```
query {
findOneUser(where: {id: 1}) {
id
name
}
}
```
This will result in an SQL query like:
```sql
select
`GQL_DAL_users__4`.`id` as `GQL_DAL_users__4__id`,
`GQL_DAL_users__4`.`name` as `GQL_DAL_users__4__name`
from `users` as `GQL_DAL_users__4`
where `GQL_DAL_users__4`.`id` = 1
limit 1
```
The preset assumes that the properties of `args.where` map exactly to field names and we want to fetch results that match all of these values.
## Pagination support
It is possible to add pagination support for `findManyOperation` through `paginatedFindManyOperation` preset:
```ts
mapSchema([operationPresets.paginatedFindManyOperation(users)]);
```
The default implementation assumes sequentially incrementing primary fields and will fail if that is not the case.
We can separately configure a monotically increasing column to be used as a cursor:
```ts
mapSchema([
operationPresets.paginatedFindManyOperation(users, mapping => ({
...mapping,
cursorColumn: "ts",
})),
]);
```
This results in GraphQL types like:
```
type GRelDALPageInfo {
prevCursor: String
nextCursor: String
totalCount: Int
}
type query {
findManyUsers(where: UserInput!): UserPageContainer
}
type User {
id: ID
name: String
age: Int
}
type UserPage {
pageInfo: GRelDALPageInfo
entities: [User]
}
type UserPageContainer {
page(cursor: String, pageSize: Int): UserPage
}
```
---
## Beyond CRUD Operations
In real world applications we would often want more flexibility in terms of how the arguments map to queries.
We will see a couple of approaches for this:
## Computed Fields
One approach that we have <Link href="mapping-data-sources#computed-fields">already seen</Link> is by defining computed fields in the data source mapping. GRelDQL can automatically resolve computed fields by mapping them to underlying concrete fields and deriving computed values from them.
## Argument Mapping
We can also specify the exact arguments we want to expose in our operation and how they map to SQL:
```ts
const argMapping = mapArgs({
fullName: mapFields({
description: "Full name of user",
type: t.string,
interceptQuery: (queryBuilder: Knex.QueryBuilder, value: string) => {
const names = value.split(" ");
return queryBuilder.where({
first_name: names[0],
last_name: names[1],
});
},
}),
});
const schema = mapSchema([
new MappedSingleSourceQueryOperation({
name: "findUsersByFullName",
rootSource: mappedDataSource,
singular: true,
args: argMapping,
}),
]);
```
## Custom (operation) resolvers
Often your business logic will not exactly map to a single database operation, and you'd want to execute custom logic in your resolvers.
At a broad level we can have two potential scenarios:
### Resolvers that don't need database access at all
GRelDAL is primarily helpful for mapping GraphQL APIs to databases. However in many cases, a few resolvers will simply call external APIs, or do some in-memory computation, or access a local file etc. and return data.
GRelDAL doesn't have anything to make such use cases easier, but it does make it easy to have such resolvers live alongside GRelDAL powered resolvers, and be a part of the same GraphQL without any schema-stitching.
`mapSchema` function accepts an array of operations. These operations are objects that conform to the `Operation` interface.
<CodeSnippet name="Operation_type" />
The `fieldConfig` property here is any graphql-js compatible [FieldConfig](https://github.com/graphql/graphql-js/blob/49d86bbc810d1203aa3f7d93252e51f257d9460f/docs/APIReference-TypeSystem.md#graphqlobjecttype).
**Examples:**
**Simple Custom operation (without any args):**
<CodeSnippet name="AdhocOperation_withoutArgs" />
**Custom operation that accepts args:**
<CodeSnippet name="AdhocOperation_withDefaultArgs" />
### Specifying types through io-ts
GRelDAL supports specifying input/output types of operations through io-ts.
This has the benefit that we can auto-derive the typescript types and use them elsewhere in our code.
For example:
<CodeSnippet name="AdhocQueryOperation_iots" />
We can check upon the generated graphql types through an introspection query:
<CodeSnippet name="AdhocQueryOperation_iots_schema_introspection_query" />
Which will give us something like:
<CodeSnippet name="AdhocQueryOperation_iots_schema_introspection_query_result" stripHeadLines={1} stripTailLines={1} />
### Resolvers that need database access
We can use the above approach to interact with database directly using Knex (or any other library). But GRelDAL makes this
use case slightly simpler through `SourceAwareOperationResolver` class.
More often than not, a resolver will delegate to one or more of other operation resolvers as illustrated below:
```ts
import {SourceAwareOperationResolver, MappedSingleSourceQueryOperation} from "greldal";
const findOperation = operationPresets.query.findOneOperation(users);
class CustomFindOperationResolver extends SourceAwareOperationResolver {
resolve() {
return findOperation.resolve({
this.source,
{
department_id: this.args.department
},
this.context,
this.resolveInfoRoot
});
}
}
const schema = mapSchema([
new MappedSingleSourceQueryOperation({
name: 'findByDepartmentId',
rootSource: users,
singular: true,
args: mapArgs({
department: {
type: t.string
}
}),
resolver: (operation, source, context, args, resolveInfoRoot) =>
new CustomFindOperationResolver(
operation,
source,
context,
args,
resolveInfoRoot
)
})
]);
```
Note that we delegated to just a single operation here (`findOperation`) but we could have delegated to multiple operations and then combined their values, which is common in practice.
It is also occasionally useful to have `resolver` function return different resolvers based on the context. So we can choose different resolution strategies (eg. whether or not to query a view) based on what is being queried.
GRelDAL makes it easy to model complex business logic as a composition of individual operations by leveraging delegation.
## Writing custom operation mapping
While custom resolvers are flexible enough for most common scenarios, in some cases it may be helpful to write a custom operation mapping which provides a more granular control over how an operation is mapped to the graphql API.
This approach involves extending the `MappedOperation` or `MappedSourceAwareOperation` class and providing a custom implementation for the `graphQLOperation` getter.
---
<NextPageLink>Mapping Associations</NextPageLink>
<file_sep>/src/MappedMultiSourceUnionQueryOperation.ts
import { GraphQLFieldConfigArgumentMap, GraphQLList } from "graphql";
import { MappedDataSource } from "./MappedDataSource";
import { MultiSelectionItem } from "./utils/util-types";
import { MappedMultiSourceOperation } from "./MappedMultiSourceOperation";
import { deriveDefaultShallowUnionInputType } from "./graphql-type-mapper";
import * as types from "./utils/types";
import { MultiSourceUnionQueryOperationResolver } from "./MultiSourceUnionQueryOperationResolver";
import { camelCase, upperFirst } from "lodash";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { OperationType } from "./operation-types";
/**
* @api-category MapperClass
*/
export class MappedMultiSourceUnionQueryOperation<
TSrc extends MappedDataSource,
TArgs extends {}
> extends MappedMultiSourceOperation<TSrc, TArgs> {
constructor(
public mapping: MappedMultiSourceOperation<TSrc, TArgs>["mapping"] & {
unionMode: "union" | "unionAll";
},
) {
super(mapping);
}
defaultResolver<TResolved>(ctx: any): SourceAwareOperationResolver<any, any, TArgs, TResolved> {
return new MultiSourceUnionQueryOperationResolver(ctx);
}
get defaultArgs(): GraphQLFieldConfigArgumentMap {
return {
where: {
type: deriveDefaultShallowUnionInputType(this.dataSources),
},
};
}
operationType = OperationType.Query;
get dataSources() {
return Object.values(this.mapping.dataSources()).map((d: MultiSelectionItem<MappedDataSource, any>) =>
d.selection(),
);
}
get name() {
return (
this.mapping.name ||
`UnionOf${Object.keys(this.mapping.dataSources())
.map(k => upperFirst(camelCase(k)))
.join("And")})`
);
}
get outputTypeName() {
return `${this.name}Output`;
}
get type() {
if (this.mapping.returnType) {
return this.mapping.returnType;
}
const outputType = types.intersection(
this.outputTypeName,
this.dataSources.map(d => d.entityTypeSpec),
);
if (this.singular) {
return outputType.graphQLOutputType;
}
return GraphQLList(outputType.graphQLOutputType);
}
}
<file_sep>/src/OperationMapping.ts
import * as t from "io-ts";
import _debug from "debug";
import { GraphQLOutputType } from "graphql";
import { MappedArgs } from "./MappedArgs";
import { MaybeMappedRT } from "./utils/util-types";
export const OperationMappingRT = t.intersection(
[
t.type({
/**
* Name of operation
* (surfaced as-is to GraphQL)
* (not used internally by GRelDAL)
*
* @memberof OperationMapping
*/
name: MaybeMappedRT(t.string, t.string),
}),
t.partial({
/**
* A human readable description of what this operation does
* (surfaced as-is to GraphQL)
* (not used internally by GRelDAL)
*
* @memberof OperationMapping
*/
description: t.string,
/**
* Whether the operation operates on a single entity (true) or a collection of entities (false)
*
* @memberof OperationMapping
*/
singular: t.boolean,
/**
* Whether the operation can operate on the concerned entity (or entities) as well as other associated entities (false)
* or just the top level entity (or entities)
*
* @memberof OperationMapping
*/
shallow: t.boolean,
}),
],
"OperationMapping",
);
/**
* @api-category ConfigType
*/
export interface OperationMapping<TArgs extends {}> extends t.TypeOf<typeof OperationMappingRT> {
/**
* GraphQL return type (or output type) of this operation
*
* (Surfaced as-is to GraphQL)
* (Not used internally by GRelDAL)
*/
returnType?: GraphQLOutputType;
/**
* Mapped operation arguments. This would be obtained by invoking the mapArgs function
*/
args?: MappedArgs<TArgs>;
resolver?: Function;
}
<file_sep>/src/docs/pages/type-safety.md
import { Link } from "../components/Link";
# Type Safety
GRelDAL is written in TypeScript and comes with type definitions. However having type definitions and being type safe are two different things.
GRelDAL attempts to balance a compromise between type-safety and ease of use. If enforcement of type-safety causes the APIs to significantly depart from
idomatic JavaScript or TypeScript conventions we are usually willing to compromise on type-safety.
Having said that, we do make a sincere attempt to ensure that as many bugs are caught at the compile time as opposed to run time and your contributions to make this better are very much appreciated.
In addition, if the error checking has to happen at runtime we try to fail-fast with clear error messages up-front.
## Runtime Type Validators
In the introduction section, we saw that stores are defined like this:
```ts
import { types, mapDataSource } from "greldal";
const users = mapDataSource({
name: "User",
description: "users",
fields: {
id: {
type: types.string,
},
name: {
type: types.string,
},
},
});
```
The type specifications (eg. `types.string`) in the mapping above are referred to as runtime types, and they validate the type of arguments at runtime.
You may wonder that given GraphQL already does validation of types at boundaries, why bother with this at all.
There are two reasons:
1. We can extract out static types from these runtime types. This enables us to write type-safe code, when using TypeScript, without ever having to define any additional types. We can simply derive the types of the entities from the data source mapping itself and if you use incorrect fields or arguments, your code will fail to compile.
2. Runtime types are composable and support [refinements](https://github.com/gcanti/io-ts#refinements), so you can embed generic validation logic in the runtime types and share them across field mappings & argument mappings across multiple stores and operations.
We not only extract static types from runtime types, we also derive GraphQL types from them - so you have to specify only the runtime types for most cases.
In some cases automatic type derivations are not possible and you may need to specify the GraphQL types separately - as is the case with `GraphQLID` in the snippet above.
The inferred GraphQL type would have been `GraphQLString` but because we have specified `GraphQLID` it would take precedence.
<file_sep>/src/index.ts
export * from "./universal";
import { generate } from "./generator";
export { generate };
<file_sep>/src/docs/pages/subscriptions.md
import {NextPageLink} from "../components/Link";
import Link from "next/link";
import {CodeSnippet} from "../components/CodeSnippet";
# Subscriptions
It is easy to use [graphql-subscriptions](https://github.com/apollographql/graphql-subscriptions) alongside GRelDAL to support real-time subscriptions.
<CodeSnippet name="mapSchema_insert_subscription" />
NotificationDispatcher facilitates adding interceptors which can receive mutation events and add additional metadata to them, add additional mutation events to be published in same batch or prevent certain mutation events from being dispatched.
## Notifying about associated data sources
A common use case is that from an application perspective certain entities can be thought of as belonging to other entities.
So in that case, we would want to trigger mutation events for one or more associated entities when an entitiy is mutated.
For example, if a Comment entity is inserted, then we may want to notify that a Post has been updated.
Common pattern for this is that in an operation interceptor we can trigger other operations (eg. queries to identify associated models) and trigger additional mutation events for them.
## Notifications from outside GRelDAL
Notifications don't have to originate from inside GRelDAL or even GraphQL operations. It is straightforward to directly use `NotificationDispatcher` and dispatch notifications from anywhere in your application code eg. background jobs, command line scripts etc.
```ts
NotificationDispatcher.dispatch({
// Type is commonly used to distinguish between notifications
// in the interceptors
type: "OrderDispatchCompletion",
// (Optional) List of entities which were affected by the change
// that caused this notification
entities: [
{id: 10, name: "Key"},
{id: 11, name: "KeyChain"}
],
// Application specific metadata attached to this notification
metadata: {
priority: 1
}
});
```
<NextPageLink>Best Practices</NextPageLink>
<file_sep>/src/docs/pages/best-practices.md
# Best Practices
Following best practices are strongly recommended by the developers of GRelDAL based on their experience of working with ambitious data driven applications.
## Ensure that database schema is in Source Control
GRelDAL currently doesn't do anything to ensure that the fields defined in data store are in sync with the database schema and you are responsible for ensuring that they don't go out of sync.
One of the most practical ways to ensure this is to use [migrations](https://knexjs.org/#Migrations) and ensure that any schema changes are tracked in version control.
For the same reason we also insist on having integration tests which test against an actual database on which the migrations have been run before each deployment.
Because our underlying data access layer Knex already has good migration support and [CLI](https://knexjs.org/#Migrations-CLI), GRelDAL doesn't provide any additional utilities for database schema management.
## Ensure backward compatibility of APIs
It is also recommended to have a [snapshot test](https://jestjs.io/docs/en/snapshot-testing) of the output of `printSchema(generatedSchema)`, where [printSchema](https://graphql.org/graphql-js/utilities/#printschema) is a function exposed from `graphql-js` which prints out a human readable description of the schema and types involved in [GraphQL SDL](https://alligator.io/graphql/graphql-sdl/) format.
It is useful for auditing changes in the exposed API as the application involves. GraphQL APIs are generally expected to be forever backward compatible and auditing of the schema is a practical way of ensuring that.
The schema snapshot also serves as contract document that describes your API in an industry standard format.
<file_sep>/src/docs/components/LibInfoBanner.js
import styled from "styled-components";
import Link from "next/link";
import logo from "../assets/logo.png";
export default function LibInfoBanner() {
return (
<Link href={`${ROOT_PATH}/`}>
<div
style={{
paddingBottom: "10px",
display: "flex",
flexDirection: "row",
cursor: "pointer",
}}
>
<img src={logo} style={{ height: "50px" , width: "50px"}} />
<div
style={{
fontWeight: "600",
fontSize: "2rem",
lineHeight: "50px",
paddingLeft: "10px",
color: "#8dd35f",
}}
>
GRelDAL
<span
css={`
font-size: 0.8rem;
font-weight: 100;
color: orange;
background: lemonchiffon;
padding: 4px;
border-radius: 4px;
border: 1px solid orange;
position: relative;
top: -20px;
`}
>
Beta
</span>
</div>
</div>
</Link>
);
}
<file_sep>/src/generator/adapters/BaseAdapter.ts
import { Adapter, TableLike, TableSchema } from "./Adapter";
import { GenConfig } from "../GenConfig";
import { globalConnector, assertConnectorConfigured } from "../../utils/connector";
import * as Knex from "knex";
export abstract class BaseAdapter implements Adapter {
constructor(private config: GenConfig) {}
get connector() {
const knex: Knex = this.config.knex || globalConnector;
assertConnectorConfigured(knex);
return knex;
}
abstract getTables(): Promise<TableLike[]>;
abstract getSchemaForTable(table: TableLike): Promise<TableSchema>;
}
<file_sep>/src/docs/components/DynamicTableOfContents.js
import React from "react";
import { times, isEqual, isEmpty } from "lodash";
import { SectionHeader } from "./Sidebar";
export default class DynamicTableOfContents extends React.Component {
state = { headers: [] };
render() {
if (isEmpty(this.state.headers)) {
return null;
}
return (
<>
<SectionHeader>Page Outline</SectionHeader>
{this.state.headers.map(h => (
<a href={`#${h.id}`}>
<div
style={{
paddingLeft: h.level * 10 + "px",
display: "flex",
flexDirection: "row",
}}
>
<div style={{ marginRight: "5px" }}>►</div>
<div>{h.label}</div>
</div>
</a>
))}
</>
);
}
componentDidMount() {
this.updateOutline();
}
componentDidUpdate() {
this.updateOutline();
}
updateOutline() {
const selectors = times(6)
.map(i => `#container h${i + 1}`)
.join(",");
const headers = [...document.querySelectorAll(selectors)]
.map(h => ({
level: Number(h.tagName.slice(1)) - 1,
label: h.innerText,
id: h.getAttribute("id"),
}))
.filter(h => h.id);
if (isEqual(this.state.headers, headers)) return;
this.setState({
headers,
});
}
}
<file_sep>/src/__specs__/test-helpers.ts
export const reportErrors = async <T>(cb: () => T | Promise<T>): Promise<T> => {
try {
return await cb();
} catch (e) {
console.error(e);
throw e;
}
};
<file_sep>/src/generator/adapters/information-schema-support.ts
import * as Knex from "knex";
import { identity, isEmpty } from "lodash";
import { TableLike, TableSchema, ForeignKeyInfo } from "./Adapter";
import { TYPES_MAPPING } from "./types-mapping";
export const retrieveTables = async (
knex: Knex,
intercept: (knex: Knex.QueryBuilder) => Knex.QueryBuilder = identity,
): Promise<TableLike[]> =>
(
await intercept(
knex("information_schema.tables").select([
// Ensures lower case keys
"table_name as table_name",
"table_schema as table_schema",
"table_type as table_type",
]),
)
).map((row: any) => {
const { table_name, table_schema, table_type } = row;
return {
schema: table_schema,
name: table_name,
type: table_type === "VIEW" ? "view" : "table",
};
});
export const getSchemaForTable = async (knex: Knex, table: TableLike): Promise<TableSchema> => {
const colInfo = await knex("information_schema.columns").where({
table_schema: table.schema,
table_name: table.name,
});
const columns = colInfo.map((c: any) => {
const typeMapping = c.data_type && TYPES_MAPPING.find(t => c.data_type.match(t.regexp));
return {
name: c.column_name,
isPrimary: false,
type: typeMapping && typeMapping.type,
};
});
const primaryKeyCols = await knex("information_schema.key_column_usage")
.leftJoin(
"information_schema.table_constraints",
"information_schema.key_column_usage.constraint_name",
"information_schema.table_constraints.constraint_name",
)
.where("information_schema.table_constraints.table_name", table.name)
.where("information_schema.key_column_usage.table_name", table.name)
.where("information_schema.table_constraints.constraint_type", "PRIMARY KEY");
if (!isEmpty(primaryKeyCols)) {
for (const pkCol of primaryKeyCols) {
for (const col of columns) {
if (col.name === pkCol.column_name) col.isPrimary = true;
}
}
}
const fkInfo: any[] = await knex("information_schema.table_constraints as tc")
.innerJoin("information_schema.key_column_usage AS kcu", function() {
this.on("tc.constraint_name", "=", "kcu.constraint_name").andOn("tc.table_schema", "=", "kcu.table_schema");
})
.innerJoin("information_schema.constraint_column_usage AS ccu", function() {
this.on("ccu.constraint_name", "=", "tc.constraint_name").andOn("ccu.table_schema", "=", "tc.table_schema");
})
.where("tc.constraint_type", "FOREIGN_KEY")
.where("tc.table_name", table.name)
.select(
"tc.table_schema",
"tc.constraint_name",
"tc.table_name",
"kcu.column_name",
"ccu.table_schema AS foreign_table_schema",
"ccu.table_name AS foreign_table_name",
"ccu.column_name AS foreign_column_name",
);
const foreignKeys: ForeignKeyInfo[] = fkInfo.map(f => {
return {
associatedTable: {
name: f.foreign_table_name,
schema: f.foreign_table_schema,
type: "table",
},
associatorColumns: {
inSource: f.column_name,
inRelated: f.foreign_column_name,
},
};
});
return {
columns,
foreignKeys,
};
};
<file_sep>/src/MappedUDF.ts
import { UDFMapping } from "./UDFMapping";
export class MappedUDF<TArgs> {
constructor(public mapping: UDFMapping<TArgs>) {}
}
export const mapFunction = <TArgs>(mapping: UDFMapping<TArgs>) => new MappedUDF(mapping);
<file_sep>/src/__specs__/helpers/snapshot-sanitizers.ts
import { isString, isFunction } from "lodash";
import { isObject } from "util";
import Maybe from "graphql/tsutils/Maybe";
const replaceCode = (err: string) => err.replace(/\[GRelDAL:\S+Error:\d+\]/, "[GRelDAL:ERR_CODE_OMITTED]");
export const removeErrorCodes = (errors: Maybe<any[]>) =>
(errors || []).map(err => {
if (isString(err)) return replaceCode(err);
if (isObject(err) && err.message) return replaceCode(err.message);
if (isObject(err) && isFunction(err.toString)) return replaceCode(err.toString());
return replaceCode(`${err}`);
});
<file_sep>/src/docs/data/faqs.yml
members:
- title: General
members:
- title: What problems does GRelDAL focus on ?
members:
- content: >
GRelDAL is primarily focussed on making it easier to build GraphQL APIs that are backed by relational databases.
GRelDAL drastically reduces the boilerplate needed to make this mapping efficient - so you fetch exactly the data you need from your data source
(Postgres, SQLite, MySQL etc.) in minimal number of roundtrips.
GRelDAL empowers you to easily leverage powerful features of modern database engines like joins, (materialized) views, procedures, jsonb etc. in your
GraphQL APIs without having to write tons of code.
- title: Why use GRelDAL instead of using graphql.js, apollo-server or TypeGraphQL ?
members:
- content: >
GRelDAL is built around a different objectives than these libraries.
These libraries are agnostic about where your data is coming from and don't provide features to optimize the data-transfer between your primary database and your API.
So it very easy to end up with N+1 queries, a chain of tiny hierarchical rquests etc.
GRelDAL makes the assumption that your primary data source is a relational database and so is able to utilize the features of relational database to optimize the
data transfer between the database and your API through batch loading, join queries, and dynamic SQL that requests the exact columns the API needs.
- title: How to debug/profile applications written using GRelDAL ?
members:
- content: >
GRelDAL is a node.js library and applications can be debugged using tools you normally use to debug Node.js applications.
We are big fans of [ndb](https://www.npmjs.com/package/ndb).
Also, GRelDAL internally uses debug package for debug logging. So you can set the DEBUG environment variable to get informative logs on exactly what is going
on under the hood. (eg. `DEBUG=greldal*`)
- title: What are the best testing strategies for applications using GRelDAL ?
members:
- content: >
We recommend having a test suite that tests your individual operations against the database you deploy to.
While GRelDAL supports multiple data stores, it is highly recommended that you develop and test against the exact same version of the database that you use
in production.
- title: My preferred database is not supported by GRelDAL. Can it be supported ?
members:
- content: >
We are currently focussing on databases which are supported by [Knex](https://knexjs.org/) -
which is our underlying data access layer.
If your database is supported by Knex then it is very likely that in very near future your
database will be supported by GRelDAL as well.
However, if your database is not supported by Knex we encourage you to create an issue or PR to have it supported in Knex first.
- title: Does/Will GRelDAL support NoSQL databases ?
members:
- content: >
GRelDAL is focussed on Relational databases. However, in future other projects in gql-dal organization may target NoSQL data stores.
Please feel free to reach out to us if you have interesting use cases around this.
- title: Database Integration
members:
- title: What databases are supported by GRelDAL ?
members:
- content: >
We officially support following databases: Postgres, MySQL and SQlite.
We eventually plan to support other datastores supported by Knex (Oracle, Redshift, MSSQL). These may already work, but we currently don't run our test suite
against them.
- title: Is GRelDAL completely database agnostic ?
members:
- content: >
GRelDAL is **reasonably agnostic**. The core of GRelDAL doesn't have database specific features, but in future we may introduce extension
modules to simplify integration with database specific features.
In case you need to use database vendor specific features right now, it is easily to construct and use raw queries.
- title: Can we use database vendor specific features ?
members:
- content: >
Yes. It is straightforward to use vendor specific features through use of raw queries.
- title: Can we build a single GraphQL API backend by multiple databases ?
members:
- content: >
Yes. It is straightforward to have different data sources connected to different databases within the same application.
- content: >
It will not be possible to perform join operations across data stores, but we can still efficiently load related data from related sources through batch loading
of associations.
- title: Schema Mapping
members:
- title: What is schema mapping ?
members:
- content: >
Schema mapping is mapping of a database schema to a GraphQL API schema.
GRelDAL supports configuration driven schema mapping with many nifty features like computed fields, json(b) support etc.
GRelDAL also supports specifying associations between your data sources so you can perform operations that span across multiple data sources.
- title: Can the name of our Input/Output types differ from database table names ?
members:
- content: >
Yes - we can explicitly specify a mappedName for a data source.
- title: Can the name of our fields differ from the table column names ?
members:
- content: >
Yes - we can explicitly specify a mappedName for a field
- title: Can we have fields which don't correspond to a column in the table being mapped ?
members:
- content: >
Yes - we can have computed fields. Computed fields don't correspond to a single column in their table, but their value is derived from the values of
multiple other columns which they depend on.
- title: Can we use plain GraphQL resolvers (unaware of GRelDAL) in our mapped schema ?
members:
- content: >
Yes - the mapSchema accepts external operation mappings as well, which don't need to be aware of GRelDAL.
This is especially helpful when we are incrementally migrating an application to use GRelDAL.
- title: Operation Resolution
members:
- title: What is an operation in GRelDAL ?
members:
- content: >
An operation is an object that can resolve a GraphQL query or mutation.
GRelDAL supports two kinds of operations
2. Source aware operations - These operations have access to GRelDAL specific APIs and are usually associated with one (or more) relational data sources.
1. External operations - These operations are not aware of GRelDAL and are usually not associated with a relational data sources.
- title: How do we define an operation ?
members:
- content: >
The mapOperation function can be used to define source aware operations.
External operations can be defined by creating an object that conforms to the MappedExternalOperation interface.
# - title: How do operations relate to GraphQL resolvers ?
# members:
# - content: >
# TBD
# - title: How does GRelDAL resolve operations ?
# - title: Can we write raw queries and map them as GraphQL queries ?
# - title: Can we map stored procedures to GraphQL mutations ?
- title: How can we implement access control for operations ?
members:
- content: >
Through interceptors
- title: How can we implement secondary caching (say using Redis/memcached) for our operations ?
members:
- content: >
Through interceptors
- title: Where do we put business logic ?
members:
- content: >
For business logic you are recommended to write pure functions which operate on entities (plain javascript objects which represent real world objects relevant to your business contexts).
These functions are often easy to unit test in isolation and easy to reason about.
These functions can later be invoked from GRelDAL resolvers which are invoked by GRelDAL when resolving operations.
- title: Does GRelDAL support express-like middlewares for operations ?
members:
- content: >
GRelDAL supports interceptors for mapped operations. You can associate an interceptor with a mapped operation through the intercept method.
Interceptors can modify arguments before they are passed to the resolver, can transform result returned by the resolver and can enforce user/group specific
permissions and constraints.
- title: How does GRelDAL manage transactions ?
members:
- content: >
GRelDAL wraps every root operation in a transactions. Any secondary operation that the root operation delegates to is run in the same transaction.
We intend to provide more control to application developers over transaction management in future.
- title: Operation presets
members:
- title: What are operation presets ?
members:
- content: >
operation presets are pre-configured operations for common use cases.
- title: How can we customize some aspects of a preset ?
members:
- content: >
If you want to customize how a preset resolves the operation, it is possible to intercept the preset.
For some more advanced use cases, you can pass a second argument to the preset factory that can transform the operation mapping.
- title: When is it better to define a custom operation instead of using an operation preset ?
members:
- content: >
When you want to introduce minor changes to the behavior of a preset, it is advisable to intercept the preset or pass a transformer.
However, if the behavior is significantly different from what any preset has to offer then it is advisable to define a custom operation.<file_sep>/src/Paginator.ts
import * as Knex from "knex";
import { PaginationConfig, ControlledPaginationConfig, isAutoPaginationConfig } from "./PaginationConfig";
import { Dict, MaybeLazy, MaybePromise } from "./utils/util-types";
import { ResolverContext } from "./ResolverContext";
import { MappedDataSource } from "./MappedDataSource";
import { MappedOperation } from "./MappedOperation";
import { isNumber } from "util";
import { isNil } from "lodash";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { ColumnSelection } from "./SingleSourceQueryOperationResolver";
import { AutoDerivedControlledPaginationConfig } from "./AutoDerivedControlledPaginationConfig";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
const DEFAULT_PAGE_SIZE = 10;
interface PageArgs {
cursor?: string;
pageSize?: number;
}
export interface PageInfo {
prevCursor: MaybeLazy<string>;
nextCursor: MaybeLazy<string>;
totalCount: MaybeLazy<MaybePromise<number>>;
}
export interface PageContainer<T> {
page: {
pageInfo: PageInfo;
entities: T[];
};
}
export type MaybePageContainer<T> = T | T[] | PageContainer<T>;
export class Paginator {
private config: ControlledPaginationConfig;
constructor(
config: PaginationConfig,
private resolverContext: SourceAwareResolverContext<
MappedSourceAwareOperation<MappedDataSource, any>,
MappedDataSource,
any
>,
private aliasHierarchyVisitor: AliasHierarchyVisitor,
) {
this.config = isAutoPaginationConfig(config) ? new AutoDerivedControlledPaginationConfig(config) : config;
}
get dataSource() {
return this.resolverContext.primaryDataSource;
}
interceptQuery(qb: Knex.QueryBuilder, selectedColumns: ColumnSelection): Knex.QueryBuilder {
return this.config.interceptQuery(
qb,
this.pageArgs.cursor,
this.pageSize,
selectedColumns,
this.aliasHierarchyVisitor,
);
}
getNextCursor(results: Dict[]): string {
return this.config.getNextCursor(results, this.aliasHierarchyVisitor);
}
getPrevCursor(results: Dict[]): string {
return this.config.getPrevCursor(results, this.aliasHierarchyVisitor);
}
getTotalCount(qb: Knex.QueryBuilder): Promise<number> {
return this.config.getTotalCount(qb, this.aliasHierarchyVisitor);
}
get parsedResolveInfo() {
return this.resolverContext.primaryPaginatedResolveInfoVisitor!.parsedResolveInfo;
}
get parsedPageContainerResolveInfo() {
return this.parsedResolveInfo.fieldsByTypeName[this.dataSource.pageContainerName];
}
get parsedPageInfoResolveInfo() {
const { pageName } = this.dataSource;
const { pageInfo } = this.parsedPageContainerResolveInfo.page.fieldsByTypeName[pageName];
return pageInfo && pageInfo.fieldsByTypeName.GRelDALPageInfo;
}
get pageArgs(): PageArgs {
return this.parsedResolveInfo.fieldsByTypeName[
this.resolverContext.operation.shallow
? this.dataSource.shallowPageContainerName
: this.dataSource.pageContainerName
].page.args;
}
get pageSize() {
const specifiedSize = this.pageArgs.pageSize;
if (isNumber(specifiedSize)) {
if (isNumber(this.config.pageSize)) {
if (this.config.pageSize !== specifiedSize) {
throw new Error(`The only permissible value of pageSize is ${this.config.pageSize}`);
}
return specifiedSize;
}
if (isNil(this.config.pageSize)) return specifiedSize;
if (isNumber(this.config.pageSize.max)) {
if (specifiedSize <= this.config.pageSize.max) return specifiedSize;
throw new Error(`pageSize exceeds maximum permissible value (${this.config.pageSize.max})`);
}
return specifiedSize;
} else {
if (isNumber(this.config.pageSize)) return this.config.pageSize;
if (isNil(this.config.pageSize)) return DEFAULT_PAGE_SIZE;
if (isNumber(this.config.pageSize.default)) return this.config.pageSize.default;
if (isNumber(this.config.pageSize.max)) {
if (DEFAULT_PAGE_SIZE < this.config.pageSize.max) return DEFAULT_PAGE_SIZE;
return this.config.pageSize.max;
}
return DEFAULT_PAGE_SIZE;
}
}
}
<file_sep>/src/InvocableMapping.ts
export interface InvocableArg<TKey extends string, TVal> {
name: TKey;
type: TVal;
argMode: ArgMode;
}
export type ArgMode = "IN" | "OUT" | "INOUT";
export interface ArgSpec<TArgs extends {}, TKey extends keyof TArgs> {
mode: ArgMode;
name: TKey;
}
// TODO: Can this be improved to ensure inclusion of all keys
export type ArgSpecsFor<TArgs extends {}> = Array<ArgSpec<TArgs, keyof TArgs>>;
<file_sep>/src/docs/components/Link.js
import L from "next/link";
import styled from "styled-components";
import slugify from "slugify";
import { toLower } from "lodash";
import {
getGuideHref,
getTermHref,
getAPIHref,
API_HREF_PATTERN,
GUIDE_HREF_PATTERN,
TERM_HREF_PATTERN,
} from "../utils/api";
export const Link = ({ href, className, style, children, highlighted, ...props }) => {
if (!children) return null;
href = href || toLower(slugify(children));
let match;
if ((match = href.match(API_HREF_PATTERN))) {
href = getAPIHref(match[1]);
children = match[1];
} else if ((match = href.match(GUIDE_HREF_PATTERN))) {
href = getGuideHref(match[1]);
children = match[1];
} else if ((match = href.match(TERM_HREF_PATTERN))) {
href = getTermHref(match[1]);
children = match[1];
} else href = `${ROOT_PATH}/${href}`;
return (
<L {...props} href={href}>
<Anchor {...{ className, style, highlighted }}>{children}</Anchor>
</L>
);
};
export const Anchor = styled.a`
cursor: pointer;
${props =>
props.highlighted &&
`background: black;
padding: 5px;
text-transform: uppercase;
border-radius: 4px;
margin: 1.6rem 0;
color: white !important;`};
`;
export const TrailingIcon = styled.div`
margin-right: 5px;
float: right;
`;
export const NextPageLink = ({ children, href = toLower(slugify(children)), ...props }) => (
<Link highlighted {...props} href={href} style={{ display: "inline-block", cursor: "pointer" }}>
<TrailingIcon
css={`
margin-left: 10px;
padding-left: 5px;
border-left: 1px solid white;
`}
>
⯈
</TrailingIcon>
<div
css={`
float: left;
background: gray;
margin: -5px;
padding: 5px 10px;
border-radius: 4px 0 0 4px;
margin-right: 5px;
`}
>
Next
</div>{" "}
<strong>{children}</strong>
</Link>
);
<file_sep>/src/__specs__/knex-helpers.ts
import * as Knex from "knex";
import { first, values } from "lodash";
export const getCount = async (qb: Knex.QueryBuilder) => Number(first(values(first(await qb.count<any>()))));
<file_sep>/src/MySQLStoredProcInvocationOperationResolver.ts
import { BaseResolver } from "./BaseResolver";
import { ResolverContext } from "./ResolverContext";
import { MappedStoredProcInvocationOperation } from "./MappedStoredProcInvocationOperation";
import { isNil, get } from "lodash";
export class MySQLStoredProcInvocationOperationResolver<
TCtx extends ResolverContext<MappedStoredProcInvocationOperation<TArgs>, TArgs>,
TArgs extends {},
TResolved
> extends BaseResolver<TCtx, TArgs, TResolved> {
/**
* Should be overriden in sub-class with the logic of resolution
*/
async resolve(): Promise<any> {
const params = this.operation.deriveParams(this.args);
const knex = this.operation.connector;
const { procedureName } = this.operation;
let result: any = {};
await knex.transaction(async trx => {
const paramPlaceholders = [];
const paramBindings: [string, string][] = [];
const toSelect = [];
for (let i = 0; i < params.length; i++) {
const placeholder = `@p${i}`;
const param = params[i];
if (param.argMode === "OUT" || param.argMode === "INOUT") {
paramPlaceholders.push(placeholder);
toSelect.push([placeholder, param.name]);
if (param.argMode === "INOUT") {
await trx.raw(`SELECT ? INTO ${placeholder};`, [isNil(param.value) ? null : param.value]);
}
} else {
paramPlaceholders.push("?");
paramBindings.push(isNil(param.value) ? null : param.value);
}
}
await trx.raw(`CALL ??(${paramPlaceholders.join(", ")})`, [procedureName, ...paramBindings]);
if (toSelect.length === 0) return;
const row = await trx.raw(`SELECT ${toSelect.map(it => it[0]).join(", ")}`);
for (const [placeholder, key] of toSelect) {
result[key!] = row[0][0][placeholder!];
}
});
return this.operation.deriveResult(result);
}
}
<file_sep>/src/ResolverContext.ts
import { GraphQLResolveInfo } from "graphql";
import { getTypeAccessorError } from "./utils/errors";
import { MappedOperation } from "./MappedOperation";
export class ResolverContext<
TMappedOperation extends MappedOperation<TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any
> {
constructor(
public operation: TMappedOperation,
public source: TGQLSource,
public args: TGQLArgs,
public context: TGQLContext,
public resolveInfoRoot: GraphQLResolveInfo,
) {}
get GQLArgsType(): TGQLArgs {
throw getTypeAccessorError("GQLArgsType", "ResolverContext");
}
get GQLSourceType(): TGQLSource {
throw getTypeAccessorError("GQLSourceType", "ResolverContext");
}
get GQLContextType(): TGQLContext {
throw getTypeAccessorError("GQLContextType", "ResolverContext");
}
get MappedOperationType(): TMappedOperation {
throw getTypeAccessorError("MappedOperationType", "ResolverContext");
}
}
<file_sep>/.gitattributes
docs/* linguist-documentation
lib/* linguist-generated=true
<file_sep>/src/generator/__specs__/__fixtures__/northwind.ts
import Knex from "knex";
import { uniqueId } from "lodash";
import { ReturnType } from "../../../utils/util-types";
const prefixTableNames = (prefix: string) => {
const prefixedName = (n: string) => `${prefix}_${n}`;
return {
employees: prefixedName("employees"),
categories: prefixedName("categories"),
customers: prefixedName("customers"),
shippers: prefixedName("shippers"),
suppliers: prefixedName("suppliers"),
orders: prefixedName("orders"),
products: prefixedName("products"),
order_details: prefixedName("order_details"),
customer_customer_demos: prefixedName("customer_customer_demos"),
customer_demographics: prefixedName("customer_demographics"),
regions: prefixedName("regions"),
territories: prefixedName("territories"),
employees_territories: prefixedName("employees_territories"),
};
};
interface SetupOptions {
shouldSetup?: (name: TableKeys) => boolean;
}
export type TableKeys = keyof ReturnType<typeof prefixTableNames>;
export const northwindFixture = (knex: Knex, prefix = uniqueId("tscope_")) => {
const tables = prefixTableNames(prefix);
const setup = async (setupOptions?: SetupOptions) => {
const addressFields = (t: Knex.CreateTableBuilder) => {
t.string("address");
t.string("city");
t.string("region");
t.string("postal_code");
t.string("country");
t.string("phone");
};
const orgAddressFields = (t: Knex.CreateTableBuilder) => {
addressFields(t);
t.string("fax");
};
const createdTables: string[] = [];
const createTable = async (name: keyof typeof tables, callback: (t: Knex.CreateTableBuilder) => void) => {
if (setupOptions && setupOptions.shouldSetup && setupOptions.shouldSetup(name) === false) return;
const tableName = tables[name];
await knex.schema.dropTableIfExists(tableName);
await knex.schema.createTable(tableName, callback);
createdTables.push(tableName);
};
await createTable("employees", t => {
t.integer("id").primary();
t.string("first_name");
t.string("last_name");
t.string("title");
t.date("birth_date");
t.date("hire_date");
t.string("address");
t.string("city");
t.string("region");
t.string("postal_code");
t.string("country");
t.string("home_home");
t.string("extension");
t.binary("photo");
t.string("notes");
t.integer("reports_to")
.references("id")
.inTable(tables.employees);
t.string("photo_path");
});
await createTable("categories", t => {
t.integer("id").primary();
t.string("category_name");
t.string("description");
});
await createTable("customers", t => {
t.string("id").primary();
t.string("company_name");
t.string("contact_name");
t.string("contact_title");
orgAddressFields(t);
});
await createTable("shippers", t => {
t.string("id").primary();
t.string("company_name");
t.string("phone");
});
await createTable("suppliers", t => {
t.integer("id").primary();
t.string("company_name");
t.string("contact_name");
t.string("contact_title");
orgAddressFields(t);
t.string("home_page");
});
await createTable("orders", t => {
t.integer("id").primary();
t.string("customer_id")
.references("id")
.inTable(tables.customers);
t.integer("employee_id")
.references("id")
.inTable(tables.employees);
t.date("order_date");
t.date("required_date");
t.date("shipped_date");
t.integer("ship_via");
t.decimal("freight");
t.string("ship_name");
t.string("ship_address");
t.string("ship_city");
t.string("ship_region");
t.string("ship_postal_code");
t.string("ship_country");
});
await createTable("products", t => {
t.integer("id").primary();
t.string("product_name");
t.integer("supplier_id").notNullable();
t.integer("category_id").notNullable();
t.string("quantity_per_unit");
t.decimal("unit_price");
t.integer("units_in_stock");
t.integer("units_on_order");
t.integer("reorder_level");
t.integer("discontinued");
});
await createTable("order_details", t => {
t.string("id").primary();
t.integer("order_id");
t.integer("product_id");
t.decimal("unit_price");
t.integer("quantity");
t.decimal("discount");
});
await createTable("customer_customer_demos", t => {
t.string("id").primary();
t.string("customer_type_id");
});
await createTable("customer_demographics", t => {
t.string("id").primary();
t.string("customer_desc");
});
await createTable("regions", t => {
t.integer("id").primary();
t.string("region_description");
});
await createTable("territories", t => {
t.string("id").primary();
t.string("territory_description");
t.integer("region_id")
.notNullable()
.references("id")
.inTable(tables.regions);
});
await createTable("employees_territories", t => {
t.string("id").primary();
t.integer("employee_id")
.notNullable()
.references("id")
.inTable(tables.employees);
t.string("territory_id")
.notNullable()
.references("id")
.inTable(tables.territories);
});
const teardown = async () => {
for (let i = createdTables.length - 1; i >= 0; i--) {
console.log("Dropping Table:", createdTables[i]);
await knex.schema.dropTable(createdTables[i]);
}
};
return { teardown };
};
return {
tables,
setup,
};
};
<file_sep>/src/StoredProcMapping.ts
import { ArgSpecsFor } from "./InvocableMapping";
export interface StoredProcMapping<TArgs> {
name: string;
args: ArgSpecsFor<TArgs>;
}
<file_sep>/src/MappedAssociation.ts
import { MappedDataSource } from "./MappedDataSource";
import { singularize } from "inflection";
import { SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver";
import { getTypeAccessorError } from "./utils/errors";
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { isBoolean, isPlainObject, transform } from "lodash";
import _debug from "debug";
import * as Knex from "knex";
import { indexBy, MemoizeGetter } from "./utils/utils";
import { isString, isFunction } from "util";
import { TypeGuard, Dict, PartialDeep } from "./utils/util-types";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { assertType } from "./utils/assertions";
import {
AssociationMappingRT,
AssociationMapping,
AssociationPreFetchConfig,
MappedForeignOperation,
AssociationPostFetchConfig,
AssociationJoinConfig,
JoinTypeId,
} from "./AssociationMapping";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { createJoinBuilder } from "./utils/JoinBuilder";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
const debug = _debug("greldal:MappedAssociation");
/**
* A mapped association represents an association among multiple data sources and encapsulates the knowledge of how to fetch a connected
* data source while resolving an operation in another data source.
*
* @api-category MapperClass
*/
export class MappedAssociation<TSrc extends MappedDataSource = any, TTgt extends MappedDataSource = any> {
constructor(public dataSource: TSrc, public mappedName: string, private mapping: AssociationMapping<TSrc, TTgt>) {
assertType(
AssociationMappingRT,
mapping,
`Association mapping configuration:\nDataSource<${dataSource}>[associations][${mappedName}]`,
);
}
/**
* If the association will resolve to at most one associated entity
*/
@MemoizeGetter
get singular() {
if (isBoolean(this.mapping.singular)) {
return this.mapping.singular;
}
return singularize(this.mappedName) === this.mappedName;
}
/**
* If the association will be exposed through GraphQL API
*/
get exposed() {
return this.mapping.exposed !== false;
}
/**
* Linked data source
*/
get target(): TTgt {
return this.mapping.target.apply(this);
}
/**
* Association description made available through the GraphQL API
*/
get description() {
return this.mapping.description;
}
/**
* If the association supports paginated response
*/
get isPaginated() {
return !!this.mapping.paginate;
}
/**
* For a given operation, identify one of the (potentially) many many fetch configurations specified
* using the fetchThrough mapping property.
*/
getFetchConfig<
TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>,
TRootSrc extends MappedDataSource<any>,
TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any,
TResolved = any
>(operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>) {
for (const config of this.mapping.fetchThrough) {
if (
!config.useIf ||
config.useIf.call<
MappedAssociation<TSrc, TTgt>,
[SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>],
boolean
>(this, operation)
) {
return config;
}
}
return null;
}
/**
* Start Side loading associated entities before the parent entity has been fetched
*/
preFetch<
TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>,
TRootSrc extends MappedDataSource<any>,
TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any,
TResolved = any
>(
preFetchConfig: AssociationPreFetchConfig<TSrc, TTgt>,
operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>,
) {
return preFetchConfig.preFetch.call<
MappedAssociation<TSrc, TTgt>,
[SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>],
MappedForeignOperation<MappedSingleSourceOperation<TTgt, any>>
>(this, operation);
}
/**
* Side-load associated entities after parent entity has been fetched
*/
postFetch<
TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>,
TRootSrc extends MappedDataSource<any>,
TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any,
TResolved = any
>(
postFetchConfig: AssociationPostFetchConfig<TSrc, TTgt>,
operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>,
parents: PartialDeep<TSrc["EntityType"]>[],
) {
return postFetchConfig.postFetch.call<
MappedAssociation<TSrc, TTgt>,
[
SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>,
PartialDeep<TSrc["EntityType"]>[],
],
MappedForeignOperation<MappedSingleSourceOperation<TTgt, any>>
>(this, operation, parents);
}
join(
joinConfig: AssociationJoinConfig<TSrc, TTgt>,
queryBuilder: Knex.QueryBuilder,
aliasHierarchyVisitor: AliasHierarchyVisitor,
): AliasHierarchyVisitor {
if ((isFunction as TypeGuard<Function>)(joinConfig.join)) {
return joinConfig.join(createJoinBuilder(queryBuilder, aliasHierarchyVisitor)).aliasHierarchyVisitor;
}
if ((isString as TypeGuard<JoinTypeId>)(joinConfig.join) && isPlainObject(this.associatorColumns)) {
const { storedName } = this.target;
const sourceAlias = aliasHierarchyVisitor.alias;
const nextAliasHierarchyVisitor = aliasHierarchyVisitor.visit(this.mappedName)!;
const { alias } = nextAliasHierarchyVisitor;
queryBuilder[joinConfig.join](
`${storedName} as ${alias}`,
`${sourceAlias}.${this.associatorColumns!.inSource}`,
`${alias}.${this.associatorColumns!.inRelated}`,
);
return nextAliasHierarchyVisitor;
}
throw new Error(`Not enough information to autoJoin association. Specify a join function`);
}
isAutoJoinable(joinConfig: AssociationJoinConfig<TSrc, TTgt>) {
return isString(joinConfig.join) && isPlainObject(this.associatorColumns);
}
/**
* Associates side loaded entities with parent entity.
*/
associateResultsWithParents(
fetchConfig: AssociationPreFetchConfig<TSrc, TTgt> | AssociationPostFetchConfig<TSrc, TTgt>,
) {
return (parents: PartialDeep<TSrc["EntityType"]>[], results: PartialDeep<TTgt["EntityType"]>[]) => {
if (fetchConfig.associateResultsWithParents) {
return fetchConfig.associateResultsWithParents.call(this, parents, results);
}
debug("associating results with parents -- parents: %O, results: %O", parents, results);
if (!this.mapping.associatorColumns) {
throw new Error("Either associatorColumns or associateResultsWithParents must be specified");
}
const { inRelated, inSource } = this.mapping.associatorColumns!;
const parentsIndex = indexBy(parents, inSource);
results.forEach(result => {
const pkey = result[inRelated] as any;
if (!pkey) return;
const parent = parentsIndex[pkey] as any;
if (!parent) return;
if (this.mapping.singular) {
parent[this.mappedName] = result;
} else {
parent[this.mappedName] = parent[this.mappedName] || [];
parent[this.mappedName].push(result);
}
});
};
}
/**
* Columns used to link the data sources at the persistence layer
*/
get associatorColumns() {
return this.mapping.associatorColumns;
}
/**
* Getter to obtain the type of source DataSource.
*
* This is expected to be used only in mapped typescript types. Invoking the getter directly
* at runtime will throw.
*/
get DataSourceType(): TSrc {
throw getTypeAccessorError("DataSourceType", "MappedAssociation");
}
/**
* Getter to obtain the type of associated DataSource.
*
* This is expected to be used only in mapped typescript types. Invoking the getter directly
* at runtime will throw.
*/
get AssociatedDataSourceType(): TTgt {
throw getTypeAccessorError("AssociatedDataSourceType", "MappedAssociation");
}
/**
* Getter to obtain the type of entity from source DataSource.
*
* This is expected to be used only in mapped typescript types. Invoking the getter directly
* at runtime will throw.
*/
get SourceEntityType(): TSrc["EntityType"] {
throw getTypeAccessorError("SourceEntityType", "MappedAssociation");
}
/**
* Getter to obtain the type of entity from associated DataSource.
*
* This is expected to be used only in mapped typescript types. Invoking the getter directly
* at runtime will throw.
*/
get AssociatedEntityType(): TTgt["EntityType"] {
throw getTypeAccessorError("AssociatedEntityType", "MappedAssociation");
}
}
type AssociationMappingResult<
TMapping extends Dict<AssociationMapping<any, MappedDataSource>>,
TSrc extends MappedDataSource
> = {
[K in keyof TMapping]: MappedAssociation<TSrc, ReturnType<TMapping[K]["target"]>>;
};
/**
* Used to define an association between two data sources.
*
* Make sure you have gone through the [Association Mapping](guide:mapping-associations) guide first which elaborates on
* the concepts behind association mapping.
*
* Association mapping determines how two data sources can be linked (through joins, or auxiliary queries) so
* that operations can be performed over multiple data sources.
*
* Accepts an [AssociationMapping](api:AssociationMapping) configuration.
*
* @api-category PrimaryAPI
* @param associations
*/
export const mapAssociations = <TMapping extends Dict<AssociationMapping<any, MappedDataSource>>>(
associations: TMapping,
) => <TSrc extends MappedDataSource>(dataSource: TSrc): AssociationMappingResult<TMapping, TSrc> =>
transform(
associations,
(result: Dict, associationMapping, name) => {
result[name] = new MappedAssociation(dataSource, name, associationMapping);
},
{},
) as any;
<file_sep>/src/UDFInvocationOperationResolver.ts
import { BaseResolver } from "./BaseResolver";
import { ResolverContext } from "./ResolverContext";
import { MappedUDFInvocationOperation } from "./MappedUDFInvocationOperation";
import { get } from "lodash";
export class UDFInvocationOperationResolver<
TCtx extends ResolverContext<MappedUDFInvocationOperation<TArgs>, TArgs>,
TArgs extends {},
TResolved
> extends BaseResolver<TCtx, TArgs, TResolved> {
/**
* Should be overriden in sub-class with the logic of resolution
*/
async resolve(): Promise<any> {
const params = this.operation.deriveParams(this.args);
const knex = this.operation.connector;
const { procedureName } = this.operation;
const result = await knex
.select("*")
.from(
knex.raw(`??(${params.map(() => "?").join(" ,")})`, [
procedureName,
...params.map(({ value }) => value),
]),
);
const invocationResult = get(result, [0, procedureName]);
return this.operation.deriveResult(invocationResult);
}
}
<file_sep>/src/MappedMultiSourceOperation.ts
import _debug from "debug";
import { MappedDataSource } from "./MappedDataSource";
import { MultiSelection, MultiSelectionItem, Dict } from "./utils/util-types";
import { MappedAssociation } from "./MappedAssociation";
import { GraphQLResolveInfo } from "graphql";
import { ResolveInfoVisitor } from "./ResolveInfoVisitor";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
export type DataSourceTypes<
TOp extends MappedMultiSourceOperation<TSrc, TArgs>,
TSrc extends MappedDataSource,
TArgs extends {}
> = {
[K in keyof ReturnType<TOp["mapping"]["dataSources"]>]: ReturnType<
ReturnType<TOp["mapping"]["dataSources"]>[K]["selection"]
>;
};
export abstract class MappedMultiSourceOperation<
TSrc extends MappedDataSource,
TArgs extends object
> extends MappedSourceAwareOperation<TSrc, TArgs> {
constructor(
public readonly mapping: MappedSourceAwareOperation<TSrc, TArgs>["mapping"] & {
dataSources: <
TCtx extends SourceAwareResolverContext<MappedMultiSourceOperation<TSrc, TArgs>, TSrc, TArgs>
>() => MultiSelection<
TSrc,
TCtx,
MultiSelectionItem<TSrc, TCtx> & {
deriveWhereParams?: (args: TArgs, association?: MappedAssociation) => Dict;
}
>;
},
) {
super(mapping);
}
get supportsMultipleDataSources() {
return true;
}
async createResolverContext(
source: any,
args: TArgs,
context: any,
resolveInfo: GraphQLResolveInfo,
resolveInfoVisitor?: ResolveInfoVisitor<any>,
): Promise<SourceAwareResolverContext<MappedMultiSourceOperation<TSrc, TArgs>, TSrc, TArgs>> {
return SourceAwareResolverContext.create(
this,
this.mapping.dataSources(),
source,
args,
context,
resolveInfo,
resolveInfoVisitor,
);
}
async *iterateDataSources<
TCtx extends SourceAwareResolverContext<MappedMultiSourceOperation<TSrc, TArgs>, TSrc, TArgs>
>(resolverContext: TCtx) {
for (const [key, { shouldUse, ...dataSourceConfig }] of Object.entries(this.mapping.dataSources())) {
if (!shouldUse || (await shouldUse(resolverContext))) {
const dataSource = dataSourceConfig.selection();
yield { key, dataSource, dataSourceConfig };
}
}
}
}
<file_sep>/src/PaginationConfig.ts
import * as t from "io-ts";
import * as Knex from "knex";
import { Dict, Maybe } from "./utils/util-types";
import { has } from "lodash";
import { ColumnSelection } from "./SingleSourceQueryOperationResolver";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
export const BasePaginationConfigRT = t.partial(
{
pageSize: t.union([
t.number,
t.partial({
max: t.number,
default: t.number,
}),
]),
},
"BasePaginationConfig",
);
export const AutoPaginationConfigRT = t.intersection(
[
t.interface({
cursorColumn: t.string,
}),
BasePaginationConfigRT,
],
"AutoPaginationConfig",
);
export const ControlledPaginationConfigRT = t.intersection(
[
BasePaginationConfigRT,
t.interface({
interceptQuery: t.Function,
getNextCursor: t.Function,
getPrevCursor: t.Function,
getTotalCount: t.Function,
}),
],
"ControlledPaginationConfig",
);
export const PaginationConfigRT = t.union([AutoPaginationConfigRT, ControlledPaginationConfigRT], "PaginationConfig");
export interface AutoPaginationConfig extends t.TypeOf<typeof AutoPaginationConfigRT> {}
export interface ControlledPaginationConfig extends t.TypeOf<typeof ControlledPaginationConfigRT> {
interceptQuery(
qb: Knex.QueryBuilder,
cursor: Maybe<string>,
pageSize: number,
selectedColumns: ColumnSelection,
ahv: AliasHierarchyVisitor,
): Knex.QueryBuilder;
getNextCursor(results: Dict[], ahv: AliasHierarchyVisitor): string;
getPrevCursor(results: Dict[], ahv: AliasHierarchyVisitor): string;
getTotalCount(qb: Knex.QueryBuilder, ahv: AliasHierarchyVisitor): Promise<number>;
}
export type PaginationConfig = AutoPaginationConfig | ControlledPaginationConfig;
export const isAutoPaginationConfig = (config: PaginationConfig): config is AutoPaginationConfig =>
has(config, "cursorColumn");
<file_sep>/src/SingleSourceInsertionOperationResolver.ts
import _debug from "debug";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { Dict } from "./utils/util-types";
import { MemoizeGetter } from "./utils/utils";
import { pick, isEqual, uniqWith } from "lodash";
import { MappedSingleSourceInsertionOperation } from "./MappedSingleSourceInsertionOperation";
import { MappedDataSource } from "./MappedDataSource";
import { isPresetSingleInsertionParams, isPresetMultiInsertionParams } from "./operation-presets";
import { expectedOverride } from "./utils/errors";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import * as NotificationDispatcher from "./NotificationDispatcher";
const debug = _debug("greldal:InsertionOperationResolver");
/**
* Implements resolution of insertion operation on a single data source
*
* Sample GraphQL request:
*
* ```graphql
* mutation {
* insertManyUsers(entities: [{id: 1, name: "<NAME>"}]) {
* id, name
* }
* }
* ```
*
* ```graphql
* mutation {
* insertOneUser(entity: {id: 1, name: "<NAME>"}) {
* id, name
* }
* }
* ```
*
* Assumes that:
*
* 1. Mapped entity being inserted is available through an entity/entities argument
* 2. result fields in query correspond to mapped field names in data source
*
* 1 is not a hard assumption and custom argument mapping can be specified through args property in the OperationMapping.
*
* @see ArgMapping.interceptEntity
*
* @api-category CRUDResolvers
*/
export class SingleSourceInsertionOperationResolver<
TCtx extends SourceAwareResolverContext<MappedSingleSourceInsertionOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc extends MappedDataSource,
TArgs extends {},
TResolved
> extends SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved> {
@MemoizeGetter
get entities(): Dict[] {
let entities: Dict[];
const { args } = this.resolverContext;
if (this.resolverContext.operation.singular) {
if (!isPresetSingleInsertionParams(args)) throw expectedOverride();
entities = [args.entity || {}];
} else {
if (!isPresetMultiInsertionParams(args)) throw expectedOverride();
entities = args.entities;
}
const argsSpec = this.resolverContext.operation.args;
if (!argsSpec) return entities;
return entities.map(entity => argsSpec.interceptEntity(entity));
}
get aliasHierarchyVisitor() {
return new AliasHierarchyVisitor().visit(this.resolverContext.primaryDataSource.storedName)!;
}
async resolve(): Promise<any> {
let primaryKeyValues: Dict[];
const source = this.resolverContext.primaryDataSource;
const result = await this.wrapInTransaction(async () => {
let queryBuilder = this.createRootQueryBuilder(source);
const mappedRows = source.mapEntitiesToRows(this.entities);
const pkSourceCols = source.primaryFields.map(f => f.sourceColumn!);
primaryKeyValues = uniqWith(
mappedRows.map(r => pick(r, pkSourceCols)),
isEqual,
);
debug("Mapped entities to rows:", this.entities, mappedRows);
if (this.supportsReturning) queryBuilder = queryBuilder.returning(source.storedColumnNames);
const results = await queryBuilder
.clone()
.from(source.storedName) // MySQL doesn't support aliases during insert
.insert<Dict[]>(mappedRows);
// When returning is available we map from returned values to ensure that database level defaults etc. are correctly
// accounted for:
if (this.supportsReturning) return source.mapRowsToShallowEntities(results);
this.queryByPrimaryKeyValues(queryBuilder, primaryKeyValues);
const fetchedRows = await queryBuilder.select(source.storedColumnNames);
return source.mapRowsToShallowEntities(fetchedRows);
});
NotificationDispatcher.publish([
{
type: NotificationDispatcher.PrimitiveMutationType.Insert,
entities: {
[source.mappedName]: source.mapRowsToShallowEntities(primaryKeyValues!),
},
},
]);
return result;
}
}
<file_sep>/src/SingleSourceQueryOperationResolver.ts
import _debug from "debug";
import { uniqBy, some, has, transform } from "lodash";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { MappedDataSource } from "./MappedDataSource";
import { DataSourceMapping } from "./DataSourceMapping";
import { MappedField } from "./MappedField";
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { ResolveInfoVisitor } from "./ResolveInfoVisitor";
import { Dict, PartialDeep } from "./utils/util-types";
import { indexBy, MemoizeGetter } from "./utils/utils";
import { MappedAssociation } from "./MappedAssociation";
import {
AssociationFetchConfig,
isPreFetchConfig,
AssociationPreFetchConfig,
isPostFetchConfig,
AssociationPostFetchConfig,
isJoinConfig,
AssociationJoinConfig,
MappedForeignOperation,
} from "./AssociationMapping";
import { SourceAwareOperationResolver, BaseStoreParams } from "./SourceAwareOperationResolver";
import { Paginator, PageContainer } from "./Paginator";
import { MaybePaginatedResolveInfoVisitor, PaginatedResolveInfoVisitor } from "./PaginatedResolveInfoVisitor";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
const debug = _debug("greldal:QueryOperationResolver");
/**
* @api-category ConfigType
*/
export interface PrimaryRowMapper {
readonly field: MappedField;
readonly tablePath: string[];
readonly columnAlias?: string;
}
/**
* @api-category ConfigType
*/
export interface PreFetchedRowMapper<TResult, TParent> {
readonly propertyPath: string[];
readonly result: Promise<TResult[]>;
readonly reverseAssociate: (parents: TParent[], results: TResult[]) => void;
}
/**
* @api-category ConfigType
*/
export interface PostFetchedRowMapper<TResult, TParent> {
readonly propertyPath: string[];
readonly run: (parents: TParent[]) => Promise<TResult[]>;
readonly reverseAssociate: (parents: TParent[], results: TResult[]) => void;
}
export type ColumnSelection = { /* Column alias: */ [k: string]: /* Mapped field name: */ string }[];
/**
* @api-category ConfigType
*/
export interface StoreQueryParams<T extends MappedDataSource> extends BaseStoreParams {
readonly whereParams: Dict;
readonly columns: ColumnSelection;
readonly primaryMappers: PrimaryRowMapper[];
readonly secondaryMappers: {
readonly preFetched: PreFetchedRowMapper<any, Partial<T["ShallowEntityType"]>>[];
readonly postFetched: PostFetchedRowMapper<any, Partial<T["ShallowEntityType"]>>[];
};
}
/**
* Implements query operation resolution on a single data source
*
* @api-category CRUDResolvers
*/
export class SingleSourceQueryOperationResolver<
TCtx extends SourceAwareResolverContext<TMappedOperation, TSrc, TArgs>,
TSrc extends MappedDataSource,
TMappedOperation extends MappedSingleSourceQueryOperation<TSrc, TArgs>,
TArgs extends {},
TResolved
> extends SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved> {
resultRows?: Dict[];
aliasColumnsToTableScope: boolean = true;
private paginator?: Paginator;
constructor(public resolverContext: TCtx) {
super(resolverContext);
if (this.operation.paginationConfig) {
this.paginator = new Paginator(
this.operation.paginationConfig,
resolverContext,
this.aliasHierarchyVisitor,
);
}
}
@MemoizeGetter
get aliasHierarchyVisitor() {
const source = this.resolverContext.primaryDataSource;
return this.getAliasHierarchyVisitorFor(source);
}
@MemoizeGetter
get storeParams(): StoreQueryParams<TCtx["DataSourceType"]> {
const source = this.resolverContext.primaryDataSource;
const storeParams = {
whereParams: this.resolverContext.primaryDataSource.mapQueryParams(
this.resolverContext.operation.deriveWhereParams(
this.resolverContext.primaryResolveInfoVisitor.parsedResolveInfo.args as any,
),
this.getAliasHierarchyVisitorFor(source),
),
queryBuilder: this.createRootQueryBuilder(source),
columns: [],
primaryMappers: [],
secondaryMappers: {
preFetched: [],
postFetched: [],
},
};
debug("storeParams:", storeParams);
return storeParams;
}
async resolve(): Promise<TResolved> {
const source = this.resolverContext.primaryDataSource;
return this.wrapInTransaction(async () => {
this.resolveFields<TSrc>(
[],
this.getAliasHierarchyVisitorFor(source),
source,
this.resolverContext.primaryResolveInfoVisitor,
);
const resultRows = await this.runQuery();
if (this.paginator) {
this.resultRows = resultRows.slice(0, this.paginator.pageSize);
} else {
this.resultRows = resultRows;
}
debug("Fetched rows:", this.resultRows);
const entities: TSrc["EntityType"][] = await source.mapRowsToEntities(
this.resultRows!,
this.storeParams as any,
);
if (this.paginator) {
const pageInfoResolveInfo = this.paginator.parsedPageInfoResolveInfo;
let totalCount: number;
if (pageInfoResolveInfo && pageInfoResolveInfo.totalCount) {
totalCount = await this.paginator!.getTotalCount(this.getQueryBuilder());
}
const pageContainer: PageContainer<TSrc["EntityType"]> = {
page: {
pageInfo: {
prevCursor: () => this.paginator!.getPrevCursor(resultRows),
nextCursor: () => this.paginator!.getNextCursor(resultRows),
totalCount: totalCount!,
},
entities,
},
};
return pageContainer as any;
}
return entities as any;
});
}
getQueryBuilder() {
return this.resolverContext.operation.interceptQueryByArgs(
this.storeParams.queryBuilder.where(this.storeParams.whereParams),
this.resolverContext.args,
);
}
async runQuery() {
let queryBuilder = this.getQueryBuilder().clone();
if (this.paginator) {
this.resolverContext.primaryPaginatedResolveInfoVisitor!.parsedResolveInfo;
queryBuilder = this.paginator.interceptQuery(queryBuilder, this.storeParams.columns);
}
if (this.resolverContext.operation.singular) {
const { primaryColumnNames } = this.resolverContext.primaryDataSource;
const { alias } = this.aliasHierarchyVisitor;
if (primaryColumnNames.length > 0) {
const primaryColsSatisfied = !some(
primaryColumnNames,
colName => !has(this.storeParams.whereParams, `${alias}.${colName}`),
);
if (!primaryColsSatisfied) {
const pkQueryBuilder = queryBuilder
.clone()
.columns(primaryColumnNames.map(c => `${alias}.${c}`))
.limit(1);
const pkVals: Dict[] = await pkQueryBuilder;
const whereParams = transform(
pkVals[0],
(result: Dict, primaryColVal, primaryColName) => {
result[`${alias}.${primaryColName}`] = primaryColVal;
},
{},
);
queryBuilder.clearWhere().where(whereParams);
}
}
}
const rows = await queryBuilder.columns(this.storeParams.columns);
return rows;
}
resolveFields<TCurSrc extends MappedDataSource>(
tablePath: string[] = [],
aliasHierarchyVisitor: AliasHierarchyVisitor,
dataSource: TCurSrc,
resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>,
typeName = this.resolverContext.operation.shallow ? dataSource.shallowMappedName : dataSource.mappedName,
ignoreMissing = false,
) {
for (const { fieldName } of resolveInfoVisitor!.iterateFieldsOf(typeName)) {
this.resolveFieldName(
fieldName,
tablePath,
aliasHierarchyVisitor,
dataSource,
resolveInfoVisitor,
ignoreMissing,
);
}
}
private resolveFieldName<
TCurSrcMapping extends DataSourceMapping,
TCurSrc extends MappedDataSource<TCurSrcMapping>
>(
fieldName: keyof TCurSrc["fields"] | keyof TCurSrc["associations"],
tablePath: string[],
aliasHierarchyVisitor: AliasHierarchyVisitor,
dataSource: MappedDataSource<TCurSrcMapping>,
resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>,
ignoreMissing = false,
) {
const fieldName_: any = fieldName;
const field: MappedField<MappedDataSource<TCurSrcMapping>> = (dataSource.fields as Dict<
MappedField<MappedDataSource<TCurSrcMapping>>
>)[fieldName_];
if (field) {
debug("Identified field corresponding to fieldName %s -> %O", fieldName, field);
this.deriveColumnsForField(field, tablePath, aliasHierarchyVisitor, this.aliasColumnsToTableScope);
return;
}
if (!this.resolverContext.operation.shallow) {
const association = (dataSource.associations as Dict<MappedAssociation<MappedDataSource<TCurSrcMapping>>>)[
fieldName_
];
if (association) {
debug("Identified candidate associations corresponding to fieldName %s -> %O", fieldName, association);
const fetchConfig = association.getFetchConfig<TCtx, TSrc, TMappedOperation, TArgs>(this);
if (!fetchConfig) {
throw new Error("Unable to resolve association through any of the specified fetch configurations");
}
this.resolveAssociation(association, fetchConfig, tablePath, aliasHierarchyVisitor, resolveInfoVisitor);
return;
}
}
if (ignoreMissing) return;
throw new Error(`Unable to resovle fieldName ${fieldName} in dataSource: ${dataSource.mappedName}`);
}
private resolveAssociation<TCurSrc extends MappedDataSource>(
association: MappedAssociation<TCurSrc>,
fetchConfig: AssociationFetchConfig<TCurSrc, any>,
tablePath: string[],
aliasHierarchyVisitor: AliasHierarchyVisitor,
resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>,
) {
const associationVisitor = resolveInfoVisitor.visitRelation(association);
if (isPreFetchConfig(fetchConfig)) {
this.storeParams.secondaryMappers.preFetched.push({
propertyPath: tablePath,
reverseAssociate: association.associateResultsWithParents(
fetchConfig as AssociationPreFetchConfig<any, any>,
),
result: this.invokeSideLoader(
() => association.preFetch(fetchConfig as AssociationPreFetchConfig<any, any>, this),
associationVisitor,
),
});
} else if (isPostFetchConfig(fetchConfig)) {
this.storeParams.secondaryMappers.postFetched.push({
propertyPath: tablePath,
reverseAssociate: association.associateResultsWithParents(
fetchConfig as AssociationPostFetchConfig<any, any>,
),
run: async (parents: PartialDeep<TCurSrc["EntityType"]>[]) =>
this.invokeSideLoader(
() => association.postFetch(fetchConfig as AssociationPostFetchConfig<any, any>, this, parents),
associationVisitor,
),
});
} else if (isJoinConfig(fetchConfig)) {
if (associationVisitor instanceof PaginatedResolveInfoVisitor) {
throw new Error("Pagination is current not supported with joined associations");
}
this.deriveJoinedQuery(association, fetchConfig, tablePath, aliasHierarchyVisitor, associationVisitor);
} else {
throw new Error(`Every specified association should be resolvable through a preFetch, postFetch or join`);
}
}
private deriveJoinedQuery<TCurSrc extends MappedDataSource>(
association: MappedAssociation<TCurSrc>,
fetchConfig: AssociationJoinConfig<TCurSrc, any>,
tablePath: string[],
aliasHierarchyVisitor: AliasHierarchyVisitor,
resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>,
) {
const relDataSource: MappedDataSource = association.target;
const nextAliasHierarchyVisitor = association.join(
fetchConfig,
this.storeParams.queryBuilder,
aliasHierarchyVisitor,
);
this.resolverContext.primaryDataSource.mapQueryParams(
this.resolverContext.operation.deriveWhereParams(
resolveInfoVisitor.parsedResolveInfo.args as any,
association,
),
nextAliasHierarchyVisitor,
);
this.resolveFields(
tablePath.concat(association.mappedName),
nextAliasHierarchyVisitor,
relDataSource,
resolveInfoVisitor,
);
}
private invokeSideLoader<TCurSrc extends MappedDataSource>(
sideLoad: <TArgs extends {}>() => MappedForeignOperation<MappedSingleSourceOperation<TCurSrc, TArgs>>,
associationVisitor: MaybePaginatedResolveInfoVisitor<TCurSrc>,
) {
const { operation: query, args } = sideLoad();
return query.resolve(
this.resolverContext.source,
args,
this.resolverContext.context,
this.resolverContext.resolveInfoRoot,
associationVisitor,
resolver => {
const r = resolver as SourceAwareOperationResolver<any, any, any, any>;
r.isDelegated = true;
r.activeTransaction = this.activeTransaction;
return r;
},
);
}
associateResultsWithParents<TCurSrc extends MappedDataSource>(association: MappedAssociation<TCurSrc>) {
if (!association.associatorColumns) {
throw new Error(
"Either association.associatorColumns or association.associateResultsWithParents is mandatory",
);
}
return (parents: Dict[], results: Dict[]) => {
debug("associating results with parents -- parents: %O, results: %O", parents, results);
const { inSource, inRelated } = association.associatorColumns!;
const parentsIndex = indexBy(parents, inSource);
results.forEach(result => {
const pkey = result[inRelated] as any;
if (!pkey) return;
const parent = parentsIndex[pkey] as any;
if (!parent) return;
if (association.singular) {
parent[association.mappedName] = result;
} else {
parent[association.mappedName] = parent[association.mappedName] || [];
parent[association.mappedName].push(result);
}
});
};
}
private deriveColumnsForField(
field: MappedField,
tablePath: string[],
aliasHierarchyVisitor: AliasHierarchyVisitor,
aliasColumnsToTableScope = true,
): any {
field.getColumnMappingList(aliasHierarchyVisitor, aliasColumnsToTableScope).forEach(colMapping => {
this.storeParams.columns.push({
[colMapping.columnAlias]: colMapping.columnRef,
});
this.storeParams.primaryMappers.push({
field: colMapping.field,
tablePath,
columnAlias: colMapping.columnAlias,
});
});
if (field.isComputed) {
this.storeParams.primaryMappers.push({
field,
tablePath,
});
}
}
get primaryFieldMappers() {
const { primaryFields } = this.resolverContext.operation.rootSource;
if (primaryFields.length === 0) {
throw new Error("This operation preset requires one/more primary key fields but none were found");
}
const primaryMappers = uniqBy(
this.storeParams.primaryMappers.filter(pm => pm.field.isPrimary),
pm => pm.field.mappedName,
);
if (primaryMappers.length !== primaryFields.length) {
throw new Error(
`Not all primary keys included in query. Found ${primaryMappers.length} instead of ${primaryFields.length}`,
);
}
return primaryMappers;
}
}
<file_sep>/src/__specs__/helpers/setup-user-schema.ts
import * as Knex from "knex";
import * as types from "../../utils/types";
import { mapDataSource } from "../../MappedDataSource";
import { GraphQLID, GraphQLString, GraphQLInt } from "graphql";
import { times, isString } from "lodash";
import { mapFields } from "../..";
export const setupUserSchema = async (knex: Knex) => {
await knex.schema.createTable("users", t => {
t.increments("id");
t.string("name");
t.integer("age");
t.jsonb("metadata");
});
};
export const insertFewUsers = async (knex: Knex) => {
await knex("users").insert([
{
id: 1,
name: "Lorefnon",
age: 50,
metadata: JSON.stringify({
positionsHeld: [
{
title: "Software Architect",
organization: "Foo Bar Inc",
duration: 5,
},
{
title: "Software Developer",
organization: "Lorem Ipsum Gmbh",
duration: 10,
},
],
awards: [
{
title: "Top Achiever",
compensation: 1000,
},
],
}),
},
{ id: 2, name: "Gandalf", age: 1000 },
]);
};
export const insertManyUsers = async (knex: Knex) => {
let users = [];
for (const idx of times(500)) {
const id = idx + 1;
users.push({
id,
name: `User ${id}`,
age: 50,
metadata: JSON.stringify({
positionsHeld: times(5).map(idx => ({
title: `Pos ${id}:${idx}`,
organization: `Org ${id}:${idx}`,
duration: 3,
})),
awards:
id > 100
? []
: times(3).map(idx => ({
title: `Award: ${idx}`,
compensation: 100,
})),
}),
});
if (users.length >= 20) {
await knex("users").insert(users);
users = [];
}
}
};
export const mapUsersDataSource = () => {
// @snippet:start mapDataSource_user_simple
/// import {mapDataSource, mapFields, types} from "greldal";
const users = mapDataSource({
name: "User",
fields: mapFields({
id: {
type: types.intId,
isPrimary: true,
},
name: {
type: types.string,
},
age: {
type: types.integer,
},
}),
});
// @snippet:end
return users;
};
export const mapUsersDataSourceWithJSONFields = () =>
mapDataSource({
name: "User",
fields: mapFields({
id: {
type: types.intId,
isPrimary: true,
},
name: {
type: types.string,
},
age: {
type: types.integer,
},
metadata: {
type: types.object("Metadata", {
positionsHeld: types.array(
types.object("Position", {
title: types.string,
organization: types.string,
duration: types.integer,
}),
),
awards: types.array(
types.object("Award", {
compensation: types.number,
title: types.string,
}),
),
}),
fromSource: (i: any) => {
if (isString(i)) return JSON.parse(i);
return i;
},
toSource: (i: any) => JSON.stringify(i),
},
}),
});
export const teardownUserSchema = async (knex: Knex) => {
await knex.schema.dropTable("users");
};
<file_sep>/README.md
<p align="center">
<img src="https://raw.githubusercontent.com/gql-dal/greldal/master/src/docs/assets/banner.png" width="600" />
</p>
**A simple micro-framework to expose your relational datastore as a GraphQL API (powered by Node.js).**
[Home](https://gql-dal.github.io/greldal/) | [Issues](https://github.com/gql-dal/greldal/issues) | [API Docs](https://gql-dal.github.io/greldal/api)
[](https://travis-ci.org/gql-dal/greldal) [](https://greenkeeper.io/)
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fgql-dal%2Fgreldal?ref=badge_shield)
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fgql-dal%2Fgreldal?ref=badge_large)
<file_sep>/src/generator/__specs__/index.spec.ts
import Knex from "knex";
import { setupKnex } from "../../__specs__/helpers/setup-knex";
import { useDatabaseConnector } from "../..";
import { generate } from "../index";
import { northwindFixture } from "./__fixtures__/northwind";
import { reportErrors } from "../../__specs__/test-helpers";
jest.setTimeout(60000);
describe("Generator integration", () => {
let knex: Knex;
let teardown: () => Promise<void>;
beforeAll(async () => {
await reportErrors(async () => {
knex = setupKnex();
useDatabaseConnector(knex);
const fixture = northwindFixture(knex, "tscope_1");
const setupResult = await fixture.setup();
({ teardown } = setupResult);
});
});
afterAll(async () => {
await reportErrors(async () => {
await teardown();
});
});
it("identifies fields and associations", async () => {
const generated = await generate({
knex,
dataSources: {
transform: {
dataSourceName(name: string) {
const match = name.match(/^tscope\d+(\S+)/i);
return match ? match[1] : name;
},
},
},
});
expect(generated).toMatchSnapshot();
});
});
<file_sep>/src/generator/index.ts
import _debug from "debug";
import * as fs from "fs-extra";
import { sortBy, camelCase, find, get, isEqual, keys, transform, uniq, values, trimEnd } from "lodash";
import { assertType } from "../utils/assertions";
import { assertConnectorConfigured, globalConnector } from "../utils/connector";
import {
deriveMappedDataSourceName,
deriveMappedFieldName,
deriveStoredDataSourceName,
} from "../utils/conventional-naming";
import { MemoizeGetter } from "../utils/utils";
import { adapters } from "./adapters";
import { Adapter, DataSourceInfo, TableLike, TableSchema } from "./adapters/Adapter";
import {
DataSourceMemberGenConfig,
GenConfig,
GenConfigRT,
Interceptable,
matchesSelectionFilter,
ModuleSpec,
} from "./GenConfig";
import { IndentationTracker } from "./indentation-tracker";
const debug = _debug("greldal:generator");
type StoredKToDSMapping = { [storedName: string]: DataSourceMemberGenConfig | undefined };
export class Generator {
constructor(private config: GenConfig, private adapter: Adapter) {}
@MemoizeGetter
get configuredDataSources(): StoredKToDSMapping {
return transform(
(this.config.dataSources && this.config.dataSources.members) || [],
(result: StoredKToDSMapping, d) => {
result[deriveStoredDataSourceName(d.name)] = d;
},
{},
);
}
async getFilteredTableList(): Promise<TableLike[]> {
let tables = await this.adapter.getTables();
const { dataSources } = this.config;
if (dataSources) tables = tables.filter(({ name }) => matchesSelectionFilter(name, dataSources));
return sortBy(tables, "name");
}
async populateFields(dataSource: DataSourceInfo, schema: TableSchema) {
const dataSourceGenConfig = this.configuredDataSources[dataSource.table.name];
let { columns } = schema;
if (dataSourceGenConfig && dataSourceGenConfig.fields) {
columns = schema.columns.filter(({ name }) => matchesSelectionFilter(name, dataSourceGenConfig.fields!));
}
for (const column of sortBy(columns, "name")) {
const members =
(dataSourceGenConfig && dataSourceGenConfig.fields && dataSourceGenConfig.fields.members) || {};
let mappedFieldName: string | undefined = find(keys(members) as string[], mappedFieldName => {
const member = members[mappedFieldName];
return !!member.sourceColumn && member.sourceColumn === column.name;
});
if (!mappedFieldName) {
let derivedMappedFieldName = deriveMappedFieldName(column.name);
if (members[derivedMappedFieldName] && members[derivedMappedFieldName].sourceColumn !== column.name) {
continue;
}
mappedFieldName = derivedMappedFieldName;
}
dataSource.fields[mappedFieldName] = {
...members[mappedFieldName],
column,
};
}
}
async populateAssociations(
dataSource: DataSourceInfo,
schema: TableSchema,
dataSources: { [storedName: string]: DataSourceInfo },
) {
let { foreignKeys } = schema;
const dataSourceGenConfig = this.configuredDataSources[dataSource.table.name];
if (dataSourceGenConfig && dataSourceGenConfig.associations) {
foreignKeys = foreignKeys.filter(({ associatorColumns: { inSource } }) =>
matchesSelectionFilter(inSource, dataSourceGenConfig.associations!),
);
}
for (const foreignKey of foreignKeys) {
const members =
(dataSourceGenConfig && dataSourceGenConfig.associations && dataSourceGenConfig.associations.members) ||
{};
let mappedName: string | undefined = find(keys(members) as string[], mappedName => {
const member = members[mappedName];
return (
!!member.associatorColumns &&
member.associatorColumns.inSource === foreignKey.associatorColumns.inSource &&
member.associatorColumns.inRelated === foreignKey.associatorColumns.inRelated &&
member.associatedTableName === foreignKey.associatedTable.name
);
});
if (!mappedName) {
let mappedNameCandidate = [
foreignKey.associatorColumns.inRelated,
foreignKey.associatorColumns.inSource,
].find(n => n.toLowerCase() !== "id");
if (!mappedNameCandidate) continue;
const match = mappedNameCandidate.match(/^(.*)id$/i);
const derivedMappedName = camelCase(match ? match[1] : mappedNameCandidate);
const member = members[derivedMappedName];
if (
member &&
((member.associatedTableName && member.associatedTableName !== foreignKey.associatedTable.name) ||
(member.associatorColumns && !isEqual(member.associatorColumns, foreignKey.associatorColumns)))
)
continue;
mappedName = derivedMappedName;
}
const targetDataSourceName =
get(members, [mappedName, "targetDataSourceName"]) ||
get(dataSources[foreignKey.associatedTable.name], ["name", "mapped"]);
dataSource.associations[mappedName] = {
...members[mappedName],
foreignKey,
targetDataSourceName,
};
}
}
async getDataSourcesToGenerate(): Promise<DataSourceInfo[]> {
const tables = await this.getFilteredTableList();
let dataSourceInfoIdx: { [storedName: string]: DataSourceInfo } = {};
for (const table of tables) {
const dataSourceGenConfig = this.configuredDataSources[table.name];
let mappedName =
(dataSourceGenConfig?.name && deriveMappedDataSourceName(dataSourceGenConfig.name)) ||
deriveMappedDataSourceName(table.name);
const transformName = this.config.dataSources?.transform?.dataSourceName;
if (transformName) {
mappedName = transformName(mappedName);
}
const dataSourceInfo: DataSourceInfo = {
...dataSourceGenConfig,
name: {
stored: table.name,
mapped: mappedName,
},
table,
fields: {},
associations: {},
};
dataSourceInfoIdx[dataSourceInfo.name.stored] = dataSourceInfo;
}
for (const [, dataSourceInfo] of Object.entries(dataSourceInfoIdx)) {
const schema = await this.adapter.getSchemaForTable(dataSourceInfo.table);
this.populateFields(dataSourceInfo, schema);
this.populateAssociations(dataSourceInfo, schema, dataSourceInfoIdx);
}
return values(dataSourceInfoIdx);
}
private applyInterceptor(baseStr: IndentationTracker, topLevelImports: string[], interceptable: Interceptable) {
if (interceptable.mergeWith) {
topLevelImports.push(generateImport(interceptable.mergeWith));
baseStr.addLine(`...${interceptable.mergeWith.imported}`);
}
baseStr.wrap();
if (interceptable.interceptThrough) {
topLevelImports.push(generateImport(interceptable.interceptThrough));
baseStr.wrap("interceptable.interceptThrough.imported(", ")");
}
}
async generate() {
let topLevelImports = ['import { types, mapDataSource, mapFields, mapAssociations } from "greldal";'];
const body = new IndentationTracker();
for (const dataSource of await this.getDataSourcesToGenerate()) {
const fieldsConstName = camelCase(`${dataSource.name.mapped}Fields`);
const associationsConstName = camelCase(`${dataSource.name.mapped}Associations`);
const dataSourceConstName = camelCase(dataSource.name.mapped);
let generatedFields = new IndentationTracker();
let generatedAssociations = new IndentationTracker();
for (const [mappedName, field] of Object.entries(dataSource.fields)) {
const fieldStr = new IndentationTracker();
fieldStr.addLine(`sourceColumn: "${field.column.name}",`);
if (field.column.type) {
fieldStr.addLine(`type: types.${field.column.type},`);
}
if (field.column.isPrimary) {
fieldStr.addLine(`isPrimary: true,`);
}
this.applyInterceptor(fieldStr, topLevelImports, field);
generatedFields.addLine(
generatedFields.reIndentBlock(`${mappedName}: ${trimEnd(fieldStr.toString())},`),
);
}
for (const [mappedName, association] of Object.entries(dataSource.associations)) {
const assocStr = new IndentationTracker();
if (association.targetDataSourceName) {
assocStr.addLine(`target: () => ${association.targetDataSourceName},`);
}
assocStr.addLine(`singular: ${!!association.singular},`);
assocStr.addLine(`fetchThrough: [{join: "leftOuterJoin"}],`);
assocStr.addBlock(
`associatorColumns: {`,
() => {
assocStr.addLine(`inSource: "${association.foreignKey.associatorColumns.inSource}",`);
assocStr.addLine(`inRelated: "${association.foreignKey.associatorColumns.inRelated}",`);
},
"},",
);
this.applyInterceptor(assocStr, topLevelImports, association);
generatedAssociations.addLine(
generatedAssociations.reIndentBlock(`${mappedName}: ${trimEnd(assocStr.toString())},`),
);
}
if (!generatedFields.isEmpty()) {
generatedFields.wrap(`const ${fieldsConstName} = {`, "};");
body.addLine(body.reIndentBlock(generatedFields.output));
}
if (!generatedAssociations.isEmpty()) {
generatedAssociations.wrap(`const ${associationsConstName} = {`, "};");
body.addLine(body.reIndentBlock(generatedAssociations.output));
}
if (!generatedFields.isEmpty() || !generatedAssociations.isEmpty()) {
body.addBlock(
`const ${dataSourceConstName} = {`,
() => {
body.addLine(`name: ${JSON.stringify(dataSource.name)},`);
if (!generatedFields.isEmpty()) body.addLine(`fields: mapFields(${fieldsConstName}),`);
if (!generatedAssociations.isEmpty())
body.addLine(`associations: mapAssociations(${associationsConstName}),`);
},
"};",
);
}
}
return `${uniq(topLevelImports).join("\n")}\n${body.toString()}`;
}
}
const generateImport = (mod: ModuleSpec) => {
let { imported } = mod;
if (!mod.isDefault) imported = `{${imported}}`;
return `import ${imported} from "${mod.module}";`;
};
export const generate = async (config: GenConfig) => {
assertType(GenConfigRT, config, "config");
const connector = config.knex || globalConnector;
assertConnectorConfigured(connector);
const client: keyof typeof adapters = connector.client.config.client;
debug("Identified client: %s", client);
if (!adapters[client]) throw new Error(`Client ${client} is currently not supported`);
const adapter = new adapters[client](config);
const generator = new Generator(config, adapter);
const generated: string = await generator.generate();
if (config.generatedFilePath) {
await fs.writeFile(config.generatedFilePath, generated);
}
return generated;
};
<file_sep>/src/utils/util-types.ts
import * as t from "io-ts";
import { Dictionary, isRegExp } from "lodash";
import { GraphQLInputType, isInputType, GraphQLOutputType, isOutputType } from "graphql";
/** Convenience utility types */
export const MappedRT = <RT1 extends t.Mixed, RT2 extends t.Mixed = RT1>(mapped: RT1, stored: RT2) =>
t.type({
stored,
mapped,
});
export const MaybeMappedRT = <RT1 extends t.Mixed, RT2 extends t.Mixed = RT1>(mapped: RT1, stored: RT2) =>
t.union([mapped, MappedRT(mapped, stored)]);
export type Maybe<T> = null | undefined | T;
export type NNil<T> = Exclude<T, undefined | null>;
export interface Dict<T = any> extends Dictionary<T> {}
export interface Lazy<T> {
(): T;
}
export type MaybeLazy<T> = T | Lazy<T>;
export type MaybePromise<T> = T | Promise<T>;
export type MaybeArray<T> = T | T[];
export type MaybeArrayItem<T extends MaybeArray<any>> = T extends MaybeArray<infer I> ? I : never;
export interface Factory<T> {
(...args: any[]): T;
}
export interface Newable<T> {
new (...args: any[]): T;
}
export type StrKey<T> = keyof T & string;
export type IdxKey<T> = keyof T & number;
export type Normalizer<PreNormalizedT, NormalizedT> = (v: PreNormalizedT) => NormalizedT;
export type MandateProps<T, P extends keyof T> = Omit<T, P> & { [K in keyof Pick<T, P>]-?: T[K] };
export type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
export type Fn<A extends any[] = any[], R = any> = (...args: A) => R;
export type TypeGuard<S> = (v: any) => v is S;
export type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
export type ReplaceWith<TSource, TKey, TSub = never> = { [K in keyof TSource]: K extends TKey ? TSub : TSource[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export interface Mapped<TMapped, TStored = TMapped> {
mapped: TMapped;
stored: TStored;
}
export type MaybeMapped<T> = T | Mapped<T>;
export type KeyOf<T> = keyof T;
export type ValueOf<T> = T[KeyOf<T>];
/**
* Runtime type representation to validate if a value is instance of a class
*/
export class InstanceType<T> extends t.Type<T> {
readonly _tag: "InstanceType" = "InstanceType";
constructor(Ctor: Newable<T>) {
super(
`Instance<${Ctor.name || "Unknown"}>`,
(m): m is T => m instanceof Ctor,
(m, c) => (this.is(m) ? t.success(m) : t.failure(m, c)),
t.identity,
);
}
}
export const InstanceOf = <T>(Ctor: Newable<T>) => new InstanceType<T>(Ctor);
export const IOType: InstanceType<t.Type<any>> = InstanceOf<t.Type<any>>(t.Type);
export type MakePartial<T extends object, K extends keyof T> = Partial<Pick<T, K>> & Omit<T, K>;
export const GQLInputType = new t.Type<GraphQLInputType>(
"GQLInputType",
(m): m is GraphQLInputType => isInputType(m),
(m, c) => (isInputType(m) ? t.success(m) : t.failure(m, c)),
t.identity,
);
export const GQLOutputType = new t.Type<GraphQLOutputType>(
"GQLOutputType",
(m): m is GraphQLOutputType => isOutputType(m),
(m, c) => (isOutputType(m) ? t.success(m) : t.failure(m, c)),
t.identity,
);
export const RegExpType = new t.Type<RegExp>(
"RegExp",
(m): m is RegExp => isRegExp(m),
(m, c) => (isRegExp(m) ? t.success(m) : t.failure(m, c)),
t.identity,
);
export type ExtendsWitness<U extends T, T> = U;
interface _MultiSelectionItem<TTgt, TCtx> {
selection(): TTgt;
shouldUse(ctx: TCtx): Promise<boolean>;
}
export type MultiSelectionItem<TTgt, TCtx> = MakeOptional<_MultiSelectionItem<TTgt, TCtx>, "shouldUse">;
export type MultiSelection<
TTgt,
TCtx,
TMember extends MultiSelectionItem<TTgt, TCtx> = MultiSelectionItem<TTgt, TCtx>
> = Dictionary<TMember>;
export type Interceptor<T> = (i: T) => T;
export type PartialDeep<T> = {
[P in keyof T]?: T[P] extends Array<infer U>
? Array<PartialDeep<U>>
: T[P] extends ReadonlyArray<infer U>
? ReadonlyArray<PartialDeep<U>>
: PartialDeep<T[P]>;
};
export type Predicate<T> = (i: T) => boolean;
<file_sep>/src/docs/components/NotificationBanner.js
import styled from 'styled-components';
const NotificationBanner = styled.div`
background: #e15506;
padding: 20px;
color: #ffd0b6;
border-radius: 5px;
text-align: left;
& + & {
margin-top: 10px;
}
`;
export default NotificationBanner;<file_sep>/src/MappedStoredProc.ts
export class MappedStoredProc {}
<file_sep>/src/docs/utils/SQLJSClient.js
import SQLiteClient from "knex/lib/dialects/sqlite3";
import initSqlJs from "sql.js";
import { once, first } from "lodash";
const initSqlJSOnce = once(initSqlJs);
export default class SQLJSClient extends SQLiteClient {
dialect = "sqljs";
driverName = "sqljs";
_driver() {
throw new Error("ExpectedToNotBeReachable");
}
// Get a raw connection from the database, returning a promise with the connection object.
async acquireRawConnection() {
const SQL = await initSqlJSOnce({
locateFile: pathname => {
if (pathname === "sql-wasm.wasm") {
return require("sql.js/dist/sql-wasm.wasm").default;
}
throw new Error("Unhandled locate path:", pathname);
},
});
return new SQL.Database();
}
// Runs the query on the specified connection, providing the bindings and any
// other necessary prep work.
async _query(connection, obj) {
const stmt = connection.prepare(obj.sql)
stmt.bind(obj.bindings);
obj.response = [];
while (stmt.step()) {
obj.response.push(stmt.getAsObject());
}
obj.context = this;
return obj;
}
_stream(connection, sql, stream) {
throw new Error("Unsupported");
}
// Ensures the response is returned in the same format as other clients.
processResponse(obj, runner) {
const ctx = obj.context;
let { response } = obj;
switch (obj.method) {
case "pluck":
throw new Error("Unsupported");
case "select":
case "first":
// const selectResult = map(get(response, [0, 'values']), (row) => zipObject(get(response, [0, 'columns']), row));
return obj.method === "first" ? first(response) : response;
case "insert":
case "del":
case "update":
case "counter":
return [];
default:
return response;
}
}
}
<file_sep>/src/SourceAwareOperationResolver.ts
import * as Knex from "knex";
import { memoize } from "lodash";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { supportsReturning } from "./utils/connector";
import { MemoizeGetter } from "./utils/utils";
import { PrimaryRowMapper } from "./SingleSourceQueryOperationResolver";
import { Dict, Maybe } from "./utils/util-types";
import { uniqWith, compact, isEqual, every } from "lodash";
import { decorate } from "core-decorators";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import { BaseResolver } from "./BaseResolver";
export interface BaseStoreParams {
queryBuilder: Knex.QueryBuilder;
}
/**
* Base class for operation resolvers that need to interact with one or more mapped data sources
*
* @api-category CRUDResolvers
*/
export class SourceAwareOperationResolver<
TCtx extends SourceAwareResolverContext<MappedSourceAwareOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc extends MappedDataSource,
TArgs extends {},
TResolved
> extends BaseResolver<TCtx, TArgs, TResolved> {
isDelegated: boolean | undefined;
protected _activeTransaction?: Maybe<Knex.Transaction>;
constructor(public resolverContext: TCtx) {
super(resolverContext);
}
/**
* Can be overriden to return a collection of resolver instances that we are delegating to.
*
* This is required for sharing the same transactions across the root resolver and all the
* delegated resolvers
*/
get delegatedResolvers(): SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved>[] {
return [];
}
/**
* Currently active Knex transaction instance
*/
get activeTransaction(): Maybe<Knex.Transaction> {
return this._activeTransaction;
}
/**
* Set a transaction as currently active
*/
set activeTransaction(transaction: Maybe<Knex.Transaction>) {
this._activeTransaction = transaction;
this.delegatedResolvers.forEach(r => (r.activeTransaction = transaction));
}
/**
* Get AliasHeirarchyVisitor for specified data source
*/
@decorate(memoize)
getAliasHierarchyVisitorFor(dataSource: TCtx["DataSourceType"]) {
return new AliasHierarchyVisitor().visit(dataSource.storedName)!;
}
/**
* Use associated operation's primary data source to construct the root query builder
* and wrap it in active transaction.
*
* Currently this can be used only if the operation is a single source operation, and throws otherwise.
*/
createRootQueryBuilder(dataSource: TCtx["DataSourceType"], shouldAlias = true) {
const operation = this.resolverContext.operation;
if (!(operation instanceof MappedSingleSourceOperation)) {
throw new Error("rootQuery is not applicable in this context");
}
const queryBuilder = operation.rootQuery(
dataSource,
this.resolverContext.args,
shouldAlias ? this.getAliasHierarchyVisitorFor(dataSource) : null,
);
if (this.activeTransaction) return queryBuilder.transacting(this.activeTransaction);
return queryBuilder;
}
/**
* Check if all the involved data sources support SQL returning statement
*/
@MemoizeGetter
get supportsReturning() {
return every(this.resolverContext.connectors, supportsReturning);
}
/**
* Use columnAlias mappings to reverse map retrieved rows to fields of entities
*/
protected extractPrimaryKeyValues(primaryMappers: PrimaryRowMapper[], rows: Dict[]) {
return uniqWith(
compact(
rows.map(r => {
let queryItem: Dict = {};
for (const primaryMapper of primaryMappers) {
queryItem[primaryMapper.field.sourceColumn!] = r[primaryMapper.columnAlias!];
}
return queryItem;
}),
),
isEqual,
);
}
/**
* Given a set of primary key + value combinations, compose a knex query to match any of these
* values
*/
protected queryByPrimaryKeyValues(queryBuilder: Knex.QueryBuilder, primaryKeyValues: Dict[]) {
primaryKeyValues = [...primaryKeyValues];
queryBuilder.where(primaryKeyValues.shift()!);
let whereParam;
while ((whereParam = primaryKeyValues.shift())) {
queryBuilder.orWhere(whereParam);
}
return queryBuilder;
}
/**
* Wrap database operations in a transaction
*
* Creates a new transaction only if the operation is not delegated from some other operation. Reuses
* parent operation transaction for delegated transactions.
*/
protected async wrapInTransaction<T>(cb: () => Promise<T>): Promise<T> {
if (this.isDelegated) {
return cb();
}
let returned: T;
const connectors = this.resolverContext.connectors;
if (connectors.length === 0) throw new Error("Unable to find a connector for creating transaction");
if (connectors.length > 1)
throw new Error("Unable to wrap operations on sources having different connectors in single transaction");
await connectors[0].transaction(async trx => {
this.activeTransaction = trx;
returned = await cb();
this.activeTransaction = undefined;
});
return returned!;
}
}
<file_sep>/src/docs/components/HierarchyContext.js
import React from "react";
export const HierarchyContext = React.createContext();
<file_sep>/CONTRIBUTING.md
# Contributing
First off, thanks for taking the time to contribute!
GRelDAL welcomes contributions in form of:
1. Bug reports (Use github issues),
2. Bug fixes (Use github pull requests or email patches to the collaborators),
3. Other code contributions that add new features and enhancements
4. Improvements to documentation
In case of code contributions, please note that GRelDAL takes backward compatibility very seriously and unless absolutely needed backward incompatible changes are to be avoided. Also if needed at all, the older behavior will have to go through a deprecation cycle (over one major release).
# Terminology
Unless otherwise specified in the context, following terms can be assumed to have these semantics in the context of GRelDAL:
## DataSource
dataSource (camel-cased, concatenated) always refers to a `MappedDataSource` instance returned by `mapDataSource` function, which can be used to interact with a backend data source (eg. database table, view etc.)
## Row
A row of a table returned from a database query
## Column
A column in a relational database table.
## Entity
Plain javascript object that represents an entity in the application. Business logic in application code is always expected to interact with mapped entities as opposed to rows or instances of library defined classes.
## Operation
A GRelDAL Operation is an operation against a data source such as simple CRUD operations (query, delete, update, insert) or custom user defined operations.
Operations represent individual steps in business process and can be composed together to form larger workflows.
# Writing documentation
It is important to have documentation with small and to-the-point illustrative examples wherever possible.
GRelDAL uses [snippet-collector](https://www.npmjs.com/package/snippet-collector) to extract examples from our test suite, which ensures:
1. Examples are actually runnable, and don't have typos or errors.
2. Examples are easier to keep up to date as the library evolves.
In addition, it is important to:
1. Have API docs for all newly added code
2. Link to APIs from user manual and vice versa
The documentation site uses Next.js as a static site generator and uses (github-flavored) markdown format for content.
Usually markdown files are named by dasherizing the page heading so they are easy to find using github's file finder. For minor changes (eg. typos) it is perfectly fine to edit the markdown files from github itself and sending a PR.
English is not the first language for any of the project maintainers, so any help around documentation is highly appreciated. Also, translations in other languages would be really appreciated.
Please don't send PRs against the gh-pages branch. The documentation site is auto-generated. Project maintainers will deploy that using the `deploy:site` npm script.
# Coding conventions
While GRelDAL can be used from both JavaScript and TypeScript, code contributions to the library must always be in TypeScript and should strive to be type-safe as much as reasonably possible.
Following general practices are recommended:
1. Don't create a class where a function would suffice
2. Instead of large functions, create smaller functions/methods and compose them so the intent is easy to grok by looking at a fewer lines of code.
3. ES6 Classes are preferrable over usage of function prototype.
4. Don't change indentation or reformat existing code. The codebase is configured to use prettier to ensure a consistent styling - run `yarn run format` before submitting PRs.
5. For code that heavily uses generics - keep covariance and contravariant behavior in mind and ensure that whenever generics have default type parameters, type with specified params is always compatible with the type with default params (`Foo<A, B> extends Foo` for all `A`, `B` that are allowed). If this doesn't hold true, one of the following may be required:
1. Add restrictions to generic type params, or
2. Change default type params, or
3. Remove the defaults entirely.
6. Prefix generic type params with `T` eg. `TArgs`.
7. Use yarn to add/remove dependencies and ensure that `yarn.lock` is up to date.
<file_sep>/src/__specs__/adhoc-operations.spec.ts
import { mapSchema } from "../MappedSchema";
import { graphql, GraphQLString } from "graphql";
import { OperationType } from "../operation-types";
import { types } from "../universal";
describe("Adhoc operations", () => {
test("custom operation without args", async () => {
// @snippet:start AdhocOperation_withoutArgs
const customOperation = {
operationType: OperationType.Query,
name: "printHello",
fieldConfig: {
type: GraphQLString,
description: "Prints hello",
resolve: () => {
return "hello";
},
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
const result = await graphql(
schema,
`
query {
printHello
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"printHello": "hello",
},
}
`);
});
test("custom operations with args", async () => {
// @snippet:start AdhocOperation_withArgs
const customOperation = {
operationType: OperationType.Query,
name: "printGreeting",
fieldConfig: {
type: GraphQLString,
args: {
name: {
type: GraphQLString,
},
},
description: "Prints hello",
resolve: (_obj: any, args: { name: string }) => {
return `hello ${args.name}`;
},
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
const result = await graphql(
schema,
`
query {
printGreeting(name: "Lorefnon")
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"printGreeting": "hello Lorefnon",
},
}
`);
});
test("custom operations with args and default values", async () => {
// @snippet:start AdhocOperation_withDefaultArgs
const customOperation = {
operationType: OperationType.Query,
name: "printGreeting",
fieldConfig: {
type: GraphQLString,
args: {
name: {
type: GraphQLString,
defaultValue: "Lorefnon",
},
},
description: "Prints hello",
resolve: (_obj: any, args: { name: string }) => {
return `hello ${args.name}`;
},
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
const result = await graphql(
schema,
`
query {
greetSpecific: printGreeting(name: "John")
greetDefault: printGreeting
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"greetDefault": "hello Lorefnon",
"greetSpecific": "hello John",
},
}
`);
});
test("Custom query operation with types specified through io-ts", async () => {
// @snippet:start AdhocQueryOperation_iots
const OrderDetailTypeSpec = types.object("OrderDetail", {
orderId: types.number,
purchasedAt: types.isoDate,
purchasedBy: types.array(
types.object("OrderDetailPurchaser", {
customerId: types.number,
name: types.string,
}),
),
});
type OrderDetail = typeof OrderDetailTypeSpec["Type"];
const customOperation = {
operationType: OperationType.Query,
name: "orderDetails",
fieldConfig: {
type: OrderDetailTypeSpec.graphQLOutputType,
args: {
orderId: {
type: types.number.graphQLInputType,
},
},
description: "Prints hello",
resolve: (_parent: any, args: { orderId: number }): OrderDetail => ({
orderId: args.orderId,
purchasedAt: new Date("2020-01-01"),
purchasedBy: [
{
customerId: 1,
name: "<NAME>",
},
{
customerId: 2,
name: "<NAME>",
},
],
}),
},
};
const schema = mapSchema([customOperation]);
// @snippet:end
// @snippet:start AdhocQueryOperation_iots_schema_introspection_query
const introspectionResult = await graphql(
schema,
`
query {
__schema {
types {
name
fields {
name
type {
name
}
}
}
}
}
`,
);
// @snippet:end
// @snippet:start AdhocQueryOperation_iots_schema_introspection_query_result
expect(introspectionResult).toMatchInlineSnapshot(`
Object {
"data": Object {
"__schema": Object {
"types": Array [
Object {
"fields": Array [
Object {
"name": "orderDetails",
"type": Object {
"name": "OrderDetail",
},
},
],
"name": "query",
},
Object {
"fields": null,
"name": "Float",
},
Object {
"fields": Array [
Object {
"name": "orderId",
"type": Object {
"name": "Float",
},
},
Object {
"name": "purchasedAt",
"type": Object {
"name": "Date",
},
},
Object {
"name": "purchasedBy",
"type": Object {
"name": null,
},
},
],
"name": "OrderDetail",
},
Object {
"fields": null,
"name": "Date",
},
Object {
"fields": Array [
Object {
"name": "customerId",
"type": Object {
"name": "Float",
},
},
Object {
"name": "name",
"type": Object {
"name": "String",
},
},
],
"name": "OrderDetailPurchaser",
},
Object {
"fields": null,
"name": "String",
},
Object {
"fields": Array [
Object {
"name": "types",
"type": Object {
"name": null,
},
},
Object {
"name": "queryType",
"type": Object {
"name": null,
},
},
Object {
"name": "mutationType",
"type": Object {
"name": "__Type",
},
},
Object {
"name": "subscriptionType",
"type": Object {
"name": "__Type",
},
},
Object {
"name": "directives",
"type": Object {
"name": null,
},
},
],
"name": "__Schema",
},
Object {
"fields": Array [
Object {
"name": "kind",
"type": Object {
"name": null,
},
},
Object {
"name": "name",
"type": Object {
"name": "String",
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "fields",
"type": Object {
"name": null,
},
},
Object {
"name": "interfaces",
"type": Object {
"name": null,
},
},
Object {
"name": "possibleTypes",
"type": Object {
"name": null,
},
},
Object {
"name": "enumValues",
"type": Object {
"name": null,
},
},
Object {
"name": "inputFields",
"type": Object {
"name": null,
},
},
Object {
"name": "ofType",
"type": Object {
"name": "__Type",
},
},
],
"name": "__Type",
},
Object {
"fields": null,
"name": "__TypeKind",
},
Object {
"fields": null,
"name": "Boolean",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "args",
"type": Object {
"name": null,
},
},
Object {
"name": "type",
"type": Object {
"name": null,
},
},
Object {
"name": "isDeprecated",
"type": Object {
"name": null,
},
},
Object {
"name": "deprecationReason",
"type": Object {
"name": "String",
},
},
],
"name": "__Field",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "type",
"type": Object {
"name": null,
},
},
Object {
"name": "defaultValue",
"type": Object {
"name": "String",
},
},
],
"name": "__InputValue",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "isDeprecated",
"type": Object {
"name": null,
},
},
Object {
"name": "deprecationReason",
"type": Object {
"name": "String",
},
},
],
"name": "__EnumValue",
},
Object {
"fields": Array [
Object {
"name": "name",
"type": Object {
"name": null,
},
},
Object {
"name": "description",
"type": Object {
"name": "String",
},
},
Object {
"name": "locations",
"type": Object {
"name": null,
},
},
Object {
"name": "args",
"type": Object {
"name": null,
},
},
],
"name": "__Directive",
},
Object {
"fields": null,
"name": "__DirectiveLocation",
},
],
},
},
}
`);
// @snippet:end
const result = await graphql(
schema,
`
query {
orderDetails(orderId: 1) {
orderId
purchasedAt
purchasedBy {
customerId
name
}
}
}
`,
);
expect(result).toMatchInlineSnapshot(`
Object {
"data": Object {
"orderDetails": Object {
"orderId": 1,
"purchasedAt": "2020-01-01",
"purchasedBy": Array [
Object {
"customerId": 1,
"name": "<NAME>",
},
Object {
"customerId": 2,
"name": "<NAME>",
},
],
},
},
}
`);
});
});
<file_sep>/src/docs/utils/api.js
const { merge, forEach, find, compact, map, flatten, memoize, get } = require("lodash");
const climber = require("tree-climber");
const qs = require("qs");
function getAPINode(entityInfo) {
const name = getAPIName(entityInfo);
const path = name.split(".");
const root = {};
let curLevel = root;
path.forEach((fragment, index) => {
curLevel.name = fragment;
if (index === path.length - 1) {
curLevel.entity = entityInfo;
curLevel.children =
entityInfo.children &&
entityInfo.children.map(childEntityInfo => {
const node = getAPINode(childEntityInfo);
// node.entity.parent = entityInfo;
return node;
});
} else {
curLevel.children = [{}];
curLevel = curLevel.children[0];
}
});
return root;
}
function injectIntoHierarchy(hierarchy, node) {
const prevChild = find(hierarchy, child => child.name === node.name);
if (!prevChild) {
hierarchy.push(node);
return;
}
prevChild.entity = prevChild.entity || node.entity;
if (node.children) {
prevChild.children = prevChild.children || [];
forEach(node.children, nextChild => {
injectIntoHierarchy(prevChild.children, nextChild);
});
}
}
function injectIntoEntity(entity, childEntity) {
entity.children = entity.children || [];
const prevChild = entity.children.find(c => c.name === childEntity.name);
if (prevChild) merge(prevChild, childEntity);
else entity.children.push(childEntity);
}
function findInHierarchy(root, entityPath) {
if (!root || !root.children || !entityPath.length) return root;
const child = root.children.find(child => child.name === entityPath[0]);
return findInHierarchy(child, entityPath.slice(1));
}
function findAnywhereInHierarchy(root, entityName) {
if (!root) return null;
return root.find(c => {
if (c.name === entityName) return c;
return findAnywhereInHierarchy(c.children, entityName);
});
}
const getAllTags = memoize(entityInfo => {
return compact(flatten(map(compact([entityInfo].concat(entityInfo.signatures)), "comment.tags")));
});
function getAPIName(entityInfo) {
const nameTag = getAllTags(entityInfo).find(t => t.tag === "name");
if (nameTag) return nameTag.text.trim();
return entityInfo.name;
}
function getAPICategory(entityInfo) {
const tags = compact(flatten(map(compact([entityInfo].concat(entityInfo.signatures)), "comment.tags")));
const categoryTag = tags.find(t => t.tag === "api-category");
if (!categoryTag) return null;
const category = categoryTag.text.trim();
return category;
}
function getAPIHierarchy(apiData) {
const categories = {
PrimaryAPI: [],
ConfigType: [],
MapperClass: [],
CRUDResolvers: [],
};
const entities = {};
apiData.children.forEach(moduleInfo => {
if (!moduleInfo.children) return;
moduleInfo.children.forEach(entityInfo => {
const category = getAPICategory(entityInfo);
if (!category || !categories[category]) return;
const node = getAPINode(entityInfo);
injectIntoHierarchy(categories[category], node);
entities[getAPIName(entityInfo)] = node;
});
});
climber.climb(apiData, (key, value, path) => {
if (key === "tag" && value === "memberof") {
const tag = get(apiData, path.split(".").slice(0, -1));
console.log("Associating orphaned member:", tag);
const curEntity = get(apiData, path.split(".").slice(0, -4));
const parentNode = entities[tag.text.trim()];
if (!parentNode) {
console.log("Unable to find parentNode:", tag);
return;
}
parentNode.children = parentNode.children || [];
injectIntoHierarchy(parentNode.children, {
entity: curEntity,
name: getAPIName(curEntity),
});
injectIntoEntity(parentNode.entity, curEntity);
}
});
return [
{
name: "Primary API",
toggled: true,
id: "PrimaryAPI",
children: categories.PrimaryAPI || [],
banners: [],
},
{
name: "CRUD Resolvers",
toggled: true,
id: "CRUDResolvers",
children: categories.CRUDResolvers || [],
banners: [],
},
{
name: "Configuration Types",
toggled: true,
id: "ConfigType",
children: categories.ConfigType || [],
banners: [
{
children:
"This page describes the type of a configuration type. Some of the functions exposed in the primary APIs would accept arguments of this type.",
},
],
},
{
name: "Mapper Classes",
toggled: true,
id: "MapperClass",
children: categories.MapperClass || [],
banners: [
{
children:
"This page describes a Mapper class which is instantiated by one of the functions exposed in primary APIs. You would usually not want to create instances of this class yourself.",
},
],
},
{
name: "Utils",
toggled: false,
id: "Utils",
children: categories.Utils || [],
},
];
}
function getAPIHref(ref) {
let [rootEntityName, entityName] = ref.split(":");
if (!entityName) entityName = rootEntityName;
return `${ROOT_PATH}/api?${qs.stringify({
entityName,
rootEntityName,
})}`;
}
function getGuideHref(ref) {
return `${ROOT_PATH}/${ref}`;
}
function getTermHref(ref) {
return `${ROOT_PATH}/api?term=${ref}`;
}
const SPECIAL_HREF_PATTERN = /href="(api|guide|term):.*"/g;
const API_HREF_PATTERN = /href="api:(.*)"/;
const GUIDE_HREF_PATTERN = /href="guide:(.*)"/;
const TERM_HREF_PATTERN = /href="term:(.*)"/;
function convertLinks(html) {
const specialLinks = html.match(SPECIAL_HREF_PATTERN);
if (specialLinks) {
for (const link of specialLinks) {
const apiLinkMatch = link.match(API_HREF_PATTERN);
if (apiLinkMatch) {
html = html.replace(apiLinkMatch[0], `href="${getAPIHref(apiLinkMatch[1])}"`);
continue;
}
const guideLinkMatch = link.match(GUIDE_HREF_PATTERN);
if (guideLinkMatch) {
const slug = guideLinkMatch[1];
html = html.replace(guideLinkMatch[0], `href="${getGuideHref(slug)}"`);
continue;
}
const termLinkMatch = link.match(TERM_HREF_PATTERN);
if (termLinkMatch) {
const term = termLinkMatch[1];
html = html.replace(termLinkMatch[0], `href="${getTermHref(term)}"`);
continue;
}
}
}
const relLinks = html.match(/href="\/.*"/g);
if (relLinks) {
for (const link of relLinks) {
const m = link.match(/href="\/(.*)"/);
html = html.replace(m[0], `href="${ROOT_PATH}/${m[1]}"`);
}
}
return html;
}
module.exports = {
getAPINode,
injectIntoHierarchy,
findInHierarchy,
findAnywhereInHierarchy,
getAllTags,
getAPIName,
getAPICategory,
getAPIHierarchy,
convertLinks,
getAPIHref,
getGuideHref,
getTermHref,
SPECIAL_HREF_PATTERN,
API_HREF_PATTERN,
GUIDE_HREF_PATTERN,
TERM_HREF_PATTERN,
};
<file_sep>/src/AutoDerivedControlledPaginationConfig.ts
import { ControlledPaginationConfig, AutoPaginationConfig } from "./PaginationConfig";
import * as Knex from "knex";
import Maybe from "graphql/tsutils/Maybe";
import { ColumnSelection } from "./SingleSourceQueryOperationResolver";
import { Dict } from "./utils/util-types";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { last, get, first } from "lodash";
import { getCount } from "./__specs__/knex-helpers";
export class AutoDerivedControlledPaginationConfig implements ControlledPaginationConfig {
constructor(private config: AutoPaginationConfig) {}
interceptQuery(
qb: Knex.QueryBuilder,
cursor: Maybe<string>,
pageSize: number,
selectedColumns: ColumnSelection,
ahv: AliasHierarchyVisitor,
): Knex.QueryBuilder {
const alias = this.getAlias(ahv);
const isAlreadySelected = !!selectedColumns.find(col => !!col[alias]);
if (cursor) qb.whereRaw(`??.?? >= ?`, [ahv.alias, this.config.cursorColumn, cursor]);
if (!isAlreadySelected) qb.column([{ [alias]: this.config.cursorColumn }]);
return qb.orderBy(alias).limit(pageSize + 1);
}
getAlias(ahv: AliasHierarchyVisitor) {
return ahv.getMemberColumnAlias(this.config.cursorColumn);
}
getNextCursor(results: Dict[], ahv: AliasHierarchyVisitor): string {
return get(last(results), ahv.getMemberColumnAlias(this.config.cursorColumn));
}
getPrevCursor(results: Dict[], ahv: AliasHierarchyVisitor): string {
return get(first(results), ahv.getMemberColumnAlias(this.config.cursorColumn));
}
getTotalCount(qb: Knex.QueryBuilder, ahv: AliasHierarchyVisitor): Promise<number> {
return getCount(qb);
}
}
<file_sep>/src/utils/errors.ts
/**
* Construct an error to be thrown if a getter intended solely for exposing a derived type is accessed at runtime
*
* @param name property name on parent class
* @param parent parent/owner name
*/
export const getTypeAccessorError = (name: string, parent: string) =>
new Error(
`Property ${name} must not be accessed directly. ` +
`Use typeof ${parent}Instance.${name} to get the ${name} type for this ${parent}`,
);
/**
* Construct error to be thrown when accessing a method which was expected to be overriden in child class
*/
export const expectedOverride = () => new Error("Expected to be overriden in child class");
<file_sep>/src/__specs__/operation-presets/find.spec.ts
import * as Knex from "knex";
import { GraphQLSchema, printSchema, graphql } from "graphql";
import {
setupUserSchema,
teardownUserSchema,
insertManyUsers,
mapUsersDataSourceWithJSONFields,
} from "../helpers/setup-user-schema";
import { MappedDataSource } from "../../MappedDataSource";
import { mapSchema, operationPresets, useDatabaseConnector } from "../..";
import { setupKnex } from "../helpers/setup-knex";
import { last, first } from "lodash";
let users: MappedDataSource, schema: GraphQLSchema, knex: Knex;
describe("find operation presets", () => {
beforeAll(async () => {
knex = useDatabaseConnector(setupKnex());
await setupUserSchema(knex);
await insertManyUsers(knex);
users = mapUsersDataSourceWithJSONFields();
schema = mapSchema([operationPresets.paginatedFindManyOperation(users)]);
}, 60000);
afterAll(async () => {
await teardownUserSchema(knex);
await knex.destroy();
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("paginated response with default page size", async () => {
const r1 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
page {
entities {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
const entities = r1.data!.findManyUsers.page.entities;
expect(entities.length).toBe(10);
expect(first<any>(entities)!.id).toEqual("1");
expect(last<any>(entities)!.id).toEqual("10");
expect(r1.data).toMatchSnapshot();
});
test("paginated response with specified page size", async () => {
const r1 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
page(pageSize: 100) {
pageInfo {
prevCursor
nextCursor
totalCount
}
entities {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
const entities = r1.data!.findManyUsers.page.entities;
expect(entities.length).toBe(100);
expect(first<any>(entities)!.id).toEqual("1");
expect(last<any>(entities)!.id).toEqual("100");
expect(r1.data).toMatchSnapshot();
const r2 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
page(pageSize: 100, cursor: "101") {
pageInfo {
prevCursor
nextCursor
totalCount
}
entities {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
}
}
`,
);
expect(r2.errors).not.toBeDefined();
const nextEntities = r2.data!.findManyUsers.page.entities;
expect(nextEntities.length).toBe(100);
expect(first<any>(nextEntities)!.id).toEqual("101");
expect(last<any>(nextEntities)!.id).toEqual("200");
expect(r2.data).toMatchSnapshot();
});
});
<file_sep>/src/docs/components/TypePresenter.js
import React from "react";
import qs from "qs";
import JSONTree from "react-json-tree";
import { findAnywhereInHierarchy } from "../utils/api";
import { HierarchyContext } from "./HierarchyContext";
import { Link } from "./Link";
// https://github.com/reduxjs/redux-devtools/blob/75322b15ee7ba03fddf10ac3399881e302848874/src/react/themes/default.js
const theme = {
scheme: "default",
author: "<NAME> (http://chriskempson.com)",
base00: "#181818",
base01: "#282828",
base02: "#383838",
base03: "#585858",
base04: "#b8b8b8",
base05: "#d8d8d8",
base06: "#e8e8e8",
base07: "#f8f8f8",
base08: "#ab4642",
base09: "#dc9656",
base0A: "#f7ca88",
base0B: "#a1b56c",
base0C: "#86c1b9",
base0D: "#7cafc2",
base0E: "#ba8baf",
base0F: "#a16946",
};
export const TypePresenter = ({ type }) => (
<HierarchyContext.Consumer>
{hierarchy => {
let primary;
if (type.type === "reference") {
primary = type.name;
if (primary) {
const primaryEntity = findAnywhereInHierarchy(hierarchy, primary);
if (primaryEntity) {
primary = (
<a
href={
`${ROOT_PATH}/api?` +
qs.stringify({
apiCategory: "ConfigType",
rootEntityName: primary,
entityName: primary,
})
}
>
{primary}
</a>
);
} else {
primary = <a href={`https://github.com/gql-dal/greldal/search?q=${primary}`}>{primary}</a>;
}
}
}
const tree = <JSONTree data={type} theme={theme} />;
return (
<>
{primary}
{primary && (
<div
css={`
color: #ddd;
`}
>
---
</div>
)}
<a title="The parsed representation of type. This structure can provide more information about type parameters">
Details
</a>
{tree}
</>
);
}}
</HierarchyContext.Consumer>
);
<file_sep>/src/utils/guards.ts
import { isArray, isFunction, isNil } from "lodash";
import { TypeGuard } from "./util-types";
import { isString, isRegExp } from "util";
export const checkArray = isArray as TypeGuard<any[]>;
export const checkNil = isNil as TypeGuard<null | undefined>;
export const checkFn = isFunction as TypeGuard<Function>;
export const checkStr = isString as TypeGuard<String>;
export const checkRegexp = isRegExp as TypeGuard<RegExp>;
<file_sep>/src/MappedDataSource.ts
import { getTypeAccessorError } from "./utils/errors";
import { Dict, NNil, Maybe, ReturnType } from "./utils/util-types";
import { transform, forEach, reduce } from "lodash";
import * as t from "io-ts";
import * as types from "./utils/types";
import * as Knex from "knex";
import _debug from "debug";
import { GraphQLInputType, GraphQLOutputType } from "graphql";
import { MappedField } from "./MappedField";
import { FieldMapping } from "./FieldMapping";
import { MappedAssociation } from "./MappedAssociation";
import {
deriveDefaultShallowOutputType,
deriveDefaultOutputType,
deriveDefaultShallowInputType,
derivePaginatedOutputType,
} from "./graphql-type-mapper";
import { assertSupportedConnector, globalConnector, assertConnectorConfigured } from "./utils/connector";
import { MemoizeGetter } from "./utils/utils";
import { StoreQueryParams } from "./SingleSourceQueryOperationResolver";
import { ReverseMapper } from "./ReverseMapper";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { DataSourceMapping } from "./DataSourceMapping";
import { deriveMappedDataSourceName, deriveStoredDataSourceName } from "./utils/conventional-naming";
import { deriveDefaultIdOutputType } from "./graphql-type-mapper";
const debug = _debug("greldal:MappedDataSource");
type AssociationsIn<T extends DataSourceMapping> = ReturnType<NNil<T["associations"]>>;
type FieldsIn<T extends DataSourceMapping> = ReturnType<NNil<T["fields"]>>;
type AssociationKeysIn<T extends DataSourceMapping> = keyof AssociationsIn<T>;
type FieldKeysIn<T extends DataSourceMapping> = keyof FieldsIn<T>;
type AssociatedDataSource<T extends DataSourceMapping, K extends AssociationKeysIn<T>> = AssociationsIn<T>[K]["target"];
type ShallowEntityType<T extends DataSourceMapping> = { [K in FieldKeysIn<T>]: FieldsIn<T>[K]["Type"] };
type NestedEntityType<T extends DataSourceMapping> = ShallowEntityType<T> &
{ [K in AssociationKeysIn<T>]: AssociatedDataSource<T, K>["EntityType"] };
/**
* Represents mapping between a relational data source and associated GraphQL types
* originating from the schema of this data source.
*
* @api-category MapperClass
*/
export class MappedDataSource<T extends DataSourceMapping = any> {
fields: Dict<MappedField>;
associations: Dict<MappedAssociation>;
constructor(private mapping: T) {
this.fields = mapping.fields ? mapping.fields(this) : {};
this.associations = mapping.associations ? mapping.associations(this) : {};
debug(
"Mapped data source with name: %s, fields: %O, associations: %O",
this.mappedName,
Object.keys(this.fields),
Object.keys(this.associations),
);
if (mapping.connector) {
assertSupportedConnector(mapping.connector);
}
}
/**
* Knex instance used to connect to data source.
*
* This can be a data-source specific connector (if provided in the mapping configuration), and if not,
* will fall back to global connector.
*
* Throws if a connector is not found.
*/
get connector(): Knex {
return assertConnectorConfigured(this.mapping.connector || globalConnector);
}
/**
* Get a knex query builder for this data source
*
* This internally aliases tables for ease of reverse-mapping.
*/
rootQueryBuilder(aliasHierarchyVisitor?: Maybe<AliasHierarchyVisitor>): Knex.QueryBuilder {
if (this.mapping.rootQuery) return this.mapping.rootQuery(aliasHierarchyVisitor);
return aliasHierarchyVisitor
? this.connector(`${this.storedName} as ${aliasHierarchyVisitor.alias}`)
: this.connector(this.storedName);
}
/**
* Get list of fields representing columns covered by primary key constraint
*/
get primaryFields() {
return Object.values<MappedField<any>>(this.fields).filter(f => f.isPrimary);
}
get primaryColumnNames() {
return this.primaryFields.map(f => f.sourceColumn!);
}
/**
* Name of the GraphQL output type representing an entity from this data source. Also used in other GraphQL output
* types for this data source.
*/
@MemoizeGetter
get mappedName() {
return deriveMappedDataSourceName(this.mapping.name);
}
/**
* Name of the GraphQL output type representing a shallow entity (containing only fields and not associations) from this data source.
*/
@MemoizeGetter
get shallowMappedName() {
return `Shallow${this.mappedName}`;
}
/**
* Name of the table/view backing this data source
*/
@MemoizeGetter
get storedName() {
return deriveStoredDataSourceName(this.mapping.name);
}
/**
* Name of the GraphQL output type representing a page container that wraps page specific metadata along with
* entities in the page (in a paginated query)
*/
@MemoizeGetter
get pageContainerName() {
return `${this.mappedName}PageContainer`;
}
/**
* Name of the GraphQL output type representing a page container that wraps page specific metadata along with
* shallow entities in the page (in a paginated query)
*/
@MemoizeGetter
get shallowPageContainerName() {
return `${this.shallowMappedName}PageContainer`;
}
/**
* Name of the GraphQL output type representing a page that wraps a subset of result entities (in a paginated query)
*/
@MemoizeGetter
get pageName() {
return `${this.mappedName}Page`;
}
/**
* Name of the GraphQL output type representing a page that wraps a subset of shallow result entities (in a paginated query)
*/
@MemoizeGetter
get shallowPageName() {
return `${this.shallowMappedName}Page`;
}
/**
* List of names of the columns in the data source which are mapped through the fields in the data source mapping
*
* It is not necessary that all columns of backing table are covered by fields of the data source.
*/
@MemoizeGetter
get storedColumnNames(): string[] {
return transform(
this.fields,
(result: string[], field: MappedField<MappedDataSource<T>, FieldMapping<any, any>>) => {
if (field.isMappedFromColumn) {
result.push(field.sourceColumn!);
}
},
[],
);
}
/**
* io-ts type props for field properties of a member entity
*/
@MemoizeGetter
get shallowEntityTypeSpecProps(): Dict<types.AnyTypeSpec> {
return transform(this.fields, (result, field, name) => {
result[name] = field.typeSpec;
return result;
});
}
/**
* io-ts type props for association properties of a member entity
*/
@MemoizeGetter
get associationTypeSpecProps(): Dict<types.AnyTypeSpec> {
const result: Dict<types.AnyTypeSpec> = {};
forEach(this.associations, (association, name) => {
result[name] = association.target.entityType;
});
return transform(
this.associations,
(result: t.Props, association: MappedAssociation<MappedDataSource<T>>, name: string) => {
result[name] = association.target.entityType;
},
{},
);
}
/**
* io-ts type props for all properties (from fields and associations)
*/
@MemoizeGetter
get entityTypeSpecProps(): Dict<types.AnyTypeSpec> {
return {
...this.shallowEntityTypeSpecProps,
...this.associationTypeSpecProps,
};
}
/**
* io-ts runtime type for shallow member entity (excludes associations) from this data source.
*/
@MemoizeGetter
get shallowEntityTypeSpec() {
return types.object(`Shallow${this.mappedName}`, this.shallowEntityTypeSpecProps);
}
/**
* io-ts runtime type for member entity from this data source.
*/
@MemoizeGetter
get entityTypeSpec() {
return types.object(this.mappedName, this.entityTypeSpecProps);
}
/**
* Getter to extract static type of Shallow member entity
*
* This is only useful in maped types. Throws if invoked directly.
*/
get ShallowEntityType(): ShallowEntityType<T> {
throw getTypeAccessorError("ShallowEntityType", "MappedDataSource");
}
/**
* Getter to extract static type of member entity
*
* This is only useful in maped types. Throws if invoked directly.
*/
get EntityType(): NestedEntityType<T> {
throw getTypeAccessorError("NestedEntityType", "MappedDataSource");
}
/**
* Getter to extract static type of the mapping used to configure the data source
*
* This is only useful in maped types. Throws if invoked directly.
*/
get MappingType(): T {
throw getTypeAccessorError("MappingType", "MappedDataSource");
}
/**
* Get the default GraphQL output type for a member entity
*/
@MemoizeGetter
get defaultOutputType(): GraphQLOutputType {
return deriveDefaultOutputType(this);
}
/**
* Get the output type for the response ofa paginated response performed against this data source
*/
@MemoizeGetter
get paginatedOutputType() {
return derivePaginatedOutputType(this.pageContainerName, this.pageName, this.defaultOutputType);
}
/**
* Get the output type for the response of a paginated query (for shallow entities) performed against this data source
*/
@MemoizeGetter
get paginatedShallowOutputType() {
return derivePaginatedOutputType(
this.shallowPageContainerName,
this.shallowPageName,
this.defaultShallowOutputType,
);
}
/**
* Get the default GraphQL input type for a shallow member entity (excludes associations)
*/
@MemoizeGetter
get defaultShallowInputType(): GraphQLInputType {
debug("Deriving default shallow input type for: ", this.mappedName);
return deriveDefaultShallowInputType(this);
}
/**
* Get the default GraphQL output type for a shallow member entity (excludes associations)
*/
@MemoizeGetter
get defaultShallowOutputType(): GraphQLOutputType {
return deriveDefaultShallowOutputType(this);
}
@MemoizeGetter
get defaultIdOutputType(): GraphQLOutputType {
return deriveDefaultIdOutputType(this);
}
/**
* Maps member entities (what the application interacts with) to rows (in the format the persistence layer expects)
*/
mapEntitiesToRows(entities: ShallowEntityType<T>[]): Dict[] {
return entities.map(entity =>
reduce<ShallowEntityType<T>, Dict>(
entity,
(result: Dict, val, key: any) => {
const field = this.fields[key];
if (field) {
return field.updatePartialRow(result, val);
}
return result;
},
{},
),
);
}
/**
* Reverse map the rows obtained from the data source (the persistence layer) to member entities (what the application interacts with)
*/
mapRowsToEntities(rows: Dict[], storeParams: StoreQueryParams<MappedDataSource<T>>) {
return new ReverseMapper(storeParams).reverseMap(rows);
}
/**
* Reverse map the rows obtained from the data source (the persistence layer) to shallow member entities
* (what the application interacts with)
*
* This does not deal with mapping of associations, so is relatively cheaper than mapRowsToEntities
*/
mapRowsToShallowEntities(rows: Dict[]) {
return rows.map(row => {
const mappedRow: Dict = {};
for (const [, field] of Object.entries<MappedField<MappedDataSource<T>, FieldMapping<any, any>>>(
this.fields,
)) {
mappedRow[field.mappedName] = field.getValue(row);
}
return mappedRow;
});
}
/**
* Given a query (entity field name -> value mapping), translates it into a query that the persistence
* layer can process by mapping entity field names to source column names.
*/
mapQueryParams(whereArgs: Dict, aliasHierarchyVisitor: AliasHierarchyVisitor) {
const whereParams: Dict = {};
Object.entries(whereArgs).forEach(([name, arg]) => {
const field: MappedField = (this.fields as any)[name];
if (field) {
whereParams[`${aliasHierarchyVisitor.alias}.${field.sourceColumn}`] = arg;
return;
}
});
return whereParams;
}
}
/**
* Used to map a relational data source using specified configuration (of type [DataSourceMapping](api:DataSourceMapping)).
*
* Refer the guide on [Mapping Data Sources](guide:mapping-data-sources) for detailed explanation and examples.
*
* @api-category PrimaryAPI
*/
export const mapDataSource = <T extends DataSourceMapping>(mapping: T) => new MappedDataSource<T>(mapping);
<file_sep>/src/docs/pages/architecture-overview.md
import NotificationBanner from '../components/NotificationBanner';
<NotificationBanner>
⚠️ This document is not an introduction for beginners. If you are new to GRelDAL it is strongly recommended that you first go through the Quick Start section and the guides first.
</NotificationBanner>
# Architecture Overview
This post describes the architecture of GRelDAL at a high level. The primary intended audience are the potential contributors. For lower level specifics, readers are encouraged to read the source.
It is also advisable to go through the terminology section of the API Overview before going through the content below.
There are four primary concepts around which GRelDAL is built:
1. Mapped Data Sources
2. Mapped Operations
3. Operation Resolvers
4. Operation Presets
## Mapped data sources
Mapped data sources represent a source in a relational database (usually a table, or a view, sometimes a joined table) which can serve as our primary source of truth.
It is the responsibility of a `MappedDataSource` instance to talk to the data source it represents. In many cases the actual data structure we expose to the application layer (referred here as Entities) differs from the table schema of the data source and in these cases it is the responsibility of the mapped data source to transparently convert between these representations and shield the application from having to know about the table schema.
Unlike ORMs, GRelDAL recommends usage of plain old javascript objects as entities.
A `MappedDataSource` instance can be constructed by calling the `mapDataSource` function, which accepts a mapping configuration.
This mapping configuration determines:
1. How the columns (in the source) are mapped to fields (of the entity).
2. What other data sources this data source can be associated with, and how can these associations be loaded.
Data sources can "cooperate" (by transforming a shared query builder) when the operation spans over multiple data sources - eg. when performing operations on join tables.
## Mapped Operations
Operations generalize the concepts of Queries and mutations in GraphQL.
```
Operation // Abstract interface for an operation mapSchema can handle (1)
^
|
|_ MappedOperation // Base class for GRelDAL aware operations
^
|
|_ MappedSingleSourceOperation // Base class for operations that operates on a single primary source
| ^
| |_ MappedSingleSourceQueryOperation
| |_ MappedSingleSourceInsertionOperation
| |_ MappedSingleSourceUpdateOperation
| |_ MappedSingleSourceDeletionOperation
|
|_ MappedMultiSourceOperation // Base class for operations that operate on multiple sources
^
|_ MappedMultiSourceUnionQueryOperation
```
Operations delegate the actual resolution to an associated operation resolver. All the information that the resolver may need are encapsulated in the ResolverContext DTO which is instantiated by the Operation implementation.
## Operation Resolvers
Operation resolvers implement the actual logic for resolving the operations. All the `MappedOperation` implementations defined by GRelDAL are associated with corresponding default resolvers, however they can be overriden through operation mapping configuration.
```
Operation OperationResolver
^ ^
| |
MappedOperation |
| |
|_ MappedSourceAwareOperation SourceAwareOperationResolver___|
^ ^
| |
|_ MappedSingleSourceOperation |
| ^ |
| |_ MappedSingleSourceQueryOperation ------ (defaults to)-> SingleSourceQueryOperationResolver __|
| |_ MappedSingleSourceInsertionOperation -- (defaults to)-> SingleSourceInsertionOperationResolver __|
| |_ MappedSingleSourceUpdateOperation ----- (defaults to)-> SingleSourceUpdateOperationResolver __|
| |_ MappedSingleSourceDeletionOperation --- (defaults to)-> SingleSourceDeletionOperationResolver __|
| |
|_ MappedMultiSourceOperation |
^ |
|_ MappedMultiSourceUnionQueryOperation -- (defaults to)-> MultiSourceUnionQueryOperationResolver __|
```
Query resolvers can also "delegate" through "side-loading" - this is a better alternative to hierarchical resolution in GraphQL that often results in N+1 query patterns because side-loading supports batch resolution and resolved results are automatically mapped and associated to parent entities.
## Operation Presets
Operation presets are pre-configured operation for common use cases (CRUD operations).
Despite being pre-configured presets afford a great deal of flexibility because it accomodates custom transformation of mapping through interceptors.
# Operation resolution process
GRelDAL is designed to work with graphql.js - the reference implementation of GraphQL provided by facebook.
`mapSchema` function constructs a graphql.js compatible schema from a collection of GRelDAL operations. Every operation has a fieldConfig getter that returns a graphql.js compatible fieldConfig. Application can associate interceptors for the fieldConfig which can transform how an operation is mapped to a query/mutation field.
Most of the GraphQL types are derived from the DataSource mapping configuration.
Resolution of a typical GraphQL Query looks something like this:
```
___
| Parsing of GraphQL DSL
| |
| |
In graphql.js -| V
| Identify fieldConfig using query/mutation name
| |
| V
| Invoke fieldConfig.resolve
| |
_|_ ___ V
| | Initialize ResolverContext (1)
| | |
| | V
| | Locate OperationResolver implementation
| In | |
| MappedOperation | V
| | Initialize OperationResolver with resolverContext
| | |
| | V
| -+- Invoke OperationResolver#resolve
| | |
| | V
| | Invoke dataSource methods to construct SQL query
In | In | |
GRelDAL | OperationResolver |_ V
| | Invoke Knex to construct SQL query
| | |
| | V
| | In Use configured data source connector to run SQL
| | MappedDataSource |
| | |
| | V
| | Transform response to format expected in the GraphQL Query
| | |
| | V
_|_ _|_ Return response
In graphql.js | |
| V
_|_ Recursively visit and validate response
```
<file_sep>/src/MappedSingleSourceDeletionOperation.ts
import { GraphQLFieldConfigArgumentMap, GraphQLNonNull } from "graphql";
import { SingleSourceDeletionOperationResolver } from "./SingleSourceDeletionOperationResolver";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceMutationOperation } from "./MappedSingleSourceMutationOperation";
import { MemoizeGetter } from "./utils/utils";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
/**
* @api-category MapperClass
*/
export class MappedSingleSourceDeletionOperation<
TSrc extends MappedDataSource,
TArgs extends {}
> extends MappedSingleSourceMutationOperation<TSrc, TArgs> {
constructor(
public mapping: MappedSingleSourceMutationOperation<TSrc, TArgs>["mapping"] & {
resolver?: <
TCtx extends SourceAwareResolverContext<MappedSingleSourceDeletionOperation<TSrc, TArgs>, TSrc, TArgs>,
TResolved
>(
ctx: TCtx,
) => SingleSourceDeletionOperationResolver<TCtx, TSrc, TArgs, TResolved>;
},
) {
super(mapping);
}
defaultResolver(
resolverContext: SourceAwareResolverContext<MappedSingleSourceDeletionOperation<TSrc, TArgs>, TSrc, TArgs>,
): SingleSourceDeletionOperationResolver<
SourceAwareResolverContext<MappedSingleSourceDeletionOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc,
TArgs,
any
> {
return new SingleSourceDeletionOperationResolver(resolverContext);
}
@MemoizeGetter
get defaultArgs(): GraphQLFieldConfigArgumentMap {
return {
where: {
type: GraphQLNonNull(this.rootSource.defaultShallowInputType),
},
};
}
}
<file_sep>/src/ArgMapping.ts
import * as t from "io-ts";
import * as Knex from "knex";
import { Dict, InstanceOf } from "./utils/util-types";
import { TypeSpec } from "./utils/types";
export const ArgMappingRT = t.intersection(
[
t.partial({
/**
* Description exposed to clients through mapped GraphQL API
*
* @memberof ArgMapping
*/
description: t.string,
interceptQuery: t.Function,
interceptEntity: t.Function,
defaultValue: t.any,
}),
t.type({
type: InstanceOf(TypeSpec),
}),
],
"ArgMapping",
);
export const ArgMappingDictRT = t.record(t.string, ArgMappingRT, "ArgMappingDict");
/**
* Configuration for mapping of an input argument
*
* @api-category ConfigType
*/
export interface ArgMapping<TMapped> extends t.TypeOf<typeof ArgMappingRT> {
/**
* Type specification for this argument
*
* Normally this would be a composition of one of the runtime types exposed through types library.
* These types are simply re-exported from [io-ts](https://github.com/gcanti/io-ts) and detailed documentation can be found there.
*
* Example:
*
* ```
* // Primitives
* t.string
* t.number
*
* // Composite types
* t.type({
* x: t.number,
* y: t.number
* })
*
* t.array(t.string)
* ```
*/
type: TypeSpec<TMapped>;
/**
* Default value of this argument.
*
* Exposed to clients through mapped GraphQL API
*/
defaultValue?: TMapped;
/**
* Can be used to intercept the database query being constructed during query
*
* This opens up the ability to map an argument value to an arbitrary database query operation.
*/
interceptQuery?: (queryBuilder: Knex.QueryBuilder, value: TMapped, args: Dict) => Knex.QueryBuilder;
/**
* Can be used to intercept the derived entity to be used for the operation this argument is part of.
*
* Typically useful for insert, update operations.
*/
interceptEntity?: <TEntity>(entity: Partial<TEntity>) => Partial<TEntity>;
}
<file_sep>/src/MappedSingleSourceOperation.ts
import { GraphQLFieldConfigArgumentMap, GraphQLList, GraphQLOutputType, GraphQLResolveInfo } from "graphql";
import * as t from "io-ts";
import * as Knex from "knex";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { assertType } from "./utils/assertions";
import { getTypeAccessorError } from "./utils/errors";
import { MappedAssociation } from "./MappedAssociation";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
import { OperationMappingRT } from "./OperationMapping";
import { ResolveInfoVisitor } from "./ResolveInfoVisitor";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { Dict } from "./utils/util-types";
import { MemoizeGetter } from "./utils/utils";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
type RCtx<TSrc extends MappedDataSource, TArgs extends object> = SourceAwareResolverContext<
MappedSingleSourceOperation<TSrc, TArgs>,
TSrc,
TArgs
>;
export const SingleSourceOperationMappingRT = t.intersection([
OperationMappingRT,
t.partial({
rootQuery: t.Function,
deriveWhereParams: t.Function,
}),
]);
/**
* A MappedOperation encapsulates the logic and information needed to map an operation
* on a data source to a GraphQL Query/Mutation
*
* A MappedOperation is expected to not contain the actual logic for the operation - it delegates
* to a Resolver class which will handle how this operation can be resolved in the context of
* specified data source using the provided args.
*
* MappedOperation is primarily concerned with selection of appropriate data sources (if more than one
* are specified), selection of an appropriate resolver (if more than one are specified) and delegating
* to the selected resolver for perforrming the actual operation in database.
*
* Creating a custom sub-class of a MappedOperation is usually not required for most common use cases
* because most use cases are better served by a custom resolver used with either MappedQueryOperation
* or MappedMutationOperation, both of which descend from this class.
*
* In rare cases, sub-classing MappedOperation (or one of its descendants) can be beneficial when
* consumer wants a more control over the mapping of operation to GraphQL layer than is possible through
* the OperationMapping configuration.
*
* Example of such use cases include:
*
* - When GraphQL args can not be deduced from a static configuration and need to be defined dynamically
* - Arbitrary adhoc (potentially async) transformation of args before delegating to a resolver.
*
* @api-category MapperClass
*/
export abstract class MappedSingleSourceOperation<
TSrc extends MappedDataSource,
TArgs extends object
> extends MappedSourceAwareOperation<TSrc, TArgs> {
constructor(
public mapping: MappedSourceAwareOperation<TSrc, TArgs>["mapping"] & {
rootSource: TSrc;
rootQuery?: (
dataSource: TSrc,
args: TArgs,
aliasHierarchyVisitor?: AliasHierarchyVisitor | null,
) => Knex.QueryBuilder;
deriveWhereParams?: (args: TArgs, association?: MappedAssociation) => Dict;
resolver?: <
TCtx extends SourceAwareResolverContext<MappedSingleSourceOperation<TSrc, TArgs>, TSrc, TArgs>,
TResolved
>(
ctx: TCtx,
) => SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved>;
},
) {
super(mapping);
assertType(SingleSourceOperationMappingRT, mapping, `Operation configuration: ${mapping.name}`);
}
get rootSource() {
return this.mapping.rootSource;
}
get mappedArgs(): GraphQLFieldConfigArgumentMap {
if (this.mapping.args) {
return this.mapping.args.getMappedArgsFor(this.rootSource);
}
return this.defaultArgs;
}
@MemoizeGetter
get type(): GraphQLOutputType {
if (this.mapping.returnType) {
return this.mapping.returnType;
}
let baseType: GraphQLOutputType;
const { rootSource } = this.mapping;
if (this.paginationConfig) {
if (this.shallow) {
return rootSource.paginatedShallowOutputType;
} else {
return rootSource.paginatedOutputType;
}
}
if (this.shallow) {
baseType = rootSource.defaultShallowOutputType;
} else {
baseType = rootSource.defaultOutputType;
}
if (this.singular) {
return baseType;
} else {
return GraphQLList(baseType);
}
}
get ResolverContextType(): RCtx<TSrc, TArgs> {
throw getTypeAccessorError("ResolverContextType", "MappedOperation");
}
rootQuery(dataSource: TSrc, args: TArgs, aliasHierachyVisitor: AliasHierarchyVisitor | null): Knex.QueryBuilder {
if (this.mapping.rootQuery) {
return this.mapping.rootQuery.call<
MappedSingleSourceOperation<TSrc, TArgs>,
[TSrc, TArgs, AliasHierarchyVisitor | null],
Knex.QueryBuilder
>(this, dataSource, args, aliasHierachyVisitor);
}
return dataSource.rootQueryBuilder(aliasHierachyVisitor);
}
async createResolverContext(
source: any,
args: TArgs,
context: any,
resolveInfo: GraphQLResolveInfo,
resolveInfoVisitor?: ResolveInfoVisitor<any>,
): Promise<RCtx<TSrc, TArgs>> {
return SourceAwareResolverContext.create(
this,
{ [this.rootSource.mappedName]: { selection: () => this.rootSource } },
source,
args,
context,
resolveInfo,
resolveInfoVisitor,
);
}
}
<file_sep>/src/operation-types.ts
import { isNil } from "lodash";
export enum OperationType {
Query = "query",
Mutation = "mutation",
Subscription = "subscription",
}
export const operationType = (input: string | null | undefined, defaultType: OperationType) => {
if (isNil(input)) return defaultType;
switch (input) {
case OperationType.Query:
return OperationType.Query;
case OperationType.Mutation:
return OperationType.Mutation;
case OperationType.Subscription:
return OperationType.Subscription;
}
throw new TypeError("Invalid operationType: " + operationType);
};
<file_sep>/src/utils/json.ts
import * as t from "io-ts";
import { isNil } from "lodash";
import { Validation } from "io-ts";
import { isLeft } from "fp-ts/lib/Either";
import _debug from "debug";
import { isString } from "util";
const debug = _debug("greldal:json");
const stringifyCache = new WeakMap();
const cachedStringify = <T extends {}>(input: T) => {
if (isNil(input)) return undefined;
const cached = stringifyCache.get(input);
if (cached) return cached;
const stringified = JSON.stringify(input);
stringifyCache.set(input, stringified);
return stringified;
};
export class JSONType<RT> extends t.Type<RT, string, unknown> {
readonly _tag: "JSONType" = "JSONType";
constructor(public type: t.Type<RT>, public name = `JSON(${type.name})`) {
super(
name,
type.is,
(i: unknown, c: t.Context) => {
const validation = type.validate(i, c);
if (isLeft(validation)) return validation as any;
try {
cachedStringify(validation);
return t.success(i);
} catch (e) {
return t.failure(i, c);
}
},
cachedStringify,
);
}
decode(input: any): Validation<RT> {
try {
debug("Parsing input:", input);
const parsed = isString(input) ? JSON.parse(input) : input;
return this.type.decode(parsed);
} catch (e) {
t.failure(input, []);
}
return JSON.parse(input);
}
}
export const json = <T>(baseType: t.Type<T>, name?: string) => new JSONType<T>(baseType, name);
<file_sep>/src/generator/indentation-tracker.ts
import { times, noop, constant, isEmpty } from "lodash";
export class IndentationTracker {
constructor(private baseIndent = 4, private curIndent = 0, public output = "") {}
indent() {
this.curIndent += this.baseIndent;
}
dedent() {
this.curIndent -= this.baseIndent;
if (this.curIndent < 0) this.curIndent = 0;
}
addLine(str: string) {
times(this.curIndent, () => (this.output += " "));
this.output += str;
if (this.output.charAt(this.output.length - 1) !== "\n") this.output += "\n";
}
reIndentBlock(str: string) {
return str
.split("\n")
.map(line => times(this.curIndent, constant(" ")).join("") + line)
.filter(line => !isEmpty(line))
.join("\n");
}
addBlock(start = "{", callback = noop, end = "}") {
if (start) this.addLine(start);
this.indent();
callback();
this.dedent();
if (end) this.addLine(end);
}
wrap(start = "{", end = "}") {
const { output } = this;
this.output = "";
if (start) this.addLine(start);
this.curIndent = 0;
this.indent();
const lines = output.split("\n").slice(0, -1);
for (const line of lines) {
this.addLine(line);
}
this.dedent();
if (end) this.addLine(end);
}
isEmpty() {
return isEmpty(this.output);
}
toString() {
return this.output;
}
}
<file_sep>/src/MappedField.ts
import { Dict, Maybe } from "./utils/util-types";
import { GraphQLInputType, GraphQLOutputType } from "graphql";
import { getTypeAccessorError } from "./utils/errors";
import { MappedDataSource } from "./MappedDataSource";
import { snakeCase, map, transform, pick, has } from "lodash";
import { MemoizeGetter } from "./utils/utils";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { assertType } from "./utils/assertions";
import assert from "assert";
import {
FieldMapping,
FieldMappingRT,
ComputedFieldMapping,
ColumnFieldMapping,
ColumnMapping,
FieldMappingArgs,
} from "./FieldMapping";
function isMappedFromColumn(f: FieldMapping<any, any>): f is ColumnFieldMapping<any> {
return !has(f, "derive");
}
function isComputed(f: FieldMapping<any, any>): f is ComputedFieldMapping<any, any> {
return has(f, "derive");
}
/**
* Represents a field that has been mapped from one or more columns in a data source
*
* Encapsulates the difference between primary and computed fields
*
* @api-category MapperClass
*/
export class MappedField<
TSrc extends MappedDataSource = MappedDataSource,
TFMapping extends FieldMapping<any, any> = any
> {
constructor(public dataSource: TSrc, public mappedName: string, private mapping: TFMapping) {
assertType(
FieldMappingRT,
mapping,
`Field mapping configuration:\nDataSource<${dataSource.mappedName}>[fields][${mappedName}]`,
);
}
get dependencies(): MappedField<TSrc>[] {
if (this.isMappedFromColumn) {
return [];
}
return map(
(this.mapping as ComputedFieldMapping).dependencies,
name => this.dataSource.fields[name] as MappedField<TSrc>,
);
}
/**
* If the field is directly mapped from a column.
*
* Returns false for computed fields
*/
get isMappedFromColumn() {
return isMappedFromColumn(this.mapping);
}
/**
* If the field corresponds to a primary key in backing table
*/
get isPrimary() {
if (isMappedFromColumn(this.mapping)) {
return (this.mapping as ColumnFieldMapping<any>).isPrimary;
}
return false;
}
/**
* If this is a computed field
*/
get isComputed() {
return isComputed(this.mapping);
}
/**
* The name of column which this field is mapped from
*
* Returns undefined for computed fields
*/
get sourceColumn() {
if (this.isMappedFromColumn) {
const mapping: ColumnFieldMapping<any> = this.mapping;
return mapping.sourceColumn || snakeCase(this.mappedName);
}
return undefined;
}
/**
* Names of all the columns which this field is derived from.
*
* For directly mapped column fields, this will always have a singular entry - the name of backing column.
* For derived columns it will contain list of dependencies
*/
get sourceColumns() {
if (isMappedFromColumn(this.mapping)) {
return [this.sourceColumn!];
} else {
return this.dependencies.reduce((result: string[], dependency: MappedField<any>) => {
result.push(...dependency.sourceColumns);
return result;
}, []);
}
}
/**
* If this field is exposed in the GraphQL API
*/
get exposed() {
return this.mapping.exposed !== false;
}
/**
* Description of this field - available to clients through the GraphQL API for exposed fields
*/
get description() {
return this.mapping.description;
}
/**
* Type specification for field
*/
get typeSpec() {
return this.mapping.type;
}
/**
* Human friendly represenation of the path of the field relative to data source - primarily useful for logging and debugging
*/
get keyPath() {
return `${this.dataSource.mappedName}[fields][${this.mappedName}]`;
}
/**
* Field derivation function - undefined if the field is not a computed field
*/
get derive() {
if (isComputed(this.mapping)) return this.mapping.derive;
return undefined;
}
/**
* Get aliased name for the column, derived from table alias.
*
* Throws for computed columns
*/
getColumnAlias(tableAlias: Maybe<string>) {
assert(this.isMappedFromColumn, "Field is not mapped from column");
if (!tableAlias) return this.sourceColumn;
return `${tableAlias}__${this.sourceColumn}`;
}
getColumnMappingList(
aliasHierarchyVisitor: AliasHierarchyVisitor,
aliasColumnsToTableScope = true,
): ColumnMapping[] {
if (this.mapping.getColumnMappingList) {
return this.mapping.getColumnMappingList(aliasHierarchyVisitor, aliasColumnsToTableScope);
}
if (this.isMappedFromColumn) {
const tableAlias = aliasHierarchyVisitor.alias;
return [
{
field: this,
columnRef: `${tableAlias}.${this.sourceColumn}`,
columnAlias: this.getColumnAlias(aliasColumnsToTableScope ? tableAlias : undefined)!,
},
];
} else {
return transform(
this.dependencies,
(list: ColumnMapping[], f: MappedField) => list.push(...f.getColumnMappingList(aliasHierarchyVisitor)),
[],
);
}
}
/**
* GraphQL output type for this field
*/
@MemoizeGetter
get graphQLOutputType(): GraphQLOutputType {
return this.mapping.type.graphQLOutputType;
}
/**
* GraphQL input type for this field
*/
@MemoizeGetter
get graphQLInputType(): GraphQLInputType {
return this.mapping.type.graphQLInputType;
}
/**
* Getter useful to get the static type for this field.
*
* Useful only in mapped/computed typescript types - will throw if actually invoked.
*/
get Type(): TFMapping["type"]["Type"] {
throw getTypeAccessorError("Type", "MappedField");
}
fromSource(i: any) {
if (this.isMappedFromColumn) {
const mapping = this.mapping as ColumnFieldMapping<any>;
if (mapping.fromSource) return mapping.fromSource(i);
}
return i;
}
toSource(i: TFMapping["type"]["Type"]) {
if (this.isMappedFromColumn) {
const mapping = this.mapping as ColumnFieldMapping<any>;
if (mapping.toSource) return mapping.toSource(i);
}
return i;
}
/**
* Get the value for this field given a source row obtained from the data source
*/
getValue(sourceRow: Dict) {
if (this.isComputed) {
const { dependencies, derive } = this.mapping as ComputedFieldMapping<
TFMapping["type"],
FieldMappingArgs<TFMapping>
>;
const args: any = pick(sourceRow, dependencies);
return derive(args);
}
const key = this.sourceColumn;
if (key) {
return sourceRow[key];
}
}
/**
* Reducer mapping a partial row (from data source) from a partial entity.
*
* Reduce functions from all fields can be composed to arrive at a data source row from Shallow entity
*/
updatePartialRow(partialRow: Dict, value: any): Dict {
if (this.sourceColumn) {
partialRow[this.sourceColumn] = this.toSource(value);
return partialRow;
}
const { mapping } = this;
if (isComputed(mapping) && mapping.reduce) {
return mapping.reduce(partialRow);
}
return partialRow;
}
}
/**
* @api-category PrimaryAPI
*/
export const mapFields = <TFieldMapping extends Dict<FieldMapping<any, TArgs>>, TArgs extends {}>(
fields: TFieldMapping,
) => <TSrc extends MappedDataSource>(
dataSource: TSrc,
): { [K in keyof TFieldMapping]: MappedField<TSrc, TFieldMapping[K]> } =>
transform(
fields,
(result: Dict, fieldMapping, name) => {
result[name] = new MappedField(dataSource, name, fieldMapping);
},
{},
) as any;
<file_sep>/src/docs/components/Editor.js
import ReactCodeMirror from "react-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/mode/javascript/javascript";
import "codemirror/theme/monokai.css";
import "codemirror/addon/hint/show-hint";
import "codemirror/addon/lint/lint";
import "codemirror-graphql/hint";
import "codemirror-graphql/lint";
import "codemirror-graphql/mode";
const Editor = ({innerRef, ...props}) => (
<ReactCodeMirror {...props} ref={innerRef} />
);
export default Editor;
<file_sep>/src/ResolveInfoVisitor.ts
import { GraphQLResolveInfo } from "graphql";
import { ResolveTree, parseResolveInfo } from "graphql-parse-resolve-info";
import { MappedDataSource } from "./MappedDataSource";
import { Maybe } from "./utils/util-types";
import _debug from "debug";
import { MappedAssociation } from "./MappedAssociation";
import assert from "assert";
import { PaginatedResolveInfoVisitor, MaybePaginatedResolveInfoVisitor } from "./PaginatedResolveInfoVisitor";
const debug = _debug("greldal:ResolveInfoVisitor");
/**
* Encapsulates the current position while traversing the GraphQLResolveInfo hierarchy while a query is being resolved.
*/
export class ResolveInfoVisitor<
TSrc extends MappedDataSource,
TParentVisitor extends Maybe<MaybePaginatedResolveInfoVisitor<any, any>> = any
> {
public parsedResolveInfo: ResolveTree;
constructor(
public originalResolveInfoRoot: GraphQLResolveInfo,
public rootSource: TSrc,
parsedResolveInfo?: ResolveTree,
public parentSource?: TParentVisitor,
) {
this.parsedResolveInfo =
parsedResolveInfo ||
//TODO: Remove any after version incompatibility with typings is resolved
(parseResolveInfo(originalResolveInfoRoot as any) as any);
}
visitRelation<A extends MappedAssociation>(
association: A,
): PaginatedResolveInfoVisitor<A["target"], any> | ResolveInfoVisitor<A["target"], any> {
const returnTypeName = this.rootSource.mappedName;
const nextResolveInfo = this.parsedResolveInfo.fieldsByTypeName[returnTypeName][association.mappedName];
debug("Visiting association:", association.mappedName);
debug(
"Deduced next resolve info: %O[fieldsByTypeName][%s][%s] => %O",
this.parsedResolveInfo,
returnTypeName,
association.mappedName,
nextResolveInfo,
);
assert(
nextResolveInfo,
`Failed to deduce resolveInfo for next level when visiting association ${association.mappedName} from ${this.rootSource.mappedName}`,
);
if (association.isPaginated) {
return new PaginatedResolveInfoVisitor(
this.originalResolveInfoRoot,
association.target,
nextResolveInfo,
this,
);
}
return new ResolveInfoVisitor(this.originalResolveInfoRoot, association.target, nextResolveInfo, this);
}
*iterateFieldsOf(typeName: string) {
const fields = this.parsedResolveInfo.fieldsByTypeName[typeName];
if (!fields) return;
debug("Iterating fields %s -> %O", typeName, fields, this.parsedResolveInfo);
for (const [fieldName, fieldInfo] of Object.entries(fields)) {
yield { fieldName, fieldInfo };
}
}
}
<file_sep>/src/utils/types.ts
import {
GraphQLString,
GraphQLInputType,
GraphQLOutputType,
GraphQLFloat,
GraphQLBoolean,
GraphQLList,
GraphQLScalarType,
GraphQLObjectType,
GraphQLObjectTypeConfig,
GraphQLUnionType,
GraphQLUnionTypeConfig,
GraphQLInt,
GraphQLInputObjectType,
GraphQLFieldConfigMap,
GraphQLInputFieldConfigMap,
GraphQLID,
GraphQLNonNull,
} from "graphql";
import { getTypeAccessorError } from "./errors";
import { Dict, Maybe } from "./util-types";
import { GraphQLDate, GraphQLTime, GraphQLDateTime } from "graphql-iso-date";
export class TypeSpec<
TBase,
TGraphQLInputType extends GraphQLInputType = GraphQLInputType,
TGraphQLOutputType extends GraphQLOutputType = GraphQLOutputType
> {
constructor(
readonly name: string,
readonly graphQLInputType: TGraphQLInputType,
readonly graphQLOutputType: TGraphQLOutputType,
) {}
get Type(): TBase {
throw getTypeAccessorError("Type", "TypeSpec");
}
get GraphQLInputType(): TGraphQLInputType {
throw getTypeAccessorError("GraphQLInputType", "TypeSpec");
}
get GraphQLOutputType(): TGraphQLOutputType {
throw getTypeAccessorError("GraphQLOutputType", "TypeSpec");
}
}
export type AnyTypeSpec = TypeSpec<any>;
export class ScalarTypeSpec<TBase, TGraphQLType extends GraphQLScalarType> extends TypeSpec<
TBase,
TGraphQLType,
TGraphQLType
> {
constructor(readonly graphQLType: TGraphQLType) {
super(graphQLType.name, graphQLType, graphQLType);
}
}
export const wrapScalar = <TBase, TGraphQLType extends GraphQLScalarType = GraphQLScalarType>(scalar: TGraphQLType) =>
new ScalarTypeSpec<TBase, TGraphQLType>(scalar);
class NonNullTypeSpec<
TBase,
TGraphQLInputType extends GraphQLInputType,
TGraphQLOutputType extends GraphQLOutputType
> extends TypeSpec<NonNullable<TBase>, GraphQLNonNull<TGraphQLInputType>, GraphQLNonNull<TGraphQLOutputType>> {
constructor(readonly wrapped: TypeSpec<TBase, TGraphQLInputType, TGraphQLOutputType>) {
super(
`${wrapped.name}!`,
GraphQLNonNull(wrapped.graphQLInputType) as GraphQLNonNull<TGraphQLInputType>,
GraphQLNonNull(wrapped.graphQLOutputType) as GraphQLNonNull<TGraphQLOutputType>,
);
}
}
export const nonNull = <
TBase,
TGraphQLInputType extends GraphQLInputType,
TGraphQLOutputType extends GraphQLOutputType
>(
wrapped: TypeSpec<TBase, TGraphQLInputType, TGraphQLOutputType>,
) => new NonNullTypeSpec(wrapped);
export const string = wrapScalar<Maybe<string>>(GraphQLString);
export const integer = wrapScalar<Maybe<number>>(GraphQLInt);
export const float = wrapScalar<Maybe<number>>(GraphQLFloat);
export const number = wrapScalar<Maybe<number>>(GraphQLFloat);
export const boolean = wrapScalar<Maybe<boolean>>(GraphQLBoolean);
export const isoDateStr = wrapScalar<Maybe<string>>(GraphQLDate);
export const isoTimeStr = wrapScalar<Maybe<string>>(GraphQLTime);
export const isoDateTimeStr = wrapScalar<Maybe<string>>(GraphQLDateTime);
export const isoDate = wrapScalar<Maybe<Date>>(GraphQLDate);
export const isoTime = wrapScalar<Maybe<Date>>(GraphQLTime);
export const isoDateTime = wrapScalar<Maybe<Date>>(GraphQLDateTime);
export const stringId = wrapScalar<Maybe<string>>(GraphQLID);
export const intId = wrapScalar<Maybe<number>>(GraphQLID);
export type SourceFromTypeSpecMapping<TSpec extends Dict<TypeSpec<any, any, any>>> = {
[Key in keyof TSpec]: TSpec[Key]["Type"];
};
export type ObjectTypeSpecConfig<TSource, TContext> = Omit<
GraphQLObjectTypeConfig<TSource, TContext>,
"name" | "fields"
>;
export class ObjectTypeSpec<
TSpecMapping extends Dict<TypeSpec<any, any, any>>,
TSource = SourceFromTypeSpecMapping<TSpecMapping>,
TContext = any
> extends TypeSpec<TSource, GraphQLInputObjectType, GraphQLObjectType<TSource, TContext>> {
constructor(
readonly name: string,
readonly fields: TSpecMapping,
readonly config?: ObjectTypeSpecConfig<TSource, TContext>,
) {
super(
name,
new GraphQLInputObjectType({
name: `${name}Input`,
description: config?.description,
fields: Object.keys(fields).reduce(
(partialFields, key) =>
Object.assign(partialFields, {
[key]: {
type: fields[key].graphQLInputType,
},
}),
{} as GraphQLInputFieldConfigMap,
),
}),
new GraphQLObjectType<TSource, TContext>({
...config,
name,
fields: Object.keys(fields).reduce(
(partialFields, key) =>
Object.assign(partialFields, {
[key]: {
type: fields[key].graphQLOutputType,
},
}),
{} as GraphQLFieldConfigMap<TSource, TContext>,
),
}),
);
}
get Source(): TSource {
throw getTypeAccessorError("Source", "TypeSpec");
}
get Context(): TContext {
throw getTypeAccessorError("Context", "TypeSpec");
}
}
export function object<
TSpecMapping extends Dict<TypeSpec<any, any, any>>,
TSource = SourceFromTypeSpecMapping<TSpecMapping>,
TContext = any
>(name: string, typeMapping: TSpecMapping) {
return new ObjectTypeSpec<TSpecMapping, TSource, TContext>(name, typeMapping);
}
export class ArrayTypeSpec<TSpec extends TypeSpec<any, any, any>> extends TypeSpec<
TSpec["Type"][],
GraphQLList<TSpec["GraphQLInputType"]>,
GraphQLList<TSpec["GraphQLOutputType"]>
> {
constructor(readonly type: TSpec) {
super(`Array<${type.name}>`, GraphQLList(type.graphQLInputType), GraphQLList(type.graphQLOutputType));
}
}
export const array = <TSpec extends TypeSpec<any, any, any>>(type: TSpec) => new ArrayTypeSpec(type);
export type UnionTypeSpecConfig<TSource, TContext> = Omit<GraphQLUnionTypeConfig<TSource, TContext>, "name" | "fields">;
export class UnionTypeSpec<TSpec extends TypeSpec<any, any, any>> extends TypeSpec<
TSpec["Type"],
TSpec["GraphQLInputType"],
TSpec["GraphQLOutputType"]
> {
constructor(readonly name: string, readonly types: TSpec[]) {
super(
name,
new GraphQLUnionType({
name: `${name}Input`,
types: types.map(t => t.graphQLInputType),
}),
new GraphQLUnionType({
name,
types: types.map(t => t.graphQLOutputType),
}),
);
}
}
export const union = <TSpec extends TypeSpec<any, any, any>>(name: string, types: TSpec[]) =>
new UnionTypeSpec(name, types);
export class ObjIntersectionTypeSpec<TSpec extends ObjectTypeSpec<any>> extends TypeSpec<
TSpec["Type"],
TSpec["GraphQLInputType"],
TSpec["GraphQLOutputType"]
> {
constructor(readonly name: string, readonly types: TSpec[]) {
super(
name,
new GraphQLInputObjectType({
name: `${name}Input`,
fields: types.reduce((r, t) => {
const fields: any = t.fields;
Object.keys(fields).forEach(k => {
r[k] = {
type: fields[k].graphQLInputType,
};
});
return r;
}, {} as GraphQLInputFieldConfigMap),
}),
new GraphQLObjectType({
name,
fields: types.reduce((r, t) => {
const fields: any = t.fields;
Object.keys(fields).forEach(k => {
r[k] = {
type: fields[k].graphQLOutputType,
};
});
return r;
}, {} as GraphQLFieldConfigMap<TSpec["Source"], TSpec["Context"]>),
}),
);
}
}
export const intersection = <TSpec extends ObjectTypeSpec<any>>(name: string, types: TSpec[]) =>
new ObjIntersectionTypeSpec(name, types);
<file_sep>/src/universal.ts
import { KNEX_SUPPORTED_DBS, OFFICIALLY_SUPPORTED_DBS, useDatabaseConnector } from "./utils/connector";
import { SingleSourceInsertionOperationResolver } from "./SingleSourceInsertionOperationResolver";
import { SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver";
import { mapSchema } from "./MappedSchema";
import { mapDataSource } from "./MappedDataSource";
import { mapArgs } from "./MappedArgs";
import * as types from "./utils/types";
import * as operationPresets from "./operation-presets";
import { SingleSourceUpdateOperationResolver } from "./SingleSourceUpdateOperationResolver";
import { SingleSourceDeletionOperationResolver } from "./SingleSourceDeletionOperationResolver";
import { MappedSingleSourceInsertionOperation } from "./MappedSingleSourceInsertionOperation";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { MappedSingleSourceUpdateOperation } from "./MappedSingleSourceUpdateOperation";
import { MappedSingleSourceDeletionOperation } from "./MappedSingleSourceDeletionOperation";
import { MultiSourceUnionQueryOperationResolver } from "./MultiSourceUnionQueryOperationResolver";
import { MappedMultiSourceUnionQueryOperation } from "./MappedMultiSourceUnionQueryOperation";
import { MappedMultiSourceOperation } from "./MappedMultiSourceOperation";
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { MappedOperation } from "./MappedOperation";
import { mapFields } from "./MappedField";
import { mapAssociations } from "./MappedAssociation";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
import { OperationType } from "./operation-types";
import * as NotificationDispatcher from "./NotificationDispatcher";
import { mapUserDefinedFunction } from "./MappedUDFInvocationOperation";
import { mapStoredProcedure } from "./MappedStoredProcInvocationOperation";
export {
KNEX_SUPPORTED_DBS,
OFFICIALLY_SUPPORTED_DBS,
mapSchema,
mapArgs,
mapDataSource,
mapFields,
mapAssociations,
useDatabaseConnector,
types,
operationPresets,
SingleSourceInsertionOperationResolver,
SingleSourceQueryOperationResolver,
SingleSourceUpdateOperationResolver,
SingleSourceDeletionOperationResolver,
MultiSourceUnionQueryOperationResolver,
MappedSingleSourceInsertionOperation,
MappedSingleSourceQueryOperation,
MappedSingleSourceUpdateOperation,
MappedSingleSourceDeletionOperation,
MappedMultiSourceUnionQueryOperation,
MappedMultiSourceOperation,
MappedSingleSourceOperation,
MappedOperation,
MappedSourceAwareOperation,
OperationType as OperationTypes,
NotificationDispatcher,
mapUserDefinedFunction,
mapStoredProcedure,
};
<file_sep>/src/__specs__/stored-proc-invocation.spec.ts
import * as Knex from "knex";
import { setupKnex } from "./helpers/setup-knex";
import { useDatabaseConnector, operationPresets } from "..";
import { setupUserSchema, insertFewUsers, mapUsersDataSource, teardownUserSchema } from "./helpers/setup-user-schema";
import { GraphQLSchema, graphql, GraphQLInt } from "graphql";
import { mapSchema } from "../MappedSchema";
import { mapArgs } from "../MappedArgs";
import { MappedDataSource } from "../MappedDataSource";
import { mapStoredProcedure } from "../universal";
let knex: Knex;
describe("Stored Procedure mapping", () => {
let schema: GraphQLSchema;
let users: MappedDataSource;
const db = process.env.DB;
if (db === "mysql2" || db === "pg") {
beforeAll(async () => {
knex = setupKnex();
useDatabaseConnector(knex);
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSource();
if (db === "pg") {
// @snippet:start stored_proc_pg_example
await knex.raw(`
CREATE OR REPLACE PROCEDURE get_avg_user_age(
INOUT avg_age INT
)
LANGUAGE plpgsql
AS $$
BEGIN
SELECT AVG(age)
INTO avg_age
FROM users;
END;
$$
`);
// @snippet:end
} else {
// @snippet:start stored_proc_mysql_example
await knex.raw(`
CREATE PROCEDURE get_avg_user_age(
INOUT avg_age INT
)
BEGIN
SELECT AVG(age)
INTO @avg_age
FROM users;
SET avg_age = @avg_age;
END
`);
// @snippet:end
}
schema = mapSchema([
operationPresets.findOneOperation(users),
// @snippet:start stored_proc_mapping
mapStoredProcedure({
type: "query",
name: {
stored: "get_avg_user_age",
mapped: "getAvgAge",
},
args: mapArgs({}),
returnType: GraphQLInt,
deriveParams: () => [
{
name: "avg_age",
argMode: "INOUT" as const,
value: undefined,
},
],
deriveResult: (r: any) => r.avg_age,
}),
// @snippet:end
]);
});
afterAll(async () => {
await knex.raw("DROP PROCEDURE get_avg_user_age");
});
it("returns result of invocation of stored procedure", async () => {
const users = await knex("users");
const avgAge = users.reduce((sum, u) => sum + u.age, 0) / users.length;
// @snippet:start stored_proc_mapping_usage
const graphQLResult = await graphql(
schema,
`
query {
getAvgAge
}
`,
);
// @snippet:end
expect(graphQLResult.data!.getAvgAge).toEqual(avgAge);
});
afterAll(async () => {
await teardownUserSchema(knex);
await knex.raw("drop function get_sum(numeric, numeric)");
});
} else {
test.todo("Stored procedures not yet supported for this database");
}
});
<file_sep>/src/docs/pages/stored-procedures.md
import {NextPageLink} from "../components/Link";
import Link from "next/link";
import {CodeSnippet} from "../components/CodeSnippet";
# Stored Procedures
GRelDAL supports mapping GraphQL Operations to stored procedures or user defined functions.
## User defined functions:
From [Wikipedia](https://en.wikipedia.org/wiki/User-defined_function):
> In relational database management systems, a user-defined function provides a mechanism for extending the functionality of the database server by adding a function, that can be evaluated in standard query language (usually SQL) statements.
Here is an example of a simple UDF that adds two numbers:
<CodeSnippet name="udf_example" stripHeadLines={1} stripTailLines={1} />
We can map this UDF to a GrelDAL operation using the `mapUserDefinedFunction` function:
<CodeSnippet name="udf_mapping" />
We can expose this operation in the GraphQL API by passing the above to the `mapSchema` function similar to any other operation.
Once exposed, we can use GraphQL to perform the operation:
<CodeSnippet name="udf_mapping_usage" />
## Stored Procedures:
From [Wikipedia](https://en.wikipedia.org/wiki/Stored_procedure)
> A stored procedure (also termed proc, storp, sproc, StoPro, StoredProc, StoreProc, sp, or SP) is a subroutine available to applications that access a relational database management system (RDBMS). Such procedures are stored in the database data dictionary.
Stored procedures are usually more powerful than User defined functions in that they can perform transactions and return multiple values.
The syntax of defining stored procedures differs across databases:
Here is an example of defining a stored procedure in MySQL:
<CodeSnippet name="stored_proc_mysql_example" stripHeadLines={1} stripTailLines={1} />
Here is the equivalent in PostgreSQL (using PL/PgSQL):
<CodeSnippet name="stored_proc_pg_example" stripHeadLines={1} stripTailLines={1} />
We can map this stored proc to a GrelDAL operation using the `mapStoredProcedure` function:
<CodeSnippet name="stored_proc_mapping" />
We can expose this operation in the GraphQL API by passing the above to the `mapSchema` function similar to any other operation.
Once exposed, we can use GraphQL to perform the operation:
<CodeSnippet name="stored_proc_mapping_usage" />
<NextPageLink>Subscriptions</NextPageLink><file_sep>/src/docs/components/APIBody.js
import APIEntityContainer, {APIContainer} from "./APIEntityContainer";
import styled from "styled-components";
import { Link } from "./Link";
export const EmptyMsgContainer = styled.div`
color: silver;
font-weight: 900;
font-size: 3rem;
padding: 20px;
padding-top: 100px;
text-align: center;
line-height: 4rem;
`;
export function APIIntro(props) {
return (
<APIContainer>
<h1>Welcome to GRelDAL's API Documentation </h1>
<div>
Please make sure that you have first gone through the <Link href="guides">Guides</Link> before diving
deep into the API docs.
</div>
<div>
<h1>Terms</h1>
<p>Summary of the terminology used in the API docs</p>
<ul>
<li>
<strong>DataSource</strong>
<p>
A DataSource is a mapper that mediates operations against a table/view in the persistence
layer.
</p>
<p>
DataSources are expected to have a fixed set of <strong>fields</strong> (see below) and can
interact with other data sources through <strong>associations</strong> (see below).
</p>
</li>
<li>
<strong>Entity</strong>
<p>
Entities are plain JavaScript objects returned by operations on data sources.
</p>
<p>
When application logic is written against Entities, it is sheilded from the specifics
of persistence layer. Using plain js entities instead of ORM models or managed instances
prevents accidental coupling of application logic and persistence specific concerns.
</p>
<p>
The shape of an entity may not be same as rows in the underlying persistence layer (table or
view) and whenever required, the DataSource will perform coversion between rows and
entities.
</p>
</li>
<li>
<strong>Row</strong>
<p>
In the documentation here, rows always refer to rows in a table/view in the persistence
layer.
</p>
</li>
<li>
<strong>Association</strong>
<p>An association is a link using which operations can span over multiple data source</p>
</li>
<li>
<strong>Field</strong>
<p>
A field refers to an attribute in an Entity. A field can either be directly mapped from a
column or be derived from a combination of multiple columns.
</p>
<p>
The <Link href="mapping-data-sources">DataSource mapping guide</Link> elaborates more on
mapping fields.
</p>
</li>
</ul>
</div>
<div>
<h1>Important top level functions</h1>
<ul>
<li>
<strong>useDatabaseConnector</strong>
<p>
Configures a knex instance to be used for connecting to the database. For polyglot
persistence, we can also specify a knex instance at a data source level.
</p>
</li>
<li>
<strong>mapDataSource</strong>
<p>
Map tables (or views) in database to data sources which operations exposed through the
GraphQL schema can interact with.
</p>
</li>
<li>
<strong>mapSchema</strong>
<p>Derive a GraphQL schema from GRelDAL data sources and operations.</p>
</li>
</ul>
</div>
<h2>Looking for a particular class/function ?</h2>
<p>← Find it through the sidebar</p>
</APIContainer>
);
}
export default function APIBody(props) {
if (!props.activeCategory || !props.rootEntity) {
return <APIIntro />;
}
return <APIEntityContainer entity={props.rootEntity} activeEntityName={props.activeEntityName} />;
}
<file_sep>/src/InvocationMapping.ts
import * as t from "io-ts";
import * as Knex from "knex";
import { OperationMapping, OperationMappingRT } from "./OperationMapping";
import { OperationResolver } from "./OperationResolver";
import { MappedOperation } from "./MappedOperation";
import { ResolverContext } from "./ResolverContext";
import { MappedArgs } from "./MappedArgs";
import { GraphQLOutputType } from "graphql";
import { MaybeMapped } from "./utils/util-types";
export interface BaseInvocationParam {
name?: string;
value: any;
}
export interface InInvocationParam extends BaseInvocationParam {
argMode: "IN";
}
export interface OutInvocationParam extends BaseInvocationParam {
argMode: "OUT";
}
export interface InOutInvocationParam extends BaseInvocationParam {
argMode: "INOUT";
}
export type InvocationParam = InInvocationParam | OutInvocationParam | InOutInvocationParam;
export const InvocationMappingRT = t.intersection(
[
OperationMappingRT,
t.partial({
type: t.union([t.literal("query"), t.literal("mutation")]),
deriveParams: t.Function,
deriveResult: t.Function,
}),
],
"InvocationMapping",
);
/**
* @api-category ConfigType
*/
export interface InvocationMapping<TArgs extends {}>
extends t.TypeOf<typeof InvocationMappingRT>,
OperationMapping<TArgs> {
name: MaybeMapped<string>;
resolver?: <TCtx extends ResolverContext<MappedOperation<TArgs>, TArgs>, TResolved>(
ctx: TCtx,
) => OperationResolver<TCtx, TArgs, TResolved>;
args: MappedArgs<TArgs>;
returnType: GraphQLOutputType;
deriveParams(args: TArgs): InvocationParam[];
deriveResult?: (output: any) => any;
connector?: Knex;
}
<file_sep>/src/docs/pages/faqs.js
import faqs from "../data/faqs.yml";
import { ContentHierarchy } from "../components/ContentSection";
export default function FAQsPage() {
return (
<ContentHierarchy root={faqs} />
)
}<file_sep>/src/operation-presets.ts
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { MappedSingleSourceInsertionOperation } from "./MappedSingleSourceInsertionOperation";
import { MappedSingleSourceUpdateOperation } from "./MappedSingleSourceUpdateOperation";
import { MappedSingleSourceDeletionOperation } from "./MappedSingleSourceDeletionOperation";
import { pluralize, singularize } from "inflection";
import { has, isPlainObject, identity } from "lodash";
import { isArray } from "util";
import { Interceptor } from "./utils/util-types";
/**
* Default type of arguments expected by query operation preset
* @api-category ConfigType
*/
export interface PresetQueryParams<TSrc extends MappedDataSource> {
where: Partial<TSrc["ShallowEntityType"]>;
}
/**
* Default type of arguments expected by update operation preset
* @api-category ConfigType
*/
export interface PresetUpdateParams<TSrc extends MappedDataSource> extends PresetQueryParams<TSrc> {
update: Partial<TSrc["ShallowEntityType"]>;
}
/**
* Default type of arguments expected by deletion operation preset
* @api-category ConfigType
*/
export interface PresetDeletionParams<TSrc extends MappedDataSource> extends PresetQueryParams<TSrc> {}
/**
* Default type of arguments expected by singular insertion preset
* @api-category ConfigType
*/
export interface PresetSingleInsertionParams<TSrc extends MappedDataSource> {
entity: TSrc["ShallowEntityType"];
}
/**
* Default type of arguments expected by multi-insertion preset
* @api-category ConfigType
*/
export interface PresetMultiInsertionParams<TSrc extends MappedDataSource> {
entities: TSrc["ShallowEntityType"][];
}
export function isPresetSingleInsertionParams(params: any): params is PresetSingleInsertionParams<any> {
return isPlainObject(params.entity);
}
export function isPresetMultiInsertionParams(params: any): params is PresetMultiInsertionParams<any> {
return isArray(params.entities);
}
/**
* Default type of arguments expected by insertion preset
* @api-category ConfigType
*/
export type PresetInsertionParams<TSrc extends MappedDataSource> =
| PresetSingleInsertionParams<TSrc>
| PresetMultiInsertionParams<TSrc>;
export function isPresentInsertionParams(params: any): params is PresetInsertionParams<any> {
return isPresetSingleInsertionParams(params) || isPresetMultiInsertionParams(params);
}
export function isPresetQueryParams<TSrc extends MappedDataSource>(t: any): t is PresetQueryParams<TSrc> {
return has(t, "where") && isPlainObject(t.where);
}
export function isPresetUpdateParams<TSrc extends MappedDataSource>(t: any): t is PresetUpdateParams<TSrc> {
return isPresetQueryParams(t) && has(t, "update") && isPlainObject((t as any).update);
}
/**
* @name operationPresets.query.findOneOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function findOneOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>(
interceptMapping({
rootSource,
name: `findOne${singularize(rootSource.mappedName)}`,
description: undefined,
returnType: undefined,
args: undefined,
singular: true,
shallow: false,
}),
);
}
const getPresetPaginationConfig = (rootSource: MappedDataSource) => {
const { primaryFields } = rootSource;
if (primaryFields.length !== 1) throw new Error("Preset expects a single primary field");
const [primaryField] = primaryFields;
return {
cursorColumn: primaryField.sourceColumn!,
};
};
/**
* @name operationPresets.query.findManyOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function findManyOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>(
interceptMapping({
rootSource,
name: `findMany${pluralize(rootSource.mappedName)}`,
returnType: undefined,
description: undefined,
args: undefined,
singular: false,
shallow: false,
}),
);
}
/**
* @name operationPresets.query.findManyOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function paginatedFindManyOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>["mapping"]
> = identity,
) {
const mapping = interceptMapping({
rootSource,
name: `findMany${pluralize(rootSource.mappedName)}`,
returnType: undefined,
description: undefined,
args: undefined,
singular: false,
shallow: false,
});
mapping.paginate = mapping.paginate || getPresetPaginationConfig(rootSource);
return new MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>(interceptMapping(mapping));
}
/**
* @name operationPresets.mutation.insertOneOpeeration
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function insertOneOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceInsertionOperation<TSrc, PresetSingleInsertionParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceInsertionOperation<TSrc, PresetSingleInsertionParams<TSrc>>(
interceptMapping({
rootSource,
name: `insertOne${singularize(rootSource.mappedName)}`,
description: undefined,
returnType: undefined,
args: undefined,
singular: true,
shallow: true,
}),
);
}
/**
* @name operationPresets.mutation.insertManyOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function insertManyOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceInsertionOperation<TSrc, PresetMultiInsertionParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceInsertionOperation<TSrc, PresetMultiInsertionParams<TSrc>>(
interceptMapping({
rootSource,
name: `insertMany${pluralize(rootSource.mappedName)}`,
description: undefined,
returnType: undefined,
args: undefined,
singular: false,
shallow: true,
}),
);
}
/**
* @name operationPresets.mutations.updateManyOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function updateOneOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>(
interceptMapping({
rootSource,
name: `updateOne${singularize(rootSource.mappedName)}`,
description: undefined,
returnType: undefined,
args: undefined,
singular: true,
shallow: true,
}),
);
}
/**
* @name operationPresets.mutations.updateManyOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function updateManyOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>(
interceptMapping({
rootSource,
name: `updateMany${pluralize(rootSource.mappedName)}`,
description: undefined,
returnType: undefined,
args: undefined,
singular: false,
shallow: true,
}),
);
}
/**
* Operation preset to delete a single entity matching some query criteria
*
* @name operationPresets.mutations.deleteOneOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function deleteOneOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>(
interceptMapping({
rootSource,
name: `deleteOne${singularize(rootSource.mappedName)}`,
singular: true,
shallow: true,
}),
);
}
/**
* Operation preset to delete multiple entities matching specified query criteria
*
* @name operationPresets.mutations.deleteManyOperation
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function deleteManyOperation<TSrc extends MappedDataSource>(
rootSource: TSrc,
interceptMapping: Interceptor<
MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>["mapping"]
> = identity,
) {
return new MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>(
interceptMapping({
rootSource,
name: `deleteMany${pluralize(rootSource.mappedName)}`,
description: undefined,
returnType: undefined,
args: undefined,
singular: false,
shallow: true,
}),
);
}
/**
* Get list of all available query presets applied to specified data source
*
* @name operationPresets.query.all
* @api-category PriamryAPI
* @param rootSource The data source on which the operation is to be performed
*/
const defaultQueries = (rootSource: MappedDataSource) => [findOneOperation(rootSource), findManyOperation(rootSource)];
export const query = {
findOneOperation,
findManyOperation,
defaults: defaultQueries,
};
/**
* Get list of all available mutation presets applied to specified data source
*
* @name operationPresets.mutation.all
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
const defaultMutations = (rootSource: MappedDataSource) => [
insertOneOperation(rootSource),
insertManyOperation(rootSource),
updateOneOperation(rootSource),
updateManyOperation(rootSource),
deleteOneOperation(rootSource),
deleteManyOperation(rootSource),
];
export const mutation = {
insertOneOperation,
insertManyOperation,
updateOneOperation,
updateManyOperation,
deleteOneOperation,
deleteManyOperation,
defaults: defaultMutations,
};
/**
* Get list of all available presets applied to specified data source
*
* @name operationPresets.all
* @api-category PrimaryAPI
* @param rootSource The data source on which the operation is to be performed
*/
export function defaults(rootSource: MappedDataSource) {
return [...query.defaults(rootSource), ...mutation.defaults(rootSource)];
}
<file_sep>/src/docs/components/Nav.js
import React from "react";
export const Nav = props => (
<>
{props.children.map(item => {
const Heading = `h${item.level}`;
return (
<>
<a href={`#${item.id}`}>
<Heading>{item.title}</Heading>
</a>
<div className="toc-children">{item.children && <Nav>{item.children}</Nav>}</div>
</>
);
})}
</>
);
<file_sep>/src/docs/pages/index.md
import {NextPageLink, Link} from "../components/Link";
import {LibHeader} from "../components/LibHeader";
import {CodeSnippet} from "../components/CodeSnippet";
<LibHeader />
<div style={{fontSize: "1.5rem", lineHeight: "2.5rem", margin: "2rem 0", fontWeight: 100, color: "slategray"}}>
GRelDAL is a micro-framework for exposing your relational datastore as a GraphQL API powered by Node.js
</div>
The project is hosted on [GitHub](https://github.com/gql-dal/greldal), and has a growing [test suite](https://travis-ci.org/gql-dal/greldal).
GRelDAL is available for use under the [MIT software license](https://github.com/gql-dal/greldal/blob/master/LICENSE).
You can report bugs on the [GitHub issues page](https://github.com/gql-dal/greldal/issues).
# Motive / Goals
[GraphQL](https://graphql.org/) is a powerful solution for making your server side data available to clients through a flexible and bandwidth efficient API.
However, if your primary data source is a **relational database** then mapping GraphQL queries to efficient database queries can be arduous. With naive hierarchical resolution of resolvers it is very easy to end up with inefficient data access patterns and [N+1 queries](https://stackoverflow.com/questions/97197/what-is-the-n1-select-query-issue). Caching strategies, dataloader etc. partly mitigate the problem but the fact remains that you are not taking the full advantage of the capabilities of your powerful datastore.
GRelDAL is a simple **low level** library that gives you a declaritive API to map your relational data sources to GraphQL APIs. It is data store agnostic thanks to [Knex](https://knexjs.org), the underlying data access library that supports all common databases. Currently MySQL, PostgreSQL and SQLite are well tested.
When you generate your GraphQL API through GRelDAL, you can choose exactly how:
- Your database table schema maps to GraphQL types.
- Your GraphQL queries are mapped to SQL queries, including:
- which tables can be joined under which circumstances
- when batched queries can be performed
- when related rows can be fetched in advance in bulk, etc.
GRelDAL puts you on the _driver's seat_, gives you complete control and takes care of a lot of hairy mapping and reverse-mapping logic for you, allowing you to take full advantage of your database engine. It is assumed that you (or your team) has deep understanding of the capabilities your datastore and want to ensure that only efficient queries are allowed and the possibility of a client inadvertantly triggering complex inefficient database operations is minimized.
# Installation
```sh
// Using npm:
npm install --save greldal
// Using yarn:
yarn add greldal
```
# Quick Start
## What you already need to know ?
In order to use GRelDAL you need to have a basic understanding of GraphQL. We don't cover GraphQL features in the docs here, but many great resources are available online, a particularly good example being [How to GraphQL](https://www.howtographql.com/).
You also need to have a good grasp over Javascript. Most examples here use ES6 features. If terms like harmony imports, arrow functions, destructuring sound unfamiliar, you may want to start out by reading [Javascript for impatient programmers](http://exploringjs.com/impatient-js/) and [Exploring ES6](http://exploringjs.com/es6/), both authored by Dr. <NAME>.
[TypeScript](http://typescriptlang.org) is not required, but recommended for larger projects. GRelDAL itself is written in TypeScript and comes with type definitions. We take a pragmatic stance towards <Link href="type-safety">Type Safety</Link>
## Try in your browser
You can try out GRelDAL in the <Link href="playground">browser based playground</Link> without installing anything.
The playground is currently experimental and offers a limited set of features.
## Our pre-configured starter project
GRelDAL core library is fairly un-opinionated.
However, to make getting started easier, we provide an official seed starter project that has some opinionated defaults pre-configured.
To get started you can `git clone https://github.com/gql-dal/greldal-starter.git` and start tinkering with the application without having to worry about the initial boilerplate.
## Basic Usage
Using GRelDAL involves two steps:
1. Configuring a Knex instance
2. Defining data sources mappers
3. Defining operations on these data sources
4. Generating a GraphQL Schema from these operations
5. Exposing this schema through a HTTP Server
### Configuring a Knex instance
GRelDAL uses Knex to connect to databases. We need to provide GRelDAL a knex instance configured to connect to our database of choice.
```ts
import Knex from "knex";
import {useDatabaseConnector} from "greldal";
const knex = Knex({
client: 'pg',
connection: process.env.DATABASE_URL
});
useDatabaseConnector(knex)
```
More details around Knex initialization are available in the [Knex documentation](https://knexjs.org/#Installation-client).
While the above code illustrates usage with postgres, Knex supports all major databases. GRelDAL officially supports `Postgres`,
`MySQL` & `SQLite` at the moment.
GRelDAL supports polyglot persistence through DataSource level connectors.
### Defining a data source mapper
<CodeSnippet name="mapDataSource_user_simple" />
This defines a `User` data source having three fields: `id`, `name` and `age`. This essentially maps a `users` table (having two columns `id` and `name`) in database to a `GraphQLOutput` type with three fields `id` (type: `GraphQLID`), `name` (type: `GraphQLString`) and `age` (type: `GraphQLInt`).
Note that the above configuration practically has zero duplication of information. We didn't have to specify the name of table this data source was linked to (it was inferred as plural of 'User').
Also, because our column names and field names are same we didn't have to specify them twice. When we have equivalent types available in typescript and GraphQL (eg. `string` and `GraphQLString`) we don't have to specify the type mapping either. GRelDAL leverages [convention-over-configuration](https://en.wikipedia.org/wiki/Convention_over_configuration) to minimize the development effort.
### Defining operations
Once we have data sources, we can define operations on these data sources.
```ts
import { operationPresets } from "greldal";
const findManyUsers = operationPresets.query.findManyOperation(users);
```
GRelDAL comes with some operation presets. These operation presets make it trivial to perform CRUD operations on data sources with minimal code.
The above line of code defines a `findMany` operation on the users data source.
The section on <Link>Mapping Operations</Link> covers more ground on defining custom operations and reusing operations.
### Generating GraphQL Schema
Once we have operations, we can expose them to the GraphQL API by mapping them to a schema:
```ts
import { mapSchema } from "greldal";
const generatedSchema = mapSchema([findManyUsers]);
```
The `generatedSchema` here is a [GraphQLSchema](https://graphql.org/graphql-js/type/#graphqlschema) instance which [graphql-js](https://graphql.org/graphql-js) can use for resoluton of operations.
In this case, the `findMany` operation on users table can be invoked like this:
```ts
import { graphql } from "graphql";
graphql(
generatedSchema,
`findManyUsers(where: {name: "John"}) {
id,
name
}
`,
);
```
### Exposing GraphQL API
While the ability to query the generated schema directly is useful in itself, most likely you are building a web application and you would like to expose this GraphQL schema through an API over HTTP.
There are popular libraries already available for this, and this step is the same as what you would do when building any GraphQL API.
For example, if we are using [express](https://expressjs.com/) as our web framework, we can use the [express-graphql](https://github.com/graphql/express-graphql) package to expose our GraphQL API.
```ts
import express from "express";
import graphqlHTTP from "express-graphql";
const app = express();
app.use(
"/graphql",
graphqlHTTP({
schema: generatedSchema,
graphiql: true
}),
);
app.listen(4000);
```
Now if we visit [`localhost:4000`](http://localhost:4000) in a browser, we will see a [graphiql](https://github.com/graphql/graphiql) interface which we can use to query our data source. We can also use any client side library like [react-apollo](https://github.com/apollographql/react-apollo) to interact with this API. No GRelDAL specific code is required on the client side.
### Where to go next ?
GRelDAL <Link href="guides">guides</Link> cover most important features and going through the guides will enable you hit the ground running building real world applications in no time.
You can also checkout the <Link href="api">API Documentation</Link>, <Link>Architecture Overview</Link> and <a href="https://github.com/gql-dal/greldal">Source Code</a>.
<file_sep>/src/docs/components/LibHeader.js
import logo from "../assets/logo.png";
import styled from "styled-components";
export const LibHeader = () => (
<Container>
<ImgContainer>
<img src={logo} style={{ height: "100px", width: "100px" }} />{" "}
</ImgContainer>
<HeaderText>
<PrimaryHeader>GRelDAL</PrimaryHeader>{" "}
<SecondaryHeader>
<SecondaryHeader.Section>
(<strong>G</strong>raphQL ⇋ <strong>Rel</strong>ational DB)
</SecondaryHeader.Section>
<SecondaryHeader.Section>
{" "}
<strong>D</strong>ata <strong>A</strong>
ccess <strong>L</strong>ayer
</SecondaryHeader.Section>
</SecondaryHeader>
</HeaderText>
</Container>
);
const ImgContainer = styled.div`
text-align: center;
@media only screen and (min-width: 1000px) {
flex-basis: 100px;
flex-grow: 0;
flex-shrink: 0;
}
`;
const HeaderText = styled.div`
padding-top: 20px;
@media only screen and (min-width: 1000px) {
padding-left: 10px;
}
`;
const PrimaryHeader = styled.h1`
line-height: 25px;
color: #8dd35f;
font-size: 2.5rem;
margin: 0 5px 0 0 !important;
`;
const SecondaryHeader = styled.h2`
color: #ddd;
font-size: 1.8rem;
text-overflow: initial;
white-space: nowrap;
strong {
color: #acacac;
}
`;
SecondaryHeader.Section = styled.span`
display: inline;
@media only screen and (max-width: 1000px) {
display: block;
text-align: center;
line-height: 2.5rem;
}
@media only screen and (max-width: 500px) {
font-size: 1.5rem;
}
`;
const Container = styled.div`
@media only screen and (max-width: 1000px) {
flex-direction: column;
text-align: center;
}
@media only screen and (min-width: 1000px) {
flex-direction: row;
}
display: flex;
border-bottom: 1px solid #ddd;
padding-bottom: 2rem;
max-width: max(100%, 1000px);
`;
<file_sep>/src/SingleSourceOperationMapping.ts
import * as t from "io-ts";
import { OperationMappingRT } from "./OperationMapping";
export const SingleSourceOperationMappingRT = t.intersection(
[
OperationMappingRT,
t.partial({
rootQuery: t.Function,
deriveWhereParams: t.Function,
}),
],
"SingleSourceOperationMapping",
);
<file_sep>/src/utils/predicate.ts
import { some } from "lodash";
import { Predicate, MaybeArray, Maybe } from "./util-types";
import { checkStr, checkRegexp, checkArray, checkNil } from "./guards";
export const matchString = (predicate: MaybeArray<string | RegExp | Predicate<string>>): Predicate<Maybe<string>> =>
checkArray(predicate)
? (i: Maybe<string>) => !checkNil(i) && some(predicate, p => matchString(p)(i))
: checkStr(predicate)
? (i: Maybe<string>) => i === predicate
: checkRegexp(predicate)
? (i: Maybe<string>) => !checkNil(i) && !!i.match(predicate)
: (i: Maybe<string>) => !checkNil(i) && predicate(i);
<file_sep>/src/__specs__/map-schema.spec.ts
import { mapSchema } from "..";
import { GraphQLString, graphql, GraphQLObjectType, printSchema } from "graphql";
import { OperationType } from "../operation-types";
test("External resolver mapping", async () => {
const schema = mapSchema([
{
operationType: OperationType.Query,
name: "hello",
fieldConfig: {
type: GraphQLString,
resolve() {
return "world";
},
},
},
]);
const r1 = await graphql(
schema,
`
query {
hello
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("Schema interceptor", () => {
const schema = mapSchema(
[
{
operationType: OperationType.Query,
name: "hello",
fieldConfig: {
type: GraphQLString,
resolve() {
return "world";
},
},
},
],
schemaConfig => {
schemaConfig.subscription = new GraphQLObjectType({
name: "Subscription",
fields: {},
});
return schemaConfig;
},
);
expect(printSchema(schema)).toMatchSnapshot();
});
<file_sep>/src/AliasHierarchyVisitor.ts
import { Maybe } from "./utils/util-types";
import { uniqueId } from "lodash";
import { MappedField } from "./MappedField";
/**
* Internal data structure used by AliasHierarchyVisitor for book-keeping
* of hierarchy of table aliases when visiting a composite join.
*
* Should be manipulated through a visitor only.
*/
export interface AliasHierarchy {
alias?: string;
children?: {
[key: string]: AliasHierarchy;
};
}
/**
* Provides a convenient approach to explore and retrieve table aliases when multiple tables are being joined as a part of
* composite query.
*
* Visitors form an internally tracked hierarchy, so we can traverse back to the
* parent visitor by accessing parent public property.
*
* Let us say we have following query:
*
* ```
* SELECT classes.id, teachers.id, teachers.name, students.id, students.name
* FROM classes
* LEFT OUTER JOIN users as teachers
* LEFT OUTER JOIN users as students
* ```
*
* Then our alias hierarchy visitor will visit classes (with the generated alias being something like: GQL_DAL_classes__1) and
* have a child visitor which will visit users (with generated alias being something like GQL_DAL_teachers_2) which will
* in turn have another child visitor which will again visit users (with generated alias being something like GQL_DAL_students_3).
*
* When we use these aliases, our actual join will end up being something like:
*
* ```
* `classes` as `GQL_DAL_classes__1`
* LEFT OUTER JOIN `users` as `GQL_DAL_teachers_2`
* LEFT OUTER JOIN `users` as `GQL_DAL_students_3``
* ```
*
* And the complete query will be something like:
*
* ```
* SELECT `GQL_DAL_classes__1`.`id` as `GQL_DAL_classes__1_id`,
* `GQL_DAL_teachers__2`.`id` as `GQL_DAL_teachers__2_id`,
* `GQL_DAL_teachers__2`.`name` as `GQL_DAL_teachers__2_name`,
* `GQL_DAL_students__3`.`id` as `GQL_DAL_students__3_id`,
* `GQL_DAL_students__3`.`name` as `GQL_DAL_students__3_name`
* FROM `classes` as `GQL_DAL_classes__1`
* LEFT OUTER JOIN users as `GQL_DAL_teachers_2`
* LEFT OUTER JOIN users as `GQL_DAL_students_3``
* ```
*
* Reverse mapper can then use the ALiasHierarchyVisitor tree to reverse map the result set.
*
* AliasHierarchyVisitor is just for memoized book-keeping of aliases. The actual query composition logic is implemented in [QueryOperationResolver](api:QueryOperationResolver) and the
* reverse mapping logic is implemented in [ReverseMapper](api:ReverseMapper).
*
*/
export class AliasHierarchyVisitor {
constructor(private hierarchy: AliasHierarchy = {}, public parent: Maybe<AliasHierarchyVisitor> = null) {}
/**
* Get alias for the table in association tree being visited currently.
*
* Consumers are expected to use this alias when performing operations on the table
* which is being currently visited by this visitor.
*
* Note that in case a table is being recursively joined, we will recursively visit the joined tables
* and thus will have different aliases for each join target.
*/
get alias() {
return this.hierarchy.alias!;
}
/**
* Keys of previously visited children
*/
get children(): string[] {
return Object.keys(this.hierarchy.children || {});
}
/**
* Create an unique alias for specified name
*/
createAlias(label: string) {
return uniqueId(`GQL_DAL_${label}__`);
}
/**
* Visiting an associated table creates a new visitor scoped to that table.
*
* visit auto-vivifies children on the fly and is suitable for visiting during
* query visiting phase.
*/
visit(childName: string): AliasHierarchyVisitor {
if (!this.hierarchy.children) {
this.hierarchy.children = {};
}
if (!this.hierarchy.children[childName]) {
this.hierarchy.children[childName] = {
alias: this.createAlias(childName),
children: {},
};
}
const child = this.hierarchy.children[childName];
return new AliasHierarchyVisitor(child, this);
}
/**
* Find nearest child visitor visiting a source of specified name in the hierarchy
* of visitors.
*
* Does not auto-vivify children and is suitable for visiting during reverse-mapping
* phase.
*/
recursivelyVisit(childName: string): Maybe<AliasHierarchyVisitor> {
const child = this.hierarchy.children && this.hierarchy.children[childName];
if (child) return new AliasHierarchyVisitor(child, this);
for (const c of this.children) {
const descendant: Maybe<AliasHierarchyVisitor> = this.visit(c).recursivelyVisit(childName);
if (descendant) {
return descendant;
}
}
return null;
}
getMemberColumnAlias(columnName: string) {
return `${this.alias}__${columnName}`;
}
getColumnAliasForMemberField(field: MappedField) {
if (!field.isMappedFromColumn) throw new Error("Cannot get column alias for field not mapped from column");
this.getMemberColumnAlias(field.sourceColumn!);
}
}
<file_sep>/src/docs/components/CodeSnippet.js
import SyntaxHighlighter from "react-syntax-highlighter";
import dedentStr from "dedent";
import assert from "assert";
import github from "react-syntax-highlighter/dist/cjs/styles/hljs/github";
import snippets from "../../../api/snippets.json";
import {last, isEmpty} from "lodash";
export const CodeSnippet = ({
name,
language = "javascript",
stripTripleComment = true,
dedent = true,
stripHeadLines = 0,
stripTailLines = 0,
transform
}) => {
assert(snippets[name], `Snippet could not be found ${name}`);
let { content } = snippets[name];
if (stripTripleComment) content = content.replace(/\s\/\/\/\s/g, " ");
if (transform) content = transform(content);
if (stripHeadLines > 0 || stripTailLines > 0) {
const lines = content.split('\n');
if (isEmpty(last(lines))) lines.pop();
content = lines.slice(stripHeadLines, lines.length - stripTailLines).join('\n');
}
if (dedent) content = dedentStr(content);
return (
<SyntaxHighlighter language={language} style={github}>
{content}
</SyntaxHighlighter>
);
};
<file_sep>/src/MappedSingleSourceQueryOperation.ts
import { GraphQLFieldConfigArgumentMap, GraphQLNonNull } from "graphql";
import * as Knex from "knex";
import { MappedAssociation } from "./MappedAssociation";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver";
import { Dict, Omit } from "./utils/util-types";
import { MemoizeGetter } from "./utils/utils";
import { isPresetQueryParams } from "./operation-presets";
import { getTypeAccessorError } from "./utils/errors";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
import { OperationTypes } from "./universal";
/**
* @api-category MapperClass
*/
export class MappedSingleSourceQueryOperation<
TSrc extends MappedDataSource,
TArgs extends {}
> extends MappedSingleSourceOperation<TSrc, TArgs> {
operationType = OperationTypes.Query;
constructor(
// If resovler is not omitted here then type inference of resolver breaks
public mapping: Omit<MappedSingleSourceOperation<TSrc, TArgs>["mapping"], "resolver"> & {
resolver?: <
TCtx extends SourceAwareResolverContext<MappedSingleSourceQueryOperation<TSrc, TArgs>, TSrc, TArgs>,
TResolved = any
>(
ctx: TCtx,
) => SingleSourceQueryOperationResolver<
TCtx,
TSrc,
MappedSingleSourceQueryOperation<TSrc, TArgs>,
TArgs,
TResolved
>;
},
) {
super(mapping);
this.validateMapping();
}
validateMapping() {
if (this.mapping.paginate && this.mapping.singular) {
throw new Error("Pagination is not support for singular query operations");
}
}
defaultResolver(
resolverContext: SourceAwareResolverContext<MappedSingleSourceQueryOperation<TSrc, TArgs>, TSrc, TArgs>,
): SourceAwareOperationResolver<
SourceAwareResolverContext<MappedSourceAwareOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc,
TArgs,
any
> &
SingleSourceQueryOperationResolver<
SourceAwareResolverContext<MappedSingleSourceQueryOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc,
MappedSingleSourceQueryOperation<TSrc, TArgs>,
TArgs,
any
> {
return new SingleSourceQueryOperationResolver(resolverContext);
}
@MemoizeGetter
get defaultArgs(): GraphQLFieldConfigArgumentMap {
return {
where: {
type: GraphQLNonNull(this.rootSource.defaultShallowInputType),
},
};
}
interceptQueryByArgs(qb: Knex.QueryBuilder, args: TArgs) {
if (this.mapping.args) {
return this.mapping.args.interceptQuery(qb, args);
}
return qb;
}
deriveWhereParams(args: TArgs, association?: MappedAssociation): Dict {
if (this.mapping.deriveWhereParams) {
return this.mapping.deriveWhereParams.call(this, args, association);
}
if (isPresetQueryParams(args)) {
return args.where;
}
return {};
}
get ResolverContextType(): SourceAwareResolverContext<MappedSingleSourceQueryOperation<TSrc, TArgs>, TSrc, TArgs> {
throw getTypeAccessorError("ResolverContextType", "MappedQueryOperation");
}
}
<file_sep>/src/generator/adapters/PGAdapter.ts
import { Adapter, TableLike, TableSchema } from "./Adapter";
import { BaseAdapter } from "./BaseAdapter";
import { retrieveTables, getSchemaForTable } from "./information-schema-support";
export class PGAdapter extends BaseAdapter implements Adapter {
async getTables(): Promise<TableLike[]> {
return retrieveTables(this.connector, table =>
table
.where(function() {
this.where("table_type", "BASE TABLE").orWhere("table_type", "VIEW");
})
.where(function() {
this.whereNot("table_schema", "pg_catalog").andWhereNot("table_schema", "information_schema");
}),
);
}
async getSchemaForTable(table: TableLike): Promise<TableSchema> {
return getSchemaForTable(this.connector, table);
}
}
<file_sep>/src/OperationResolver.ts
import { ResolverContext } from "./ResolverContext";
import { MappedOperation } from "./MappedOperation";
export interface OperationResolver<
TCtx extends ResolverContext<MappedOperation<TArgs>, TArgs>,
TArgs extends {},
TResolved
> {
resolverContext: TCtx;
resolve(): Promise<TResolved>;
}
<file_sep>/src/FieldMapping.ts
import * as t from "io-ts";
import { StrKey, InstanceOf, Dict } from "./utils/util-types";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { MappedField } from "./MappedField";
import { TypeSpec } from "./utils/types";
import { GraphQLInputType, GraphQLOutputType } from "graphql";
const BaseFieldMappingRT = t.intersection(
[
t.type({
/**
* @memberof BaseFieldMapping
*/
type: InstanceOf(TypeSpec),
}),
t.partial({
/**
* @memberof BaseFieldMapping
*/
exposed: t.boolean,
/**
* @memberof BaseFieldMapping
*/
description: t.string,
/**
* @memberof BaseFieldMapping
*/
getColumnMappingList: t.Function,
}),
],
"BaseFieldMapping",
);
const ColumnFieldMappingRT = t.intersection(
[
BaseFieldMappingRT,
t.partial({
sourceColumn: t.string,
sourceTable: t.string,
isPrimary: t.boolean,
fromSource: t.Function,
toSource: t.Function,
}),
],
"ColumnFieldMapping",
);
const ComputedFieldMappingRT = t.intersection(
[
BaseFieldMappingRT,
t.intersection([
t.type({
dependencies: t.array(t.string),
derive: t.Function,
}),
t.partial({
reduce: t.Function,
}),
]),
],
"ComputedFieldMapping",
);
/**
*
* @api-category ConfigType
*/
export interface BaseFieldMapping<TMapped> extends t.TypeOf<typeof BaseFieldMappingRT> {
type: TypeSpec<TMapped, GraphQLInputType, GraphQLOutputType>;
getColumnMappingList?: (
aliasHierarchyVisitor: AliasHierarchyVisitor,
aliasColumnsToTableScope: boolean,
) => ColumnMapping[];
}
/**
* @api-category ConfigType
*/
type ColumnFieldMapping$1<TMapped = any> = BaseFieldMapping<TMapped> & t.TypeOf<typeof ColumnFieldMappingRT>;
export interface ColumnFieldMapping<TMapped = any> extends ColumnFieldMapping$1<TMapped> {
fromSource?: (i: any) => TMapped;
toSource?: (i: TMapped) => any;
}
/**
* @api-category ConfigType
*/
export type ComputedFieldMapping<TMapped = any, TArgs extends {} = any> = BaseFieldMapping<TMapped> &
t.TypeOf<typeof ComputedFieldMappingRT> & {
dependencies: Array<StrKey<TArgs>>;
derive: (args: TArgs) => TMapped;
reduce?: (args: TArgs) => Dict;
};
export const FieldMappingRT = t.union([ColumnFieldMappingRT, ComputedFieldMappingRT], "FieldMapping");
/**
* @api-category ConfigType
*/
export type FieldMappingArgs<T extends FieldMapping<any, any>> = T extends FieldMapping<any, infer I> ? I : never;
export interface ColumnMapping {
field: MappedField;
columnRef: string;
columnAlias: string;
}
/**
* @api-category ConfigType
*/
export type FieldMapping<TMapped, TArgs extends {}> =
| ColumnFieldMapping<TMapped>
| ComputedFieldMapping<TMapped, TArgs>;
<file_sep>/src/utils/connector.ts
import * as Knex from "knex";
import { Maybe } from "./util-types";
import { isNil, isFunction } from "lodash";
/**
* String constants representing database clients supported by Knex.
* This collection must be kept in sync with Knex.
*
* TODO: Expose this collection from knex itself.
*/
export const KNEX_SUPPORTED_DBS = ["mysql", "mysql2", "oracledb", "pg", "redshift", "sqlite3", "mssql"];
/**
* Subset of KNEX_SUPPORTED_DBS which are officially supported by GRelDAL and which are covered by GRelDAL's test coverage
*/
export const OFFICIALLY_SUPPORTED_DBS = ["mysql2", "pg", "sqlite3"];
/**
* Singleton database connector used by default if a local database connector is not specified at data source level
*/
export let globalConnector: Maybe<Knex>;
/**
* Validate if the passed knex connector is configured to use a supported datbase.
*/
export const assertSupportedConnector = (connector: Knex) => {
const { client } = connector.client.config;
if (!isFunction(client) && KNEX_SUPPORTED_DBS.indexOf(client) < 0) {
throw new Error(
`Unsupported client: "${client}". ` +
`Check Knex documentation to ensure Knex connector is properly configured`,
);
}
if (OFFICIALLY_SUPPORTED_DBS.indexOf(client) < 0) {
console.warn(
`${client} is currently not officially supported.` +
`The contributors may not be able to prioritize ${client} specific issues.`,
);
}
return connector;
};
export const assertConnectorConfigured = (connector?: Maybe<Knex>) => {
if (isNil(connector)) {
throw new Error(`You need to configure a database connector either at data source level or global level`);
}
return connector;
};
/**
* Register a database connector as the global default for the library.
*
* Connector options can be found in [knex documentation](https://knexjs.org/#Installation-client).
*
* @api-category PrimaryAPI
*/
export const useDatabaseConnector = (connector: Knex) => {
if (globalConnector) console.warn("Overriding global connector");
globalConnector = assertSupportedConnector(connector);
return connector;
};
/** Specify whether the database supports returning clause */
export const supportsReturning = (connector: Knex) => {
const { client } = connector.client.config;
return ["mssql", "oracledb", "pg"].indexOf(client) >= 0;
};
<file_sep>/src/generator/adapters/types-mapping.ts
export const TYPES_MAPPING = [
{
regexp: /INT/i,
type: "integer",
},
{
regexp: /(TEXT|CHAR|CLOB)/i,
type: "string",
},
{
regexp: /(REAL|DOUBLE|FLOAT|NUMERIC|DECIMAL)/i,
type: "number",
},
{
regexp: /DATETIME/i,
type: "dateTime",
},
{
regexp: /DATE/i,
type: "date",
},
{
regexp: /BOOLEAN/i,
type: "boolean",
},
];
<file_sep>/src/__specs__/helpers/subscriptions.ts
import { ExecutionResult } from "graphql";
import { ExecutionResultDataDefault } from "graphql/execution/execute";
import { isFunction } from "lodash";
const isAsyncIterator = (i: any): i is AsyncIterator<any> => i && isFunction(i.next);
/**
* Utility to extract a pre-specified number of results from
* an async iterator
*
* @param count Number of results to be retrieved
* @returns Function which receives an async iterator and returns a promise
* that resolves when count number of operations have been retrieved
* from the iterator.
*/
export const getSubscriptionResults = (count = 1) => async (
resultIterator:
| ExecutionResult<ExecutionResultDataDefault>
| AsyncIterator<ExecutionResult<ExecutionResultDataDefault>>,
): Promise<ExecutionResult<ExecutionResultDataDefault>[]> => {
if (!isAsyncIterator(resultIterator)) return [resultIterator];
const returned: any = [];
let idx = 0;
while (true) {
const { done, value } = await resultIterator.next();
if (done) return returned;
returned.push(value);
idx += 1;
if (idx === count) return returned;
}
};
<file_sep>/src/generator/adapters/Sqlite3Adapter.ts
import { Adapter, ForeignKeyInfo, TableLike, TableSchema } from "./Adapter";
import { BaseAdapter } from "./BaseAdapter";
import { TYPES_MAPPING } from "./types-mapping";
export class Sqlite3Adapter extends BaseAdapter implements Adapter {
async getTables(): Promise<TableLike[]> {
const tables = await this.connector("sqlite_master")
.where({ type: "table" })
.orWhere({ type: "view" });
return tables.map(({ name, type }: any) => ({ name, type }));
}
async getSchemaForTable(table: TableLike): Promise<TableSchema> {
const schemaInfo = await this.connector.raw(`PRAGMA table_info("${table.name}");`);
const columns = schemaInfo.map((c: any) => {
const typeMapping = c.type && TYPES_MAPPING.find(t => c.type.match(t.regexp));
return {
name: c.name,
isPrimary: c.pk === 1,
type: typeMapping && typeMapping.type,
};
});
const fkInfo: any[] = await this.connector.raw(`PRAGMA foreign_key_list("${table.name}");`);
const foreignKeys: ForeignKeyInfo[] = fkInfo.map((f: any) => {
return {
associatedTable: {
name: f.table,
type: "table",
},
associatorColumns: {
inSource: f.from,
inRelated: f.to,
},
};
});
return {
columns,
foreignKeys,
};
}
}
<file_sep>/config/snapshot-resolver.js
const path = require('path');
module.exports = {
resolveSnapshotPath: (testPath, snapshotExtension) => {
const db = process.env.DB || "sqlite3";
return path.join(path.dirname(testPath), '__snapshots__', db, path.basename(testPath)+snapshotExtension);
},
resolveTestPath: (snapshotPath, snapshotExtension) => {
return path.join(
path.dirname(snapshotPath),
'..',
'..',
path.basename(snapshotPath, snapshotExtension)
);
},
testPathForConsistencyCheck: path.join('src', '__specs__', 'insertion.spec.ts'),
};
<file_sep>/src/NotificationDispatcher.ts
import * as t from "io-ts";
import { MaybePromise, MaybeArray, Predicate, RegExpType, Dict } from "./utils/util-types";
import { identity, noop, isEmpty, constant, some, keys } from "lodash";
import { checkArray, checkNil, checkFn } from "./utils/guards";
import { assertType } from "./utils/assertions";
import { maybeArray } from "./utils/maybe";
import { matchString } from "./utils/predicate";
/**
* Covers all the primitive mutation types used in the MutationNotification objects
* that are constructed by GRelDAL
*/
export enum PrimitiveMutationType {
Insert = "INSERT",
Update = "UPDATE",
Delete = "DELETE",
}
/**
* A notification to be published that conveys information about a mutation that
* has happened in the application.
*
* These mutations may not be GraphQL mutations, and application backend
* can choose to use NotificationDispatcher to dispatch events which will
* become available through GraphQL subscriptions.
*
* Must be serializable
*/
export interface MutationNotification<TEntity extends {} = any> {
/**
* Type of Mutation. For notifications generated by GRelDAL this will
* always be of PrimitiveMutationType
*/
type: string;
/**
* Mapping of mapped source name to List of entities affected by this mutation.
*
* For GRelDAL generated mutation notifications, this collection will
* have only a single key-value pair
*/
entities: Dict<TEntity[]>;
/**
* Application specific metadata
*/
metadata?: any;
}
/**
* Represents a notification for a single (usually atomic) operation that changes the state of
* a singe datasource
*/
export interface PrimitiveMutationNotification<TEntity extends {}> extends MutationNotification<TEntity> {
type: PrimitiveMutationType;
}
/**
* A function that intercepts a list of notifications and can transform it.
*
* Only those notifications will be published which have been removed from the interceptor.
*/
interface NotificationDispatchInterceptor {
(notification: Array<MutationNotification<any>>): MaybePromise<Array<MutationNotification<any>>>;
}
const StringPredicateRT = maybeArray(t.union([t.string, RegExpType, t.Function]));
const NotificationDispatchInterceptorConfigRT = t.intersection(
[
t.partial({
type: StringPredicateRT,
source: StringPredicateRT,
}),
t.type({
intercept: t.union([t.Function, t.boolean]),
}),
],
"NotificationDispatchInterceptorConfig",
);
/**
* Specifies what Notifications are to be intercepted.
*/
interface NotificationDispatchInterceptorConfig extends t.TypeOf<typeof NotificationDispatchInterceptorConfigRT> {
/**
* Specifies which notifications are to be intercepted based on type.
*
* This can be:
*
* - A string: In which case an exact match is performed against the type property of notification
* - A regular expression to match the type property by a pattern
* - A function that takes the type property value and returns true/false
* - An array of the above, in which case any of the predicates matching will be considered a successful match.
*
* If both type and source are specified, then incoming notifications must match *both* of them
* to be intercepted.
*/
type?: MaybeArray<string | RegExp | Predicate<string>>;
/**
* Specifies which notifications are to be intercepted based on source.
*
* This can be:
*
* - A string: In which case an exact match is performed against the source property of notification
* - A regular expression to match the source property by a pattern
* - A function that takes the source property value and returns true/false
* - An array of the above, in which case any of the predicates matching will be considered a successful match.
*
* If both type and source are specified, then incoming notifications must match *both* of them
* to be intercepted.
*/
source?: MaybeArray<string | RegExp | Predicate<string>>;
/**
* Whether the notifications not matching the aforementioned type/source should be retained
* or discarded.
*
* True (retained) by default.
*
* In a chain of dispatch interceptors, if any of the interceptors choses not to retain
* notifications that don't match, they will not be available to other interceptors
* down the chain.
*/
retainRest?: boolean;
/**
* Interceptor function that receives list of notifications to be published and can choose
* to augment, transform or remove them.
*
* Only the notifications actually returned from the interceptor will be published.
*
* This can be:
* - A function, which will receives list of notifications to be published and can choose
* to augment, transform or remove them.
* - True, in which case all matched notifications are returned as is
* - False, in which case all matched notifications are discarded
*/
intercept: NotificationDispatchInterceptor | boolean;
}
interface NormalizedNotificationDispatcherConfig {
intercept: NotificationDispatchInterceptor;
publish: (notification: MutationNotification<any>) => void;
}
const NotificationDispatcherConfigRT = t.intersection(
[
t.partial({
intercept: maybeArray(t.union([t.Function, NotificationDispatchInterceptorConfigRT])),
}),
t.type({
publish: t.Function,
}),
],
"NotificationDispatcherConfig",
);
/**
* Global notification Dispatcher Configuration
*/
interface NotificationDispatcherConfig extends t.TypeOf<typeof NotificationDispatcherConfigRT> {
/**
* Interceptors which can receive and transform, add or remove notifications before
* they are published.
*
* The interceptor can be:
*
* 1. A configuration of type {@link NotificationDispatchInterceptorConfig} which will specify
* which notifications are to be intercepted based on type or source.
*
* 2. A function that receives an array of notifications and returns transformed list of notifications
* Only the notifications that are returned by this interceptor will be published.
*
* 3. An array of either of the above, in which case the interceptors will be composed
* as a chain of middlewares, and only the notifications that are returned by the last interceptor
* in the chain will be published.
*/
intercept?: MaybeArray<NotificationDispatchInterceptor | NotificationDispatchInterceptorConfig>;
/**
* Function used to publish the notifications to an observable channel.
*
* This can be used for graphql-subscriptions integration:
*/
publish: (notification: MutationNotification<any>) => void;
}
const normalizeInterceptor = (i: NotificationDispatchInterceptorConfig | NotificationDispatchInterceptor) => {
if (checkFn(i)) return i;
const checkSource = checkNil(i.source)
? constant(true)
: (sources: string[]) => some(sources, matchString(i.source!));
const checkType = checkNil(i.type) ? constant(true) : matchString(i.type);
const intercept = checkFn(i.intercept)
? // When provided as a function, return the interceptor as is
i.intercept
: i.intercept
? // When provided as true, assume that received notifications are to be
// returned as is.
//
// This is primarily helpful in conjunction with retainRest: false to discard
// some notifications
(identity as NotificationDispatchInterceptor)
: // When specified as false, assume that received notifications are to be
// discarded
constant([]);
return async (narr: MutationNotification[]): Promise<MutationNotification[]> => {
const retained: MutationNotification[] = [];
const consumed: MutationNotification[] = [];
for (const n of narr) {
if ((checkNil(n.entities) || checkSource(keys(n.entities))) && checkType(n.type)) {
consumed.push(n);
} else if (i.retainRest !== false) {
retained.push(n);
}
}
if (!isEmpty(consumed)) {
const intercepted = await intercept(consumed);
return intercepted.concat(retained);
}
return retained;
};
};
const normalize = (c: NotificationDispatcherConfig): NormalizedNotificationDispatcherConfig => {
let intercept: NotificationDispatchInterceptor;
if (checkNil(c.intercept)) intercept = identity;
else if (checkArray(c.intercept)) {
const steps = c.intercept.map(i => normalizeInterceptor(i));
intercept = async (notifications: MutationNotification<any>[]) => {
for (const step of steps) {
if (isEmpty(notifications)) return notifications;
notifications = await step(notifications);
}
return notifications;
};
} else intercept = normalizeInterceptor(c.intercept);
return { ...c, intercept };
};
export const defaultConfig: NormalizedNotificationDispatcherConfig = Object.freeze({
intercept: identity,
publish: noop,
});
/**
* The current configuration of NotificationDispatcher.
*
* Default configuration does nothing: it has no interceptors and it publishes nowhere.
*/
export let config = defaultConfig;
/**
* Configure NotificationDispatcher.
*
* Note that the NotificationDispatcher is singleton and thus re-invocation of this function is
* not recommended.
*
* If re-invoked the previous configuration will be overriden completely (and NOT merged). So
* any previous interceptors will get lost. If merging is desired, it should be taken care of either
* at the application level or by passing a function to configure which will receive previous/default
* configuration.
*/
export function configure(cfg: NotificationDispatcherConfig) {
assertType(NotificationDispatcherConfigRT, cfg, "NotificationDispatcher config");
config = normalize(cfg);
}
/**
* Reset Notification dispatcher configuration to default.
*
* Primarily useful in tests.
*/
export function resetConfig() {
config = defaultConfig;
}
/**
* Publish notifications to an observable channel after passing them through a chain
* of interceptors (Refer {@link NotificationDispatcherConfig}) if configured.
*/
export async function publish<TEntity>(notifications: MaybeArray<MutationNotification<TEntity>>) {
const intercepted = await config.intercept(checkArray(notifications) ? notifications : [notifications]);
intercepted.forEach(config.publish);
}
<file_sep>/src/UDFMapping.ts
import { ArgSpecsFor } from "./InvocableMapping";
export interface UDFMapping<TArgs> {
name: string;
args: ArgSpecsFor<TArgs>;
}
<file_sep>/src/PGStoredProcInvocationOperationResolver.ts
import { BaseResolver } from "./BaseResolver";
import { ResolverContext } from "./ResolverContext";
import { MappedStoredProcInvocationOperation } from "./MappedStoredProcInvocationOperation";
import { isNil, get } from "lodash";
import { inspect } from "util";
export class PGStoredProcInvocationOperationResolver<
TCtx extends ResolverContext<MappedStoredProcInvocationOperation<TArgs>, TArgs>,
TArgs extends {},
TResolved
> extends BaseResolver<TCtx, TArgs, TResolved> {
/**
* Should be overriden in sub-class with the logic of resolution
*/
async resolve(): Promise<any> {
const params = this.operation.deriveParams(this.args);
const knex = this.operation.connector;
const { procedureName } = this.operation;
let result: any = {};
await knex.transaction(async trx => {
const paramPlaceholders = [];
const paramBindings = [];
for (let i = 0; i < params.length; i++) {
const param = params[i];
paramPlaceholders.push("?");
paramBindings.push(isNil(param.value) ? null : param.value);
}
result = await trx.raw(`CALL ??(${paramPlaceholders.join(", ")})`, [procedureName, ...paramBindings]);
});
return this.operation.deriveResult(get(result, ["rows", 0]));
}
}
<file_sep>/src/generator/adapters/index.ts
import { Sqlite3Adapter } from "./Sqlite3Adapter";
import { PGAdapter } from "./PGAdapter";
import { MySQLAdapter } from "./MySQLAdapter";
export const adapters = {
sqlite3: Sqlite3Adapter,
pg: PGAdapter,
mysql: MySQLAdapter,
mysql2: MySQLAdapter,
};
<file_sep>/src/generator/adapters/Adapter.ts
import { Mapped } from "../../utils/util-types";
import { Interceptable } from "../GenConfig";
export interface TableLike {
name: string;
type: "table" | "view";
schema?: string;
}
export interface ColumnInfo {
name: string;
isPrimary: boolean;
type?: string;
}
export interface ForeignKeyInfo {
associatedTable: TableLike;
associatorColumns: {
inSource: string;
inRelated: string;
};
}
export interface TableSchema {
columns: ColumnInfo[];
foreignKeys: ForeignKeyInfo[];
}
export type DataSourceInfo = Interceptable & {
name: Mapped<string>;
table: TableLike;
fields: {
[mappedName: string]: Interceptable & {
column: ColumnInfo;
};
};
associations: {
[mappedName: string]: Interceptable & {
foreignKey: ForeignKeyInfo;
targetDataSourceName?: string;
singular?: boolean;
};
};
};
export interface Adapter {
getTables(): Promise<TableLike[]>;
getSchemaForTable(table: TableLike): Promise<TableSchema>;
}
<file_sep>/src/Operation.ts
import { GraphQLFieldConfig } from "graphql";
import { OperationType } from "./operation-types";
// @snippet:start Operation_type
/**
* Interface that all operations application must confirm to.
*
* These operations may be source aware (which interact with GRelDAL data sources)
* or completely generic (which may simply wrap graphql.js compatible resolvers).
*/
export interface Operation {
operationType: OperationType;
name: string;
fieldConfig: GraphQLFieldConfig<any, any, any>;
}
// @snippet:end
<file_sep>/src/docs/components/PageLayout.js
import React from "react";
import styled from "styled-components";
import Media from "react-media";
import { Sidebar, SidebarContainer, FixedSidebarContainer } from "./Sidebar";
import "../styles/page.css";
import "normalize.css/normalize.css";
import "highlight.js/styles/github.css";
export class PageLayout extends React.Component {
state = {
show: false,
showDrawer: false,
};
containerRef = React.createRef();
toggleDrawer = () => {
this.setState({
showDrawer: !this.state.showDrawer,
});
}
componentDidMount() {
this.setState({
show: true,
});
}
componentDidUpdate(prevProps) {
if (this.props.children !== prevProps.children) {
const {current} = this.containerRef;
if (!current) return;
current.scrollTop = 0;
}
}
render() {
if (!this.state.show) return this.renderWideLayout();
const { sidebar, children } = this.props;
return (
<Media query="(max-width: 1000px)">
{matches => {
if (matches) {
return this.renderCompactLayout();
} else {
return this.renderWideLayout();
}
}}
</Media>
);
}
renderCompactLayout() {
const { children, sidebar } = this.props;
return (
<CompactLayoutContainer ref={this.containerRef}>
<AppHeader>
<AppHeader.Action>
<AppHeader.Action.Control
onClick={this.toggleDrawer}
>
☰
</AppHeader.Action.Control>
</AppHeader.Action>
<AppHeader.Title>
GRelDAL
</AppHeader.Title>
</AppHeader>
<MobileContentContainer id="container">
{this.state.showDrawer ? (
<SidebarContainer onClick={this.toggleDrawer}>
<Sidebar>{sidebar}</Sidebar>
</SidebarContainer>
) : (
children
)}
</MobileContentContainer>
</CompactLayoutContainer>
);
}
renderWideLayout() {
const { children, sidebar } = this.props;
const { show } = this.state;
return (
<div style={{ display: show ? "block" : "none" }} ref={this.containerRef}>
<FixedSidebarContainer>
<Sidebar>{sidebar}</Sidebar>
</FixedSidebarContainer>
<DesktopContentContainer id="container">{children}</DesktopContentContainer>
</div>
);
}
}
const CompactLayoutContainer = styled.div`
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: auto;
`
const AppHeader = styled.div`
background: #53942b;
line-height: 1rem;
border-bottom: 2px solid #8a8a8a;
display: flex;
flex-direction: row;
position: sticky;
top: 0;
`;
AppHeader.Action = styled.div`
flex-grow: 0;
flex-shrink: 0;
flex-basis: 3rem;
padding: 0.4rem;
`;
AppHeader.Action.Control = styled.button`
padding: 0.6rem;
line-height: 1rem;
display: block;
border: 1px solid #5d8c3e;
box-shadow: none;
background: #94d668;
font-size: 1.6rem;
color: #60ac32;
font-weight: bold;
`;
AppHeader.Title = styled.div`
flex-grow: 1;
flex-shrink: 1;
text-align: center;
font-size: 1.6rem;
line-height: 3rem;
color: #bfe896;
font-weight: bold;
line-height: 50px;
`;
const ContentContainer = styled.div`
pre:not(.CodeMirror-line) {
padding: 0 !important;
}
h1 {
margin: 2.8rem 0;
}
h2,
h3,
h4,
h5,
h6 {
margin: 1.8rem 0;
}
p,
ol,
ul {
margin: 1.8rem 0;
}
pre:not(.CodeMirror-line) > code {
border-left: 4px solid #ddd;
display: block;
margin: 0;
padding: 5px;
}
pre:not(.CodeMirror-line) {
max-width: calc(100% - 40px);
overflow-x: auto;
border: 1px solid #ddd;
background: #f8f8f8;
}
a,
a:visited,
a:hover,
a:active {
color: #0261cd;
font-weight: bold;
text-decoration: none;
}
`;
const DesktopContentContainer = styled(ContentContainer)`
max-width: 700px;
margin: 40px 100px 50px 400px;
`;
const MobileContentContainer = styled(ContentContainer)`
width: calc(100% - 40px);
padding: 20px;
overflow-x: hidden;
`;
<file_sep>/src/docs/components/APIEntityContainer.js
import React from "react";
import marked from "marked";
import styled from "styled-components";
import Collapsible from "react-collapsible";
import { uniqBy, get, find, compact } from "lodash";
import { TypePresenter } from "./TypePresenter";
import { getAPIName, convertLinks } from "../utils/api";
import { SectionHeader } from "./Sidebar";
import { ParamsTable } from "./ParamsTable";
import "../styles/collapsible.css";
marked.setOptions({
gfm: true,
tables: true,
});
export default class APIEntityContainer extends React.Component {
containerRef = React.createRef();
componentDidMount() {
this.bringToView();
}
componentDidUpdate() {
this.bringToView();
}
bringToView() {
if (this.props.activeEntityName && this.props.entity.name === this.props.activeEntityName) {
this.containerRef.current.scrollIntoView();
}
}
render() {
const { entity, activeEntityName } = this.props;
return (
<APIContainer ref={this.containerRef}>
<EntityHeader>
{entity.kindString && <div style={{ float: "right", color: "silver" }}>({entity.kindString})</div>}
<h1>{getAPIName(entity)}</h1>
</EntityHeader>
{entity.comment && this.renderDescription()}
{entity.type && (
<Section>
<SectionHeader>Type</SectionHeader>
<TypePresenter type={entity.type} />
</Section>
)}
{entity.signatures &&
entity.signatures.map(sig => (
<>
{sig.comment &&
sig.comment.shortText && (
<section className="api-section">
<SectionHeader>Description</SectionHeader>
<p>{sig.comment.shortText}</p>
</section>
)}
{sig.parameters &&
sig.parameters.length > 0 && (
<Section>
<SectionHeader>Parameters</SectionHeader>
<ParamsTable params={sig.parameters} />
</Section>
)}
{sig.type && (
<Section>
<SectionHeader>Returns</SectionHeader>
{get(find(entity.tags, { tag: "returns" }), "text")}
<TypePresenter type={sig.type} />
</Section>
)}
</>
))}
{entity.sources && (
<Section>
<SectionHeader>Sources</SectionHeader>
<ul>
{uniqBy(entity.sources, s => s.fileName).map(src => {
const fileName = src.fileName.replace(/\.d\.ts$/, ".ts");
return (
<li>
<a href={`https://github.com/gql-dal/greldal/blob/master/src/${fileName}`}>
{fileName}
</a>
</li>
);
})}
</ul>
</Section>
)}
{entity.children && (
<Section>
<SectionHeader>Members</SectionHeader>
<MemberListContainer>
{entity.children.map(e => (
<Collapsible
trigger={
<div>
{e.kindString && (
<div style={{ float: "right", color: "silver" }}>({e.kindString})</div>
)}
{getAPIName(e)}
</div>
}
open={activeEntityName && e.name === activeEntityName}
>
<APIEntityContainer entity={e} activeEntityName={activeEntityName} />
</Collapsible>
))}
</MemberListContainer>
</Section>
)}
</APIContainer>
);
}
renderDescription() {
const { entity } = this.props;
if (!entity.comment) return null;
const { text, shortText } = entity.comment;
const fullText = compact([shortText, text]).join("<br/>");
return (
<div dangerouslySetInnerHTML={{ __html: convertLinks(marked(fullText)) }} style={{ padding: "0 10px" }} />
);
}
}
export const APIContainer = styled.div`
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 1rem 0;
}
p,
ol,
ul {
margin: 1rem 0;
}
`;
const Section = styled.section`
margin: 10px 0;
padding: 0 10px;
`;
const EntityHeader = styled.div``;
const MemberListContainer = styled.div`
padding-left: 5px;
border-left: 4px solid #ddd;
padding-right: 0;
${EntityHeader} {
display: none;
}
`;
<file_sep>/src/docs/pages/playground.js
import Knex from "knex";
import { useState, useRef } from "react";
import SQLJSClient from "../utils/SQLJSClient";
import * as greldal from "../../../lib/universal";
import * as graphql from "graphql";
import loadable from "@loadable/component";
import SplitPane from "react-split-pane";
import styled from "styled-components";
import logo from "../assets/logo.png";
import "../styles/split-pane.css";
const Loading = () => <div>Loading...</div>;
const Editor = loadable(() => import("../components/Editor"));
const AsyncFunction = Object.getPrototypeOf(eval(`(async function __test() {})`)).constructor;
if (typeof window !== "undefined") {
window.Knex = Knex;
window.greldal = greldal;
}
const defaultCode = `
// Libraries available in the sandbox
// import * as greldal from "greldal";
// import * as Knex from "knex";
// knex is a Knex instance configured to connect to an
// in memory sqlite database.
greldal.useDatabaseConnector(knex);
// Setup tables
await knex.schema.createTable("customers", t => {
t.increments("pk");
t.string("first_name");
t.string("last_name");
});
// Insert some sample data:
await knex("customers").insert([
{first_name: "Harry", last_name: "Granger"},
{first_name: "Ron", last_name: "Potter"}
]);
// Map the database schema to GraphQL API schema using GRelDAL:
const fields = greldal.mapFields({
id: {
sourceColumn: "pk",
type: greldal.types.number,
to: {
input: graphql.GraphQLID,
output: graphql.GraphQLID,
},
},
firstName: {
sourceColumn: "first_name",
type: greldal.types.string,
},
lastName: {
sourceColumn: "last_name",
type: greldal.types.string,
},
});
const users = greldal.mapDataSource({
name: {
mapped: "User",
stored: "customers",
},
fields,
});
// Generate GraphQL schema:
const schema = greldal.mapSchema(greldal.operationPresets.defaults(users));
// This return is required for the playground to work:
return schema;
`;
const defaultQuery = `
query {
findManyUsers(where: {}) {
id,
firstName,
lastName
}
}
`;
export default function() {
const [code, setCode] = useState(defaultCode);
const [schema, setSchema] = useState(null);
const [query, setQuery] = useState(defaultQuery);
const [result, setResult] = useState("");
const [error, setError] = useState("");
const codeEditorRef = useRef(null);
const gqlEditorRef = useRef(null);
const resultRef = useRef(null);
const runCode = async () => {
const knex = Knex({
client: SQLJSClient,
debug: true,
pool: { min: 1, max: 1 },
acquireConnectionTimeout: 500,
});
knex.initialize();
const run = new AsyncFunction("Knex", "knex", "greldal", "graphql", code);
try {
const schema = await run(Knex, knex, greldal, graphql);
setResult("");
setError("");
setSchema(schema);
} catch (e) {
console.error(e);
setError(`${e.message}\n${e.stack}`);
}
};
const queryAPI = () => {
if (!schema || !query) return;
graphql
.graphql(schema, query)
.then(res => {
setResult(res);
setError("");
})
.catch(e => {
console.error(e);
setError(`${e.message}\n${e.stack}`);
});
};
const refreshEditors = () => {
for (const ref of [codeEditorRef, gqlEditorRef]) {
if (!ref.current) continue;
const editor = ref.current.getCodeMirror();
if (!editor) continue;
editor.refresh();
}
};
return (
<PageContainer>
<SplitPane split="vertical" minSize={50} defaultSize="50%" onChange={refreshEditors}>
<PaneBody>
<HeaderInfo>
<a href={ROOT_PATH || "/"} style={{ display: "block", marginRight: "10px" }}>
<img src={logo} style={{ height: "50px", width: "50px" }} />
</a>
<div style={{ padding: "5px" }}>
GRelDAL Playground is an <strong>experimental</strong> sandboxed environment where you can
play around with a <a href="https://graphql.org/">GraphQL API</a> powered by{" "}
<a href="https://gql-dal.github.io/greldal/">GRelDAL</a> and{" "}
<a href="https://github.com/kripken/sql.js">sql.js</a> within your browser without having to
install anything.
</div>
<div
style={{
flexBasis: "170px",
flexGrow: "0",
flexShrink: "0",
}}
>
<PrimaryBtn style={{ marginLeft: "10px" }} onClick={runCode}>
Generate Schema ⇨
</PrimaryBtn>
</div>
</HeaderInfo>
<div style={{ position: "relative", flexGrow: 2, flexShrink: 1, overflow: "hidden" }}>
<Editor
options={{
scrollbarStyle: "native",
theme: "monokai",
mode: "javascript",
lineNumbers: true,
}}
value={code}
onChange={(c) => setCode(c)}
innerRef={codeEditorRef}
/>
</div>
</PaneBody>
<SplitPane split="horizontal" defaultSize="50%" onChange={refreshEditors}>
<PaneBody>
{schema ? (
<>
<HeaderInfo>
<div style={{ padding: "5px", flexGrow: 1 }}>Query your API using GraphQL</div>
<PrimaryBtn style={{ float: "right", marginLeft: "10px" }} onClick={queryAPI}>
Run Query ⇩
</PrimaryBtn>
</HeaderInfo>
<EditorContainer>
<Editor
options={{
theme: "monokai",
mode: "graphql",
lint: {
schema,
},
hintOptions: {
schema,
},
lineNumbers: true,
}}
value={query}
onChange={(c) => setQuery(c)}
innerRef={gqlEditorRef}
/>
</EditorContainer>
</>
) : (
<BlankPanel>
Once your Schema has been prepared, you will be able to query it from this panel.
</BlankPanel>
)}
</PaneBody>
<div>
{result ? (
<Editor
options={{
scrollbarStyle: "native",
theme: "monokai",
mode: "javascript",
readOnly: true,
lineNumbers: true,
}}
key={JSON.stringify(result, null, 2)}
value={JSON.stringify(result, null, 2)}
innerRef={resultRef}
/>
) : error ? (
<Editor
options={{
scrollbarStyle: "native",
theme: "monokai",
readOnly: true,
lineNumbers: true,
}}
value={error}
innerRef={resultRef}
/>
) : (
<BlankPanel>Once you perform a query, you will be able to see the results here</BlankPanel>
)}
</div>
</SplitPane>
</SplitPane>
</PageContainer>
);
}
const PageContainer = styled.div`
position: absolute;
top: 4px;
left: 0;
right: 0;
bottom: 0;
.ReactCodeMirror {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.CodeMirror {
height: 100%;
width: 100%;
}
.CodeMirror-linenumber {
background: black;
color: white;
padding-right: 5px;
}
`;
const HeaderInfo = styled.div`
padding: 5px;
background: lemonchiffon;
color: #404040;
border-bottom: 2px solid #8dd35f;
display: flex;
flex-direction: row;
flex-grow: 0;
flex-shrink: 0;
`;
const EditorContainer = styled.div`
position: relative;
flex-grow: 2;
flex-shrink: 1;
overflow: hidden;
`;
const PrimaryBtn = styled.button`
background: #5aac31;
border: 1px solid #abe081;
border-radius: 4px;
padding: 10px;
color: white;
cursor: pointer;
`;
const BlankPanel = styled.div`
color: #a7a6a6;
font-size: 1.5rem;
padding: 50px;
line-height: 2rem;
background: #ddd;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
`;
const PaneBody = styled.div`
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
display: flex;
flex-direction: column;
`;
<file_sep>/src/docs/components/ParamsTable.js
import Table from "react-table";
import { TypePresenter } from "./TypePresenter";
import React from "react";
import "react-table/react-table.css";
export const columns = [
{
Header: "Parameter",
accessor: "name",
},
{
Header: "Type",
accessor: "type",
Cell: props => <TypePresenter type={props.value} />,
},
{
Header: "Description",
accessor: "comment.text",
Cell: props => (
<div
css={`
text-overflow: unset;
overflow: auto;
white-space: normal;
`}
>
{props.value}
</div>
),
},
];
export const ParamsTable = ({ params }) => (
<Table
showPagination={false}
resizable={false}
sortable={false}
defaultPageSize={params.length}
style={{
marginTop: "1em",
marginBottom: "1em",
}}
columns={columns}
data={params}
/>
);
<file_sep>/src/MappedSchema.ts
import { GraphQLSchema, GraphQLObjectType, GraphQLFieldConfigMap, GraphQLSchemaConfig } from "graphql";
import { isEmpty, transform, identity, filter } from "lodash";
import { Maybe, Interceptor } from "./utils/util-types";
import { Operation } from "./Operation";
import { OperationType } from "./operation-types";
/**
* @api-category PrimaryAPI
*/
export function mapSchema(operations: Operation[], interceptFields: Interceptor<GraphQLSchemaConfig> = identity) {
return new GraphQLSchema(
interceptFields({
query: deriveGraphQLObjectType(
"query",
operations.filter(op => op.operationType === OperationType.Query),
),
mutation: deriveGraphQLObjectType(
"mutation",
operations.filter(op => op.operationType === OperationType.Mutation),
),
subscription: deriveGraphQLObjectType(
"subscription",
filter(operations, { operationType: OperationType.Subscription }),
),
}),
);
}
function deriveGraphQLObjectType(name: string, operations: Operation[]): Maybe<GraphQLObjectType> {
return isEmpty(operations)
? undefined
: new GraphQLObjectType({
name,
fields: transform(
operations,
(result: GraphQLFieldConfigMap<any, any>, operation: Operation) => {
result[operation.name] = operation.fieldConfig;
},
{},
),
});
}
<file_sep>/src/MappedSingleSourceMutationOperation.ts
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { MappedDataSource } from "./MappedDataSource";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import { OperationType } from "./operation-types";
/**
* @api-category MapperClass
*/
export abstract class MappedSingleSourceMutationOperation<
TSrc extends MappedDataSource,
TArgs extends {}
> extends MappedSingleSourceOperation<TSrc, TArgs> {
constructor(
public mapping: MappedSingleSourceOperation<TSrc, TArgs>["mapping"] & {
resolver?: <
TCtx extends SourceAwareResolverContext<MappedSingleSourceMutationOperation<TSrc, TArgs>, TSrc, TArgs>,
TResolved
>(
ctx: TCtx,
) => SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved>;
},
) {
super(mapping);
}
operationType = OperationType.Mutation;
}
<file_sep>/src/docs/pages/mapping-data-sources.md
import {NextPageLink, Link} from "../components/Link";
import {CodeSnippet} from "../components/CodeSnippet";
# Mapping Data Sources
Creation of a GraphQL API using GRelDAL essentially involves defining operations on data sources.
Operations are what we expose to the outside world through GraphQL queries and mutations and these operations interact with the data stored in our databases through data sources. These data sources are usually backed by tables, but they can also be backed by views, materialized views, joined tables, etc.
We can use the mapSource function to map a datasource:
<CodeSnippet name="mapDataSource_user_simple" />
As we have already covered in the <Link href="#quick-start">Quick Start</Link> the above configuration tells GRelDAL that we want to map the `users` table (pluralized from `User`) to a `User` data source, and this data source will have two fields: id, name.
## Type specifications
Note that for every field we had to specify a type. This type was specified through what we call runtime-types. The section on <Link>Type Safety</Link>
goes into more on detail on this, but essentially for all primitives we have corresponding runtime types:
<table>
<tr><td>string</td><td>types.string</td></tr>
<tr><td>integer</td><td>types.integer</td></tr>
<tr><td>number</td><td>types.number</td></tr>
<tr><td>boolean</td><td>types.boolean</td></tr>
</table>
We can compose these types to build composite types:
```
const addresses = types.array([
types.type({
street: types.string,
plot_no: types.number
})
])
```
Refer to the documentation of io-ts (which we simply re-export as types) for more details around using and defining runtime types.
## Computed fields
Fields don't necessarily have to map to columns one-to-one.
We can have computed fields which depend on other column-based fields and are computed on the fly:
```
fields: {
fullName: {
dependencies: ["firstName", "lastName"],
derive: ({firstName, lastName}) => `${firstName} ${lastName}`,
to: types.string
}
}
```
## Associations
GRelDAL supports linking together data sources through associations and performing operations that span across multiple data sources.
The section on <Link>association mapping</Link> will cover this in more detail.
<NextPageLink>Mapping Operations</NextPageLink>
<file_sep>/src/MappedArgs.ts
import { GraphQLFieldConfigArgumentMap } from "graphql";
import * as t from "io-ts";
import * as Knex from "knex";
import { forEach, transform, reduce } from "lodash";
import { getTypeAccessorError } from "./utils/errors";
import { Dict } from "./utils/util-types";
import { ArgMapping, ArgMappingDictRT } from "./ArgMapping";
import { assertType } from "./utils/assertions";
import { MappedDataSource } from "./MappedDataSource";
/**
* Dictionary of [ArgMapping](api:ConfigType:ArgMapping)
*
* @api-category ConfigType
*/
export type ArgMappingDict<TArgs extends {} = Dict> = { [K in keyof TArgs]: ArgMapping<TArgs[K]> };
/**
* Derive the type of arguments object (args) that the resolver receives from the ArgMapping specification.
*/
export type ArgsType<T extends ArgMappingDict> = { [K in keyof T]: T[K]["type"]["Type"] };
/**
* Input argument configuration mapper.
*
* There shouldn't be a need to extend or instantiate this class. Use the mapArgs function instead to map an argument
* mapping configuration to a MappedArgs instance.
*
* @api-category MapperClass
*/
export class MappedArgs<TArgs extends object = Dict> {
constructor(private mapping: ArgMappingDict<TArgs>) {
assertType(ArgMappingDictRT, mapping, "ArgMapping");
}
/**
* This Getter can be used to get the static type for the arguments object.
*
* Example:
* ```
* const productsArgs: ArgMapping = mapArgs({
* department_ids: {
* type: types.array(types.number),
* }
* })
*
* type IProductArgs = typeof productArgs["ArgsType"];
* // IProductArgs is
* // {department_ids: number[]}
* ```
*
* This getter should be used only for extracting type information.
* Invoking the getter at runtime will cause an error to be thrown.
*/
get ArgsType(): TArgs {
throw getTypeAccessorError("ArgsType", "MappedArgs");
}
/**
* Getter to access the ArgMappingDict specification type from which this instance was derived.
*
* This getter should be used only for extracting type information.
* Invoking the getter at runtime will cause an error to be thrown.
*/
get ArgsMappingType(): ArgMappingDict<TArgs> {
throw getTypeAccessorError("ArgsMappingType", "MappedArgs");
}
/**
* @returns The GraphQLFieldConfigArgumentMap (which is passed to graphql-js) derived from the specified argument mapping.
*/
getMappedArgsFor(dataSource?: MappedDataSource): GraphQLFieldConfigArgumentMap {
return transform(
this.mapping,
(result: GraphQLFieldConfigArgumentMap, arg: ArgMapping<any>, name: string) => {
result[name] = {
type: arg.type.graphQLInputType,
defaultValue: arg.defaultValue,
description: arg.description,
};
},
{},
);
}
/**
* Apply all argument level query interceptors on the database query being constructed
* for this operation.
*/
interceptQuery(qb: Knex.QueryBuilder, args: TArgs) {
forEach(this.mapping, (arg, name) => {
if (arg.interceptQuery) {
qb = arg.interceptQuery(qb, args[name as keyof TArgs], args) || qb;
}
});
return qb;
}
/**
* Apply all argument level entity interceptors on an entity which is being used
* for the operation.
*/
interceptEntity<TEntity>(entity: Partial<TEntity>): Partial<TEntity> {
return reduce<ArgMappingDict, Partial<TEntity>>(
this.mapping,
(result, arg) => {
if (!arg.interceptEntity) return result;
return arg.interceptEntity(result) || result;
},
entity,
);
}
}
/**
* Map arguments for an operation.
*
* ```
* const args: ArgMapping = mapArgs({
* department_ids: {
* type: types.array(types.number),
* }
* })
* ```
*
* @api-category PrimaryAPI
*/
export function mapArgs<TArgs extends {}>(mapping: ArgMappingDict<TArgs>) {
return new MappedArgs<TArgs>(mapping);
}
<file_sep>/src/DataSourceMapping.ts
import * as t from "io-ts";
import * as Knex from "knex";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { Dict, MaybeMappedRT, Maybe } from "./utils/util-types";
import { MappedField } from "./MappedField";
import { MappedDataSource } from "./MappedDataSource";
import { MappedAssociation } from "./MappedAssociation";
export const DataSourceMappingRT = t.intersection(
[
t.type({
/**
* Name of the data source.
*
* This can either be a string or an object with stored and mapped properties.
*
* If provided as a string, then the mapped name of the data source
* will be PascalCased singular variant of the name, and the stored name
* will be the snake_cased pluralized variant.
*
* Eg. if name is specified either as "ProductManager" or "product_managers",
* in both cases they will be normalized as:
*
* ```
* {
* stored: 'product_managers',
* mapped: 'ProductManager'
* }
* ```
*
* Unless rootQuery is specified, the stored name will be used to identify the table to connect to.
*
* If exposed, the GraphQL type names are derived from the mapped name:
*
* - `ProductManager` - primary GraphQL output type for the entity
* - `ShallowProductManager` - GraphQL output type containing only the fields and not associations
* - `ProductManagerInput` - GraphQL input type for the entity
* - `ShallowProductManagerInput` - Graphql input type for shallow entity (excludes associations)
*
* @property
* @memberof DataSourceMapping
*/
name: MaybeMappedRT(t.string, t.string),
}),
t.partial({
/**
* Human friendly description of an entity from this data source.
*/
description: t.string,
fields: t.Function,
associations: t.Function,
rootQuery: t.Function,
connector: t.object,
}),
],
"DataSourceMapping",
);
/**
* Make sure you have gone through the [DataSource Mapping](guide:mapping-data-sources) guide first, which provides a high level overview of how data mapping works in practice
* in GRelDAL.
*
* A DataSource mapping facilitates the mapping between the persistence layer and the application level entities.
*
* It has following major responsibilities:
*
* 1. To specify how the data source connects to the persistence layer.
* 2. To describe the shape of a `row` stored in the persistence layer
* 3. To describe the shape of an `entity` exposed to the application layer.
* 4. To define the mapping between the two representations so an entity can be coverted to a row and vice versa.
* 5. To define how this data source can connect to other data sources through joins or side-loading
*
* @api-category ConfigType
*/
export interface DataSourceMapping extends t.TypeOf<typeof DataSourceMappingRT> {
/**
* Field mapping obtained from [mapFields](api:mapFields)
*/
fields?: (dataSource: MappedDataSource) => Dict<MappedField>;
/**
* Association mapping obtained from [mapAssociations](api:mapAssociations)
*/
associations?: (dataSource: MappedDataSource) => Dict<MappedAssociation>;
/**
* By default dataSources will connect to a table matching storedName.
*
* Using a rootQuery we can configure the data source to connect to a different table, or a join of multiple tables.
* Note that when working with joins, it is generally recommended to use associations over mapping to joined tables.
*/
rootQuery?: (alias: Maybe<AliasHierarchyVisitor>) => Knex.QueryBuilder;
/**
* Dedicated Knex instance to be used for this data source.
*
* If not provided, the knex instance globally configured through [useDatabaseConnector](api:useDatabaseConnector) will be used.
*
* DataSource specific connector is primarily useful for supporting polyglot persistence and enables use of different
* databases within the application.
*/
connector?: Knex;
}
<file_sep>/src/SingleSourceUpdateOperationResolver.ts
import { pick, forEach } from "lodash";
import { SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver";
import { MemoizeGetter } from "./utils/utils";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { MappedField } from "./MappedField";
import { Maybe, Dict } from "./utils/util-types";
import { MappedSingleSourceUpdateOperation } from "./MappedSingleSourceUpdateOperation";
import { MappedDataSource } from "./MappedDataSource";
import { isPresetUpdateParams } from "./operation-presets";
import { expectedOverride } from "./utils/errors";
import { SourceAwareOperationResolver } from "./SourceAwareOperationResolver";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import * as NotificationDispatcher from "./NotificationDispatcher";
/**
* Implements update operation resolution on a single data source
*
* Sample GraphQL Request:
*
* ```graphql
* mutation {
* updateOneUser(where: { id: 5 }, update: { name: "Rahman" }) {
* id
* name
* }
* }
* ```
*
* Assumes that:
*
* 1. Fields used to query the data-source are available through a where argument
* 2. Fields to be updated are available through an update argument
* 3. result fields in query correspond to fields of the data sources.
*
* @api-category CRUDResolvers
*/
export class SingleSourceUpdateOperationResolver<
TCtx extends SourceAwareResolverContext<MappedSingleSourceUpdateOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc extends MappedDataSource,
TArgs extends {},
TResolved
> extends SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved> {
@MemoizeGetter
get queryResolver(): SingleSourceQueryOperationResolver<
SourceAwareResolverContext<any, TSrc, TArgs, any, any>,
TSrc,
MappedSingleSourceQueryOperation<TSrc, TArgs>,
TArgs,
TResolved
> {
const { resolver: _oldResolver, ...mapping } = this.operation.mapping;
const operation = new MappedSingleSourceQueryOperation<TSrc, TArgs>(mapping);
const resolverContext = SourceAwareResolverContext.derive<any, TSrc, TArgs>(
operation,
this.resolverContext.selectedDataSources,
this.resolverContext.source,
this.resolverContext.args,
this.resolverContext.context,
this.resolverContext.resolveInfoRoot,
this.resolverContext.primaryResolveInfoVisitor,
);
const resolver = new SingleSourceQueryOperationResolver<
typeof resolverContext,
TSrc,
typeof operation,
TArgs,
TResolved
>(resolverContext);
resolver.isDelegated = true;
return resolver;
}
get delegatedResolvers(): SourceAwareOperationResolver<any, TSrc, TArgs, TResolved>[] {
return [this.queryResolver];
}
@MemoizeGetter
get aliasHierarchyVisitor() {
return this.queryResolver.getAliasHierarchyVisitorFor(this.rootSource);
}
get rootSource() {
return this.resolverContext.primaryDataSource;
}
get storeParams() {
return pick(this.queryResolver.storeParams, "whereParams");
}
get updateEntityArg() {
const { args } = this.resolverContext;
if (!isPresetUpdateParams(args)) {
throw expectedOverride();
}
let updateEntity = args.update;
const passedArgs = this.operation.args;
if (passedArgs && isPresetUpdateParams(passedArgs)) {
updateEntity = passedArgs.interceptEntity(passedArgs.update) || updateEntity;
}
return updateEntity;
}
get mappedUpdate() {
let mappedUpdate: Dict = {};
const { args } = this.resolverContext;
if (!isPresetUpdateParams(args)) {
throw expectedOverride();
}
forEach(args.update, (val: any, key: string) => {
const field: Maybe<MappedField> = this.rootSource.fields[key];
if (!field)
throw new Error(
`Key ${key} used in update does not correspond to a registered field in data source: ${this.rootSource.mappedName}`,
);
mappedUpdate[field.sourceColumn!] = val;
});
return mappedUpdate;
}
private async resolvePrimaryKeyValues() {
await this.queryResolver.resolve();
const pkVals = this.extractPrimaryKeyValues(
this.queryResolver.primaryFieldMappers,
this.queryResolver.resultRows!,
);
if (pkVals.length === 0) {
throw new Error("Refusing to execute unbounded update operation");
}
return pkVals;
}
async resolve(): Promise<any> {
let primaryKeyValues: Dict[];
const result = await this.wrapInTransaction(async () => {
this.queryResolver.resolveFields(
[],
this.aliasHierarchyVisitor,
this.rootSource,
this.resolverContext.primaryResolveInfoVisitor,
);
primaryKeyValues = await this.resolvePrimaryKeyValues();
let queryBuilder = this.createRootQueryBuilder(this.rootSource);
this.queryByPrimaryKeyValues(queryBuilder, primaryKeyValues!);
queryBuilder = this.queryResolver.operation.interceptQueryByArgs(queryBuilder, this.resolverContext.args);
if (this.operation.singular) queryBuilder.limit(1);
if (this.supportsReturning) queryBuilder.returning(this.rootSource.storedColumnNames);
const results = await queryBuilder.clone().update<Dict[]>(this.mappedUpdate);
if (this.supportsReturning) return this.rootSource.mapRowsToShallowEntities(results);
const fetchedRows = await queryBuilder.select(this.rootSource.storedColumnNames);
const mappedRows = this.rootSource.mapRowsToShallowEntities(fetchedRows);
return mappedRows;
});
NotificationDispatcher.publish([
{
type: NotificationDispatcher.PrimitiveMutationType.Update,
entities: {
[this.rootSource.mappedName]: this.rootSource.mapRowsToShallowEntities(primaryKeyValues!),
},
},
]);
return result;
}
}
<file_sep>/src/BaseResolver.ts
import * as Knex from "knex";
import { expectedOverride } from "./utils/errors";
import { OperationResolver } from "./OperationResolver";
import { ResolverContext } from "./ResolverContext";
import { MappedOperation } from ".";
export interface BaseStoreParams {
queryBuilder: Knex.QueryBuilder;
}
/**
* Base class for operation resolvers that need to interact with one or more mapped data sources
*
* @api-category CRUDResolvers
*/
export class BaseResolver<TCtx extends ResolverContext<MappedOperation<TArgs>, TArgs>, TArgs extends {}, TResolved>
implements OperationResolver<TCtx, TArgs, TResolved> {
/**
* If false, then the operation was triggered directly from the GraphQL
* API.
*
* If false, then another operation delegated to this operation.
*/
isDelegated: boolean | undefined;
constructor(public resolverContext: TCtx) {}
/**
* Parsed arguments received from the API client
*/
get args() {
return this.resolverContext.args;
}
/**
* Should be overriden in sub-class with the logic of resolution
*/
async resolve(): Promise<any> {
throw expectedOverride();
}
/**
* The operation being resolved
*
* @type MappedOperation
*/
get operation(): TCtx["MappedOperationType"] {
return this.resolverContext.operation;
}
/**
* Can be overriden to return a collection of resolver instances that we are delegating to.
*
* This is required for sharing the same transactions across the root resolver and all the
* delegated resolvers
*/
get delegatedResolvers(): OperationResolver<TCtx, TArgs, TResolved>[] {
return [];
}
/**
* Get name of current operation
*/
get name() {
return this.resolverContext.operation.name;
}
}
<file_sep>/src/docs/components/Sidebar.js
import React from "react";
import styled from "styled-components";
import { Link, TrailingIcon } from "../components/Link";
import LibInfoBanner from "../components/LibInfoBanner";
import DynamicTableOfContents from "../components/DynamicTableOfContents";
export const Sidebar = ({ children }) => (
<>
<LibInfoBanner />
<Link href="api-docs" highlighted>
<TrailingIcon>→</TrailingIcon>
API
</Link>
<Link href="#quick-start"><Bolt/>Quick Start</Link>
<Link href="playground" >
<Bolt/>Playground (New)
</Link>
<Link href="faqs"><Bolt/>Frequently Asked Questions</Link>
<Link href="guides">
<SectionHeader>Guides</SectionHeader>
</Link>
<Link href="mapping-data-sources"><Bolt/>Mapping Data Sources</Link>
<Link href="mapping-operations"><Bolt/>Mapping Operations</Link>
<Link href="mapping-associations"><Bolt/>Mapping Associations</Link>
<Link href="stored-procedures"><Bolt/>Stored Procedures</Link>
<Link href="subscriptions"><Bolt/>Subscriptions</Link>
<Link href="best-practices"><Bolt/>Best Practices</Link>
<SectionHeader>Additional Topics</SectionHeader>
<Link href="type-safety"><Bolt/>Type Safety</Link>
<Link href="comparision-with-alternatives"><Bolt/>Comparision With Alternatives</Link>
<Link href="architecture-overview"><Bolt/>Architecture Overview</Link>
<DynamicTableOfContents />
{children}
</>
);
export const SidebarContainer = styled.div`
background: #fff;
padding: 10px 30px 30px 30px;
a,
a:visited {
display: block;
color: #000;
font-weight: 700;
margin-top: 5px;
text-decoration: none;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: 0.75rem !important;
font-weight: 600;
}
`;
export const FixedSidebarContainer = styled(SidebarContainer)`
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: 300px;
overflow-y: auto;
overflow-x: auto;
border-right: 1px solid #bbb;
box-shadow: 0 0 20px #ccc;
border-top: 4px solid #8dd35f;
`;
export const SectionHeader = styled.h1`
background: #dee9d8;
padding: 5px 10px;
text-transform: uppercase;
border-radius: 4px;
color: gray;
font-size: 0.75rem;
margin: 1.6rem 0;
`;
export const Bolt = styled((props) => <span {...props}>⚡</span>)`
margin-right: 5px;
`
<file_sep>/src/SourceAwareResolverContext.ts
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
import * as Knex from "knex";
import { MappedDataSource } from "./MappedDataSource";
import { ResolverContext } from "./ResolverContext";
import { MultiSelection, TypeGuard, Maybe } from "./utils/util-types";
import { GraphQLResolveInfo } from "graphql";
import { isArray, uniq } from "lodash";
import { MaybePaginatedResolveInfoVisitor, PaginatedResolveInfoVisitor } from "./PaginatedResolveInfoVisitor";
import { MemoizeGetter } from "./utils/utils";
import assert = require("assert");
import { ResolveInfoVisitor } from "./ResolveInfoVisitor";
import { getTypeAccessorError } from "./utils/errors";
export class SourceAwareResolverContext<
TMappedOperation extends MappedSourceAwareOperation<TDataSource, TGQLArgs>,
TDataSource extends MappedDataSource,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any
> extends ResolverContext<TMappedOperation, TGQLArgs, TGQLSource, TGQLContext> {
static async create<
TMappedOperation extends MappedSourceAwareOperation<TSrc, TGQLArgs>,
TSrc extends MappedDataSource,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any
>(
operation: TMappedOperation,
dataSources: MultiSelection<TSrc, ResolverContext<TMappedOperation, TGQLArgs, TGQLSource, TGQLContext>>,
source: TGQLSource,
args: TGQLArgs,
context: TGQLContext,
resolveInfoRoot: GraphQLResolveInfo,
resolveInfoVisitor?: MaybePaginatedResolveInfoVisitor<TSrc, any>,
) {
const resolverContext = new SourceAwareResolverContext(
operation,
dataSources,
source,
args,
context,
resolveInfoRoot,
resolveInfoVisitor,
);
return resolverContext.init();
}
static derive<
TMappedOperation extends MappedSourceAwareOperation<TDataSource, TGQLArgs>,
TDataSource extends MappedDataSource,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any
>(
operation: TMappedOperation,
dataSources: Array<{ dataSource: TDataSource }>,
source: TGQLSource,
args: TGQLArgs,
context: TGQLContext,
resolveInfoRoot: GraphQLResolveInfo,
resolveInfoVisitor?: MaybePaginatedResolveInfoVisitor<TDataSource, any>,
) {
const resolverContext = new SourceAwareResolverContext(
operation,
dataSources,
source,
args,
context,
resolveInfoRoot,
resolveInfoVisitor,
);
return resolverContext;
}
readonly selectedDataSources: Array<{ dataSource: TDataSource }> = [];
private constructor(
public operation: TMappedOperation,
private dataSources:
| MultiSelection<
TDataSource,
SourceAwareResolverContext<TMappedOperation, TDataSource, TGQLArgs, TGQLSource, TGQLContext>
>
| Array<{ dataSource: TDataSource }>,
public source: TGQLSource,
public args: TGQLArgs,
public context: TGQLContext,
public resolveInfoRoot: GraphQLResolveInfo,
private _resolveInfoVisitor?: MaybePaginatedResolveInfoVisitor<TDataSource, any>,
) {
super(operation, source, args, context, resolveInfoRoot);
if ((isArray as TypeGuard<Array<{ dataSource: TDataSource }>>)(this.dataSources)) {
this.selectedDataSources.push(...this.dataSources);
}
}
async init() {
await this.identifySelectedDataSources();
return this;
}
private async identifySelectedDataSources() {
assert(this.selectedDataSources.length === 0, "Applicable data sources have already been identified");
for (const [, { selection, shouldUse, ...restParams }] of Object.entries(this.dataSources)) {
if (!shouldUse || (await shouldUse(this))) {
this.selectedDataSources.push({
dataSource: selection(),
...restParams,
});
if (!this.operation.supportsMultipleDataSources) break;
}
}
Object.freeze(this.selectedDataSources);
}
get primaryDataSource() {
const numSources = this.selectedDataSources.length;
if (numSources === 1) {
return this.selectedDataSources[0].dataSource;
}
if (numSources == 0) {
throw new Error("No dataSources available");
}
throw new Error(`Cannot identify singular primary data source among ${numSources} selected`);
}
@MemoizeGetter
get primaryPaginatedResolveInfoVisitor(): Maybe<PaginatedResolveInfoVisitor<TDataSource, any>> {
if (!this.operation.paginationConfig) return null;
if (this._resolveInfoVisitor) {
if (!(this._resolveInfoVisitor instanceof PaginatedResolveInfoVisitor)) {
throw new Error("Expected provided resolveInfoVisitor to be instance of PaginatedResolveInfoVisitor");
}
return this._resolveInfoVisitor;
}
return new PaginatedResolveInfoVisitor(this.resolveInfoRoot, this.primaryDataSource);
}
@MemoizeGetter
get primaryResolveInfoVisitor(): ResolveInfoVisitor<TDataSource, any> {
if (this.operation.paginationConfig) {
return this.primaryPaginatedResolveInfoVisitor!.visitPage();
}
if (this._resolveInfoVisitor) {
if (!(this._resolveInfoVisitor instanceof ResolveInfoVisitor)) {
throw new Error("Expected provided resolveInfoVisitor to be instance of ResolveInfoVisitor");
}
return this._resolveInfoVisitor;
}
return new ResolveInfoVisitor<TDataSource, any>(this.resolveInfoRoot, this.primaryDataSource);
}
get connectors(): Knex[] {
return uniq(this.selectedDataSources.map(({ dataSource }) => dataSource.connector));
}
get DataSourceType(): TDataSource {
throw getTypeAccessorError("DataSourceType", "ResolverContext");
}
}
<file_sep>/src/AssociationMapping.ts
import * as t from "io-ts";
import { has } from "lodash";
import { isFunction } from "util";
import { MappedAssociation } from "./MappedAssociation";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation";
import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation";
import { SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver";
import { PaginationConfigRT, PaginationConfig } from "./PaginationConfig";
import { JoinBuilder } from "./utils/JoinBuilder";
import { PartialDeep } from "./utils/util-types";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
/**
* In a composite multi-step operations, we can resolve operations over associations as mapped foreign operation in another data source
*
* Internally there is not much difference between a directly exposed data source and an operation which happens as a part of another multi-step composite operation
*
* MappedForeignOperation couples an operation as well as the arguments needed to invoke that operation.
*
* @api-category ConfigType
*/
export interface MappedForeignOperation<M extends MappedSingleSourceOperation<any, any>> {
operation: M;
args: M["ArgsType"];
}
/**
* Runtime type representing union of constants representing different join types
*
* @api-category ConfigType
*/
export const JoinRT = t.union(
[
t.literal("innerJoin"),
t.literal("leftJoin"),
t.literal("leftOuterJoin"),
t.literal("rightOuterJoin"),
t.literal("rightJoin"),
t.literal("outerJoin"),
t.literal("fullOuterJoin"),
t.literal("crossJoin"),
],
"Join",
);
/**
* @api-category ConfigType
*/
export type JoinTypeId = t.TypeOf<typeof JoinRT>;
/**
* @api-category ConfigType
*/
export const AssociationJoinConfigRT = t.type(
{
join: t.union([JoinRT, t.Function]),
},
"AssociationJoinConfig",
);
/**
* @api-category ConfigType
*/
export interface AssociationJoinConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource>
extends t.TypeOf<typeof AssociationJoinConfigRT> {
join: JoinTypeId | ((joinBuilder: JoinBuilder) => JoinBuilder);
}
/**
* @api-category ConfigType
*/
export const AssociationPreFetchConfigRT = t.intersection(
[
t.type({
preFetch: t.Function,
}),
t.partial({
associateResultsWithParents: t.Function,
}),
],
"AssociationPreFetchConfig",
);
/**
* @api-category ConfigType
*/
export interface AssociationPreFetchConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource>
extends t.TypeOf<typeof AssociationPreFetchConfigRT> {
preFetch: <
TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>,
TRootSrc extends MappedDataSource<any>,
TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any,
TResolved = any
>(
this: MappedAssociation<TSrc, TTgt>,
operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>,
) => MappedForeignOperation<MappedSingleSourceOperation<TTgt, any>>;
associateResultsWithParents?: (
this: MappedAssociation<TSrc, TTgt>,
parents: PartialDeep<TSrc["EntityType"]>[],
results: PartialDeep<TTgt["EntityType"]>[],
) => void;
}
/**
* @api-category ConfigType
*/
export const AssociationPostFetchConfigRT = t.intersection(
[
t.type({
postFetch: t.Function,
}),
t.partial({
associateResultsWithParents: t.Function,
}),
],
"AssociationPostFetchConfig",
);
/**
* @api-category ConfigType
*/
export interface AssociationPostFetchConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource>
extends t.TypeOf<typeof AssociationPostFetchConfigRT> {
postFetch: <
TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>,
TRootSrc extends MappedDataSource<any>,
TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any,
TResolved = any
>(
this: MappedAssociation<TSrc, TTgt>,
operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>,
parents: PartialDeep<TSrc["EntityType"]>[],
) => MappedForeignOperation<MappedSingleSourceOperation<TTgt, any>>;
associateResultsWithParents?: (
this: MappedAssociation<TSrc, TTgt>,
parents: PartialDeep<TSrc["EntityType"]>[],
results: PartialDeep<TTgt["EntityType"]>[],
) => void;
}
/**
* @api-category ConfigType
*/
export const AssociationFetchConfigRT = t.intersection(
[
t.union([AssociationPreFetchConfigRT, AssociationPostFetchConfigRT, AssociationJoinConfigRT]),
t.partial({
useIf: t.Function,
}),
],
"AssociationFetchConfig",
);
/**
* @api-category ConfigType
*/
export type AssociationFetchConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource> = (
| AssociationJoinConfig<TSrc, TTgt>
| AssociationPreFetchConfig<TSrc, TTgt>
| AssociationPostFetchConfig<TSrc, TTgt>
) & {
useIf?: <
TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>,
TRootSrc extends MappedDataSource<any>,
TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>,
TGQLArgs extends {},
TGQLSource = any,
TGQLContext = any,
TResolved = any
>(
this: MappedAssociation<TSrc, TTgt>,
operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>,
) => boolean;
};
export function isPreFetchConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource>(
config: any,
): config is AssociationPreFetchConfig<TSrc, TTgt> {
return isFunction(config.preFetch);
}
export function isPostFetchConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource>(
config: any,
): config is AssociationPostFetchConfig<TSrc, TTgt> {
return isFunction(config.postFetch);
}
export function isJoinConfig<TSrc extends MappedDataSource, TTgt extends MappedDataSource>(
config: any,
): config is AssociationJoinConfig<TSrc, TTgt> {
return has(config, "join");
}
/**
* @api-category ConfigType
*/
export const AssociationMappingRT = t.intersection(
[
t.type({
target: t.Function,
fetchThrough: t.array(AssociationFetchConfigRT),
}),
t.partial({
description: t.string,
singular: t.boolean,
exposed: t.boolean,
associatorColumns: t.type({
inSource: t.string,
inRelated: t.string,
}),
paginate: PaginationConfigRT,
}),
],
"AssociationMapping",
);
/**
* Configuration used to map an association.
*
* Association mapping determines how two data sources can be linked (through joins, or auxiliary queries) so
* that operations can be performed over multiple data sources.
*
* @api-category ConfigType
*/
export interface AssociationMapping<TSrc extends MappedDataSource = any, TTgt extends MappedDataSource = any>
extends t.TypeOf<typeof AssociationMappingRT> {
target: (this: MappedAssociation<TSrc, TTgt>) => TTgt;
description?: string;
singular?: boolean;
associatorColumns?: {
inSource: string;
inRelated: string;
};
fetchThrough: AssociationFetchConfig<TSrc, TTgt>[];
paginate?: PaginationConfig;
}
<file_sep>/src/docs/pages/guides.md
import {Link} from "../components/Link";
# Welcome
This series of posts is a guided tour of GRelDAL. Please go through the <Link href="#quick-start">Quick Start</Link> first if you haven't already.
After walking through the guides, you will develop a good operational familiarity with GRelDAL. These guides cover all important features of GRelDAL in reasonable detail. For more granular aspects you are encouraged to checkout the <Link href="api">API docs</Link> and the [source code](https://github.com/gql-dal/greldal).
If you are looking for a quick solution to a problem you may checkout the <Link>FAQs</Link>.
## Sections
<h3><Link>Mapping Data Sources</Link></h3>
This briefly covers what a data source is, and how it relates to concepts in RDBMS and GraphQL. Going through this guide will enable you to understand how GRelDAL maps from database tables to GraphQL types and how this mapping can be configured for various use cases.
<Link href="mapping-data-sources">Read More...</Link>
<h3><Link>Mapping Operations</Link></h3>
Data sources are not useful in themselves. They are useful only if we can perform some operations on them. These operations enable us to query the database, save and update information and delete information we don't need.
This guide covers usage of operation presets which enable us to quickly setup CRUD operations and then delve deeper into custom operations which can contain complex business logic.
<Link href="mapping-operations">Read More...</Link>
<h3><Link>Mapping Associations</Link></h3>
Much of the power of relational databases comes from establishing constraints between databases and perform operations on multiple tables at ones using joins. This guide covers how we can take advantage of GRelDAL's powerful association mapping capabilities to take advantages of these features.
<Link href="mapping-associations">Read More...</Link>
<h3><Link>Best Practices</Link></h3>
This section contains some closing notes around best practices when developing data driven GraphQL APIs.
<Link href="best-practices">Read More...</Link>
<file_sep>/src/__specs__/integration.spec.ts
import { graphql, GraphQLID, GraphQLSchema, printSchema } from "graphql";
import Knex from "knex";
import { has, map, sortBy } from "lodash";
import {
mapArgs,
mapDataSource,
MappedMultiSourceUnionQueryOperation,
MappedSingleSourceQueryOperation,
mapSchema,
operationPresets,
SingleSourceQueryOperationResolver,
useDatabaseConnector,
mapFields,
mapAssociations,
types,
} from "..";
import { setupDepartmentSchema, teardownDepartmentSchema } from "./helpers/setup-department-schema";
import { setupKnex } from "./helpers/setup-knex";
import { MappedDataSource } from "../MappedDataSource";
import { getCount } from "./knex-helpers";
import { removeErrorCodes } from "./helpers/snapshot-sanitizers";
import {
setupUserSchema,
teardownUserSchema,
mapUsersDataSource,
insertFewUsers,
mapUsersDataSourceWithJSONFields,
} from "./helpers/setup-user-schema";
import { Maybe } from "../utils/util-types";
let knex: Knex;
jest.setTimeout(30000);
describe("Integration scenarios", () => {
beforeAll(() => {
knex = setupKnex();
useDatabaseConnector(knex);
});
afterAll(async () => {
await knex.destroy();
});
describe("Conventionally mapped data source", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSource();
schema = mapSchema(operationPresets.defaults(users));
});
afterAll(async () => {
await teardownUserSchema(knex);
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("singular query operation without params", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: {}) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("singular query operation with params", async () => {
const r2 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
name
}
}
`,
);
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
test("singular query operation for non-existent row", async () => {
const r3 = await graphql(
schema,
`
query {
findOneUser(where: { id: 10 }) {
id
name
}
}
`,
);
expect(r3.errors).not.toBeDefined();
expect(r3.data!.findOneUser).toBeNull();
});
test("batch query operation without args", async () => {
const r4 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
id
name
}
}
`,
);
expect(r4.errors).not.toBeDefined();
expect(r4).toMatchSnapshot();
});
test("batch query operations with arguments", async () => {
const r5 = await graphql(
schema,
`
query {
findManyUsers(where: { id: 1 }) {
id
name
}
}
`,
);
expect(r5.errors).not.toBeDefined();
expect(r5).toMatchSnapshot();
});
});
describe("Conventionally mapped data source with JSON fields", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await setupUserSchema(knex);
await insertFewUsers(knex);
users = mapUsersDataSourceWithJSONFields();
schema = mapSchema(operationPresets.defaults(users));
});
afterAll(async () => {
await teardownUserSchema(knex);
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("singular query operation without params", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: {}) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("singular query operation with params", async () => {
const r2 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
test("batch query operation without args", async () => {
const r4 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r4.errors).not.toBeDefined();
expect(r4).toMatchSnapshot();
});
test("batch query operations with arguments", async () => {
const r5 = await graphql(
schema,
`
query {
findManyUsers(where: { id: 1 }) {
id
name
metadata {
positionsHeld {
title
organization
duration
}
awards {
title
compensation
}
}
}
}
`,
);
expect(r5.errors).not.toBeDefined();
expect(r5).toMatchSnapshot();
});
});
describe("Paginated queries", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await setupUserSchema(knex);
users = mapUsersDataSource();
schema = mapSchema([operationPresets.paginatedFindManyOperation(users)]);
});
afterAll(async () => {
await teardownUserSchema(knex);
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
});
describe("Custom column field mapping", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await knex.schema.createTable("customers", t => {
t.increments("pk");
t.string("first_name");
t.string("last_name");
});
const fields = mapFields({
id: {
sourceColumn: "pk",
type: types.intId,
},
firstName: {
sourceColumn: "first_name",
type: types.string,
},
lastName: {
sourceColumn: "last_name",
type: types.string,
},
});
users = mapDataSource({
name: {
mapped: "User",
stored: "customers",
},
fields,
});
schema = mapSchema(operationPresets.defaults(users));
await knex("customers").insert([
{ pk: 1, first_name: "John", last_name: "Doe" },
{ pk: 2, first_name: "Jane", last_name: "Doe" },
]);
});
afterAll(async () => {
await knex.schema.dropTable("customers");
});
test("generated schema", () => {
expect(printSchema(schema)).toMatchSnapshot();
});
test("singular query operation", async () => {
const r1 = await graphql(schema, "query { findOneUser(where: {}) { id, firstName, lastName }}");
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const r2 = await graphql(schema, "query { findOneUser(where: {id: 2}) { id, firstName, lastName }}");
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
test("batch query operation", async () => {
const r3 = await graphql(schema, "query { findManyUsers(where: {}) { id, firstName, lastName }}");
expect(r3.errors).not.toBeDefined();
expect(r3).toMatchSnapshot();
});
test("custom mapping of arguments", async () => {
const argMapping = mapArgs({
fullName: {
description: "Full name of user",
type: types.string,
interceptQuery: (qb: Knex.QueryBuilder, value: Maybe<string>) => {
if (!value) return qb;
const names = value.split(" ");
return qb.where({
first_name: names[0],
last_name: names[1],
});
},
},
});
const schema = mapSchema([
new MappedSingleSourceQueryOperation({
name: "findUsersByFullName",
rootSource: users,
singular: true,
args: argMapping,
}),
]);
const r3 = await graphql(
schema,
`
query {
findUsersByFullName(fullName: "<NAME>") {
id
firstName
lastName
}
}
`,
);
expect(r3.errors).not.toBeDefined();
expect(r3).toMatchSnapshot();
});
});
describe("Computed fields mapping", () => {
let schema: GraphQLSchema;
beforeAll(async () => {
await knex.schema.createTable("users", t => {
t.increments("id");
t.string("first_name");
t.string("last_name");
t.integer("parent_id")
.unsigned()
.references("id")
.inTable("users");
});
const users: any = mapDataSource({
name: "User",
fields: mapFields({
id: { type: types.intId },
first_name: { type: types.string },
last_name: { type: types.string },
full_name: {
type: types.string,
dependencies: ["first_name", "last_name"],
derive: ({ first_name, last_name }: any) => {
return `${first_name} ${last_name}`;
},
reduce: (row: any, fullName: string) => {
[row.first_name, row.last_name] = fullName.split(" ");
},
},
}),
associations: mapAssociations({
parent: {
target: () => users,
singular: true,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "parent_id",
inRelated: "id",
},
},
children: {
target: () => users,
singular: false,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "id",
inRelated: "parent_id",
},
},
}),
});
schema = mapSchema(operationPresets.query.defaults(users));
await knex("users").insert([
{
id: 1,
first_name: "John",
last_name: "Doe",
},
{
id: 2,
parent_id: 1,
first_name: "Jane",
last_name: "Doe",
},
{
id: 3,
parent_id: 2,
first_name: "John",
last_name: "Delta",
},
]);
});
test("singular query operation", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: {}) {
id
full_name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
test("nested singular query operation", async () => {
const r1 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
first_name
full_name
parent {
id
first_name
last_name
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const r2 = await graphql(
schema,
`
query {
findOneUser(where: { id: 2 }) {
id
first_name
full_name
parent(where: { id: 1 }) {
full_name
children {
id
full_name
children {
id
full_name
}
}
}
}
}
`,
);
expect(r2.errors).not.toBeDefined();
expect(r2).toMatchSnapshot();
});
afterAll(async () => {
await knex.schema.dropTable("users");
});
test("batch query operation", async () => {
const r1 = await graphql(
schema,
`
query {
findManyUsers(where: {}) {
id
first_name
full_name
parent {
id
first_name
last_name
}
children {
id
full_name
}
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
});
});
describe("Multi-source operations", () => {
describe("Union query", () => {
let generatedSchema: GraphQLSchema;
let students: MappedDataSource, staff: MappedDataSource;
beforeAll(async () => {
await knex.schema.createTable("students", t => {
t.increments("id");
t.string("name");
t.integer("completion_year");
});
await knex.schema.createTable("staff", t => {
t.increments("id");
t.string("name");
t.string("designation");
});
await knex("students").insert([
{
name: "ram",
completion_year: 2009,
},
{
name: "abhi",
completion_year: 2010,
},
]);
await knex("staff").insert([
{
name: "rahman",
designation: "Principal",
},
{
name: "akbar",
designation: "Teacher",
},
]);
students = mapDataSource({
name: "Student",
fields: mapFields({
id: {
type: types.intId,
},
name: {
type: types.string,
},
completion_year: {
type: types.number,
},
}),
});
staff = mapDataSource({
name: { stored: "staff", mapped: "Staff" },
fields: mapFields({
id: {
type: types.intId,
},
name: {
type: types.string,
},
designation: {
type: types.string,
},
}),
});
generatedSchema = mapSchema([
new MappedMultiSourceUnionQueryOperation({
dataSources: () => ({
students: {
selection: () => students,
},
staff: {
selection: () => staff,
},
}),
unionMode: "union",
name: `findManyUsers`,
singular: false,
shallow: false,
description: undefined,
}),
]);
});
afterAll(async () => {
await knex.schema.dropTable("students");
await knex.schema.dropTable("staff");
});
test("generated schema", () => {
expect(printSchema(generatedSchema)).toMatchSnapshot();
});
test("batch query operation", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findManyUsers(where: {}) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(sortBy(r1.data!.findManyUsers, "name")).toMatchSnapshot();
});
});
});
describe("Data sources associated by joins", () => {
[
["with primary key", true],
["without primary key", false],
].forEach(([d1, hasPrimaryKey]) => {
describe(d1 as string, () => {
let tags: MappedDataSource, products: MappedDataSource, departments: MappedDataSource;
let generatedSchema: GraphQLSchema;
beforeAll(async () => {
await setupDepartmentSchema(knex);
await knex("tags").insert([{ name: "imported" }, { name: "third-party" }]);
await knex("departments").insert([{ name: "textile" }, { name: "heavy goods" }]);
await knex("products").insert([
{ name: "silk gown", department_id: 1 },
{ name: "steel welding machine", department_id: 2 },
{ name: "harpoon launcher", department_id: 2 },
{ name: "bulldozer", department_id: 2 },
{ name: "tractor", department_id: 2 },
]);
await knex("product_tag_associators").insert([
{ product_id: 1, tag_id: 1 },
{ product_id: 2, tag_id: 2 },
{ product_id: 2, tag_id: 1 },
]);
const fields = mapFields({
id: {
type: types.intId,
isPrimary: hasPrimaryKey ? true : undefined,
},
name: {
type: types.string,
},
});
// @snippet:start mapAssociation_multiJoin_custom
/// import {mapDataSource, mapAssociations} from "greldal";
tags = mapDataSource({
name: "Tag",
fields,
associations: mapAssociations({
products: {
target: () => products,
singular: false,
fetchThrough: [
{
join: joinBuilder =>
joinBuilder
.leftOuterJoin("product_tag_associators", "tag_id", "=", "id")
.leftOuterJoin("products", "id", "=", "product_id"),
},
],
},
}),
});
// @snippet:end
// @snippet:start mapAssociation_leftOuterJoin_default
/// import {mapDataSource, mapAssociations} from "greldal";
products = mapDataSource({
name: "Product",
fields,
associations: mapAssociations({
department: {
target: () => departments,
singular: true,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "department_id",
inRelated: "id",
},
},
}),
});
// @snippet:end
departments = mapDataSource({
name: "Department",
fields,
associations: mapAssociations({
products: {
target: () => products,
singular: false,
fetchThrough: [
{
join: "leftOuterJoin",
},
],
associatorColumns: {
inSource: "id",
inRelated: "department_id",
},
},
}),
});
generatedSchema = mapSchema([
...operationPresets.defaults(tags),
...operationPresets.defaults(departments),
...operationPresets.defaults(products),
]);
});
afterAll(async () => {
await teardownDepartmentSchema(knex);
});
test("generated schema", () => {
expect(printSchema(generatedSchema)).toMatchSnapshot();
});
test("query operations involving auto-inferred binary joins", async () => {
const r1 = await graphql(
generatedSchema,
// @snippet:start mapAssociation_leftOuterJoin_default_query
`
query {
findOneProduct(where: {}) {
id
name
department(where: {}) {
id
name
}
}
}
`,
// @snippet:end
);
expect(r1).toMatchSnapshot();
const r2 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { id: 1 }) {
id
name
products(where: {}) {
id
name
}
}
}
`,
);
expect(r2).toMatchSnapshot();
const r3 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { name: "heavy goods" }) {
id
name
products(where: {}) {
id
name
}
}
}
`,
);
expect(r3).toMatchSnapshot();
});
test("query operations involving user specified complex joins", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findManyTags(where: {}) {
id
name
products(where: {}) {
id
name
}
}
}
`,
);
expect(r1).toMatchSnapshot();
});
});
});
});
describe("Data sources linked by side-loadable associations", () => {
let generatedSchema: GraphQLSchema;
beforeAll(async () => {
await setupDepartmentSchema(knex);
await knex("tags").insert([{ name: "imported" }, { name: "third-party" }]);
await knex("departments").insert([{ name: "textile" }, { name: "heavy goods" }]);
await knex("products").insert([
{ name: "silk gown", department_id: 1 },
{ name: "steel welding machine", department_id: 2 },
]);
await knex("product_tag_associators").insert([
{ product_id: 1, tag_id: 1 },
{ product_id: 2, tag_id: 2 },
{ product_id: 2, tag_id: 1 },
]);
const fields = {
id: {
type: types.intId,
},
name: {
type: types.string,
},
};
// @snippet:start mapAssociation_sideLoading
/// import {mapDataSource, mapAssociations} from "greldal";
const departments = mapDataSource({
name: "Department",
fields: mapFields(fields),
associations: mapAssociations({
products: {
target: () => products,
singular: false,
associatorColumns: {
inSource: "id",
inRelated: "department_id",
},
fetchThrough: [
// We can define multiple side-loading strategies here.
//
// When user queried by id of department, then we don't have to wait for the query on departments to complete
// before we start fetching products. In case of preFetch strategy, these queries can happen in parallel, because
// given the parameters used to query the data source we can start a parallel query to fetch all the products in
// matching departments
{
useIf(operation) {
return has(operation.args, ["where", "id"]);
},
preFetch(operation) {
// What preFetch returns is a MappedForeignOperation - which basically points to another operation
// in the related data source (findManyProducts) and the arguments needed to initiate this operation.
const args: any = operation.args;
const department_id: string = args.where.id;
return {
operation: findManyProducts,
args: {
where: {
department_id,
},
},
};
},
},
// However if the query parameters to departments are not enough to identify which products we need to fetch,
// we can wait for the departments
{
postFetch(_operation, parents) {
// As above, we are instructing GRelDAL to initiate another operation in a foreign data source.
// However, in this case this body will execute once the query on parents has finished. So we have an array of
// fetched parents at our disposal which we can use to identify additional arguments to narrow down the
// subset of products to fetch.
return {
operation: findManyProductsByDepartmentIdList,
args: {
department_ids: map(parents, "id"),
},
};
},
},
],
},
}),
});
// @snippet:end
const products = mapDataSource({
name: "Product",
fields: mapFields({
...fields,
department_id: {
type: types.number,
},
}),
});
const findOneProduct = operationPresets.query.findOneOperation(products);
const findManyProducts = operationPresets.query.findManyOperation(products);
const args = mapArgs({
department_ids: {
type: types.array(types.number),
},
});
const findManyProductsByDepartmentIdList = new MappedSingleSourceQueryOperation({
rootSource: products,
name: `findManyProductsByDepartmentIdList`,
args,
resolver(ctx) {
return new SingleSourceQueryOperationResolver(ctx);
},
rootQuery(_dataSource, args, ahv) {
return products.rootQueryBuilder(ahv).whereIn("department_id", args.department_ids);
},
singular: false,
shallow: false,
description: undefined,
});
generatedSchema = mapSchema([...operationPresets.defaults(departments), findOneProduct, findManyProducts]);
});
afterAll(async () => {
await teardownDepartmentSchema(knex);
});
test("pre-fetch queries", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { id: 1 }) {
id
name
products(where: {}) {
id
name
department_id
}
}
}
`,
);
expect(r1).toMatchSnapshot();
});
test("post-fetch queries", async () => {
const r1 = await graphql(
generatedSchema,
`
query {
findOneDepartment(where: { name: "textile" }) {
id
name
products(where: {}) {
id
name
department_id
}
}
}
`,
);
expect(r1).toMatchSnapshot();
});
});
describe("Mutation Presets", () => {
let users: MappedDataSource, schema: GraphQLSchema;
beforeAll(async () => {
await knex.schema.createTable("users", t => {
t.increments("id");
t.string("name");
t.text("addr");
});
users = mapDataSource({
name: "User",
fields: mapFields({
id: {
type: types.intId,
isPrimary: true,
},
name: {
type: types.string,
},
address: {
type: types.string,
sourceColumn: "addr",
},
}),
});
schema = mapSchema([
...operationPresets.query.defaults(users),
...operationPresets.mutation.defaults(users),
]);
});
afterAll(async () => {
await knex.schema.dropTable("users");
});
describe("Insertion", () => {
describe("Singular", () => {
it("Inserts mapped entity", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertOneUser(
entity: { id: 1, name: "<NAME>", address: "221 B Baker Street" }
) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const numRows = await getCount(knex("users"));
expect(numRows).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertOneUser(
entity: { id: 1, name: "<NAME>", address: "221 B Baker Street" }
) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
describe("Batch", () => {
it("Inserts mapped entities", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertManyUsers(
entities: [
{ id: 2, name: "<NAME>", address: "A B C" }
{ id: 3, name: "<NAME>", address: "A B C" }
]
) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const numRows = getCount(knex("users").whereIn("id", [2, 3]));
expect(numRows).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
insertManyUsers(
entities: [
{ id: 4, name: "<NAME>", address: "A B C" }
{ id: 4, name: "<NAME>", address: "A B C" }
]
) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
});
describe("Update", () => {
beforeEach(async () => {
await knex("users").insert([
{
id: 5,
name: "Ali",
addr: "A B C",
},
{
id: 6,
name: "Ram",
addr: "A B C",
},
]);
});
afterEach(async () => {
await knex("users").del();
});
describe("Singular", () => {
it("Updates mapped entity", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateOneUser(where: { id: 5 }, update: { name: "Rahman" }) {
id
name
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const row = await knex("users").where({ id: 5 });
expect(row).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateOneUser(where: { id: 5 }, update: { id: 6 }) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
describe("Batch", () => {
it("Updates mapped entities", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateManyUsers(where: { address: "A B C" }, update: { address: "D E F" }) {
id
name
address
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const n1 = await getCount(knex("users").where({ addr: "A B C" }));
expect(n1).toMatchSnapshot();
const n2 = await getCount(knex("users").where({ addr: "D E F" }));
expect(n2).toMatchSnapshot();
});
it("surfaces database failues", async () => {
const r1 = await graphql(
schema,
`
mutation {
updateManyUsers(where: { id: 5 }, update: { id: 6 }) {
id
name
}
}
`,
);
expect(r1.errors).toBeDefined();
expect(removeErrorCodes(r1.errors as any)).toMatchSnapshot();
});
});
});
describe("Deletion", () => {
beforeEach(async () => {
await knex("users").insert([
{
id: 11,
name: "Ramesh",
addr: "H J K",
},
{
id: 12,
name: "Akbar",
addr: "H J K",
},
{
id: 13,
name: "Grisham",
addr: "P Q R",
},
{
id: 14,
name: "Gautam",
addr: "P Q R",
},
]);
});
afterEach(async () => {
await knex("users").delete();
});
describe("Singular", () => {
it("Deletes mapped entity", async () => {
const prevCount = await getCount(knex("users"));
const matchCount = await getCount(knex("users").where({ addr: "P Q R" }));
expect(matchCount).toBeGreaterThan(0);
const r1 = await graphql(
schema,
`
mutation {
deleteOneUser(where: { address: "P Q R" }) {
id
name
address
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const count = await getCount(knex("users"));
expect(count).toBe(prevCount - 1);
});
});
describe("Batch", () => {
it("Deletes mapped entities", async () => {
const prevCount = await getCount(knex("users"));
const matchCount = await getCount(
knex("users")
.where({ addr: "H J K" })
.count(),
);
const r1 = await graphql(
schema,
`
mutation {
deleteManyUsers(where: { address: "H J K" }) {
id
name
address
}
}
`,
);
expect(r1.errors).not.toBeDefined();
expect(r1).toMatchSnapshot();
const count = await getCount(knex("users"));
expect(count).toBe(prevCount - matchCount);
});
});
});
});
});
<file_sep>/src/generator/GenConfig.ts
import * as t from "io-ts";
import * as Knex from "knex";
import { MaybeMappedRT } from "../utils/util-types";
import { includes } from "lodash";
const ModuleSpecRT = t.intersection([
t.type({
module: t.string,
imported: t.string,
}),
t.partial({
isDefault: t.boolean,
}),
]);
export type ModuleSpec = t.TypeOf<typeof ModuleSpecRT>;
const InterceptableRT = t.partial({
interceptThrough: ModuleSpecRT,
mergeWith: ModuleSpecRT,
});
export type Interceptable = t.TypeOf<typeof InterceptableRT>;
const SelectionFilterRT = t.union([
t.partial({
only: t.array(t.string),
}),
t.partial({
except: t.array(t.string),
}),
]);
export type SelectionFilter = t.TypeOf<typeof SelectionFilterRT>;
export const matchesSelectionFilter = (entry: string, selectionFilter: SelectionFilter) => {
const sf1 = selectionFilter as { only: string[] };
if (sf1.only) return includes(sf1.only, entry);
const sf2 = selectionFilter as { except: string[] };
if (sf2.except) return !includes(sf2.except, entry);
return true;
};
const InnerMappingConfigRT = <T extends t.Mixed>(memberType: T) =>
t.intersection([
SelectionFilterRT,
t.partial({
members: t.record(t.string, t.intersection([InterceptableRT, memberType])),
}),
]);
const DataSourceMemberGenConfigRT = t.intersection([
InterceptableRT,
t.type({
name: MaybeMappedRT(t.string, t.string),
}),
t.partial({
fields: InnerMappingConfigRT(
t.partial({
sourceColumn: t.string,
}),
),
associations: InnerMappingConfigRT(
t.intersection([
t.partial({
singular: t.boolean,
targetDataSourceName: t.string,
}),
t.partial({
associatedTableName: t.string,
associatorColumns: t.type({
inSource: t.string,
inRelated: t.string,
}),
}),
]),
),
}),
]);
export type DataSourceMemberGenConfig = t.TypeOf<typeof DataSourceMemberGenConfigRT>;
const DataSourceMappingGenConfigRT = t.intersection([
SelectionFilterRT,
t.partial({
transform: t.partial({
dataSourceName: t.Function,
}),
members: t.array(DataSourceMemberGenConfigRT),
}),
]);
export type DataSourceMappingGenConfig = t.TypeOf<typeof DataSourceMappingGenConfigRT>;
export const GenConfigRT = t.partial({
generatedFilePath: t.string,
knex: t.any,
dataSources: DataSourceMappingGenConfigRT,
});
export type GenConfig = t.TypeOf<typeof GenConfigRT> & {
knex?: Knex;
dataSources?: {
transform: {
dataSourceName: (inferredName: string) => string;
};
};
};
<file_sep>/src/__specs__/util-types.spec.ts
import { InstanceOf, IOType } from "../utils/util-types";
import * as t from "io-ts";
import { assertType } from "../utils/assertions";
test("InstanceType", () => {
class User {
constructor(public name: string, public age: number) {}
}
const UserInstance = InstanceOf(User);
const family = t.type({
members: t.array(UserInstance),
address: t.string,
});
const familyInst: t.TypeOf<typeof family> = {
address: "221 B Baker Street",
members: [new User("<NAME>", 30)],
};
const user: t.TypeOf<typeof UserInstance> = {
name: "<NAME>",
age: 10,
};
expect(() => assertType(UserInstance, user, "subject")).toThrowErrorMatchingInlineSnapshot(`
"subject incorrectly specified:
Invalid value {\\"name\\":\\"<NAME>\\",\\"age\\":10} supplied to : Instance<User>"
`);
expect(() => assertType(UserInstance, new User("<NAME>", 30), "subject")).not.toThrowError();
expect(() =>
assertType(
family,
{
members: [new User("<NAME>", 30), new User("<NAME>", 30)],
address: "221 B Baker Street",
},
"subject",
),
).not.toThrowError();
expect(() => assertType(family, {}, "subject")).toThrowErrorMatchingInlineSnapshot(`
"subject incorrectly specified:
Invalid value undefined supplied to : { members: Array<Instance<User>>, address: string }/members: Array<Instance<User>>
Invalid value undefined supplied to : { members: Array<Instance<User>>, address: string }/address: string"
`);
expect(() =>
assertType(
family,
{
address: "221 B Baker Street",
members: [new User("<NAME>", 30), 100],
},
"subject",
),
).toThrowErrorMatchingInlineSnapshot(`
"subject incorrectly specified:
Invalid value 100 supplied to : { members: Array<Instance<User>>, address: string }/members: Array<Instance<User>>/1: Instance<User>"
`);
});
test("IOType", () => {
expect(() => {
assertType(IOType, t.string, "subject");
}).not.toThrow();
expect(() => {
assertType(
IOType,
t.type({
name: t.string,
age: t.number,
}),
"subject",
);
}).not.toThrow();
expect(() => {
assertType(IOType, IOType, "subject");
}).not.toThrow();
});
<file_sep>/src/SourceAwareOperationMapping.ts
import * as t from "io-ts";
import { MappedDataSource } from "./MappedDataSource";
import { OperationMapping, OperationMappingRT } from "./OperationMapping";
import { OperationResolver } from "./OperationResolver";
import { PaginationConfigRT, PaginationConfig } from "./PaginationConfig";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
import { MappedSourceAwareOperation } from "./MappedSourceAwareOperation";
export const SourceAwareOperationMappingRT = t.intersection(
[
OperationMappingRT,
t.partial({
paginate: PaginationConfigRT,
}),
t.type({
name: t.string,
}),
],
"SourceAwareOperationMapping",
);
/**
* @api-category ConfigType
*/
export interface SourceAwareOperationMapping<TSrc extends MappedDataSource, TArgs extends {}>
extends t.TypeOf<typeof SourceAwareOperationMappingRT>,
OperationMapping<TArgs> {
resolver?: <
TCtx extends SourceAwareResolverContext<MappedSourceAwareOperation<TSrc, TArgs>, TSrc, TArgs>,
TResolved
>(
ctx: TCtx,
) => OperationResolver<TCtx, TArgs, TResolved>;
paginate?: PaginationConfig;
name: string;
}
<file_sep>/src/__specs__/notification-dispatcher.spec.ts
import { NotificationDispatcher } from "../universal";
import { noop, sortBy } from "lodash";
describe("NotificationDispatcher", () => {
afterEach(() => {
NotificationDispatcher.resetConfig();
});
test("Single interceptor function", async () => {
const intercepted: any[] = [];
const published = new Promise(resolve => {
NotificationDispatcher.configure({
intercept(n) {
intercepted.push(n);
return n;
},
publish: resolve,
});
});
const notif = {
type: "test",
entities: {},
};
NotificationDispatcher.publish(notif);
await published;
expect(intercepted).toEqual([[notif]]);
});
test("Single interceptor configuration", async () => {
const intercepted: any[] = [];
const delivered: any[] = [];
const published = new Promise(resolve => {
NotificationDispatcher.configure({
intercept: {
type: "test1",
intercept(n) {
intercepted.push(n);
return n;
},
},
publish: n => {
delivered.push(n);
if (n.type == "test2") resolve();
},
});
});
const notif1 = {
type: "test1",
entities: {},
};
const notif2 = {
type: "test2",
entities: {},
};
NotificationDispatcher.publish(notif1);
NotificationDispatcher.publish(notif2);
await published;
expect(intercepted).toEqual([[notif1]]);
expect(sortBy(delivered, "type")).toEqual([notif1, notif2]);
});
test("Chain of interceptors", async () => {
const intercepted: any[] = [[], [], []];
const delivered: any[] = [];
const published = new Promise(resolve => {
NotificationDispatcher.configure({
intercept: [
{
type: "test1",
intercept(n) {
intercepted[0].push(n);
return n;
},
},
{
type: "test1",
source: /^test2*/,
intercept(n) {
intercepted[1].push(n);
return n;
},
},
{
type: /^test2$/,
retainRest: false,
intercept(n) {
intercepted[2].push(n);
return n;
},
},
],
publish: n => {
delivered.push(n);
if (n.type == "test2") resolve();
},
});
});
const notifs = [
{
type: "test1",
entities: {},
},
{
type: "test1",
source: "test2",
entities: {},
},
{
type: "test2",
entities: {},
},
];
notifs.forEach(n => NotificationDispatcher.publish(n));
await published;
expect(intercepted).toMatchInlineSnapshot(`
Array [
Array [
Array [
Object {
"entities": Object {},
"type": "test1",
},
],
Array [
Object {
"entities": Object {},
"source": "test2",
"type": "test1",
},
],
],
Array [],
Array [
Array [
Object {
"entities": Object {},
"type": "test2",
},
],
],
]
`);
expect(delivered).toMatchInlineSnapshot(`
Array [
Object {
"entities": Object {},
"type": "test2",
},
]
`);
});
});
<file_sep>/scripts/deploy-gh-pages.js
const pages = require("gh-pages");
pages.publish("docs", {dotfiles: true}, (err) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log('Deployed site');
})<file_sep>/src/__specs__/helpers/setup-department-schema.ts
import * as Knex from "knex";
import { reportErrors } from "../test-helpers";
export const setupDepartmentSchema = async (knex: Knex) => {
console.log("Setting up department schema: start");
try {
await knex.schema.createTable("tags", t => {
t.increments("id");
t.string("name");
});
await knex.schema.createTable("departments", t => {
t.increments("id");
t.string("name");
});
await knex.schema.createTable("products", t => {
t.increments("id");
t.integer("department_id")
.unsigned()
.references("id")
.inTable("departments")
.notNullable();
t.string("name");
});
await knex.schema.createTable("product_tag_associators", t => {
t.increments("id");
t.integer("product_id")
.unsigned()
.references("id")
.inTable("products")
.notNullable();
t.integer("tag_id")
.unsigned()
.references("id")
.inTable("tags")
.notNullable();
});
} catch (e) {
console.error("Error when setting up departments schea");
console.error(e);
throw e;
}
console.log("Setting up department schema: end");
};
export const teardownDepartmentSchema = async (knex: Knex) => {
await reportErrors(async () => {
await knex.schema.dropTable("product_tag_associators");
await knex.schema.dropTable("products");
await knex.schema.dropTable("departments");
await knex.schema.dropTable("tags");
});
};
<file_sep>/src/utils/utils.ts
import { property } from "lodash";
import { Dict } from "./util-types";
/**
* Creates an object mapping the items of a collection by a property.
*
* @param arr collection of items to be indexed
* @param path property path eg. "foo.bar", "foo[0]"
*/
export const indexBy = <T>(arr: T[], path: string) => {
const prop = property<T, string>(path);
return arr.reduce((result: Dict<T>, item) => {
result[prop(item)] = item;
return result;
}, {}) as Dict<T>;
};
/**
* Decorator for a getter which assigns the result of first invocation of getter as
* the equivalent property of the class
*/
export function MemoizeGetter(_target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const { get } = descriptor;
if (!get) {
throw new Error("MemoizeGetter can only be applied to a getter");
}
descriptor.get = function() {
const value = get.apply(this);
Object.defineProperty(this, propertyKey, { value });
return value;
};
}
<file_sep>/src/MappedSingleSourceUpdateOperation.ts
import { GraphQLFieldConfigArgumentMap, GraphQLNonNull } from "graphql";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceMutationOperation } from "./MappedSingleSourceMutationOperation";
import { SingleSourceUpdateOperationResolver } from "./SingleSourceUpdateOperationResolver";
import { MemoizeGetter } from "./utils/utils";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
/**
* @api-category MapperClass
*/
export class MappedSingleSourceUpdateOperation<
TSrc extends MappedDataSource,
TArgs extends {}
> extends MappedSingleSourceMutationOperation<TSrc, TArgs> {
opType: "mutation" = "mutation";
defaultResolver(
resolverContext: SourceAwareResolverContext<MappedSingleSourceUpdateOperation<TSrc, TArgs>, TSrc, TArgs>,
): SingleSourceUpdateOperationResolver<
SourceAwareResolverContext<MappedSingleSourceUpdateOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc,
TArgs,
any
> {
return new SingleSourceUpdateOperationResolver(resolverContext);
}
@MemoizeGetter
get defaultArgs(): GraphQLFieldConfigArgumentMap {
return {
where: {
type: GraphQLNonNull(this.rootSource.defaultShallowInputType),
},
update: {
type: GraphQLNonNull(this.rootSource.defaultShallowInputType),
},
};
}
}
<file_sep>/src/utils/maybe.ts
import * as t from "io-ts";
import { isNil } from "lodash";
import { Validation } from "io-ts";
import { Maybe } from "./util-types";
export class MaybeType<RT> extends t.Type<Maybe<RT>, any, unknown> {
readonly _tag: "MaybeType" = "MaybeType";
constructor(public type: t.Type<RT>, public name = `Maybe(${type.name})`) {
super(
name,
type.is,
(i: unknown, c: t.Context) => {
if (isNil(i)) return t.success(i as any);
return type.validate(i, c);
},
t.identity,
);
}
decode(input: any): Validation<Maybe<RT>> {
if (isNil(input)) return t.success(input);
return this.type.decode(input);
}
}
export const maybe = <T>(baseType: t.Type<T, any>, name?: string) => new MaybeType<T>(baseType, name);
export const maybeArray = <T>(baseType: t.Type<T, any>, name?: string) => t.union([baseType, t.array(baseType)], name);
<file_sep>/src/__specs__/helpers/setup-knex.ts
import Knex from "knex";
import tmp from "tmp";
import assert from "assert";
import _debug from "debug";
import { Maybe } from "../../utils/util-types";
const debug = _debug("greldal:setup-knex");
export const getConnectionString = () => {
const connectionString = process.env.DB_CONNECTION_STRING;
assert(connectionString, "Expected DB_CONNECTION_STRING environment variable to be defined");
return connectionString;
};
export const setupKnex = () => {
const isCI = process.env.CI === "true" || process.env.CI === "1";
let config: Maybe<Knex.Config>;
const db = process.env.DB;
if (!db || db === "sqlite3") {
const sqliteFile = tmp.fileSync();
config = {
client: "sqlite3",
connection: {
filename: sqliteFile.name,
multipleStatements: true,
},
useNullAsDefault: true,
};
} else if (db === "mysql2") {
if (isCI) {
config = {
client: "mysql2",
connection: {
host: "127.0.0.1",
user: "travis",
database: "greldal_test",
password: "",
},
};
} else {
config = {
client: "mysql2",
connection: getConnectionString(),
};
}
} else if (db === "pg") {
if (isCI) {
config = {
client: "pg",
connection: {
host: "127.0.0.1",
user: "postgres",
database: "greldal_test",
password: "pwd",
},
};
} else {
config = {
client: "pg",
connection: getConnectionString(),
};
}
} else {
throw new Error(`Invalid db selection: ${db}`);
}
debug("Connecting to knex using configuration: %O", config);
assert(config, "Failed to configure database for the test suite. You may need to update above configuration");
return Knex({
...config,
debug: !!process.env.DEBUG,
pool: {
min: 0,
},
});
};
<file_sep>/src/MappedOperation.ts
import { autobind } from "core-decorators";
import _debug from "debug";
import {
GraphQLFieldConfig,
GraphQLFieldConfigArgumentMap,
GraphQLFieldResolver,
GraphQLOutputType,
GraphQLResolveInfo,
} from "graphql";
import { identity, uniqueId, isString } from "lodash";
import { getTypeAccessorError } from "./utils/errors";
import { normalizeResultsForSingularity } from "./graphql-type-mapper";
import { Operation } from "./Operation";
import { OperationMapping } from "./OperationMapping";
import { OperationResolver } from "./OperationResolver";
import { MaybePaginatedResolveInfoVisitor } from "./PaginatedResolveInfoVisitor";
import { ResolverContext } from "./ResolverContext";
import { Interceptor, TypeGuard } from "./utils/util-types";
import { MemoizeGetter } from "./utils/utils";
import { OperationType } from "./operation-types";
const debug = _debug("greldal:MappedOperation");
type FieldConfigInterceptor = Interceptor<GraphQLFieldConfig<any, any, any>>;
/**
* Base class for operations that interact with one or more GRelDAL data sources.
*/
export abstract class MappedOperation<TArgs extends {}> implements Operation {
/**
* Distinguishes whether the operation is a query, mutation or subscription
*/
abstract operationType: OperationType;
/**
* Currently attached operation interceptors
*/
private interceptors: FieldConfigInterceptor[] = [];
private interceptedFieldConfig?: GraphQLFieldConfig<any, any, any>;
constructor(public readonly mapping: OperationMapping<TArgs>) {}
/**
* Default argument mapping for operation
*
* Can be overriden in Operation mapping configuration.
*/
abstract get defaultArgs(): GraphQLFieldConfigArgumentMap;
/**
* GraphQL output type for the result of the operation
*/
abstract get type(): GraphQLOutputType;
/**
* Retrieve default resolver for the operation.
*
* A resolver specified in operation mapping will take precedence
*/
abstract defaultResolver<TResolved>(ctx: any): OperationResolver<any, TArgs, TResolved>;
/**
* Construct resolver context used to instantiate the resolver
*/
async createResolverContext(
source: any,
args: TArgs,
context: any,
resolveInfo: GraphQLResolveInfo,
_resolveInfoVisitor?: MaybePaginatedResolveInfoVisitor<any>,
) {
return new ResolverContext(this, source, args, context, resolveInfo);
}
/**
* GraphQL field configuration used to expose the operation.
*
* This field configuration can be intercepted through a chain of
* interceptors before it surfaces to the GraphQL API.
*/
@MemoizeGetter
get rootFieldConfig(): GraphQLFieldConfig<any, any, TArgs> {
return {
description: this.mapping.description,
args: this.mappedArgs,
type: this.type,
resolve: this.resolve.bind(this),
};
}
/**
* Get final field config after passing the root field configuration
* through a chain of interceptors
*/
get fieldConfig(): GraphQLFieldConfig<any, any, any> {
if (this.interceptedFieldConfig) return this.interceptedFieldConfig;
let fieldConfig = this.rootFieldConfig;
for (const intercept of this.interceptors) {
fieldConfig = intercept.call(this, fieldConfig);
}
this.interceptedFieldConfig = fieldConfig;
return fieldConfig;
}
/**
* Whether the operation interacts with multiple data sources
*/
get supportsMultipleDataSources() {
return false;
}
/**
* Whether multiple resolvers are supported
*/
get supportsMultipleResolvers() {
return false;
}
/**
* Mapped argument specifications for the operation
*/
get mappedArgs(): GraphQLFieldConfigArgumentMap {
if (this.mapping.args) {
return this.mapping.args.getMappedArgsFor(undefined);
}
return this.defaultArgs;
}
/**
* Name of operation
*/
get name() {
const { name } = this.mapping;
return (isString as TypeGuard<string>)(name) ? name : name.mapped;
}
/**
* Whether the operation reaches into connected entities through associations
*/
get shallow() {
return this.mapping.shallow === true;
}
/**
* Whether the operation resolves to a single entity
*/
get singular() {
return this.mapping.singular !== false;
}
/**
* Mapped arguments for the operation
*/
get args() {
return this.mapping.args;
}
/**
* Getter to obtain the Type of arguments at type level.
*
* Throws if invoked at runtime.
*/
get ArgsType(): TArgs {
throw getTypeAccessorError("ArgsType", "MappedOperation");
}
/**
* Attach an interceptor to the current queue of interceptors.
*
* Interceptors can transform how the operation is handled. They can change
* the arguments, add validations, log results before or after resolution
* or entirely bypass the downstream resolution flow.
*
* @param interceptor A function that receives the current field configuration
* and returns a new field configuration.
*/
intercept(interceptor: FieldConfigInterceptor) {
this.interceptedFieldConfig = undefined;
this.interceptors.push(interceptor);
}
/**
* Intercept operation resolution with a higher order function.
*
* Essentially a convenience wrapper over intercept for the common case when
* we care about intercepting just the resolver and not the complete field configuration.
*
* @param interceptor A function that receives the current resolver and returns
* a new resolver which will be called when the operation is invoked.
*
* It is the responsibility of interceptor to invoke the received (old) resolver
* unless a complete bypass is intended.
*/
interceptResolve(interceptor: Interceptor<GraphQLFieldResolver<any, any, TArgs>>) {
this.intercept(fieldConfig => ({
...fieldConfig,
resolve: (...args) => interceptor(fieldConfig.resolve!)(...args),
}));
}
/**
* Clone the operation with an independent queue of interceptors
*
* Unless list of interceptors is specified, the cloned operation will inherit
* current queue of interceptors.
*/
deriveIndependentlyInterceptable(interceptors = [...this.interceptors]): MappedOperation<TArgs> {
return Object.create(this, {
interceptors: {
value: interceptors,
},
});
}
/**
* Retrieve resolver for the operation.
*
* This will typically be the default resolver for the operation, but
* can be overriden in the operation mapping
*/
getResolver(resolverContext: ResolverContext<MappedOperation<TArgs>, any, TArgs>) {
if (this.mapping.resolver) {
return {
resolver: this.mapping.resolver.call(this, resolverContext),
resolverId: `${this.constructor.name}[mapping][resolve]`,
};
} else {
return {
resolver: this.defaultResolver(resolverContext),
resolverId: `${this.constructor.name}[defaultResolve]`,
};
}
}
/**
* Wrap result in array if we are supposed to return multiple values.
* Unwrap result array if singular result is expected.
*
* This enables us to write resolvers (esp. those that will only ever return
* a single entity) that don't care whether result is singular or plural.
*/
normalizeResultsForSingularity(result: any) {
return normalizeResultsForSingularity(result, this.singular, false);
}
/**
*
* @param source
* @param args
* @param context
* @param resolveInfo
* @param resolveInfoVisitor
*/
@autobind
async resolve(
source: any,
args: TArgs,
context: any,
resolveInfo: GraphQLResolveInfo,
resolveInfoVisitor?: MaybePaginatedResolveInfoVisitor<any>,
interceptResolver: Interceptor<OperationResolver<any, TArgs, any>> = identity,
): Promise<any> {
const resolverContext = await this.createResolverContext(
source,
args,
context,
resolveInfo,
resolveInfoVisitor,
);
let result;
let { resolver, resolverId } = this.getResolver(resolverContext);
resolver = interceptResolver(resolver) || resolver;
try {
result = await resolver.resolve();
} catch (e) {
const errorId = uniqueId("GRelDAL:ResolverError:");
console.error(`[${errorId}]`, e);
const error: any = new Error(`[${errorId}] ${resolverId} faulted`);
error.originalError = e;
throw error;
}
debug("Resolved result:", result, this.singular);
const normalizedResult = this.normalizeResultsForSingularity(result);
debug("Normalized result:", normalizedResult);
return normalizedResult;
}
}
<file_sep>/src/MappedSingleSourceInsertionOperation.ts
import { GraphQLFieldConfigArgumentMap, GraphQLList } from "graphql";
import { SingleSourceInsertionOperationResolver } from "./SingleSourceInsertionOperationResolver";
import { MappedDataSource } from "./MappedDataSource";
import { MappedSingleSourceMutationOperation } from "./MappedSingleSourceMutationOperation";
import { MemoizeGetter } from "./utils/utils";
import { ResolverContext } from "./ResolverContext";
import { SourceAwareResolverContext } from "./SourceAwareResolverContext";
/**
* @api-category MapperClass
*/
export class MappedSingleSourceInsertionOperation<
TSrc extends MappedDataSource,
TArgs extends {}
> extends MappedSingleSourceMutationOperation<TSrc, TArgs> {
defaultResolver(
resolverContext: SourceAwareResolverContext<MappedSingleSourceInsertionOperation<TSrc, TArgs>, TSrc, TArgs>,
): SingleSourceInsertionOperationResolver<
SourceAwareResolverContext<MappedSingleSourceInsertionOperation<TSrc, TArgs>, TSrc, TArgs>,
TSrc,
TArgs,
any
> {
return new SingleSourceInsertionOperationResolver(resolverContext);
}
@MemoizeGetter
get defaultArgs(): GraphQLFieldConfigArgumentMap {
if (this.singular) {
return {
entity: {
type: this.rootSource.defaultShallowInputType,
},
};
} else {
return {
entities: {
type: GraphQLList(this.rootSource.defaultShallowInputType),
},
};
}
}
}
|
925e87f925918fd85421b4f04c2e9797f8d8fe63
|
[
"Git Attributes",
"Markdown",
"YAML",
"JavaScript",
"TypeScript"
] | 139 |
Git Attributes
|
gql-dal/greldal
|
9c4f6e22bab961ac8377cfabb751b9f8f1bb7dc5
|
6baf30c0aecc35fdebdc0a80c51d9b50650a428a
|
refs/heads/master
|
<repo_name>eplconnors/kidstravel<file_sep>/app/views/airports/index.json.jbuilder
json.array!(@airports) do |airport|
json.extract! airport, :id, :air_city, :air_country, :air_code, :air_eat, :air_tips, :air_post
json.url airport_url(airport, format: :json)
end
<file_sep>/db/migrate/20160425025451_create_airports.rb
class CreateAirports < ActiveRecord::Migration
def change
create_table :airports do |t|
t.string :air_city
t.string :air_country
t.string :air_code
t.text :air_eat
t.text :air_tips
t.text :air_post
t.timestamps null: false
end
end
end
<file_sep>/app/controllers/city_guides_controller.rb
class CityGuidesController < ApplicationController
before_action :set_city_guide, only: [:show, :edit, :update, :destroy]
# GET /city_guides
# GET /city_guides.json
def index
@city_guides = CityGuide.all
end
# GET /city_guides/1
# GET /city_guides/1.json
def show
end
# GET /city_guides/new
def new
@city_guide = CityGuide.new
end
# GET /city_guides/1/edit
def edit
end
# POST /city_guides
# POST /city_guides.json
def create
@city_guide = CityGuide.new(city_guide_params)
respond_to do |format|
if @city_guide.save
format.html { redirect_to @city_guide, notice: 'City guide was successfully created.' }
format.json { render :show, status: :created, location: @city_guide }
else
format.html { render :new }
format.json { render json: @city_guide.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /city_guides/1
# PATCH/PUT /city_guides/1.json
def update
respond_to do |format|
if @city_guide.update(city_guide_params)
format.html { redirect_to @city_guide, notice: 'City guide was successfully updated.' }
format.json { render :show, status: :ok, location: @city_guide }
else
format.html { render :edit }
format.json { render json: @city_guide.errors, status: :unprocessable_entity }
end
end
end
# DELETE /city_guides/1
# DELETE /city_guides/1.json
def destroy
@city_guide.destroy
respond_to do |format|
format.html { redirect_to city_guides_url, notice: 'City guide was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_city_guide
@city_guide = CityGuide.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def city_guide_params
params.require(:city_guide).permit(:city, :state, :country, :restaurants, :see, :skip, :stay, :tips, :post, :avatar)
end
end
<file_sep>/db/migrate/20160425011436_create_city_guides.rb
class CreateCityGuides < ActiveRecord::Migration
def change
create_table :city_guides do |t|
t.string :city
t.string :state
t.string :country
t.text :restaurants
t.text :see
t.text :skip
t.text :stay
t.text :tips
t.text :post
t.timestamps null: false
end
end
end
<file_sep>/app/views/airports/_form.html.erb
<%= form_for(@airport) do |f| %>
<% if @airport.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@airport.errors.count, "error") %> prohibited this airport from being saved:</h2>
<ul>
<% @airport.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :air_city %><br>
<%= f.text_field :air_city %>
</div>
<div class="field">
<%= f.label :air_country %><br>
<%= f.text_field :air_country %>
</div>
<div class="field">
<%= f.label :air_code %><br>
<%= f.text_field :air_code %>
</div>
<div class="field">
<%= f.label :air_eat %><br>
<%= f.text_area :air_eat %>
</div>
<div class="field">
<%= f.label :air_tips %><br>
<%= f.text_area :air_tips %>
</div>
<div class="field">
<%= f.label :air_post %><br>
<%= f.text_area :air_post %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<file_sep>/app/views/city_guides/index.json.jbuilder
json.array!(@city_guides) do |city_guide|
json.extract! city_guide, :id, :city, :state, :country, :restaurants, :see, :skip, :stay, :tips, :post
json.url city_guide_url(city_guide, format: :json)
end
<file_sep>/app/views/city_guides/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Listing City Guides</h1>
<table>
<thead>
<tr>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Restaurants</th>
<th>See</th>
<th>Skip</th>
<th>Stay</th>
<th>Tips</th>
<th>Post</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @city_guides.each do |city_guide| %>
<tr>
<td><%= city_guide.city %></td>
<td><%= city_guide.state %></td>
<td><%= city_guide.country %></td>
<td><%= city_guide.restaurants %></td>
<td><%= city_guide.see %></td>
<td><%= city_guide.skip %></td>
<td><%= city_guide.stay %></td>
<td><%= city_guide.tips %></td>
<td><%= city_guide.post %></td>
<%= image_tag city_guide.avatar.url(:medium), class: "img-responsive" %>
<td><%= link_to 'Show', city_guide %></td>
<td><%= link_to 'Edit', edit_city_guide_path(city_guide) %></td>
<td><%= link_to 'Destroy', city_guide, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New City guide', new_city_guide_path %>
<file_sep>/app/assets/stylesheets/application.css.erb
/*
*= require_tree .
*= require_self
*/
body{
background-image: url(<%= asset_path "bg.jpeg"%>);
background-size: cover;
}
<file_sep>/test/controllers/city_guides_controller_test.rb
require 'test_helper'
class CityGuidesControllerTest < ActionController::TestCase
setup do
@city_guide = city_guides(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:city_guides)
end
test "should get new" do
get :new
assert_response :success
end
test "should create city_guide" do
assert_difference('CityGuide.count') do
post :create, city_guide: { city: @city_guide.city, country: @city_guide.country, post: @city_guide.post, restaurants: @city_guide.restaurants, see: @city_guide.see, skip: @city_guide.skip, state: @city_guide.state, stay: @city_guide.stay, tips: @city_guide.tips }
end
assert_redirected_to city_guide_path(assigns(:city_guide))
end
test "should show city_guide" do
get :show, id: @city_guide
assert_response :success
end
test "should get edit" do
get :edit, id: @city_guide
assert_response :success
end
test "should update city_guide" do
patch :update, id: @city_guide, city_guide: { city: @city_guide.city, country: @city_guide.country, post: @city_guide.post, restaurants: @city_guide.restaurants, see: @city_guide.see, skip: @city_guide.skip, state: @city_guide.state, stay: @city_guide.stay, tips: @city_guide.tips }
assert_redirected_to city_guide_path(assigns(:city_guide))
end
test "should destroy city_guide" do
assert_difference('CityGuide.count', -1) do
delete :destroy, id: @city_guide
end
assert_redirected_to city_guides_path
end
end
<file_sep>/app/views/city_guides/_form.html.erb
<%= form_for(@city_guide) do |f| %>
<% if @city_guide.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@city_guide.errors.count, "error") %> prohibited this city_guide from being saved:</h2>
<ul>
<% @city_guide.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.text_field :city, class: "form-control", placeholder: "the city you visited!" %>
</div>
<div class="form-group">
<%= f.text_field :state, class: "form-control", placeholder: "state" %>
</div>
<div class="form-group">
<%= f.text_field :country, class: "form-control", placeholder: "country" %>
</div>
<div class="form-group">
<%= f.text_area :restaurants, class: "form-control", placeholder: "Please list any restaurants you recommend. Let us know why!" %>
</div>
<div class="form-group">
<%= f.text_area :see, class:"form-control", placeholder: "What are your must sees? What did your kids AND you love? Museums, parks, monuments etc." %>
</div>
<div class="form-group">
<%= f.text_area :skip, class: "form-control", placeholder: "What should others in your shoes skip? A kids museum that was overatted? List anything you would include in your trip nightmare journal" %>
</div>
<div class="form-group">
<%= f.text_area :stay, class: "form-control", placeholder: "Where did you stay? Would you stay again? Any cons?" %>
</div>
<div class="form-group">
<%= f.text_area :tips, class: "form-control", placeholder: "Any additional tips? transportation while visiting, gyms, nightlife" %>
</div>
<div class="form-group">
<%= f.text_area :post, class:"form-control", placeholder: "Tell us about your trip! Share a special moment with your family? Learn something new? We want to know about it!"%>
</div>
<div class="field form-group">
<%= f.label "Photos" %><br>
<%= f.file_field :avatar %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<file_sep>/test/controllers/tips_controller_test.rb
require 'test_helper'
class TipsControllerTest < ActionController::TestCase
test "should get infant" do
get :infant
assert_response :success
end
test "should get toddler" do
get :toddler
assert_response :success
end
test "should get kids" do
get :kids
assert_response :success
end
test "should get teens" do
get :teens
assert_response :success
end
end
<file_sep>/app/views/city_guides/show.html.erb
<p id="notice"><%= notice %></p>
<p>
<strong>City:</strong>
<%= @city_guide.city %>
</p>
<p>
<strong>State:</strong>
<%= @city_guide.state %>
</p>
<p>
<strong>Country:</strong>
<%= @city_guide.country %>
</p>
<p>
<strong>Restaurants:</strong>
<%= @city_guide.restaurants %>
</p>
<p>
<strong>See:</strong>
<%= @city_guide.see %>
</p>
<p>
<strong>Skip:</strong>
<%= @city_guide.skip %>
</p>
<p>
<strong>Stay:</strong>
<%= @city_guide.stay %>
</p>
<p>
<strong>Tips:</strong>
<%= @city_guide.tips %>
</p>
<p>
<strong>Post:</strong>
<%= @city_guide.post %>
</p>
<%= image_tag @city_guide.avatar.url (:medium) %>
<%= link_to 'Edit', edit_city_guide_path(@city_guide) %> |
<%= link_to 'Back', city_guides_path %>
<file_sep>/app/controllers/tips_controller.rb
class TipsController < ApplicationController
def infant
end
def toddler
end
def kids
end
def teens
end
end
<file_sep>/app/views/airports/show.html.erb
<p id="notice"><%= notice %></p>
<p>
<strong>Air city:</strong>
<%= @airport.air_city %>
</p>
<p>
<strong>Air country:</strong>
<%= @airport.air_country %>
</p>
<p>
<strong>Air code:</strong>
<%= @airport.air_code %>
</p>
<p>
<strong>Air eat:</strong>
<%= @airport.air_eat %>
</p>
<p>
<strong>Air tips:</strong>
<%= @airport.air_tips %>
</p>
<p>
<strong>Air post:</strong>
<%= @airport.air_post %>
</p>
<%= link_to 'Edit', edit_airport_path(@airport) %> |
<%= link_to 'Back', airports_path %>
<file_sep>/app/views/airports/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Listing Airports</h1>
<table>
<thead>
<tr>
<th>Air city</th>
<th>Air country</th>
<th>Air code</th>
<th>Air eat</th>
<th>Air tips</th>
<th>Air post</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @airports.each do |airport| %>
<tr>
<td><%= airport.air_city %></td>
<td><%= airport.air_country %></td>
<td><%= airport.air_code %></td>
<td><%= airport.air_eat %></td>
<td><%= airport.air_tips %></td>
<td><%= airport.air_post %></td>
<td><%= link_to 'Show', airport %></td>
<td><%= link_to 'Edit', edit_airport_path(airport) %></td>
<td><%= link_to 'Destroy', airport, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Airport', new_airport_path %>
<file_sep>/app/views/city_guides/edit.html.erb
<h1>Editing City Guide</h1>
<%= render 'form' %>
<%= link_to 'Show', @city_guide %> |
<%= link_to 'Back', city_guides_path %>
|
e44f7d2456e498349c52436ec3df6c255f5fd8fc
|
[
"HTML+ERB",
"Ruby"
] | 16 |
HTML+ERB
|
eplconnors/kidstravel
|
71e7375c23518da66889e93b6eb1efbf621d3574
|
e355f3c3a31ac2989284d18ba2a6a42b3f90b25d
|
refs/heads/master
|
<repo_name>fikriyusra44/belajar<file_sep>/src/main/java/com/belajar/spring/service/KrsService.java
package com.belajar.spring.service;
import com.belajar.spring.entity.KRS;
public interface KrsService extends BaseService<KRS> {
}
|
dcea59ccb37566c7aae0ba60a09f1ab7aca90ffc
|
[
"Java"
] | 1 |
Java
|
fikriyusra44/belajar
|
d005b37250f5a81dee0beaba873d009648de7170
|
0d03d901225bd4b15c30a23e060a671b33a3d89d
|
refs/heads/master
|
<file_sep>import keras
import numpy as np
import matplotlib as mt
from keras import backend as K
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Dropout
from keras.datasets import cifar10
from keras.optimizers import Adam
from keras.utils import np_utils
from keras.layers.convolutional import Conv2D, AveragePooling2D, MaxPooling2D
from keras.utils import plot_model
# mt.use('TkAgg') # Segmentation issue with MacOS
K.set_image_dim_ordering('tf')
# loading input data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
num_train, dep, rows, cols = x_train.shape
num_test, _, _, _ = x_test.shape
num_classes = len(np.unique(y_train))
# normalization
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255
# convert to class labels
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
def build_model(size):
# build the model
model = Sequential()
model.add(Conv2D(6, (size, size), padding='same', input_shape=x_train.shape[1:]))
model.add(AveragePooling2D(pool_size=(2, 2)))
model.add(Activation("sigmoid"))
# Trial Alternatives:
# model.add(Activation("relu"))
# model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.25))
model.add(Conv2D(16, (size, size), padding='same'))
model.add(AveragePooling2D(pool_size=(2, 2)))
model.add(Activation("sigmoid"))
# Trial Alternatives (continued):
# model.add(Activation("relu"))
# model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.25))
model.add(Conv2D(120, (size, size), padding='same'))
model.add(Flatten())
model.add(Dense(84))
model.add(Activation("sigmoid"))
model.add(Dense(10))
model.add(Activation('softmax'))
adam = Adam(lr=0.0003)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test), verbose=1)
return model, history
# method to extract the 6 filters of the first layer
def extract_1stL(model):
w = model.layers[0].get_weights()
x, y, z, num_filters = w[0].shape
fig, axes = plt.subplots(ncols=6, figsize=(6, 6))
for f in range(num_filters):
grid = [[[w[0][i][j][k][f] for k in range(z)] for j in range(y)] for i in range(x)]
axes[f].imshow(grid)
plt.show()
plt.close(fig)
# method to plot training/validation curves using pyplot
def plot_history(train_value, test_value, s):
f, axes = plt.subplots()
axes.plot(train_value, 'o-', label="Training score")
axes.plot(test_value, 'x-', label="Validation score")
axes.legend(loc = 0)
axes.set_title('Training/Validation ' + s + ' per Epoch')
axes.set_xlabel('Epoch')
axes.set_ylabel(s)
# initialize the model, plot curves and extract filters
def init(sz):
model, history = build_model(sz)
test = model.evaluate(x_test, y_test, verbose=1)
print "\nTest loss:", str(test[0])
print "Test accuracy:", str(test[1])
plot_history(history.history['loss'], history.history['val_loss'], 'Loss')
plot_history(history.history['acc'], history.history['val_acc'], 'Accuracy')
extract_1stL(model)
# Net 1
init(5)
# Net 2
init(11)
|
a3ba6e50f162381afba7c264af93ed7cf5583dea
|
[
"Python"
] | 1 |
Python
|
HodaHisham/DL_TestTask
|
896282abe95916c493136fa20b34ff28d7a159d4
|
fc32467098d809dce992e25c3a9364c85c30ecf7
|
refs/heads/master
|
<repo_name>infhyroyage/PIUSubjectChart<file_sep>/app/src/main/java/com/subject/piu/CommonParams.java
package com.subject.piu;
/**
* 全パッケージの共通パラメータを定義する抽象staticクラス
*/
public abstract class CommonParams {
/**
* 以下で定義される、メイン画面のタブの数
* ・難易度
* ・タイプ
* ・シリーズ
* ・カテゴリー
* ・その他
*/
public static final int TAB_PAGE_NUM = 5;
/**
* 現行稼働のSingle譜面の最高難易度
*/
private static final int MAX_SINGLE_DIFFICULTY = 26;
/**
* 「難易度」のSingle譜面のチェック状態
*/
public static boolean[] singleChecks = new boolean[MAX_SINGLE_DIFFICULTY];
/**
* 現行稼働のDouble譜面の最高難易度
*/
private static final int MAX_DOUBLE_DIFFICULTY = 28;
/**
* 「難易度」のSingle譜面のチェック状態
*/
public static boolean[] doubleChecks = new boolean[MAX_DOUBLE_DIFFICULTY];
/**
* 「難易度」のCOOP譜面のチェック状態
*/
public static boolean coopCheck = false;
/**
* 「タイプ」の種類
*/
public static final String[] TYPES = {
"Normal",
"Remix",
"Full Song",
"Short Cut"
};
/**
* 「タイプ」のチェック状態
*/
public static boolean[] typeChecks = new boolean[TYPES.length];
/**
* 「シリーズ」の種類
*/
public static final String[] SERIES = {
"1st~Perfect Collection",
"Extra~PREX3",
"Exceed〜Zero",
"NX〜NXA",
"Fiesta〜Fiesta EX",
"Fiesta2",
"Prime",
"Prime2"
};
/**
* 「シリーズ」のPUMP IT UP (JAPAN) WikiのURLの文字列
* 第1インデックスは、SERIESのインデックスと一致するように定義すること
*/
public static final String[][] SERIES_URL = {
{"http://seesaawiki.jp/piujpn/d/1st%a1%c1PERFECT%20COLLECTION"},
{"http://seesaawiki.jp/piujpn/d/EXTRA%a1%c1PREX%203"},
{"http://seesaawiki.jp/piujpn/d/EXCEED%a1%c1ZERO"},
{"http://seesaawiki.jp/piujpn/d/NX%a1%c1NXA"},
{"http://seesaawiki.jp/piujpn/d/FIESTA", "http://seesaawiki.jp/piujpn/d/FIESTA%20EX"},
{"http://seesaawiki.jp/piujpn/d/FIESTA2"},
{"http://seesaawiki.jp/piujpn/d/PRIME"},
{"http://seesaawiki.jp/piujpn/d/PRIME2", "http://seesaawiki.jp/piujpn/d/PRIME2%282018%29"},
};
/**
* 「シリーズ」のチェック状態
*/
public static boolean[] seriesChecks = new boolean[SERIES.length];
/**
* 「カテゴリー」の種類
*/
public static final String[] CATEGORIES = {
"Original",
"K-POP",
"World Music",
"XROSS",
"J-Music"
};
/**
* 「カテゴリー」のチェック状態
*/
public static boolean[] categoryChecks = new boolean[CATEGORIES.length];
/**
* 「その他」の「PP解禁譜面を含む」のチェック状態
*/
public static boolean ppUnlockedStepCheck = false;
/**
* 「その他」の「AM.PASS使用時限定譜面を含む」のチェック状態
*/
public static boolean amPassOnlyUsedStepCheck = false;
/**
* メイン画面のAdMobのアプリID
*/
public static final String AD_VIEW_ID_MAIN = "ca-app-pub-2231903967147229~6474652519";
/**
* MainActivityからDialogFragmentを表示するのに用いるタグ
*/
public static final String DIALOG_FRAGMENT_MAIN = "DialogFragmentMain";
// 抽象staticクラスなのでコンストラクタはprivateにする
private CommonParams() {}
}
<file_sep>/README.md
# PIUSubjectChart

Pump It Upでの今日のお題を表示・共有するAndroidアプリケーション。譜面データは[PUMP IT UP (JAPAN) Wiki](http://seesaawiki.jp/piujpn/)から取得する。
## インストール
[ここ](https://github.com/infhyroyage/PIUSubjectChart/raw/master/app/release/app-release.apk)からapkファイルをダウンロードし、**Android OS 4.0.3以上**でapkファイルを展開。
## 使い方

### お題の絞り込み
以下の5つのグループから、今日のお題を出す譜面を絞り込む。
グループはタブから直接選択するか、左右にフリックして切り替えることが可能。
1. 難易度
Single譜面はS1〜S26、Double譜面はD1〜D28の範囲で絞り込むことができる。また、**COOP譜面**も絞り込むことができる。
なお、Single Performance譜面はSingle譜面、Double Performance譜面はDouble譜面として扱う。
2. タイプ
以下の各タイプで絞り込むことができる。
* Normal(=通常譜面)
* Remix
* Full Song
* Short Cut
3. シリーズ
Pump It Up PRIME2で分類されている、以下の各シリーズで絞り込むことができる。
* 1st〜Perfect Collection
* Extra〜PREX3
* Exceed〜Zero
* NX〜NXA
* Fiesta〜Fiesta EX
* Fiesta2
* Prime
* Prime2
4. カテゴリー
Pump It Up PRIME2で分類されている、以下の各カテゴリーで絞り込むことができる。
* original
* K-POP
* World Music
* XROSS
* J-Music
5. その他
以下の観点で絞り込むことができる。
* PP解禁譜面を含む
Pump It Up PRIME2の公式サイトからPPを消費して解禁する譜面で絞り込むことができる。
* AM.PASS使用時限定譜面を含む
AM.PASSで認証してプレイした時に限定してプレイできる譜面で絞り込むことができる。
### 今日のお題を出す

「今日のお題を出す」ボタンをタップすると、[PUMP IT UP (JAPAN) Wiki](http://seesaawiki.jp/piujpn/)と通信を行い、絞り込んだ全譜面データを取得する。お題はその譜面データの中から1つだけランダムに選ばれる。
お題が選ばれると、上記のようにダイアログが表示される(共有可)。
## 制限事項
* 以下の日本限定曲は、お題の対象外。
- Unlock
- ヘビーローテーション
* 以下の南米版限定曲は、お題の対象外。
- Limbo
- Melodia
- Que Viva La Vida
<file_sep>/app/src/main/java/com/subject/piu/main/MainPagerAdapter.java
package com.subject.piu.main;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import com.subject.piu.CommonParams;
import com.subject.piu.R;
/**
* メイン画面のPagerAdapterのクラス
*/
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// デバッグ用のタグ
private static final String TAG = "MainPagerAdapter";
// 呼びだされたMainActivityのインスタンス
private MainActivity mainActivity;
/**
* コンストラクタ
* @param mainActivity メイン画面のアクティビティ
* @param manager 親クラスのコンストラクタで使用するフラグメントマネージャー
*/
MainPagerAdapter(MainActivity mainActivity, FragmentManager manager) {
super(manager);
this.mainActivity = mainActivity;
}
/**
* 選択したメイン画面のタブの番号から、それに対応するフラグメントを返す
* @param position 選択したメイン画面のタブの番号
* @return 選択したメイン画面のタブの番号に対応するフラグメント
*/
@Override
public Fragment getItem(int position) {
// ログ出力
Log.d(TAG, "getItem:position=" + position);
return MainSwitchFragment.newInstance(mainActivity, position);
}
/**
* 選択したメイン画面のタブの番号から、それに対応するタブのタイトルの文字列を返す
* @param position 選択したメイン画面のタブの番号
* @return 選択したメイン画面のタブの番号に対応するタイトルの文字列
*/
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
// 「難易度」の場合
return mainActivity.getString(R.string.difficulty);
case 1:
// 「タイプ」の場合
return mainActivity.getString(R.string.type);
case 2:
// 「シリーズ」の場合
return mainActivity.getString(R.string.series);
case 3:
// 「カテゴリー」の場合
return mainActivity.getString(R.string.category);
case 4:
// 「その他」の場合
return mainActivity.getString(R.string.other);
default:
throw new IllegalArgumentException("position is out between 0 to 4.");
}
}
/**
* メイン画面のタブの個数を返す
* @return メイン画面のタブの個数
*/
@Override
public int getCount() {
return CommonParams.TAB_PAGE_NUM;
}
}
<file_sep>/app/src/main/java/com/subject/piu/taking/ResultDialogFragment.java
package com.subject.piu.taking;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ShareCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import com.subject.piu.R;
import com.subject.piu.main.MainActivity;
/**
* お題を出した後の結果を表示するダイアログのクラス
*/
public class ResultDialogFragment extends AppCompatDialogFragment {
// MainActivityのインスタンス
private MainActivity mainActivity;
// このダイアログのメッセージ
private String message;
// このダイアログに「共有」ボタンを表示させるかどうかのフラグ
private boolean isShared;
/**
* このクラスのインスタンスの初期化を行い、それを返す
* @param mainActivity MainActivityのインスタンス
* @param message このダイアログのメッセージ
* @param isShared このダイアログに「共有」ボタンを表示させるかどうかのフラグ
* @return このクラスのインスタンス
*/
public static ResultDialogFragment newInstance(MainActivity mainActivity, String message, boolean isShared) {
ResultDialogFragment thisFragment = new ResultDialogFragment();
thisFragment.mainActivity = mainActivity;
thisFragment.message = message;
thisFragment.isShared = isShared;
return thisFragment;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle bundle) {
// ダイアログのビルダーを生成
AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity)
.setMessage(message)
.setPositiveButton(R.string.ok, null);
// 「共有」ボタンをビルダーにセット
if (isShared) {
builder = builder.setNeutralButton(R.string.share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// 共有インテントの設定
ShareCompat.IntentBuilder.from(mainActivity)
.setType("text/plain")
.setText(message)
.startChooser();
}
});
}
// ビルダーからダイアログを生成
return builder.create();
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.oss.licenses.plugin'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.subject.piu"
minSdkVersion 15
targetSdkVersion 27
versionCode 20180522
versionName "20180522"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
disable 'GoogleAppIndexingWarning'
baseline file("lint-baseline.xml") // your run of filename/path here
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// AppCompat
implementation 'com.android.support:appcompat-v7:27.1.1'
// TabLayout
implementation 'com.android.support:design:27.1.1'
// Firebase Admob
implementation 'com.google.firebase:firebase-ads:15.0.1'
implementation 'com.android.support:support-v4:27.1.1'
// Google's Open Source Notices
implementation 'com.google.android.gms:play-services-oss-licenses:15.0.1'
// Jsoup
implementation 'org.jsoup:jsoup:1.7.3'
}
repositories {
mavenCentral()
}
// Firebase Admob
apply plugin: 'com.google.gms.google-services'
|
f3299ce9f782de526961b44b42fde3c2a1e63b58
|
[
"Java",
"Markdown",
"Gradle"
] | 5 |
Java
|
infhyroyage/PIUSubjectChart
|
a9aa862bb7254092a39a205c9e46b4627bfeea34
|
a82726e826a42b81cff7ebe09d67bfd2d07beaa8
|
refs/heads/main
|
<repo_name>Kozer2/book_app_deux<file_sep>/data/books.sql
-- DROP TABLE IF EXISTS BooksTable;
CREATE TABLE IF NOT EXISTS BooksTable(
Id SERIAL PRIMARY KEY,
author VARCHAR(255),
title VARCHAR(255),
isbn VARCHAR(30),
image_url VARCHAR(255),
summary VARCHAR(255)
);<file_sep>/views/pages/books/detail-view.ejs
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="/styles/base.css" />
<link rel="stylesheet" href="/styles/reset.css" />
</head>
<body>
<header>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
<!-- This is in the header partial -->
</a>
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<!-- <li><a href="/about">About</a></li> -->
<li><a href="/searches/new">Search</a></li>
</ul>
</div>
</div>
</nav>
</header>
<main>
<section class="books-view container">
<ul id="book-list">
<li class="book-item" data-id="<%=book.id%>">
<img src="<%= book.image_url %>">
<h3>Book: <%=book.title%></h3>
<p>Author: <%=book.author%></p>
<p>ISBN: <%=book.isbn%></p>
<p>Description: <%=book.summary%></p>
</li>
</ul>
</section>
</main>
<script src="" async defer></script>
</body>
</html><file_sep>/views/pages/searches/show.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles/base.css" />
<link rel="stylesheet" href="/styles/reset.css" />
<title>Book Results</title>
</head>
<body>
<header>
<header>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
</a>
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/searches/new">Search</a></li>
</ul>
</div>
</div>
</nav>
</header>
<h2>Books Result</h2>
</header>
<div class="search-results-container">
<ul>
<% results.forEach(book => { %>
<li class="search-item">
<!-- <% let imageSource = book.image_url ? book.image_url : "https://i.imgur.com/J5LVHEL.jpg" %> -->
<!-- <img src="<%= book.image %>"> -->
<% results.forEach( item => { %>
<div class="resultsContainer">
<img src="<%= item.image %>">
<h2>Title: <%= item.title %></h2>
<h3>Author: <%= item.authors %></h3>
<p>ISBN: <%= item.isbn %></p>
<p>Description: <%= item.description %></p>
<button type="submit" class="add-to-booklist">Add to BookList</button>
</div>
<% }) %>
<!-- <p><%= book.description %></p> -->
<!-- <p>ISBN13: <%= book.isbn13 %></p> -->
<form action="/books" method="POST">
<input type="hidden" name="title" value='<%= book.title %>' />
<input type="hidden" name="author" value='<%= book.author %>' />
<input type="hidden" name="description" value='<%= book.summary %>'/>
<input type="hidden" name="isbn" value='<%= book.isbn %>'/>
<input type="hidden" name="image_url" value="<%= book.image_url %>" />
<!-- <button type="submit" class="add-to-booklist">Add to BookList</button> -->
</form>
</li>
<!-- <% }) %> -->
</ul>
</div>
<!-- <% results.forEach( item => { %>
<div class="resultsContainer">
<img src="<%= item.image %>">
<h2>Title: <%= item.title %></h2>
<h3>Author: <%= item.authors %></h3>
<p>ISBN: <%= item.isbn %></p>
<p>Description: <%= item.description %></p>
</div>
<% }) %> -->
<footer>
</footer>
</body>
</html><file_sep>/server.js
'use strict';
//Load Environment Variables from the .env file
require('dotenv').config();
// Application Dependencies
const express = require('express');
const cors = require('cors');
const pg = require('pg');
pg.defaults.ssl = process.env.NODE_ENV === 'production' && { rejectUnauthorized: false };
const superagent = require('superagent'); //<<--will go in module
const { request } = require('express');
// Database Setup
if (!process.env.DATABASE_URL) {
throw 'DATABASE_URL is missing!';
}
const client = new pg.Client(process.env.DATABASE_URL);
client.on('error', err => { throw err; });
// Our Dependencies - modules
//Application Setup
const PORT = process.env.PORT || 3001 || 3002 || 3003;
console.log('Server is running on port: ', PORT)
const app = express();
//Express Middleware
app.use(express.urlencoded({ extended: true }));
//Specify a directory for static resources
app.use(express.static('./public'));
//Cors Middleware
app.use(cors());
//Set the view engine for server-side templating
app.set('view engine', 'ejs');
//API Routes
app.get('/', getBooks);
function getBooks(request, response){
const SQL = `
SELECT *
FROM BooksTable
`;
// const SQLCounter = `
// SELECT COUNT(author)
// FROM bookstable
// `;
client.query(SQL)
.then(results => {
const {rowCount, rows} = results;
console.log('DB', rows, rowCount);
response.render('pages/index', {
books: rows,
});
})
.catch(err => {
errorHandler(err, request, response);
});
}
// app.get('/add', showAddBookForm);
// app.post('/add', addBook);
app.get('/books/:id', getOneBook);
function getOneBook(request, response){
const {id} = request.params;
console.log('id', id);
const SQL = `
SELECT *
FROM bookstable
WHERE id =$1
LIMIT 1`; // make it so only one comes back
client.query(SQL, [id])
.then(results => {
const {rows} = results;
if(rows.length < 1){
// console.log('response', response);
errorHandler('Book not Found', request, response);
} else{
response.render('pages/books/detail-view', { // take of /pages if it doesn't work
book: rows[0]
});
}
})
.catch(err => {
errorHandler(err, request, response);
});
} // end getOneBook function
app.get('/searches/new', (request, response) => {
response.render('pages/searches/new'); //do not include a / before pages or it will say that it is not in the views folder
});
app.get('/searches/show', (request, response) => {
response.render('pages/searches/show'); //do not include a / before pages or it will say that it is not in the views folder
});
app.post('/searches', booksHandler); //has to match the form action on the new.js for the /searches
//Will end up going into a module
function booksHandler(request, response) {
const url = 'https://www.googleapis.com/books/v1/volumes';
superagent.get(url)
.query({
key: process.env.GOOGLE_API_KEY,
q: `+in${request.body.searchType}:${request.body.searchQuery}`
})
.then((booksResponse) => booksResponse.body.items.map(bookResult => new Book(bookResult.volumeInfo)))
.then(results => response.render('pages/searches/show', {results: results})) //do not include a / before pages or it will say that it is not in the views folder and do not include the .ejs at the end of show
.catch(err => {
console.log(err);
errorHandler(err, request, response);
});
}
app.use('*', (request, response) => response.send('Sorry, that route does not exist.'));
//Has to be after stuff loads too
app.use(notFoundHandler);
//Has to be after stuff loads
app.use(errorHandler);
//client goes here
//Will end up going into a module
app.post('/books/detail-view', favoriteBookHandler);
function favoriteBookHandler(request, response, next) {
const { author, title, isbn, image_url, summary } = request.body;
console.log('request body', request.body);
const SQL = `
INSERT INTO bookstable (author, title, isbn, image_url, summary)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
`;
const parameters = [author, title, isbn, image_url, summary];
return client.query(SQL, parameters)
.then(result => {
let id = result.rows[0].id;
response.redirect(`/books/${id}`);
// console.log('cachedlocation', result);
})
.catch(err => {
errorHandler(err, request, response);
console.err('failed to handle three partners together', err);
});
}
// app.post('/books', (request, response) => {
// sendBookToDB(request, response);
// });
// function sendBookToDB(request, response) {
// let newBook = request.body
// console.log(newBook);
// const searchSQL = 'SELECT * FROM bookstable WHERE title = $1';
// const searchParameter = [newBook.title];
// return client.query(searchSQL, searchParameter)
// .then(searchResult => {
// if (searchResult.rowCount === 0) {
// const SQL = 'INSERT INTO bookstable (author, title, isbn, image_url, summary) VALUES ($1, $2, $3, $4, $5) Returning id';
// const sqlParameters = [newBook.author, newBook.title, newBook.isbn, newBook.image_url, newBook.summary];
// return client.query(SQL, sqlParameters).then(result => {
// console.log('Book saved', result);
// let id = result.rows[0].id;
// response.redirect(`pages/books/${id}`);
// })
// } else {
// let id = searchResult.rows[0].id;
// console.log('Book is already in the bookcase')
// response.redirect(`pages/books/${id}`);
// }
// }).catch(err => { throw err; });
// }
// function addBook(event) {
// console.log('POST /books', event);
// const { author, title, isbn, image_url, summary } = request.body;
// const SQL = `
// INSERT INTO bookstable (author, title, isbn, image_url, summary)
// VALUES ($1, $2, $3, $4, $5)
// RETURNING Id
// `;
// const values = [author, title, isbn, image_url, summary];
// // POST - REDIRECT - GET
// client.query(SQL, values)
// .then(results => {
// let id = results.rows[0].id;
// response.redirect(`/books/${id}`);
// })
// .catch(err => errorHandler(err, request, response))
// }
function errorHandler(error, request, response, next) {
console.error(error);
response.status(500).json({
error: true,
message: error.message,
});
}
function notFoundHandler(request, response) {
response.status(404).json({
notFound: true,
});
}
client.connect() //<<--keep in server.js
.then(() => {
console.log('PG connected!');
app.listen(PORT, () => console.log(`App is listening on ${PORT}`)); //<<--these are tics not single quotes
})
.catch(err => {
throw `PG error!: ${err.message}` //<<--these are tics not single quotes
});
function Book(booksData) {
let placeHolder = 'https://i.imgur.com/J5LVHEL.jpg';
let httpRegex = /^(http:\/\/)/g;
// console.log('constructor function function fun fun function ', booksData.industryIdentifiers[0].identifier );
this.title = booksData.title;
this.authors = booksData.authors;
this.isbn = booksData.industryIdentifiers[0].identifier;
this.description = booksData.description;
this.image = booksData.imageLinks ? booksData.imageLinks.smallThumbnail.replace(httpRegex, 'https://') : placeHolder; //if no image, then we use stock that is in Trello card
}
<file_sep>/views/pages/searches/new.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles/base.css" />
<link rel="stylesheet" href="/styles/reset.css" />
<title>Search for a Book</title>
</head>
<body>
<header>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
</a>
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/searches/new">Search</a></li>
</ul>
</div>
</div>
</nav>
</header>
<h1>Search Form</h1>
<form action="/searches" method="POST"> <!-- action has to be "/searches" which matches the server.js in the app.post('/searches', booksHandler); -->
<fieldset>
<legend>
Book Search
</legend>
<span>Title</span> <input type="radio" name="searchType" value="title"/>
<span>Author</span><input type="radio" name="searchType" value="author" />
<input type="text" name="searchQuery" />
</fieldset>
<button class = "google--button" type="submit">Search the Google Books API</button>
</form>
<footer>
</footer>
</body>
</html>
|
92d662cab802759f34dbff43043a205ccc604c33
|
[
"JavaScript",
"SQL",
"EJS"
] | 5 |
JavaScript
|
Kozer2/book_app_deux
|
9418964b12d3cc84d7d4ee27ba4790a529aed8fa
|
db30b76d5ac6cde06992bed8bfaf5cd402a3b0aa
|
refs/heads/master
|
<repo_name>niweisi/phpCommand<file_sep>/www/command.php
<?php
$password = '<PASSWORD>';
if($_POST['pass']==$password){
if( file_put_contents('command.txt','1') ){
echo '200';
}else{
echo '400';
}
}else{
echo '500';
}
<file_sep>/www/a.php
<?php
//header("Access-Control-Allow-Origin: http://192.168.0.150:8080");
header('Access-Control-Allow-Origin:*');
$a = array(1,2,3);
echo 'jsonp = '.json_encode($a);
<file_sep>/shell.php
<?php
set_time_limit(1800);
ini_set('default_socket_timeout',40);
date_default_timezone_set('PRC');
$phpFpm = 'php-fpm-5.3.29';
$dir = '/data/wwwroot/shell/';
$fileName = $dir.'www/command.txt';
$url = 'https://index.php';
if(!is_file($fileName)) {
exec("echo '0' > {$fileName} && chmod 777 {$fileName}");
exit;
}
$s = file_get_contents($fileName);
if( trim($s)=='1' ){
restartPHP();
}else{
for($i=0;$i<3;$i++){
file_get_contents($url);
if(strstr($http_response_header[0], '200')){
echo 'ok';
break;
}else{
echo 'no '.$i;
sleep(2);
$i++;
}
}
if($i>=3){
echo 'no '.$i;
restartPHP();
email();
}
}
function restartPHP(){
global $fileName,$phpFpm,$dir;
file_put_contents($fileName,'0');
exec("systemctl stop {$phpFpm} && systemctl start {$phpFpm}");
$log = date("Y-m-d H:i:s");
file_put_contents("{$dir}/log.txt", $log."\r\n", FILE_APPEND);
}
function email(){
global $dir;
//引入发送邮件类
require($dir."www/smtp.php");
//使用163邮箱服务器
$smtpserver = "smtp.exmail.qq.com";
//163邮箱服务器端口
$smtpserverport = 25;
//你的163服务器邮箱账号
$smtpusermail = "r@.com";
//收件人邮箱
$smtpemailto = "xxxxxxxxxxqq.com";
//你的邮箱账号(去掉<EMAIL>)
$smtpuser = "<EMAIL>";//SMTP服务器的用户帐号
//你的邮箱密码
$smtppass = "<PASSWORD>"; //SMTP服务器的用户密码
//邮件主题
$mailsubject = "测试邮件发送";
//邮件内容
$mailbody = "PHP+MySQL";
//邮件格式(HTML/TXT),TXT为文本邮件
$mailtype = "TXT";
//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);
//是否显示发送的调试信息
$smtp->debug = false;
//发送邮件
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
}
|
8e3fe212da69863d884adfaaea34c784806866d5
|
[
"PHP"
] | 3 |
PHP
|
niweisi/phpCommand
|
b51cf109e35ba6f74ff93719813c49a21aacde7a
|
0c7eba836d04745d75aa55bf97db1be90c3bf975
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConfigIt.DesertRace.Entities
{
/// <summary>
/// </summary>
/// <remarks>
/// How to extend from 2D to 3D
/// </remarks>
public class Location : IEquatable<Location>, ICloneable
{
private GameArena<GameEntity> _Container;
public GameArena<GameEntity> Container { get { return _Container; } set { SetContainer(value); } }
public int X { get; set; }
public int Y { get; set; }
public Location()
: this(0, 0)
{
}
public Location(IEnumerable<string> parameters)
{
int x, y;
var enumerator = parameters.GetEnumerator();
if (!enumerator.MoveNext())
throw new GameException(this, "Location requires X Y for initializacion");
else
if (!int.TryParse(enumerator.Current, out x))
throw new GameException("Value {0} is not a number valid for a X location", enumerator.Current);
if (!enumerator.MoveNext())
throw new GameException(this, "Location requires X Y for initializacion");
else
if (!int.TryParse(enumerator.Current, out y))
throw new GameException("Value {0} is not a number valid for a Y location", enumerator.Current);
this.X = x;
this.Y = y;
}
public Location(int x, int y)
{
this.X = x;
this.Y = y;
}
protected void SetContainer(GameArena<GameEntity> container)
{
if (container == null)
{
this._Container = null;
return;
}
if (!container.IsValidLocation(this))
{
Util.RaiseError("Location {0} is Invalid in the Arena", this);
}
this._Container = container;
}
public static string ToString(int x, int y)
{
return "[X:" + x.ToString() + "," + "Y:" + y.ToString() + "]";
}
public override string ToString()
{
return ToString(X, Y);
}
public bool IsLessThan(int x, int y)
{
return (this.X < x) || (this.Y < y);
}
public bool IsLessThan(Location other)
{
if (other == null)
return false;
return IsLessThan(other.X, other.Y);
}
public bool IsGraterThan(int x, int y)
{
return (this.X > x) || (this.Y > y);
}
public bool IsGraterThan(Location other)
{
if (other == null)
return false;
return IsGraterThan(other.X, other.Y);
}
public Location Next(Direction direction)
{
int nextX = this.X;
int nextY = this.Y;
switch (direction)
{
case Direction.North:
nextY++;
break;
case Direction.South:
nextY--;
break;
case Direction.East:
nextX++;
break;
case Direction.West:
nextX--;
break;
}
Location result = new Location(nextX, nextY);
if (this.Container != null)
{
if (!this.Container.IsValidLocation(result))
Util.RaiseError("Movement with Direction:{0} from {1} will result in {2} which is not allowed",
direction, this, ToString(nextX, nextY));
}
return result;
}
public bool Equals(Location other)
{
return (this.X == other.X) && (this.Y == other.Y);
}
public double DistanceEuclidean(Location other)
{
if (other == null)
return double.NaN;
double xDelta = this.X - other.X;
double yDelta = this.Y - other.Y;
double result = Math.Abs(Math.Sqrt(xDelta * xDelta + yDelta * yDelta));
return result;
}
public double DistanceMovement(Location other)
{
if (other == null)
return double.NaN;
double xDelta = this.X - other.X;
double yDelta = this.Y - other.Y;
double result = xDelta + xDelta;
return result;
}
public object Clone()
{
return this.MemberwiseClone();
}
}
}
<file_sep>using ConfigIt.DesertRace.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace ConfigIt.DesertRace.Test
{
/// <summary>
///This is a test class for VehicleTest and is intended
///to contain all VehicleTest Unit Tests
///</summary>
[TestClass()]
public class VehicleTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
private ArenaRectangular<GameEntity> GenArena()
{
var container = new ArenaRectangular<GameEntity>();
container.MaxLocation = new Location(10, 20);
return container;
}
private Vehicle GenVehicle(string config)
{
var container = GenArena();
Vehicle target = new Vehicle(container, Util.SeparedParams(config));
return target;
}
/// <summary>
///A test for Vehicle Constructor
///</summary>
[TestMethod(), TestCategory("Vehicle Creation")]
public void VehicleConstructorTest1()
{
var target = GenVehicle("V1 5 4 N");
Assert.AreEqual(target.Position.X,5);
Assert.AreEqual(target.Position.Y,4);
Assert.AreEqual(Direction.North, target.Direction);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Direction")]
public void ExecCommand_Left_N()
{
var target = GenVehicle("V1 5 4 N");
target.ExecCommand(VehicleCommands.Left);
Assert.AreEqual(Direction.West, target.Direction);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Direction")]
public void ExecCommand_Left_E()
{
var target = GenVehicle("V1 5 4 E");
target.ExecCommand(VehicleCommands.Left);
Assert.AreEqual(Direction.North, target.Direction);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Direction")]
public void ExecCommand_Right_N()
{
var target = GenVehicle("V1 5 4 N");
target.ExecCommand(VehicleCommands.Right);
Assert.AreEqual(Direction.East, target.Direction);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Direction")]
public void ExecCommand_Right_E()
{
var target = GenVehicle("V1 5 4 E");
target.ExecCommand(VehicleCommands.Right);
Assert.AreEqual(Direction.South, target.Direction);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement")]
public void ExecCommand_Move_N()
{
var target = GenVehicle("V1 5 4 N");
target.ExecCommand(VehicleCommands.Move);
Assert.AreEqual(5,target.Position.Y);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement")]
public void ExecCommand_Move_S()
{
var target = GenVehicle("V1 5 4 S");
target.ExecCommand(VehicleCommands.Move);
Assert.AreEqual(3,target.Position.Y);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement")]
public void ExecCommand_Move_W()
{
var target = GenVehicle("V1 5 4 W");
target.ExecCommand(VehicleCommands.Move);
Assert.AreEqual(4,target.Position.X);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement")]
public void ExecCommand_Move_E()
{
var target = GenVehicle("V1 5 4 E");
target.ExecCommand(VehicleCommands.Move);
Assert.AreEqual(6,target.Position.X);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement")]
public void ExecCommand_Move_T1()
{
var target = GenVehicle("V1 4 4 E");
target.ExecCommand(VehicleCommands.Right);
Assert.AreEqual(Direction.South, target.Direction);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement"),ExpectedException(typeof(GameException))]
public void ExecCommand_Move_E_Onvalid()
{
var target = GenVehicle("V1 10 2 E");
target.ExecCommand(VehicleCommands.Move);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement"), ExpectedException(typeof(GameException))]
public void ExecCommand_Move_N_Onvalid()
{
var target = GenVehicle("V1 5 20 N");
target.ExecCommand(VehicleCommands.Move);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement"), ExpectedException(typeof(GameException))]
public void ExecCommand_Move_S_Onvalid()
{
var target = GenVehicle("V1 5 0 S");
target.ExecCommand(VehicleCommands.Move);
}
/// <summary>
///A test for ExecCommand
///</summary>
[TestMethod(), TestCategory("Vehicle Movement"), ExpectedException(typeof(GameException))]
public void ExecCommand_Move_W_Onvalid()
{
var target = GenVehicle("V1 0 2 W");
target.ExecCommand(VehicleCommands.Move);
}
}
}
<file_sep>using ConfigIt.DesertRace.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Text;
namespace ConfigIt.DesertRace.Test
{
/// <summary>
///This is a test class for WarGameTest and is intended
///to contain all WarGameTest Unit Tests
///</summary>
[TestClass()]
public class GameTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
private static void PlayGameWithAssert(StringBuilder input, StringBuilder expected)
{
using (var results = new StringWriter())
{
using (var reader = new StringReader(input.ToString()))
{
DesertRaceGame.Play(reader, results);
}
string result = results.ToString();
Assert.AreEqual(expected.ToString(), result);
}
}
/// <summary>
///A test for PlayGame
///</summary>
[TestMethod()]
public void PlayGameTest_Case_1()
{
var input = new StringBuilder();
input.AppendLine("10 20");
input.AppendLine("5 10");
input.AppendLine("V1 2 4 E");
input.AppendLine("MMR");
var expected = new StringBuilder();
expected.AppendLine("V1 4 4 S");
PlayGameWithAssert(input, expected);
}
/// <summary>
///A test for PlayGame
///</summary>
[TestMethod()]
public void PlayGameTest_Case_2()
{
var input = new StringBuilder();
input.AppendLine("10 20");
input.AppendLine("5 10");
input.AppendLine("V2 2 4 E");
input.AppendLine("MMRMMRMRRM");
input.AppendLine("V1 3 4 N");
input.AppendLine("LMLMLMLMM");
var expected = new StringBuilder();
expected.AppendLine("V1 3 5 N");
expected.AppendLine("V2 4 2 E");
PlayGameWithAssert(input, expected);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConfigIt.DesertRace.Entities
{
public static class Util
{
[System.Diagnostics.DebuggerStepThrough()]
public static string[] SeparedParams(string parameters)
{
return parameters.Split(' ');
}
public static void RaiseError(string message, params object[] args)
{
string formattedMessage = string.Format(message, args);
var ex = new GameException(null, formattedMessage);
throw ex;
}
/// <summary>
/// Based on the available values in an Enum type, generate a dictionary
/// where the key is the the first letter of each name and the value is the enum value
/// </summary>
/// <typeparam name="TEnum">The source of the values to abbreviate</typeparam>
/// <remarks>Just Enum type with names that begins with a different letter are supported. Otherwise
/// it is expected an Exception</remarks>
public static Dictionary<char, TEnum> GetEnumAbreviations<TEnum>()
{
string[] names = Enum.GetNames(typeof(TEnum));
Array values = Enum.GetValues(typeof(TEnum));
int length = values.Length;
var result = new Dictionary<char, TEnum>(length);
for (int i = length - 1; i >= 0; i--)
result.Add(names[i][0], (TEnum)values.GetValue(i));
return result;
}
/// <summary>
/// Convert the abbreviations obtained in string to the corresponding list of
/// values that
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="sequence"></param>
/// <returns></returns>
public static List<TEnum> TranslateCharToEnum<TEnum>(string sequence)
{
if (sequence == null)
// Returns just an empty list
return new List<TEnum>();
Dictionary<char, TEnum> abreviations = GetEnumAbreviations<TEnum>();
List<TEnum> result = new List<TEnum>(sequence.Length);
foreach (char ch in sequence)
{
TEnum enumValue;
if (abreviations.TryGetValue(ch, out enumValue))
result.Add(enumValue);
else
RaiseError(Messages.InvalidEnumAbreviation, ch, typeof(TEnum).Name);
}
return result;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConfigIt.DesertRace.Entities
{
[Serializable()]
public class GameException : ApplicationException
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public GameException(object source, string message) : base(message)
{
if (source != null)
this.Source = source.ToString();
}
}
public class BaseRaceGame<TArena, TEntity>
where TArena : GameArena<TEntity> , new ()
where TEntity : GameEntity
{
public TArena Arena { get; set; }
public BaseRaceGame()
{
this.Arena = new TArena();
}
public IEnumerable<TEntity> GenerateRank()
{
var vehicleScores = from v in Arena.GameEntities
select new
{
distance = CalculateScore(v),
vehicle = v
};
vehicleScores = vehicleScores.OrderBy(v => v.distance);
var result = from r in vehicleScores
select r.vehicle;
return result;
}
public virtual double CalculateScore(TEntity entity)
{
return Arena.Goal.DistanceEuclidean(entity.Position);
}
}
public class DesertRaceGame
{
public static void Play(System.IO.TextReader reader, System.IO.TextWriter results)
{
var game = new BaseRaceGame<ArenaRectangular<GameEntity>, GameEntity>();
string inputLine = reader.ReadLine();
if (string.IsNullOrWhiteSpace(inputLine))
throw new GameException(game.Arena, "An arena configuration is required");
game.Arena.MaxLocation = new Location(Util.SeparedParams(inputLine));
inputLine = reader.ReadLine();
if (string.IsNullOrWhiteSpace(inputLine))
throw new GameException(game.Arena, "An arena Goal is required");
game.Arena.Goal = new Location(Util.SeparedParams(inputLine));
do
{
inputLine = reader.ReadLine();
if (string.IsNullOrWhiteSpace(inputLine))
break;
var Vehicle = new Vehicle(game.Arena, Util.SeparedParams(inputLine));
inputLine = reader.ReadLine();
Vehicle.ExecCommand(inputLine);
}
while (inputLine != null);
var rank = game.GenerateRank();
foreach (var vehicle in rank)
{
results.WriteLine(vehicle);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConfigIt.DesertRace.Entities;
namespace ConfigIt.DesertRace.Console
{
class Program
{
static void Main(string[] args)
{
DesertRaceGame.Play(global::System.Console.In, global::System.Console.Out);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConfigIt.DesertRace.Entities
{
public abstract class GameArena<TEntity> where TEntity : GameEntity
{
public List<TEntity> GameEntities { get; protected set; }
private Location _Goal;
public Location Goal {
get{return _Goal;}
set{
if (!IsValidLocation(value))
Util.RaiseError("The location {0} is no valid and cannot be used as a Goal",value);
this._Goal = value;
}
}
public GameArena()
: base()
{
this.GameEntities = new List<TEntity>();
}
public abstract bool IsValidLocation(Location location);
}
public class ArenaRectangular<TEntity> : GameArena<TEntity>
where TEntity : GameEntity
{
#region Properties
private Location _MinLocation = new Location();
public virtual Location MinLocation
{
get { return _MinLocation; }
set
{
if (value == null)
return;
if (value.IsGraterThan(MaxLocation))
Util.RaiseError("MinLocation {0} cannot be grater thatn MaxLocation {1}", value, MaxLocation);
_MinLocation = value;
}
}
private Location _MaxLocation = new Location();
public virtual Location MaxLocation
{
get { return _MaxLocation; }
set
{
if (value == null)
return;
if (value.IsLessThan(MinLocation))
Util.RaiseError("MaxLocation {0} cannot be less thatn MinLocation {1}", value, MinLocation);
_MaxLocation = value;
}
}
#endregion
public override bool IsValidLocation(Location location)
{
return IsValidLocation(location.X, location.Y);
}
private bool IsValidLocation(int nextX, int nextY)
{
if ((MaxLocation != null) && MaxLocation.IsLessThan(nextX, nextY))
return false;
if ((MinLocation != null) && MinLocation.IsGraterThan(nextX, nextY))
return false;
return true;
}
}
public class ArenaCompetition2012 : ArenaRectangular<Vehicle>
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConfigIt.DesertRace.Entities
{
public class GameEntity
{
public string Name { get; set; }
public Location Position { get; protected set; }
public GameArena<GameEntity> Container {
get { return Position.Container;}
set { SetContainer(value); }
}
public GameEntity(GameArena<GameEntity> container, ICollection<string> parameters)
{
if (parameters.Count < 3)
throw new GameException(this, "Requires Name Location.X Location.Y");
this.Name = parameters.First();
this.Position = new Location(parameters.Skip(1));
SetContainer(container);
}
public GameEntity(GameArena<GameEntity> container, Location position)
{
this.Position = position;
SetContainer(container);
}
private void SetContainer(GameArena<GameEntity> container)
{
Position.Container = container;
container.GameEntities.Add(this);
}
public override string ToString()
{
if (this.Position == null)
return this.Name + " ? ?";
return this.Name + " " + this.Position.X.ToString() + " " + this.Position.Y.ToString();
}
}
public enum Direction
{
North = 0,
West = 1,
South = 2,
East = 3
}
/// <summary>
/// Define de currently available commands, In case that the number or complexity of commands increase, would be better
/// to use a proper Command Class
/// </summary>
public enum VehicleCommands
{
Left,
Right,
Move
}
public class Vehicle : GameEntity
{
public Direction Direction { get; protected set; }
public const Direction DirectionMinValue = Direction.North;
public const Direction DirectionMaxValue = Direction.East;
public Vehicle(ArenaRectangular<GameEntity> container, string[] parameters)
: base (container, parameters)
{
if (parameters.Length < 3)
throw new GameException(this, "Requires Location.X Location.Y and Direcction for initializacion");
this.Direction = Util.TranslateCharToEnum<Direction>(parameters[3]).First();
}
public Vehicle(ArenaRectangular<GameEntity> container, Location position, Direction direction)
: base(container, position)
{
this.Direction = direction;
}
public void ExecCommand(string commands)
{
var listCommands = Util.TranslateCharToEnum<VehicleCommands>(commands);
ExecCommand(listCommands);
}
public void ExecCommand(IEnumerable<VehicleCommands> commands)
{
foreach (var command in commands)
{
ExecCommand(command);
}
}
public void ExecCommand(VehicleCommands command)
{
switch (command)
{
case VehicleCommands.Left:
Direction = Direction + 1;
if (Direction > DirectionMaxValue)
Direction = DirectionMinValue;
break;
case VehicleCommands.Right:
Direction = Direction - 1;
if (Direction < DirectionMinValue)
Direction = DirectionMaxValue;
break;
case VehicleCommands.Move:
this.Position = this.Position.Next(this.Direction);
break;
}
}
public override string ToString()
{
return base.ToString() + " " + this.Direction.ToString()[0];
}
}
}
|
387ac921a09b0f4137ae974b36b0329a809c9198
|
[
"C#"
] | 8 |
C#
|
JohnLeyva/Configit.Recruitment.OOPTask
|
545efbe124888a7b543c99b02c0e85e6b391a79c
|
aae63a2af1654d2fd0b9f44b229b5b5503178641
|
refs/heads/main
|
<repo_name>jam82/docker-gh-action-auto-merge-pr<file_sep>/README.md
# docker-gh-action-auto-merge-pr
Github action for automatically merging repository owners PRs.
|
396ed1bd8096c7f9cd3141085b2fe43434e2fb80
|
[
"Markdown"
] | 1 |
Markdown
|
jam82/docker-gh-action-auto-merge-pr
|
b3b2dcab1d9b17597cd435a8d52966db33ffb34f
|
2ab9c6b761d09dfcd693c934229f3a60c721aec2
|
refs/heads/master
|
<repo_name>leeneil/peaknet4psocake<file_sep>/peaknet.py
import darknet as dn
from darknet_utils import *
# cfgDefault = "cfg/newpeaksv5-asic.cfg"
# weightDefault= "weights/newpeaksv5_6240.weights"
# dataDefault = "cfg/peaks.data"
cfgPath = "/reg/neh/home5/liponan/source/peaknet4psocake/cfg/newpeaksv5-asic.cfg"
dataPath = "/reg/neh/home5/liponan/source/peaknet4psocake/cfg/peaks.data"
weightPath = "/reg/neh/home5/liponan/source/peaknet4psocake/weights/newpeaksv5_6240.weights"
class peaknet():
def __init__(self, cfgPath=cfgDefault, weightPath=weightDefault, dataPath=dataDefault):
dn.set_gpu(0)
self.net = dn.load_net( cfgPath, weightPath, 0 )
self.meta = dn.load_meta( dataPath )
def detectBatch(self, imgs, thresh=0.1, hier_thresh=.5, nms=.45):
if len(imgs.shape) < 3:
raise Exception("imgs should be 3D or 4D");
elif len(imgs.shape) == 3:
imgs = np.reshape( imgs, [1]+list(imgs.shape) )
else:
pass
n, m, h, w = imgs.shape
imgResults = []
for u in range(n):
asicResults = []
for v in range(m):
#print(imgs[u,v,:,:].shape)
result = self.detect( imgs[u,v,:,:], thresh=thresh, hier_thresh=hier_thresh, nms=nms)
asicResults.append( result )
imgResults.append( asicResults )
return imgResults
def detect(self, img, thresh=0.1, hier_thresh=.5, nms=.45):
img = array2image(dn, img)
boxes = dn.make_boxes(self.net)
probs = dn.make_probs(self.net)
num = dn.num_boxes(self.net)
dn.network_detect(self.net, img, thresh, hier_thresh, nms, boxes, probs)
res = []
for j in range(num):
if probs[j][0] > thresh:
res.append((probs[j][0], (boxes[j].x, boxes[j].y, boxes[j].w, boxes[j].h)))
res = sorted(res, key=lambda x: -x[0])
dn.free_ptrs(dn.cast(probs, dn.POINTER(dn.c_void_p)), num)
return res
def peaknet2psana( self, results ):
nPeaks = 0
for u in range(len(results)):
nPeaks += len(results[u])
s = np.zeros( (nPeaks,1) )
r = np.zeros( (nPeaks,1) )
c = np.zeros( (nPeaks,1) )
counter = 0
for u in range(len(results)):
for v in range(len(results[u])):
s[counter] = u
r[counter] = results[u][v][1][1]
c[counter] = results[u][v][1][0]
counter += 1
return s, r, c
<file_sep>/README.md
# peaknet4psocake
peaknet API
## setup
Add the following to your '~/.bashrc'
```
export PYTHONPATH=/reg/neh/home/liponan/ai/psnet:/reg/neh/home/liponan/ai/psnet/examples:/reg/neh/home/liponan/ai/psnet/python:$PYTHONPATH
```
## usage
### single image detection
First create a peaknet instance, i.e.
```
psnet = peaknet()
```
then call `detect()`, i.e.
```
res = psnet.detect(img, thresh=0.25)
```
where `img` is a 2-D numpy array, `thresh` is the detection threshold in the range [0,1]. The output `res` will be a list of tutples that look like (score, (x,y,w,h)).
### batch image detection
```
results = psnet.detectBatch(imgs, thresh=0.25)
```
where `imgs` is a 4-D numpy array of shape (n,m,h,w), where `n` is the number of images and `m` is the number of ASICs in each image, `thresh` is the detection threshold in the range [0,1]. The output `results` will be a list of lists of tutples that look like (score, (x,y,w,h)).
<file_sep>/darknet_utils.py
import numpy as np
def array2image(dn, arr):
#print(arr.shape)
arr = np.reshape(arr, (arr.shape[0], arr.shape[1], 1))
arr = np.concatenate( (arr, arr, arr), axis=2)
arr = arr.transpose(2,0,1)
c = 3 #arr.shape[0]
h = arr.shape[1]
w = arr.shape[2]
arr = (arr/25500.0).flatten()
data = dn.c_array(dn.c_float, arr)
im = dn.IMAGE(w,h,c,data)
return im
|
8bc89d78074feccfbb2157f525a30c5a42a5f1fa
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
leeneil/peaknet4psocake
|
f5871e04b1bfeecf62142227aeee525d390553b6
|
517ec6804ff09efe688368d664cb721dbff8aec2
|
refs/heads/master
|
<file_sep>{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage} = require 'hubot'
class Telegram extends Adapter
constructor: ->
super
@token = process.env.TELEGRAM_BOT_TOKEN
@refreshRate = process.env.TELEGRAM_BOT_REFRESH or 1500
@webhook = process.env.TELEGRAM_BOT_WEBHOOK or false
@apiURL = "https://api.telegram.org/bot"
@telegramBot = null
@offset = 0
@robot.logger.info "hubot-telegram-bot: Adapter loaded."
_telegramRequest: (method, params = {}, handler) ->
@robot.http("#{@apiURL}#{@token}/#{method}")
.header("Accept", "application/json")
.query(params)
.get() (err, httpRes, body) =>
if err or httpRes.statusCode isnt 200
return @robot.logger.error "hubot-telegram-bot: #{body} (#{err})"
payload = JSON.parse body
handler payload.result
_getMe: (handler) ->
@_telegramRequest "getMe", null, (res) ->
handler res
_createUser: (user, chatId) ->
_userName = user.username or user.first_name + " " + user.last_name
@robot.brain.userForId user.id, name: _userName, room: chatId
_processMsg: (msg) ->
_chatId = msg.message.chat.id
# Text message
_text = msg.message.text
if _text
# Group privacy mode
if _text.charAt(0) is "/"
_text = _text.substr(1)
if msg.message.chat.type is "group"
_text = @robot.name + " " + _text
# PM
if _chatId is msg.message.from.id
_text = @robot.name + " " + _text
# Create user
user = @_createUser msg.message.from, _chatId
message = new TextMessage user, _text.trim(), msg.message.message_id
# Enter message
else if msg.message.new_chat_participant
user = @_createUser msg.message.new_chat_participant, _chatId
message = new EnterMessage user, null, msg.message.message_id
# Leave message
else if msg.message.left_chat_participant
user = @_createUser msg.message.left_chat_participant, _chatId
message = new LeaveMessage user, null, msg.message.message_id
# Topic change
else if msg.message.new_chat_title
user = @_createUser msg.message.from, _chatId
message = new TopicMessage user, msg.message.new_chat_title, msg.message.message_id
@receive(message) if message?
@offset = msg.update_id
send: (envelope, strings...) ->
message =
chat_id: envelope.room
text: strings.join "\n"
@_telegramRequest "sendMessage", message, (res) =>
@robot.logger.debug "hubot-telegram-bot: Send -> #{res}"
reply: (envelope, strings...) ->
message =
chat_id: envelope.room
text: strings.join "\n"
reply_to_message_id: envelope.message.id
@_telegramRequest "sendMessage", message, (res) =>
@robot.logger.debug "hubot-telegram-bot: Reply -> #{res}"
run: ->
unless @token
@emit "error", new Error "You must configure the TELEGRAM_BOT_TOKEN environment variable."
@_getMe (res) =>
@telegramBot = res
@robot.logger.info "hubot-telegram-bot: Hello, I'm #{res.first_name}!"
if @webhook
@_telegramRequest "setWebhook", url: @webhook, (res) =>
@robot.logger.info "hubot-telegram-bot: Using webhook method (`#{@webhook}`) for receiving updates."
@robot.router.post "/telegram", (httpReq, httpRes) =>
payload = httpReq.body.result
@_processMsg obj for obj in payload
else
@_telegramRequest "setWebhook", url: "", (res) =>
@robot.logger.info "hubot-telegram-bot: Using long polling method. Disabling webhook."
setInterval =>
@_telegramRequest "getUpdates", offset: @offset + 1, (res) =>
@_processMsg obj for obj in res
, @refreshRate
@robot.logger.info "hubot-telegram-bot: Adapter running."
@emit "connected"
exports.use = (robot) ->
new Telegram robot<file_sep># hubot-telegram-bot
A Hubot adapter for [Telegram Bots](https://telegram.org/blog/bot-revolution) with zero external dependencies.
See [`src/telegram.coffee`](src/telegram.coffee) for full documentation.
## Installation via NPM
```
npm install --save hubot-telegram-bot
```
Now, run Hubot with the `telegram-bot` adapter:
```
./bin/hubot -a telegram-bot
```
## Configuration
Variable | Default | Description
--- | --- | ---
`TELEGRAM_BOT_TOKEN` | N/A | Your bot's authorisation token. You can create one by messaging [__BotFather__](https://telegram.me/botfather) `/newbot` [(Docs)](https://core.telegram.org/bots#botfather)
`TELEGRAM_BOT_REFRESH` | 1500 | The polling interval in seconds (i.e. how often should we fetch new messages from Telegram)
`TELEGRAM_BOT_WEBHOOK` | false | The webhook URL for incoming messages to be published by Telegram
|
58a06e3e74ace5b95e3039978e61582783009a2f
|
[
"CoffeeScript",
"Markdown"
] | 2 |
CoffeeScript
|
ClaudeBot/hubot-telegram-bot
|
dc11df3a82b039c12b5aae01255259ff61a61bfb
|
69c4b34a3d26165de1a3e4da00e515bbd0dd5607
|
refs/heads/master
|
<repo_name>theburningmonk/lambda-x-ray-demo<file_sep>/functions/utils.js
const AWSXRay = require('aws-xray-sdk')
const https = AWSXRay.captureHTTPs(require('https'))
const request = (method, hostname, path) => {
const options = { hostname, port: 443, path, method }
const promise = new Promise((resolve, reject) => {
const req = https.request(options, res => {
console.log('statusCode:', res.statusCode)
console.log('headers:', res.headers)
res.on('data', buffer => resolve(buffer.toString('utf8')))
})
req.on('error', err => reject(err))
req.end()
})
return promise
}
module.exports = {
request
}<file_sep>/serverless.yml
service: lambda-x-ray-demo
plugins:
- serverless-iam-roles-per-function
- serverless-lumigo
custom:
lumigo:
token: ${ssm:/dev/lumigo-token}
provider:
name: aws
runtime: nodejs14.x
stage: dev
region: us-east-1
tracing:
apiGateway: true
lambda: true
environment:
stage: ${self:provider.stage}
eventBridge:
useCloudFormation: true
functions:
service-a:
handler: functions/service-a.handler
timeout: 10
events:
- http:
path: /service-a
method: get
environment:
BUCKET_NAME: !Ref S3Bucket
TABLE_NAME: !Ref DynamoDB
TOPIC_ARN: !Ref Topic
QUEUE_URL: !Ref Queue
FUNCTION_NAME: !Ref CallLambdaFunction
STREAM_NAME: !Ref Kinesis
BUS_NAME: !Ref EventBus
iamRoleStatements:
- Effect: Allow
Action: dynamodb:PutItem
Resource: !GetAtt DynamoDB.Arn
- Effect: Allow
Action: s3:PutObject*
Resource:
- !GetAtt S3Bucket.Arn
- !Sub ${S3Bucket.Arn}/*
- Effect: Allow
Action: sns:Publish
Resource: !Ref Topic
- Effect: Allow
Action: sqs:SendMessage
Resource: !GetAtt Queue.Arn
- Effect: Allow
Action: lambda:InvokeFunction
Resource: !GetAtt CallLambdaFunction.Arn
- Effect: Allow
Action: kinesis:PutRecord
Resource: !GetAtt Kinesis.Arn
- Effect: Allow
Action: events:PutEvents
Resource: !GetAtt EventBus.Arn
- Effect: Allow
Action: xray:Put*
Resource: '*'
service-b:
handler: functions/service-b.handler
events:
- http:
path: /service-b
method: get
call:
handler: functions/service-c.handler
timeout:
handler: functions/timeout.handler
timeout: 1
events:
- http:
path: demo/timeout
method: get
error:
handler: functions/error.handler
events:
- http:
path: demo/error
method: get
sns:
handler: functions/sns.handler
events:
- sns:
topicName: test-topic
arn: !Ref Topic
sqs:
handler: functions/sqs.handler
events:
- sqs:
arn: !GetAtt Queue.Arn
batchSize: 10
s3:
handler: functions/s3.handler
events:
- s3:
existing: true
event: s3:ObjectCreated:*
bucket: !Ref S3Bucket
kinesis:
handler: functions/kinesis.handler
events:
- stream:
type: kinesis
arn: !GetAtt Kinesis.Arn
dynamodb:
handler: functions/dynamodb.handler
events:
- stream:
type: dynamodb
arn: !GetAtt DynamoDB.StreamArn
eventbridge:
handler: functions/event-bridge.handler
events:
- eventBridge:
eventBus: !GetAtt EventBus.Name
pattern:
source:
- xray-test
# you can add CloudFormation resource templates here
resources:
Resources:
S3Bucket:
Type: AWS::S3::Bucket
DynamoDB:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
StreamSpecification:
StreamViewType: NEW_AND_OLD_IMAGES
Topic:
Type: AWS::SNS::Topic
Properties:
TopicName: test-topic
Queue:
Type: AWS::SQS::Queue
QueuePolicy:
Type: AWS::SQS::QueuePolicy
Properties:
PolicyDocument:
Statement:
- Action:
- SQS:SendMessage
Effect: Allow
Resource: !GetAtt Queue.Arn
Principal:
Service: sns.amazonaws.com
Queues:
- !Ref Queue
Subscription:
Type: AWS::SNS::Subscription
Properties:
Protocol: sqs
Endpoint: !GetAtt Queue.Arn
TopicArn: !Ref Topic
Kinesis:
Type: AWS::Kinesis::Stream
Properties:
ShardCount: 1
EventBus:
Type: AWS::Events::EventBus
Properties:
Name: xray-test
<file_sep>/functions/error.js
module.exports.handler = async (event) => {
console.log(JSON.stringify(event))
console.log("this is going to error...")
throw new Error("boom")
}<file_sep>/functions/sns.js
module.exports.handler = async (event, context) => {
}
|
46cb77cb42aa508c060c1e99371827619082425c
|
[
"JavaScript",
"YAML"
] | 4 |
JavaScript
|
theburningmonk/lambda-x-ray-demo
|
3516c93c035198dafe9e1041fd10dea8d227460d
|
65999ae27a3ca6141fd74d5a22f3c6297672e8dc
|
refs/heads/master
|
<file_sep># Django To-Do-List
To do list coded in Python's Django framework
### Prerequisites
Django and Python 3.7
## Deployment
Migrate and start the server using:\
-python manage.py migrate\
-manage.py runserver
## Built With
* Python 3.7
* Django
* JQuery
|
0117152bc8383d6dee84bfc46648e10116c7e7b8
|
[
"Markdown"
] | 1 |
Markdown
|
MarioCode13/Django-To-Do-List
|
58195e0227ffa2b80623e947593dd6ad49eb0e9f
|
762dfaf7be913cb8cb9f9163625fd6440c67c0c0
|
refs/heads/master
|
<file_sep>package main
import (
"fmt"
"html/template"
"net/http"
)
func webfun(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Fprintln(w, "开启go web")
for k, v := range r.URL.Query() {
fmt.Println("key:", k, ", value:", v[0])
}
for k, v := range r.PostForm {
fmt.Println("key:", k, ", value:", v[0])
}
}
func name(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("./templates/index.html")
data := map[string]string{
"name": "data2",
}
t.Execute(w, data)
}
func main() {
http.HandleFunc("/", webfun)
http.HandleFunc("/name", name)
fmt.Println("服务启动")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("服务器开启错误:", err)
}
}
|
ab5ede52ab68ef974784b3ff5cd1611b9d52a987
|
[
"Go"
] | 1 |
Go
|
data2/go-web
|
9dce8b3a79ee25c6d33f9e82b85a7d0c8375c0dd
|
f27eb134b9f490a37633bb3e237a90f7e31292de
|
refs/heads/master
|
<file_sep>#Mon Feb 09 13:30:13 EST 2015
org.eclipse.core.runtime=2
org.eclipse.platform=4.4.0.v20140925-0400
<file_sep>#!/bin/bash
cd inputs
javac frontend.java
for file in *_day.txt
do
#runs the frontend of java
java frontend < $file > ../outputs/$file
#merge file contents to mergedTransactionSummaryFile.txt
cat *transaction_summary.txt > mergedTransactionSummaryFile.txt
done
javac backend.java
java backend
<file_sep>#!/bin/bash/
cd inputs
javac frontend.java
for file in *test_case.txt
do
java frontend < $file > ../outputs/$file
done
#java /Users/Weaver/Desktop/my.bitbucket/cisc-327-frontend/src/frontend < createAccountAsRetail_test_case.txt > ../outputs/createAccountAsRetail_test_case.txt<file_sep>import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Frontend {
static boolean loggedIn = false;
// static int type = 0; // if type = 1 its retail, if type=2 its agent
static LogInType type;
static ArrayList<String> transactionFile = new ArrayList<String>();
final static String CREATE = "04";
final static String DELETE = "05";
final static String DEPOSIT = "01";
final static String TRANSFER = "03";
final static String WITHDRAW = "02";
public static void main(String[] args) {
// TODO Auto-generated method stub
login();
}
public static void login(){
while (loggedIn == false) {
String logInCom = input("Please log in: Command>");
if (logInCom.equals("login")) {
loggedIn = true;
System.out.println("Log In Command Received");
} else {
System.out.println("Log In Command not received");
}
}
// if(loggedIn == true){
// Looking for type of user.
String logInTypeCom = input("Please enter a type of user. (Retail or Agent): Command>");
// System.out.println(logInTypeCom);
if (logInTypeCom.equals("retail")) {
// loggedIn = 1;
type = LogInType.RETAIL;
takeCommand();
} else if (logInTypeCom.equals("agent")) {
// loggedIn = 1;
type = LogInType.AGENT;
takeCommand();
} else {
System.out.println("Invalid command type");
System.exit(1);// Shouldnt exit, simply reset the command process
}
}
public static String input(String pretext) {
System.out.print(pretext);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String command = null;
try {
command = br.readLine();
command = command.toLowerCase();
} catch (IOException ioe) {
// Set up valid error message
System.out.println("IO error trying to read your name!");
System.exit(1);// Shouldnt exit, simply reset the command process
}
return command;
}
public static void takeCommand() {
String command = input("Command>");
if (command.equals("login")) {
error("You are already logged in.");
} else if (command.equals("logout")) {
front_logout();
} else if (command.equals("create")) {
if (type == LogInType.AGENT) {
front_create();
} else {
error("Invalid account type for delete.");
}
} else if (command.equals("delete")) {
if (type == LogInType.AGENT) {
front_delete();
} else {
error("Invalid account type for delete.");
}
} else if (command.equals("deposit")) {
front_deposit();
} else if (command.equals("withdraw")) {
front_withdraw();
} else if (command.equals("transfer")) {
front_transfer();
} else {
error("Invalid command");
}
}
public static void error(String errorMessage) {
System.out.println(errorMessage);
takeCommand();
}
public static void front_create() {
String accountNumber = input("Account Number:");
if (isAccountNumberValid(accountNumber) == false) {
error("Error: Invalid account number.");
} else {
// validate the account number
String accountName = input("Account Name:");
if (isAccountNameValid(accountName) == false) {
error("Error: Invalid account name.");
} else {
// validate the account name
accountNumber = addZeros(accountNumber, 6);// adds zeros in
// front if size is
// less than 6
transactionFile.add(CREATE + "_" + accountNumber + "_"
+ accountName);
System.out.println("Account created.");
}
}
}
public static void front_logout() {
loggedIn = false;
// run main function on frontend.java
System.out.println("Logging out...");
for (String s : transactionFile) {
writeToSummaryFile(s);
}
System.out.println("Logged out");
login();
}
public static void front_delete() {
String accountNumber = input("Please enter an account number:");
if (isAccountNumberValid(accountNumber) == false) {
error("Error: Invalid account number.");
} else {
String accountName = input("Please enter an acount name:");
if (isAccountNameValid(accountName) == false) {
error("Error: Invalid account name.");
} else {
accountNumber = addZeros(accountNumber, 6);// adds zeros in
// front if size is
// less than 6
transactionFile.add(DELETE + "_" + accountNumber + "_"
+ accountName);
// write.writeToSummaryFile(str);
System.out.println("Account deleted.");
}
}
}
public static void front_deposit() {
// get account number
// get amount
String accountNumber = input("Account Number:");
if (isAccountNumberValid(accountNumber) == false) {
error("Error: Invalid account number.");
} else {
if (doesAccountExists(accountNumber) == false) {
error("Error: Account doesnt exist.");
} else {
String accountAmount = input("Account Amount:");
if (isAccountAmountValid(accountAmount) == false) {
error("Error: Invalid account amount.");
} else {
if (lowerLimit(accountAmount) == false) {
error("Error: Invalid account amount. Must be greater than 0.");
} else {
if (upperLimit(accountAmount) == false) {
error("Error: Invalid account amount. The amount is too high for the type of login.");
} else {
// convert amountStr to int well more validate
// make sure the account number is long enough
// Does there have to be an account name?
// make sure its a valid account
accountAmount = addZeros(accountAmount, 8);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 8
accountNumber = addZeros(accountNumber, 6);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 6
transactionFile.add(DEPOSIT + "_" + accountNumber
+ "_" + accountAmount);
System.out.println("Successful Deposit.");
}
}
}
}
}
}
public static void front_transfer() {
String toAccountNumber = input("To Account Number:");
if (isAccountNumberValid(toAccountNumber) == false) {
error("Error: Invalid 'to' account.");
} else {
String fromAccountNumber = input("From Account Number:");
if (isAccountNumberValid(fromAccountNumber) == false) {
error("Error: Invalid 'From' account.");
} else {
String accountAmount = input("Account Amount:");
if (isAccountAmountValid(accountAmount) == false) {
error("Error: Invalid amount.");
} else {
if (lowerLimit(accountAmount) == false) {
error("Error: Invalid account amount. Must be greater than 0.");
} else {
if (upperLimit(accountAmount) == false) {
error("Error: Invalid account amount. The amount is too high for the type of login.");
} else {
// convert amountStr to int well more validate
// make sure the account number is long enough
// Does there have to be an account name?
// make sure they are both valid accounts
accountAmount = addZeros(accountAmount, 8);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 8
fromAccountNumber = addZeros(fromAccountNumber, 6);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 6
toAccountNumber = addZeros(toAccountNumber, 6);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 6
transactionFile.add(TRANSFER + "_"
+ toAccountNumber + "_" + fromAccountNumber
+ "_" + accountAmount);
// write.writeToSummaryFile(str);
System.out.println("Successful Transfer.");
}
}
}
}
}
}
public static boolean isAccountNameValid(String name) {
// name
// Make sure the whole name is letters.
boolean valid = true;
for (char ch : name.toCharArray()) {// /change to REGULAR EXPRESSION!
int asciiVal = (int) ch;
// if((65 <= asciiVal <= 90) || (97 <= asciiVal <= 122) || (asciiVal
// == 32)){
if ((asciiVal >= 65) || (asciiVal <= 90) || (asciiVal >= 97)
|| (asciiVal <= 122)) {
// a - z
// space
// A - Z
valid = true;
} else {
valid = false;
}
}
return valid;
}
public static boolean isAccountNumberValid(String number) {
// covert the string to integers
try {
int x = Integer.parseInt(number);
} catch (NumberFormatException e) {
return false;
}
// check length make sure the account is the proper length
if (!(number.length() <= 8)) {
return false;
}
return true;
}
public static boolean doesAccountExists(String number) {
// Check Account File for the account.
// Check length, if its less or equal to 8.
// if less add zeros.
if (number.length() > 8) {
return false;
}
String newAccountNumber = "";
if (number.length() < 8) {
newAccountNumber = addZeros(number, 8);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("./src/valid_accounts.txt"));
while ((sCurrentLine = br.readLine()) != null) {
if (number.length() == 8) {
if (sCurrentLine == number) {
return true;
}
} else {
if (sCurrentLine == newAccountNumber) {
return true;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static boolean isAccountAmountValid(String number) {
try {
int x = Integer.parseInt(number);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public static String addZeros(String number, int size) {
// get the number and subtrack it by 8 and add that many zeros
int length = number.length();
int additionalZeros = size - length;
for (int i = 0; i < additionalZeros; i++) {// use regex code
number = "0" + number;
}
return number;
}
public static boolean lowerLimit(String amount) {
try {
if (Integer.parseInt(amount) > 0) {
return true;
}
} catch (NumberFormatException e) {
// should not reach here because we validate before.
System.out.println("Error 0001");
System.exit(1);
}
return false;
}
public static boolean upperLimit(String amount) {
try {
if (type == LogInType.RETAIL) {
// retail mode
if (!(Integer.parseInt(amount) > 100000)) {// above 1,000.00
return true;
}
} else if (type == LogInType.AGENT) {
// agent
if (!(Integer.parseInt(amount) > 99999999)) {// above 999,999.99
return true;
}
} else {
// error
// Should never get here b/c in order to perform an action they
// must be logged in.
System.out.println("Error 0003");
System.exit(1);
}
} catch (NumberFormatException e) {
// should not reach here because we validate before.
System.out.println("Error 0002");
System.exit(1);
}
return false;
}
public static boolean withdrawLimit(String accountNumber,
String accountAmount) {
int totalAmount = Integer.parseInt(accountAmount);
for (String transactionStr : transactionFile) {// REGEX
int itemNum = 0;
boolean userAccount = false;
for (String str : transactionStr.split("_", 3)) {
// loops 3 items
if (itemNum == 0) {
itemNum++;
userAccount = false;
} else if (itemNum == 1) {
// account number
if (str == accountNumber) {
userAccount = true;
}
itemNum++;
} else {
// account amount
if (userAccount == true) {
int amount = Integer.parseInt(str);
totalAmount += amount;
if ((totalAmount) > 1000) {
return false;
}
userAccount = false;
}
itemNum++;
}
}
}
return true;
}
public static void front_withdraw() {
// get account number
// get amount
String accountNumber = input("Account Number:");
if (isAccountNumberValid(accountNumber) == false) {
error("Error: Invalid account number.");
} else {
if (doesAccountExists(accountNumber) == false) {
error("Error: Invalid account number.");
} else {
String accountAmount = input("Account Amount:");
if (isAccountAmountValid(accountAmount) == false) {
error("Error: Invalid account amount.");
} else {
if (lowerLimit(accountAmount) == false) {
error("Error: Invalid account amount. Must be greater than 0.");
} else {
if (upperLimit(accountAmount) == false) {
error("Error: Invalid account amount. The amount is too high for the type of login.");
} else {
if (withdrawLimit(accountNumber, accountAmount) == false) {
error("Error: Invalid account amount. The amount is too high for the type of login.");
} else {
// Pad Zeros on account number, account amount
accountAmount = addZeros(accountAmount, 8);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 8
accountNumber = addZeros(accountNumber, 6);// adds
// zeros
// in
// front
// if
// size
// is
// less
// than
// 6
transactionFile.add(WITHDRAW + "_"
+ accountNumber + "_" + accountAmount);
// write.writeToSummaryFile(str);
System.out.println("Successful Withdraw.");
}
}
}
}
}
}
}
public static void writeToAccountsFile(String content) {
try {
File file = new File("./src/valid_accounts.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Written to the accounts file.");
} catch (IOException e) {
// e.printStackTrace();
error("Error: Unable to write to accounts file.");
}
}
public static void writeToSummaryFile(String content) {
try {
File file = new File("./src/transaction_summary.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Written to the accounts file.");
} catch (IOException e) {
// e.printStackTrace();
error("Error: Unable to write to accounts file.");
}
}
}
<file_sep>#!/bin/bash
cd inputs
javac frontend.java
java frontend
`login`
`retail`<file_sep># Quinterac-Bank-System
CISC 327 Course Project. Built in Java
<file_sep>#!/bin/bash
cd inputs
javac /Users/Weaver/Desktop/my.bitbucket/cisc-327-frontend/src/frontend.java
java /Users/Weaver/Desktop/my.bitbucket/cisc-327-frontend/src/frontend
for file in *test_case.txt
do
java /Users/Weaver/Desktop/my.bitbucket/cisc-327-frontend/src/frontend < $file > ../outputs/$file.txt
done
|
8c312b513e7414815687fcb46b75fe50d1dd4efd
|
[
"Java",
"Markdown",
"Shell",
"INI"
] | 7 |
Java
|
kweaver00/Quinterac-Bank-System
|
b7a5c59425c8c27feeea983ca8eb65e393376382
|
5bd454ecd20d628088d6edf41a7d43e849d6a8df
|
refs/heads/master
|
<repo_name>sukkla01/mycarlist<file_sep>/src/Header.js
import React, { Component } from 'react';
class Header extends Component {
constructor(props) {
super(props)
this.handleHeaderClick = this.handleHeaderClick.bind(this)
}
handleHeaderClick() {
alert(this.props.currentUser)
}
render() {
let { currentUser, isLoggedIn } = this.props
// currentUser = "Logg in as " + currentUser
return (
<div>
<nav class="navbar fixed-top navbar-light bg-secondary">
<a class="navbar-brand text-white" href="#">React MyCar</a>
</nav>
</div>
);
}
}
export default Header;<file_sep>/src/App.js
import React, { Component } from 'react';
import Header from './Header'
import Footer from './Footer'
import TodoInput from './TodoInput'
import CarList from './CarList'
import CarItem from './CarItem';
class App extends Component {
constructor(props){
super(props)
this.state = {
currentTime:0,
carItem:[]
}
this.handleFooterClick= this.handleFooterClick.bind(this)
this.onAddCar = this.addCar.bind(this)
this.addCar= this.addCar.bind(this)
}
handleFooterClick(time){
this.setState({ currentTime: time})
}
addCar(newCar){
this.setState({
carItem: this.state.carItem.concat([newCar])
})
}
render() {
let { currentTime,carItem } =this.state
return (
<div>
<hr/>
Add My Car :
<br />
<br />
<TodoInput onAddCar= { this.addCar} />
<CarList items={carItem} />
<hr/>
<Header currentUser="Sujin" isLoggedIn={true} />
<div>currenttime : { currentTime }</div>
<Footer onTimerClick={this.handleFooterClick}/>
</div>
);
}
}
export default App;
<file_sep>/push.bat
git add -A
git commit -m "jub %date% %time%"
git push orgin master<file_sep>/src/Footer.js
import React, { Component } from 'react';
class Footer extends Component {
constructor (prop){
super(prop)
this.state = {
time :0
}
setInterval(()=>{
this.setState({
time: this.state.time+1
})
},1000)
}
render() {
let {time} = this.state
let { onTimerClick } = this.props
return (
<div>
<div onClick={()=>onTimerClick(time)}>Footer Online Time { time }</div>
</div>
);
}
}
export default Footer;
|
db50a1bf49ed66a9e7208019fe3cd122cc565122
|
[
"Batchfile",
"JavaScript"
] | 4 |
Batchfile
|
sukkla01/mycarlist
|
291117b6d6ae510acda0533f459adde1016e0856
|
138bda0b45ffee446e803e4728d3f0583012d360
|
refs/heads/master
|
<repo_name>herbertpaz13/Laboratorio3<file_sep>/Laboratorio3.cpp
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
using std::cout;
using std::endl;
using std::cin;
void ordenamiento(int[],int);
void imprimir(int[]);
int main(int argc, char*argv[]){
srand(time(NULL));
cout<<"Laboratorio 3"<<endl;
cout<<"1. Ejercicio 1"<<endl;
cout<<"2. Ejercicio 2"<<endl;
int respuesta;
cout<<"Eleccion: ";
cin>>respuesta;
cout<<endl;
if(respuesta==1){
const int size=10;
int arreglo[size];
for(int i=0;i<size;i++){
arreglo[i]=rand()%20+1;
}
ordenamiento(arreglo,size);
cout<<"Bienvenido"<<endl;
cout<<"EL NUMERO MAGICO"<<endl;
cout<<endl;
int numero;
bool resp=true;
int aleatorio;
int contador=0;
aleatorio=-500+rand()%(501-(-500));
while(resp){
contador++;
cout<<"ingrese el numero: ";
cin>>numero;
if(numero==aleatorio){
resp=false;
cout<<endl;
cout<<"GANASTEEEEE"<<endl;
}else{
if(numero>aleatorio){
cout<<"El numero es menor"<<endl;
}else{
cout<<"El numero es mayor"<<endl;
}
}
}
cout<<"Cantidad de intentos: "<<contador<<endl;
if(contador>arreglo[9]){
cout<<"Lo sentimos,no alcanzo entrar al highscore"<<endl;
imprimir(arreglo);
}else{
cout<<"Felicidades estas entre los mejores resultados"<<endl;
arreglo[9]=contador;
ordenamiento(arreglo,size);
imprimir(arreglo);
}
} else if(respuesta==2){
cout<<endl;
cout<<"Matriz"<<endl;
const int ROW=4;
const int COL=3;
int matriz[ROW][COL];
for(int i=0;i<ROW;i++){
matriz[i][0]=85+rand()%(116-(85));
}
for(int i=0;i<ROW;i++){
matriz[i][1]=50+rand()%(76-(50));
}
for(int i=0;i<ROW;i++){
matriz[i][2]=150+rand()%(201-(150));
}
int continuar=1;
while(continuar==1){
for(int i=0;i<ROW;i++){
for(int j=0;j<COL;j++){
cout<<matriz[i][j]<<" ";
}
cout<<endl;
}
int random1=rand()%3;
int random2=rand()%3;
int random3=rand()%3;
int random4=rand()%3;
int random5=rand()%3;
int random6=rand()%3;
//jugador 1
int ataque1 = matriz[random1][0];
int defensa1 = matriz[random2][1];
int velocidad1 = matriz[random3][2];
//jugador 2
int ataque2 = matriz[random4][0];
int defensa2 = matriz[random5][1];
int velocidad2 = matriz[random6][2];
cout<<endl;
cout<<"Jugador 1: Ataque "<<ataque1<<" Defensa "<<defensa1<<" Velocidad "<<velocidad1<<endl;
cout<<"Jugador 2: Ataque "<<ataque2<<" Defensa "<<defensa2<<" Velocidad "<<velocidad2<<endl;
int punto1=ataque1-defensa2;
int punto2=ataque2-defensa1;
cout<<endl;
cout<<"Jugador 1: "<<punto1<<" puntos"<<endl;
cout<<"Jugador 2: "<<punto2<<" puntos"<<endl;
cout<<endl;
if(punto1>punto2){
cout<<"Jugador 1,gana con "<<punto1-punto2<<" de diferencia,no gano por velocidad"<<endl;
}else if(punto2>punto1){
cout<<"Jugador 2,gana con "<<punto2-punto1<<" de diferencia,no gano por velocidad"<<endl;
}else if(punto1==punto2){
if(velocidad1>velocidad2){
cout<<"Jugador 1,gano,si gano por velocidad"<<endl;
}else if(velocidad2>velocidad1){
cout<<"Jugador 2,gano,si gano por velocidad"<<endl;
}else if(velocidad1==velocidad2){
cout<<"Hubo un empate absoluto"<<endl;
}
}
cout<<"Desea seguir jugando[1/0]: ";
cin>>continuar;
cout<<endl;
}
}else{
cout<<"Opcion que tecleo no es valida"<<endl;
}
return 0;
}
void ordenamiento(int arreglo[],int size){
int p1,p2,y;
int size1=size;
bool bandera=true;
while((size1>1)&&(bandera==true)){
y=0;
p1 = arreglo[y];
p2 = arreglo[y+1];
size1--;
bandera=false;
for(int i=0;i<size1;i++){
if(p1>p2){
arreglo[i]=p2;
arreglo[i+1]=p1;
bandera=true;
}
y++;
if(y<size1){
p1 = arreglo[y];
p2 = arreglo[y+1];
}
}
}
}
void imprimir(int arreglo[]){
cout<<endl;
cout<<"Tabla de Highscore"<<endl;
cout<<"Primero "<<arreglo[0]<<endl;
cout<<"Segundo "<<arreglo[1]<<endl;
cout<<"Tercero "<<arreglo[2]<<endl;
cout<<"Cuarto "<<arreglo[3]<<endl;
cout<<"Quinto "<<arreglo[4]<<endl;
cout<<"Sexto "<<arreglo[5]<<endl;
cout<<"Septimo "<<arreglo[6]<<endl;
cout<<"Octavo "<<arreglo[7]<<endl;
cout<<"Noveno "<<arreglo[8]<<endl;
cout<<"Decimo "<<arreglo[9]<<endl;
cout<<endl;
}
|
e95055e860dc2e9026b56652e4b0bc3b98d52a84
|
[
"C++"
] | 1 |
C++
|
herbertpaz13/Laboratorio3
|
ab9bd89dc38fce898616908f23723e00c02daedb
|
734f5e9316e5b63c9e18cabe8ed78c85c4dc4131
|
refs/heads/master
|
<file_sep># hello-world
repository
Let´s talk about pomerains.
|
d0caf83f6fd920f1ef97748c3b3c08eff9e0da06
|
[
"Markdown"
] | 1 |
Markdown
|
nathaliahalla/hello-world
|
ea78bc1c515703c96e36fc7aa4ceb4fdf0ad472b
|
748a018d5d2b84b81471da449b6609e66781c73a
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
import dice
import streets
import player
'''Start event loop'''
def get_player_ready():
playerlist_length = len(player.playerlist)
print("Anzahl der Spieler: ", playerlist_length)
press = input("Los gehts mit [Enter]...")
if press == "":
start_game(playerlist_length)
else:
quit()
def start_game(playerlist_length):
for element in range(0, playerlist_length):
print("Spieler "+player.playerlist[element]+" würfelt!")
play(player.playerlist[element])
decision = input("Nächster Spieler? (y/n)")
if decision == "y" and (int(playerlist_length)-int(element) == 1):
#print("Element: "+str(element)+" / Player: "+str(playerlist_length))
start_game(playerlist_length)
elif decision == "y" and element < playerlist_length:
#print("Element: "+str(element)+" / Player: "+str(playerlist_length))
continue
else:
main()
def play(playername):
spieler = player.Playerclass(playername, 10000)
print(spieler.name)
wurf = spieler.throw_dice()
print(wurf)
# throw_dice and move to field number X
# Klasse player
# playername
# playerid (einmalig)
# kontostand
# zahlen
# kassieren
# aktuelles feld
# würfeln
# feld wechseln
# kartenbesitz
# karte ziehen
# karte anwenden
# karte behalten
# Straßenbesitz
# mit drei Straßen
# mit einem Haus
# ...
# mit Hypothek
# Werkbesitz
# mit einem Werk
# Bahnhofsbesitz
# mit einem Bahnhof
# ...
# add player profile
go_to_field = spieler.move_forward()
print(str(playername)+" würfelt eine "+str(wurf))
print(str(playername)+" landet auf Feld "+str(go_to_field))
doublecheck = dice.double[0]
if doublecheck == 1:
print("Pasch!")
# a) User plays again
# b) User goes to Jail
else:
pass
# If move-to-field is a street...
if dice.get_field_type(go_to_field) == "street":
# start an instance of class Street()...
move_to_street = streets.Street()
print("Straßenname: ", move_to_street.allstreets[go_to_field])
print("Basismiete:", move_to_street.allbaserents[go_to_field])
#print("Miete mit allen Straßen: ", move_to_street.allbaserents_with_all_streets[go_to_field])
#print("Miete mit einem Haus:", move_to_street.allbaserent_with_one_house[go_to_field])
#print("Miete mit zwei Häusern: ", move_to_street.allbaserent_with_two_houses[go_to_field])
#print("Miete mit drei Häusern:", move_to_street.allbaserent_with_three_houses[go_to_field])
#print("Miete mit vier Häusern: ", move_to_street.allbaserent_with_four_houses[go_to_field])
#print("Miete mit einem Hotel:", move_to_street.allbaserent_with_one_hotel[go_to_field])
# ...check, who the street belongs to...
# ...pay rent, buy houses, hotels, take mortage...
elif dice.get_field_type(go_to_field) == "community":
#print("Community!")
pass
elif dice.get_field_type(go_to_field) == "taxes":
#print("Taxes!")
pass
elif dice.get_field_type(go_to_field) == "station":
#print("Station!")
pass
elif dice.get_field_type(go_to_field) == "event":
#print("Event!")
pass
elif dice.get_field_type(go_to_field) == "visiting":
#print("Visiting!")
pass
elif dice.get_field_type(go_to_field) == "plant":
#print("Plant!")
pass
elif dice.get_field_type(go_to_field) == "parking":
print("Free Parking!")
# update player profile
# autosave player profile
# autosave state
def main_menu():
print("Willkommen bei Monopoly.")
print("")
print("\t\tNeues Spiel starten [n].")
print("\t\tAltes Spiel laden [l].")
print("\t\tEinstellungen ändern [e].")
print("\t\tSpiel fortsetzen [f].")
print("\t\tSpiel beenden [b].")
print("")
choice = input("Wähle eine Option:")
if choice == "n":
player.add_number_of_players()
elif choice == "l":
pass
elif choice == "e":
pass
elif choice == "f":
pass
elif choice == "b":
quit()
def main():
main_menu()
get_player_ready()
main()
"""
# write in json file
import json
file = open('/filesave/playername.json', 'w+')
data = { "x": 12153535.232321, "y": 35234531.232322 }
json.dump(data, file)
# https://stackoverflow.com/questions/4450144/easy-save-load-of-data-in-python#4450248
# load from json file
import json
file = open('/usr/data/application/json-dump.json', 'r')
print json.load(file) """<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
def get_playername(currentplayername):
print("Spielername: ", str(currentplayername))
""" def next_turn():
print("Erste Runde")
input("Restart?") """<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
# 13 Einträge als Test
class Street:
allstreets = 'Badstraße', 0, 'Turmstraße', 0, 0, 'Chausseestraße', 0, 'Elisenstraße', 'Poststraße', 0, 'Seestraße', 0, 0
allbaserents = 2, 0, 4, 0, 0, 6, 0, 6, 8, 0, 10, 0, 0
allbaserents_with_all_streets = 4, 0, 8, 0, 0, 12, 0, 12, 16, 0, 20, 0, 0
allstreetprices = 60, 0, 60, 0, 0, 100, 0, 100, 120, 0, 140, 0, 0
allhouseprices = 50, 0, 50, 0, 0, 50, 0, 50, 50, 0, 100, 0, 0
allbaserent_with_one_house = 10, 0, 20, 0, 0, 30, 0, 30, 40, 0, 50, 0, 0
allbaserent_with_two_houses = 30, 0, 60, 0, 0, 90, 0, 90, 100, 0, 150, 0, 0
allbaserent_with_three_houses = 90, 0, 180, 0, 0, 270, 0, 270, 300, 0, 450, 0, 0
allbaserent_with_four_houses = 160, 0, 320, 0, 0, 400, 0, 400, 450, 0, 625, 0, 0
allbaserent_with_one_hotel = 250, 0, 450, 0, 0, 550, 0, 550, 600, 0, 750, 0, 0
class Plant:
pass
class Community:
pass
class Event:
pass
class Go:
pass
class Taxes:
pass
class Jail:
pass
<file_sep>
var scene = new THREE.Scene();
//(Field of view, Aspect Ratio, nahe sichtbare Ebene, ferne sichtb...)
var camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000 );
var renderer = new THREE.WebGLRenderer({});
//set background color
renderer.setClearColor( 0xFFFFFF, 1)
// viewable area in browser window
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// Plane
// Tile dimensions
var plane_width = 50;
var plane_height = 50;
var plane_depth = 0;
// Plane Position
var globalPosX = 0;
var globalPosY = 0;
var globalPosZ = 0;
var geometry = new THREE.BoxGeometry( plane_width, plane_depth, plane_height );
var material = new THREE.MeshBasicMaterial({
ambient: 0xFFFFFF,
color: 0x5ECD00,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var plane = new THREE.Mesh(geometry, material);
plane.position.x = globalPosX;
plane.position.y = globalPosY;
plane.position.z = globalPosZ;
scene.add( plane );
scene.add(new THREE.AmbientLight(0x00FFC6));
// Unit positions
// Box dimensions
var width = 5;
var height = 5;
var depth = 5;
// Absolute Position
var globalPosX = -20;
var globalPosY = 5;
var globalPosZ = -20;
// Unit
var geometry = new THREE.BoxGeometry( width, depth, height );
var material = new THREE.MeshPhongMaterial({
//var material = new THREE.MeshBasicMaterial({
ambient: 0xFFFFFF,
color: 0x20C220,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile = new THREE.Mesh(geometry, material);
tile.position.x = globalPosX;
tile.position.y = globalPosY;
tile.position.z = globalPosZ;
scene.add( tile );
scene.add(new THREE.AmbientLight(0x00FFC6));
// Trace
var geometry = new THREE.BoxGeometry( width, depth, height );
var material = new THREE.MeshPhongMaterial({
//var material = new THREE.MeshBasicMaterial({
ambient: 0xFFFFFF,
color: 0x000000,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var trace = new THREE.Mesh(geometry, material);
trace.position.x = globalPosX;
trace.position.y = globalPosY;
trace.position.z = globalPosZ;
scene.add( trace );
scene.add(new THREE.AmbientLight(0x00FFC6));
// Camera
camera.position.set(50, 50, 50);
camera.lookAt(scene.position);
var light = new THREE.PointLight(0xffffff, 6, 40);
light.position.set(10, 20, 15);
scene.add(light);
function render() {
// Random number between 0.1 and 1.0
function makerndx () {
var rndx = Math.floor((Math.random() * 1) + 0.1);
return rndx;
}
function makerndz () {
var rndz = Math.floor((Math.random() * 1) + 0.1);
return rndz;
}
function forward () {
tile.position.x += makerndx();
trace.position.x += makerndx();
tile.position.z += makerndz();
trace.position.z += makerndz();
}
if ((tile.position.x < 20 && tile.position.z < 20) || (trace.position.x < 20 && trace.position.z < 20)) {
forward();
}
requestAnimationFrame( render );
renderer.render( scene, camera );
}
render();
/*
// Box 1
var geometry = new THREE.BoxGeometry( 1, 0.1, 1 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile1 = new THREE.Mesh(geometry, material);
tile1.position.x = -5;
tile1.position.y = -5;
tile1.position.z = 0;
scene.add( tile1 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Box 2
var geometry = new THREE.BoxGeometry( 0.95, 0.1, 0.95 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile2 = new THREE.Mesh(geometry, material);
tile2.position.x = -3.6;
tile2.position.y = -3.6;
tile2.position.z = 0;
scene.add( tile2 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Box 3
var geometry = new THREE.BoxGeometry( 0.9, 0.1, 0.9 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile3 = new THREE.Mesh(geometry, material);
tile3.position.x = -2.35;
tile3.position.y = -2.35;
tile3.position.z = 0;
scene.add( tile3 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Box 4
var geometry = new THREE.BoxGeometry( 0.85, 0.1, 0.85 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile3 = new THREE.Mesh(geometry, material);
tile3.position.x = -1.2;
tile3.position.y = -1.2;
tile3.position.z = 0;
scene.add( tile3 );
scene.add(new THREE.AmbientLight(0x4000ff));
*/
<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
"""Set up all players"""
player_minimum = 2
player_maximum = 4
player_name_max_length = 12
playerlist = []
addplayer = []
def add_number_of_players():
chose_players = input(
"Zahl der Spieler "
"(["+str(player_minimum)+"] "
"bis ["+str(player_maximum)+"]): ")
# we need to add one player for the range statement
number_of_players = ((int(chose_players)+1))
if int(chose_players) < player_minimum:
print ("Falsche Eingabe")
elif int(chose_players) > player_maximum:
print ("Falsche Eingabe")
else:
name_players(number_of_players)
def name_players(number_of_players):
for i in list(range(1,number_of_players)):
addplayer = input(
"Bitte wähle einen Namen"
" für Spieler "+str(i)+" "
"(nur Buchstaben): ")
if addplayer and len(addplayer) > player_name_max_length:
print(
"Bitte nicht mehr als "
""+str(player_name_max_length)+" "
"Buchstaben eingeben.")
break
else:
add_player(addplayer)
print("Spieler "+str(i)+" heißt "+str(addplayer)+"!")
def add_player(addplayer):
playerlist.append(addplayer)
return playerlist<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
import random
"""Set up all players"""
player_minimum = 2
player_maximum = 4
first_player = 1
player_name_max_length = 12
playerlist = []
addplayer = []
onfield = [0]
double = [0]
move_fwd = 0
dice_result = [0]
def add_number_of_players():
chose_players = input(
"Zahl der Spieler "
"(["+str(player_minimum)+"] "
"bis ["+str(player_maximum)+"]): ")
check_input(chose_players)
def check_input(chose_players):
try:
chose_players = int(chose_players)
evaluate_input(chose_players)
except ValueError:
print("Bitte eine Zahl eingeben!")
add_number_of_players()
def evaluate_input(chose_players):
if int(chose_players) < player_minimum:
print("Zahl zu klein.")
add_number_of_players()
elif int(chose_players) > player_maximum:
print("Zahl zu groß.")
add_number_of_players()
else:
# we need to add one player for the range statement
number_of_players = ((int(chose_players)+1))
name_players(number_of_players)
def name_players(number_of_players):
for player in list(range(first_player,number_of_players)):
add_playernames(player)
def add_playernames(player):
addplayer = input(
"Bitte wähle einen Namen"
" für Spieler "+str(player)+" "
"(nur Buchstaben): ")
if addplayer and len(addplayer) > player_name_max_length:
print(
"Bitte nicht mehr als "
""+str(player_name_max_length)+" "
"Buchstaben eingeben.")
add_playernames(int(player))
else:
add_player(addplayer)
print("Spieler "+str(player)+" heißt "+str(addplayer)+"!")
def add_player(addplayer):
playerlist.append(addplayer)
return playerlist
class Playerclass:
def __init__(self, name, credit):
self.name = name
self.credit = credit
def throw_dice(self):
'''Throw two dice, add result and return'''
dice1 = random.randrange(1, 7)
dice2 = random.randrange(1, 7)
result_of_dices = ((dice1 + dice2))
# check for double
if dice1 == dice2:
double[0] = 1
else:
double[0] = 0
return result_of_dices
def move_forward(self):
dice_result[0] = Playerclass.throw_dice(self)
move_fwd = ((onfield[0] + dice_result[0]))
if move_fwd > 12:
move_fwd = ((onfield[0] + dice_result[0] - 12))
onfield[0] = move_fwd
return move_fwd
else:
onfield[0] = move_fwd
return move_fwd<file_sep>def get_field_type(from_dice_number):
fieldtypes = 'street', 'community', 'street', 'taxes', 'station', 'street', 'event', 'street', 'street', 'visiting', 'street', 'plant', 'station'
return fieldtypes[from_dice_number]
class Street:
allstreets = 'Badstraße', 0, 'Turmstraße', 0, 0, 'Chausseestraße', 0, 'Elisenstraße', 'Poststraße', 0, 'Seestraße', 0, 0
allrents = 2, 0, 4, 0, 0, 6, 0, 6, 8, 0, 10, 0, 0
class Station:
allstations = 0, 0, 0, 0, 'Südbahnhof', 0, 0, 0, 0, 0, 0, 0, 'Westbahnhof'
class Plant:
pass
class Community:
pass
class Event:
pass
class Go:
pass
class Taxes:
pass
class Jail:
pass
<file_sep>FROM ubuntu:18.04
LABEL description="This container contains an Ubuntu 18.04, Flask."
MAINTAINER <NAME> "<EMAIL>"
ENV TERM=xterm
ENV HOME /home/flask
RUN apt-get update && \
apt-get install -y python3-pip python3-venv locales vim && \
groupadd -r flask && \
useradd -r -u 1000 -g flask flask && \
mkdir -p /home/flask/mnp
RUN locale-gen de_DE.UTF-8
ENV LANG de_DE.UTF-8
ENV LANGUAGE de_DE.UTF-8
ENV LC_ALL de_DE.UTF-8
RUN chown flask:flask -R /home/flask && \
cd /home/flask/mnp
CMD ["/bin/bash", "start"]
WORKDIR /home/flask/mnp
USER flask
# Container bauen
# sudo docker build -t ubuntu1804/flask:1.0 .
# Container starten
# sudo docker run -ti -h Flask -v /mnp:/home/flask/mnp --name FLASK --user flask -p 127.0.0.1:5000:5000 ubuntu1804/flask:1.0
# Startskript m. Auto-Reload bei Änderungen (Debug) und Erreichbarkeit auf 127.0.0.1:5000
<file_sep>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 10, window.innerWidth / window.innerHeight, 1, 1000 );
var renderer = new THREE.WebGLRenderer({});
renderer.setClearColor( 0xffffff, 1)
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// Box 1
class newtile (vx,vy,vz){
var geometry = new THREE.BoxGeometry( 1, 0.1, 1 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile1 = new THREE.Mesh(geometry, material);
tile1.position.x = vx;
tile1.position.y = vy;
tile1.position.z = vz;
scene.add( tile1 );
scene.add(new THREE.AmbientLight(0x4000ff));
}
// Camera
camera.position.set(20, 20, 20);
camera.lookAt(scene.position);
var light = new THREE.PointLight(0xffffff, 6, 40);
light.position.set(10, 20, 15);
scene.add(light);
function render() {
requestAnimationFrame( render );
renderer.render( scene, camera );
}
render();
<file_sep># monopoly
This is supposed to become a browser-based monopoly version [very much work-in-progress]
with Python/Flask serving as backend logic and Node/Three.js for the graphical and server part.
<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
import random
double = [0]
move_fwd = 0
dice_result = [0]
onfield = [0]
playername = ['Hans', 'Franz']
class Playerclass:
def __init__(self, name, credit, dice, field):
self.name = name
self.credit = credit
self.dice = dice
self.field = field
def throw_dice(self):
dice = random.randrange(1, 7)
return dice
def move_forward(self, playername, playerdice, playerfield):
move_fwd = ((playerfield + playerdice))
if move_fwd > 12:
move_fwd = ((playerfield + playerdice - 12))
playerfield = move_fwd
return playerfield
else:
playerfield = move_fwd
return playerfield
def play(playername):
player = Playerclass(playername, 0, 0, 0)
playerdice = player.throw_dice()
playercredit = 1500
playerfield = player.move_forward(playername, playerdice, player.field)
player.field = playerfield
print("Spieler: "+str(playername)+""
" würfelt eine "+str(playerdice)+""
" landet auf Feld "+str(playerfield)+""
" und verfügt über: "+str(playercredit)+" Monopoly-Dollar.")
for elements in range(0,len(playername)):
play(playername[elements])
if elements > len(playername):
elements = 0
""" def throw_dice(self):
'''Throw two dice, add result and return'''
dice1 = random.randrange(1, 7)
dice2 = random.randrange(1, 7)
result_of_dices = ((dice1 + dice2))
# check for double
if dice1 == dice2:
double[0] = 1
else:
double[0] = 0
return result_of_dices
def move_forward(self):
dice_result[0] = Playerclass.throw_dice(self)
move_fwd = ((playerfield + dice_result[0]))
if move_fwd > 12:
move_fwd = ((playerfield + dice_result[0] - 12))
playerfield = move_fwd
return move_fwd
else:
playerfield = move_fwd
return move_fwd
for player in range(0,len(playername)):
spieler = Playerclass(playername[player], 10000)
print(spieler.name)
wurf = spieler.throw_dice()
print(wurf)
go_to_field = spieler.move_forward()
print(str(spieler.name)+" würfelt eine "+str(wurf))
print(str(spieler.name)+" landet auf Feld "+str(go_to_field))
doublecheck = double[0]
if doublecheck == 1:
print("Pasch!")
# a) User plays again
# b) User goes to Jail
else:
pass
"""
""" import player
import dice
playerlist = ["Eins", "Zwo", "Drei", "Vier", "Fünf", "Sechs"]
def get_player_ready():
playerlist_length = 6
print("Anzahl der Spieler: ", playerlist_length)
print("Los gehts!")
start_game()
def start_game():
playerlist_length = 6
for element in range(0, playerlist_length):
print("Spieler "+playerlist[element]+" würfelt!")
# dice
# If Pasch
# play(playerlist[element])
# play again
# Else
# play(playerlist[element])
def play(playername):
print("Dice")
print("Kaufen")
print("Spieler:", playername)
"""
""" def add_players():
chose_players = input(
"Zahl der Spieler "
"([2] "
"bis [4]): ")
check_input(chose_players)
def check_input(chose_players):
try:
chose_players = int(chose_players)
evaluate_input(chose_players)
except ValueError:
print("Bitte eine Zahl eingeben!")
add_players()
def evaluate_input(chose_players):
if int(chose_players) < 2:
print("Zahl zu klein.")
add_players()
elif int(chose_players) > 4:
print("Zahl zu groß.")
add_players()
add_players()
get_player_ready()"""<file_sep>#!/bin/bash
python3 -m venv virtenv
source virtenv/bin/activate
pip3 install flask
mkdir -p app
cd app
touch __init__.py
cat <<EOF > __init__.py
from flask import Flask
app = Flask(__name__)
from app import routes
EOF
cd ..
touch mnp.py
cat <<EOF > mnp.py
from app import app
EOF
export FLASK_APP=mnp.py
export FLASK_DEBUG=1
flask run --host=0.0.0.0
<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
"""This module throws dice."""
import random
onfield = [0]
double = [0]
move_fwd = 0
def throw_dice():
'''Throw two dice, add result and return'''
dice1 = random.randrange(1, 7)
dice2 = random.randrange(1, 7)
result_of_dices = ((dice1 + dice2))
# check for double
if dice1 == dice2:
double[0] = 1
else:
double[0] = 0
return result_of_dices
def move_forward():
dice_result = throw_dice()
move_fwd = ((onfield[0] + dice_result))
if move_fwd > 12:
move_fwd = ((onfield[0] + dice_result - 12))
onfield[0] = move_fwd
return move_fwd
else:
onfield[0] = move_fwd
return move_fwd
def get_field_type(from_dice_number):
fieldtypes = 'street', 'community', 'street', 'taxes', 'station', 'street', 'event', 'street', 'street', 'visiting', 'street', 'plant', 'station'
return fieldtypes[from_dice_number]<file_sep>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 10, window.innerWidth / window.innerHeight, 1, 1000 );
var renderer = new THREE.WebGLRenderer({});
renderer.setClearColor( 0x2ECCFA, 1)
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// Load Objects
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("box.json", function ( obj ) {
scene.add( obj );
} );
// Camera
camera.position.set(50, 50, 50);
camera.lookAt(scene.position);
var light = new THREE.PointLight(0xffffff, 6, 40);
light.position.set(10, 20, 15);
scene.add(light);
function render() {
requestAnimationFrame( render );
renderer.render( scene, camera );
}
render();
<file_sep>
#streetname = streetbase.get_streetname(moveto)
#base_rent = streetbase.get_base_rent(moveto)
#stop_on_street = streetbase.Street(streetname, base_rent)
#print(stop_on_street.name)
#print(stop_on_street.base_rent)
#print("Feldnummer:", moveto)
#print("Straße:", streetname)
#print("Basismiete:", base_rent)
def get_streetname(streetname):
#badstraße_mieten = 2, 4, 10, 30, 90, 160, 250
badstraße_kaufen = 60, 50
return badstraße_kaufen[streetname]
#def get single_street():
# street_field = 1
# street_name =
def __init__(self, name, base_rent):
self.name = name
self.base_rent = base_rent
class Badstraße:
field = "0"
field_type = "street"
name = "Badstraße"
base_rent = 4
class Turmstraße:
field = "1"
field_type = "street"
name = "Turmstraße"
base_rent = 6
streetnames = 'Badstraße', 0
strasse = streetnames[0]
strasse = Badstraße()
print(strasse.field)
print(strasse.name)
print(strasse.base_rent)
streetname = streetbase.get_streetname(moveto)
print(streetname)
def get_streetname(from_dice_number):
streetnames = 'Badstraße', 0, 'Turmstraße', 0, 0, 'Chausseestraße', 0, 'Elisenstraße', 'Poststraße', 0, 'Seestraße', 0, 0
return streetnames[from_dice_number]
def get_stationname(from_dice_number):
stationname = 0, 0, 0, 0, 'Südbahnhof', 0, 0, 0, 0, 0, 0, 0, 'Westbahnhof'
return stationname[from_dice_number]
def get_base_rent(from_dice_number):
base_rents = 2, 0, 4, 200, 25, 6, 0, 6, 8, 0, 10, 44, 25
return base_rents[from_dice_number]<file_sep>class Station:
allstations = 0, 0, 0, 0, 'Südbahnhof', 0, 0, 0, 0, 0, 0, 0, 'Westbahnhof'
<file_sep>
# Neues Spiel oder neuer Würfelwurf?
# Game = 0
# Wenn neues Spiel (Game = False)
# ergänze neue Spieler
# player.add_player()
# wenn 1 Spieler
# bestimme mindestens einen weiteren Spieler
# add_player
# wenn 2 Spieler
# starte Spiel: würfele, wer die höchste Zahl hat
# game = Fingerprint
# Zwei Spieler würfeln, der mit der höchsten Zahl gewinnt
# oder bestimme einen weiteren Spieler
# add_player
# wenn 3 Spieler
# Starte Spiel: würfele, wer die höchste Zahl hat
# game = Fingerprint
# Drei Spieler würfeln, der mit der höchsten Zahl gewinnt
# oder bestimme einen weiteren Spieler
# add_player
# wenn 4 Spieler
# Starte Spiel: würfele, wer die höchste Zahl hat
# game = Fingerprint
# Vier Spieler würfeln, der mit der höchsten Zahl gewinnt
#print(game)
# Check:
# 1) Neues Spiel? oder 2) Spiel laden
# If 1)
# game = 0: Neues Spiel
# Spieler anlegen: Zahl = Liste von X
# Current Spieler = X[0]
#
# check, welcher Player gerade d
#if player.add_allplayer[3] == True:
# pass
#else:
# player.add_player()
# print(player.allplayer)
#chose_player = player.add_player.allplayer
#nextplayer = player.allplayer[counter]
#print("Spieler:", nextplayer)
<file_sep>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 10, window.innerWidth / window.innerHeight, 1, 1000 );
var renderer = new THREE.WebGLRenderer({});
renderer.setClearColor( 0xffffff, 1)
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// Box 1
var geometry = new THREE.BoxGeometry( 1, 0.1, 1 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile1 = new THREE.Mesh(geometry, material);
tile1.position.x = -5;
tile1.position.y = -5;
tile1.position.z = 0;
scene.add( tile1 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Box 2
var geometry = new THREE.BoxGeometry( 0.95, 0.1, 0.95 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile2 = new THREE.Mesh(geometry, material);
tile2.position.x = -3.6;
tile2.position.y = -3.6;
tile2.position.z = 0;
scene.add( tile2 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Box 3
var geometry = new THREE.BoxGeometry( 0.9, 0.1, 0.9 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile3 = new THREE.Mesh(geometry, material);
tile3.position.x = -2.35;
tile3.position.y = -2.35;
tile3.position.z = 0;
scene.add( tile3 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Box 4
var geometry = new THREE.BoxGeometry( 0.85, 0.1, 0.85 );
var material = new THREE.MeshPhongMaterial({
ambient: 0x555555,
color: 0x555555,
specular: 0xffffff,
shininess: 50,
shading: THREE.SmoothShading
});
var tile3 = new THREE.Mesh(geometry, material);
tile3.position.x = -1.2;
tile3.position.y = -1.2;
tile3.position.z = 0;
scene.add( tile3 );
scene.add(new THREE.AmbientLight(0x4000ff));
// Camera
camera.position.set(20, 20, 20);
camera.lookAt(scene.position);
var light = new THREE.PointLight(0xffffff, 6, 40);
light.position.set(10, 20, 15);
scene.add(light);
function render() {
requestAnimationFrame( render );
renderer.render( scene, camera );
}
render();
<file_sep>from flask import render_template
from app import app
from app.dice import throw_dice, move_forward
@app.route('/')
@app.route('/index')
def index():
dice = throw_dice()
dice_result = {'dice': dice}
go_to_field = move_forward()
field_result = {'go_to_field': go_to_field}
user = {'username': 'Kris'}
return render_template('index.html', title='Home', user=user, dice_result=dice_result, field_result=field_result)
<file_sep>#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
import player
'''Start event loop'''
def get_player_ready():
playerlist_length = len(player.playerlist)
for elements in list(range(1,playerlist_length)):
playername = player.playerlist[elements]
print("Pop:", playername)
play(playername)
print("Zurück")
def play(playername):
#
print("Dice")
print(playername)
""" # write in json file
import json
file = open('/filesave/playername.json', 'w+')
data = { "x": 12153535.232321, "y": 35234531.232322 }
json.dump(data, file)
# https://stackoverflow.com/questions/4450144/easy-save-load-of-data-in-python#4450248
# load from json file
import json
file = open('/usr/data/application/json-dump.json', 'r')
print json.load(file) """
def main():
player.add_number_of_players()
get_player_ready()
main()
# throw_dice and move to field number X
#""" decision = str(input("Nächster Wurf...[Y/n]"))
#if decision == "Y":
# if doublecheck == 1:
# counter == counter
# elif counter < 3:
# counter += 1
# else:
# counter = 0
#else:
# print("Ende")
# break """<file_sep>
var scene = new THREE.Scene();
//(Field of view, Aspect Ratio, nahe sichtbare Ebene, ferne sichtb...)
var camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000 );
var renderer = new THREE.WebGLRenderer({});
//set background color
renderer.setClearColor( 0xFFFFFF, 1)
// viewable area in browser window
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// define field dimension
function addFieldDim (pwidth, pheight, pdepth) {
var geometry = new THREE.BoxGeometry(pwidth, pheight, pdepth);
return geometry;
}
// define field material
function addFieldBasicMaterial (col) {
var material = new THREE.MeshBasicMaterial({
color: col, //0x5ECD00,
});
return material;
}
var plane = new THREE.Mesh(addFieldDim(20,20,20), addFieldBasicMaterial(0x5ECD00));
scene.add( plane );
plane.position.set(0,0,0);
scene.add(new THREE.AmbientLight(0x00FFC6));
// Camera
camera.position.set(50, 50, 50);
camera.lookAt(scene.position);
var light = new THREE.PointLight(0xffffff, 6, 40);
light.position.set(10, 20, 15);
scene.add(light);
function render() {
requestAnimationFrame( render );
renderer.render( scene, camera );
}
render();
/*
// Random number between 0.1 and 1.0
function makerndx () {
var rndx = Math.floor((Math.random() * 1) + 0.1);
return rndx;
}
function makerndz () {
var rndz = Math.floor((Math.random() * 1) + 0.1);
return rndz;
}
function forward () {
tile.position.x += makerndx();
trace.position.x += makerndx();
tile.position.z += makerndz();
trace.position.z += makerndz();
}
if ((tile.position.x < 20 && tile.position.z < 20) || (trace.position.x < 20 && trace.position.z < 20)) {
forward();
}
*/
<file_sep>var container, stats;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
var container = document.createElement( 'div' );
document.body.appendChild( container );
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 4;
var scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x444444 );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( ambient );
scene.add( directionalLight );
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("box.json", function ( obj ) {
scene.add( obj );
} );
var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
var mouseX = ( event.clientX - windowHalfX ) / 2;
var mouseY = ( event.clientY - windowHalfY ) / 2;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( - mouseY - camera.position.y ) * .05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
|
22959d9e46d5598ad0e956afd5907e73973065dd
|
[
"Shell",
"Markdown",
"Dockerfile",
"JavaScript",
"Python"
] | 22 |
Shell
|
textvrbrln/monopoly
|
a1d1488464f153965dcbf3c92a53407edf907452
|
70ccccfc44df634a4205874a641b9a4cc20a8674
|
refs/heads/main
|
<file_sep>- 👋 Hi, I’m @aarn-783
- 👀 I’m interested in learning more about programming.
- 🌱 I’m currently learning C++ with Computer Engineering course in college. And I'm a freshman student.
- 💞️ I’m looking to collaborate on
- 📫 How to reach me ...
<!---
aarn-783/aarn-783 is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile.
You can click the Preview link to take a look at your changes.
--->
|
1e64ba1ae87081df7939d611426eb4358c72775e
|
[
"Markdown"
] | 1 |
Markdown
|
aarn-783/aarn-783
|
62352f8337207b0f32b0b496adeda6d787204e2c
|
348f5e2bff2496e14721245fdd59f8cebfcdf094
|
refs/heads/main
|
<file_sep>import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
import QtQuick.Controls 2.0 as QQC2
// QtQuick2 button using Kirigami theme
// /usr/lib/x86_64-linux-gnu/qt5/qml/QtQuick/Controls.2/org.kde.desktop/Button.qml
// import org.kde.qqc2desktopstyle.private 1.0 as StylePrivate
// https://github.com/KDE/qqc2-desktop-style/blob/master/plugin/kquickstyleitem.cpp#L1162
// The normal 'button' elementType centers the IconLabel,
// with no way to set the alignment or the minimum width.
// So we use toolbutton which left aligns.
QQC2.ToolButton {
id: iconButton
property string iconName: ""
Component.onCompleted: {
// icon.name is a Qt 5.10 feature
// So to be backward compatible with Kubuntu which has Qt 5.9, we need to do this.
if (iconButton.hasOwnProperty("icon") && iconName && !icon.name) {
icon.name = iconName
}
}
}
<file_sep>import QtQuick 2.0
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1
import QtQuick.Layouts 1.1
import QtQuick.Window 2.1
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
SidebarMenu {
id: sidebarContextMenu
visible: open
open: false
anchors.left: parent.left
anchors.bottom: parent.top
implicitWidth: content.implicitWidth
implicitHeight: content.implicitHeight
z: 2
default property alias _contentChildren: content.data
ColumnLayout {
id: content
spacing: 0
}
// onVisibleChanged: {
// if (sidebarContextMenu.visible) {
// sidebarContextMenu.focus = true
// }
// }
onFocusChanged: {
// console.log('sidebarContextMenu.onFocusChanged', focus)
if (!sidebarContextMenu.focus) {
sidebarContextMenu.open = false
}
}
onActiveFocusChanged: {
// console.log('sidebarContextMenu.onActiveFocusChanged', activeFocus)
if (!sidebarContextMenu.activeFocus) {
sidebarContextMenu.open = false
}
}
}
<file_sep># TiledMenuMod
This is a mod of the popular startmenu extension by zren for KDE Plasma.
Changes:
- smaller icons
- added shadows
- improved font readability

# Preview


<file_sep>import QtQuick 2.0
Item {
id: style
property int paddingTop: 0
property int paddingRight: 0
property int paddingBottom: 0
property int paddingLeft: 0
Loader {
id: hoverOutlineEffectLoader
anchors.fill: parent
active: control.containsMouse
visible: active
source: "HoverOutlineButtonEffect.qml"
property var __control: control
}
}
<file_sep>import QtQuick 2.0
import QtGraphicalEffects 1.12
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1
import QtQuick.Layouts 1.1
import QtQuick.Window 2.1
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.draganddrop 2.0 as DragAndDrop
Rectangle {
id: tileItemView
color: appObj.backgroundColor
property color gradientBottomColor: Qt.darker(appObj.backgroundColor, 2.0)
Component {
id: tileGradient
Gradient {
GradientStop { position: 0.0; color: appObj.backgroundColor }
GradientStop { position: 1.0; color: tileItemView.gradientBottomColor }
}
}
gradient: appObj.backgroundGradient ? tileGradient.createObject(tileItemView) : null
readonly property int tilePadding: 4 * units.devicePixelRatio
readonly property int smallIconSize: 32 * units.devicePixelRatio
readonly property int mediumIconSize: 48 * units.devicePixelRatio
readonly property int largeIconSize: 64 * units.devicePixelRatio
readonly property int tileLabelAlignment: config.tileLabelAlignment
property bool hovered: false
states: [
State {
when: modelData.w == 1 && modelData.h >= 1
PropertyChanges { target: icon; size: smallIconSize }
PropertyChanges { target: label; visible: false }
},
State {
when: modelData.w >= 2 && modelData.h == 1
AnchorChanges { target: icon
anchors.horizontalCenter: undefined
anchors.left: tileItemView.left
}
PropertyChanges { target: icon; anchors.leftMargin: tilePadding }
PropertyChanges { target: label
verticalAlignment: Text.AlignVCenter
}
AnchorChanges { target: label
anchors.left: icon.right
}
},
State {
when: (modelData.w >= 2 && modelData.h == 2) || (modelData.w == 2 && modelData.h >= 2)
PropertyChanges { target: icon; size: mediumIconSize }
},
State {
when: modelData.w >= 3 && modelData.h >= 3
PropertyChanges { target: icon; size: largeIconSize }
}
]
Image {
id: backgroundImage
anchors.fill: parent
visible: appObj.backgroundImage
source: appObj.backgroundImage
fillMode: Image.PreserveAspectCrop
asynchronous: true
}
PlasmaCore.IconItem {
id: icon
visible: appObj.showIcon
source: appObj.iconSource
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
// property int size: 72 // Just a default, overriden in State change
property int size: Math.min(parent.width, parent.height) / 2
width: appObj.showIcon ? size : 0
height: appObj.showIcon ? size : 0
anchors.fill: appObj.iconFill ? parent : null
smooth: appObj.iconFill
}
DropShadow {
anchors.fill: icon
horizontalOffset: 0
verticalOffset: 0
radius: 7.0
samples: 17
color: "#77000000"
source: icon
}
PlasmaComponents.Label {
id: label
visible: appObj.showLabel
text: appObj.labelText
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.leftMargin: tilePadding
anchors.rightMargin: tilePadding
anchors.left: parent.left
anchors.right: parent.right
wrapMode: Text.Wrap
horizontalAlignment: tileLabelAlignment
verticalAlignment: Text.AlignBottom
width: parent.width
renderType: Text.QtRendering // Fix pixelation when scaling. Plasma.Label uses NativeRendering.
styleColor: appObj.backgroundGradient ? tileItemView.gradientBottomColor : appObj.backgroundColor
}
}
<file_sep>import QtQuick 2.0
import org.kde.plasma.components 2.0 as PlasmaComponents
PlasmaComponents.MenuItem {
id: presetMenuItem
icon: "list-add-symbolic"
text: i18n("Add Preset")
//---
function addDefault() {
var pos = tileGrid.findOpenPos(6, 6)
addProductivity(pos.x, pos.y)
addExplore(pos.x, pos.y + 3)
}
function addProductivity(x, y) {
var group = tileGrid.addGroup(x, y, {
label: i18n("Productivity"),
})
var writer = addWriter(x, y + 1)
var calc = addCalc(x + 2, y + 1)
var mail = addMail(x + 4, y + 1)
}
function addExplore(x, y) {
var group = tileGrid.addGroup(x, y, {
label: i18n("Explore"),
})
var appCenter = addAppCenter(x, y + 1)
var browser = addWebBrowser(x + 2, y + 1)
var steam = addSteam(x + 4, y + 1)
}
//---
function addWriter(x, y) {
return tileGrid.addTile(x, y, {
url: 'libreoffice-writer.desktop',
backgroundColor: '#802584b7',
})
}
function addCalc(x, y) {
return tileGrid.addTile(x, y, {
url: 'libreoffice-calc.desktop',
backgroundColor: '#80289769',
})
}
function addMail(x, y) {
if (appsModel.allAppsModel.hasApp('org.kde.kmail2.desktop')) {
return addKMail(x, y)
} else {
return addGmail(x, y)
}
}
function addKMail(x, y) {
return tileGrid.addTile(x, y, {
url: 'org.kde.kmail2.desktop',
})
}
function addGmail(x, y) {
return tileGrid.addTile(x, y, {
url: 'https://mail.google.com/mail/u/0/#inbox',
label: i18n("Gmail"),
icon: 'mail-message',
backgroundColor: '#80a73325',
})
}
function addAppCenter(x, y) {
if (appsModel.allAppsModel.hasApp('octopi.desktop')) {
return tileGrid.addTile(x, y, {
url: 'octopi.desktop',
label: i18n("Software Center"),
})
} else if (appsModel.allAppsModel.hasApp('org.opensuse.YaST.desktop')) {
return tileGrid.addTile(x, y, {
url: 'org.opensuse.YaST.desktop',
label: i18n("Software Center"),
})
} else if (appsModel.allAppsModel.hasApp('org.kde.discover')) {
return tileGrid.addTile(x, y, {
url: 'org.kde.discover',
label: i18n("Software Center"),
})
} else {
return null
}
}
function addWebBrowser(x, y) {
return tileGrid.addTile(x, y, {
url: 'preferred://browser',
})
}
function addSteam(x, y) {
if (appsModel.allAppsModel.hasApp('steam.desktop')) {
return tileGrid.addTile(x, y, {
url: 'steam.desktop',
})
} else {
return null
}
}
//---
PlasmaComponents.ContextMenu {
visualParent: presetMenuItem.action
PlasmaComponents.MenuItem {
icon: "libreoffice-startcenter"
text: i18n("Productivity")
onClicked: {
var pos = tileGrid.findOpenPos(6, 3)
presetMenuItem.addProductivity(pos.x, pos.y)
}
}
PlasmaComponents.MenuItem {
icon: "internet-web-browser"
text: i18n("Explore")
onClicked: {
var pos = tileGrid.findOpenPos(6, 3)
presetMenuItem.addExplore(pos.x, pos.y)
}
}
PlasmaComponents.MenuItem {
icon: "mail-message"
text: i18n("Gmail")
onClicked: {
var tile = presetMenuItem.addGmail(cellContextMenu.cellX, cellContextMenu.cellY)
tileGrid.editTile(tile)
}
}
}
}
|
32ffbf7420ab7c35c46e0430762693af4529b0f1
|
[
"Markdown",
"QML"
] | 6 |
Markdown
|
nnamliehbes/TiledMenuMod
|
9ec49af8dbfd4c5173054a9b774c9122232a5212
|
3491d7db867732459648acc7ca609eb28d73b718
|
refs/heads/master
|
<repo_name>aarzho/aaronblog.github.io<file_sep>/README.md
# aaronblog.github.io
# This is the original blog script, and it is out of dated. No more maintainance.
|
34fea9bf16d08ee5b701b1f20cc8b9fdb97cced9
|
[
"Markdown"
] | 1 |
Markdown
|
aarzho/aaronblog.github.io
|
572bbf25f71c490b47e3f2b0e6eba98bb8e94baf
|
74768370fe795f010480130f5a03f6b9a248c9a2
|
refs/heads/master
|
<repo_name>brook-code/titanic<file_sep>/README.md
# titanic
1. Rose is standing on the fron of the deck.
2. Jack is standing on the deck with Rose. with his hand spread apart.
3. A famouse actoresse joined in the scene.
4. A scene with all the actors without the famouse actor exaggerated emotions.
5. A scene with all the actors with exaggerated emotions.
6. An advert for a cigar company.
|
739776bdb7ed81f407b7f62f312959dd5d84927e
|
[
"Markdown"
] | 1 |
Markdown
|
brook-code/titanic
|
93c21a5dbc01d3d4329772ab6efd07a0ff1af6c3
|
1f9ce8906e44d3dfeca07923747e33b9f15d629b
|
refs/heads/master
|
<file_sep># Python-learner
no best,only better
|
4c67611bd6c6b9aafa0c9acae3bf64c62741aa89
|
[
"Markdown"
] | 1 |
Markdown
|
SamhainYan/Python-learner
|
05e377e3fb55480f7e850872ae36a5599ace7a2d
|
090d039300a1a383c964710a644a521b44a8f766
|
refs/heads/master
|
<file_sep>-- Generated from nabla.lua.tl using ntangle.nvim
local parser = require("nabla.parser")
local ascii = require("nabla.ascii")
local vtext = vim.api.nvim_create_namespace("nabla")
local function init()
local scratch = vim.api.nvim_create_buf(false, true)
local curbuf = vim.api.nvim_get_current_buf()
local attach = vim.api.nvim_buf_attach(curbuf, true, {
on_lines = function(_, buf, _, _, _, _, _)
vim.schedule(function()
vim.api.nvim_buf_set_lines(scratch, 0, -1, true, {})
vim.api.nvim_buf_clear_namespace( buf, vtext, 0, -1)
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, true)
for y, line in ipairs(lines) do
if line ~= "" then
local exp, errmsg = parser.parse_all(line)
if exp then
local g = ascii.to_ascii(exp)
local drawing = {}
for row in vim.gsplit(tostring(g), "\n") do
table.insert(drawing, row)
end
if whitespace then
for i=1,#drawing do
drawing[i] = whitespace .. drawing[i]
end
end
vim.api.nvim_buf_set_lines(scratch, -1, -1, true, drawing)
else
vim.api.nvim_buf_set_virtual_text(buf, vtext, y-1, {{ vim.inspect(errmsg), "Special" }}, {})
end
end
end
end)
end
})
local prewin = vim.api.nvim_get_current_win()
local height = vim.api.nvim_win_get_height(prewin)
local width = vim.api.nvim_win_get_width(prewin)
if width > height*2 then
vim.api.nvim_command("vsp")
else
vim.api.nvim_command("sp")
end
vim.api.nvim_win_set_buf(prewin, scratch)
end
local function replace_current()
local line = vim.api.nvim_get_current_line()
local whitespace = string.match(line, "^(%s*)%S")
local exp, errmsg = parser.parse_all(line)
if exp then
local g = ascii.to_ascii(exp)
local drawing = {}
for row in vim.gsplit(tostring(g), "\n") do
table.insert(drawing, row)
end
if whitespace then
for i=1,#drawing do
drawing[i] = whitespace .. drawing[i]
end
end
local curline, _ = unpack(vim.api.nvim_win_get_cursor(0))
vim.api.nvim_buf_set_lines(0, curline-1, curline, true, drawing)
else
if type(errmsg) == "string" then
print("nabla error: " .. errmsg)
else
print("nabla error!")
end
end
end
local function replace_all()
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)
result = {}
for i,line in ipairs(lines) do
if line == "" then
table.insert(result, "")
else
local whitespace = string.match(line, "^(%s*)%S")
local exp, errmsg = parser.parse_all(line)
if exp then
local g = ascii.to_ascii(exp)
local drawing = {}
for row in vim.gsplit(tostring(g), "\n") do
table.insert(drawing, row)
end
if whitespace then
for i=1,#drawing do
drawing[i] = whitespace .. drawing[i]
end
end
for _, newline in ipairs(drawing) do
table.insert(result, newline)
end
else
if type(errmsg) == "string" then
print("nabla error: " .. errmsg)
else
print("nabla error!")
end
end
end
end
vim.api.nvim_buf_set_lines(0, 0, -1, true, result)
end
return {
init = init,
replace_current = replace_current,
replace_all = replace_all,
}
<file_sep>nabla.nvim
-----------
Take your scientific notes in Neovim.
[](https://postimg.cc/PPwGJKK9)
**nabla.nvim** is an ASCII math generator.
**Work in progress**
Install
-------
Install using a plugin manager such as [vim-plug](https://github.com/junegunn/vim-plug).
```
Plug 'jbyuki/nabla.nvim'
```
Configuration
-------------
For example to bind it to <kbd>F5</kbd>:
```
nnoremap <F5> :lua require("nabla").replace_current()<CR>
```
Usage
-----
Press <kbd>F5</kbd> on the math expression line.
Reference
---------
| Name | Expression |
|------|------------|
| square root | `sqrt(x)` |
| integral | `int(A, B, f(x))` |
| sum | `sum(A, B, f(x))` or `sum(f(x))` |
| limit | `lim(x, a, f(x))` |
| superscript | `x^a` |
| subscript | `x_a` |
| special symbols | `alpha`, `inf`, `nabla`, ... |
| vector, matrix | `[x,y;z,w]` |
| derivative | `d(x, f(x))` |
| partial derivative | `dp(x, f(x))` |
| absolute value | `abs(x)` |
| delta | `delta(x)` or `Delta(x)` |
**Note**: If the notation you need is not present or there is a misaligned expression, feel free to open an [Issue](https://github.com/jbyuki/nabla.nvim/issues).
<file_sep>@../lua/nabla/parser.lua=
@requires
@declare_functions
@script_variables
@expressions
@tokens
@functions
@parse
return {
@export_symbols
}
@declare_functions+=
local parse_all
@parse+=
function parse_all(str)
tokenize(str)
@clear_error_msg
@parse_tokens
@if_any_error_msg_return_it
return exp
end
@export_symbols+=
parse_all = parse_all,
@declare_functions+=
local tokenize
@functions+=
function tokenize(str)
@clear_tokens
@tokenize_string
end
@clear_tokens+=
tokens = {}
@tokenize_string+=
local i = 1
while i <= string.len(str) do
@get_character
@skip_whitespace
@tokenize_op
@tokenize_par
@tokenize_bracket
@tokenize_equalsign
@tokenize_comma
@tokenize_semicolon
@tokenize_apostrophe
@tokenize_num
@tokenize_symbol
@handle_error_tokenize
end
@get_character+=
local c = string.sub(str, i, i)
@skip_whitespace+=
if string.match(c, "%s") then
i = i+1
@tokens+=
-- closure-based object
local function AddToken() local self = { kind = "add" }
@add_token_methods
return self end
local function SubToken() local self = { kind = "sub" }
@sub_token_methods
return self end
local function MulToken() local self = { kind = "mul" }
@mul_token_methods
return self end
local function DivToken() local self = { kind = "div" }
@div_token_methods
return self end
@script_variables+=
tokens = {}
@tokenize_op+=
elseif c == "+" then table.insert(tokens, AddToken()) i = i+1
elseif c == "-" then table.insert(tokens, SubToken()) i = i+1
elseif c == "*" then table.insert(tokens, MulToken()) i = i+1
elseif c == "/" then table.insert(tokens, DivToken()) i = i+1
@tokens+=
local function RParToken() local self = { kind = "rpar" }
@rpar_token_methods
return self end
local function LParToken() local self = { kind = "lpar" }
@lpar_token_methods
return self end
@tokenize_par+=
elseif c == "(" then table.insert(tokens, LParToken()) i = i+1
elseif c == ")" then table.insert(tokens, RParToken()) i = i+1
@tokens+=
local function NumToken(num) local self = { kind = "num", num = num }
@num_token_methods
return self end
@tokenize_num+=
elseif string.match(c, "%d") then
local parsed = string.match(string.sub(str, i), "%d+%.?%d*")
i = i+string.len(parsed)
table.insert(tokens, NumToken(tonumber(parsed)))
@script_variables+=
local errmsg = ""
@handle_error_tokenize+=
else
errmsg = "Unexpected character insert " .. c
i = i+1
end
@tokens+=
local function SymToken(sym) local self = { kind = "sym", sym = sym }
@sym_token_methods
return self end
@tokenize_symbol+=
elseif string.match(c, "[%a_%.]") then
@add_mul_token_if_num_just_before
@get_all_char_sym
@crete_sym_token
@add_mul_token_if_num_just_before+=
if #tokens > 0 and tokens[#tokens].kind == "num" then
table.insert(tokens, MulToken())
end
@get_all_char_sym+=
local parsed = string.match(string.sub(str, i), "[%w%.]+")
i = i+string.len(parsed)
@crete_sym_token+=
table.insert(tokens, SymToken(parsed))
@declare_functions+=
local nextToken
@script_variables+=
local token_index
@parse_tokens-=
token_index = 1
@functions+=
function nextToken()
local token = tokens[token_index]
token_index = token_index + 1
return token
end
@declare_functions+=
local finish
@functions+=
function finish()
return token_index > #tokens
end
@declare_functions+=
local getToken
@functions+=
function getToken()
return tokens[token_index]
end
@parse_tokens+=
local exp = parse(0)
@declare_functions+=
local parse
@functions+=
function parse(p)
local t = nextToken()
if not t or not t.prefix then
return nil
end
local exp = t.prefix()
while exp and not finish() and p <= getToken().priority() do
t = nextToken()
exp = t.infix and t.infix(exp)
end
return exp
end
@add_token_methods+=
function self.prefix()
return parse(self.priority())
end
@declare_functions+=
local AddExpression
@expressions+=
function AddExpression(left, right)
local self = { kind = "addexp", left = left, right = right }
@add_exp_methods
return self end
@add_token_methods+=
function self.infix(left)
local t = parse(self.priority())
if not t then
return nil
end
return AddExpression(left, t)
end
function self.priority() return priority_list["add"] end
@script_variables+=
local priority_list = {
@priority_list
}
@priority_list+=
["add"] = 50,
@declare_functions+=
local PrefixSubExpression
@expressions+=
function PrefixSubExpression(left)
local self = { kind = "presubexp", left = left }
@presub_exp_methods
return self end
@sub_token_methods+=
function self.prefix()
local t = parse(90)
if not t then
return nil
end
return PrefixSubExpression(t)
end
@declare_functions+=
local SubExpression
@expressions+=
function SubExpression(left, right)
local self = { kind = "subexp", left = left, right = right }
@sub_exp_methods
return self end
@sub_token_methods+=
function self.infix(left)
local t = parse(self.priority()+1)
if not t then
return nil
end
return SubExpression(left, t)
end
function self.priority() return priority_list["sub"] end
@priority_list+=
["sub"] = 50,
@declare_functions+=
local MulExpression
@expressions+=
function MulExpression(left, right)
local self = { kind = "mulexp", left = left, right = right }
@mul_exp_methods
return self end
@mul_token_methods+=
function self.infix(left)
local t = parse(self.priority())
if not t then
return nil
end
return MulExpression(left, t)
end
function self.priority() return priority_list["mul"] end
@priority_list+=
["mul"] = 60,
@declare_functions+=
local DivExpression
@expressions+=
function DivExpression(left, right)
local self = { kind = "divexp", left = left, right = right }
@div_exp_methods
return self end
@div_token_methods+=
function self.infix(left)
local t = parse(self.priority()+1)
if not t then
return nil
end
return DivExpression(left, t)
end
function self.priority() return priority_list["div"] end
@priority_list+=
["div"] = 70,
@lpar_token_methods+=
function self.prefix()
local exp = parse(20)
if not exp then
return nil
end
@check_rpar
return exp
end
@check_rpar+=
local rpar = nextToken()
if not rpar or rpar.kind ~= "rpar" then
errmsg = "Unmatched '('"
return nil
end
@lpar_token_methods+=
function self.priority() return priority_list["lpar"] end
@priority_list+=
["lpar"] = 100,
@rpar_token_methods+=
function self.priority() return priority_list["rpar"] end
@priority_list+=
["rpar"] = 10,
@declare_functions+=
local NumExpression
@expressions+=
function NumExpression(num)
local self = { kind = "numexp", num = num }
@num_exp_methods
return self end
@num_token_methods+=
function self.prefix()
return NumExpression(self.num)
end
@declare_functions+=
local SymExpression
@expressions+=
function SymExpression(sym)
local self = { kind = "symexp", sym = sym }
@sym_exp_methods
return self end
@sym_token_methods+=
function self.prefix()
return SymExpression(self.sym)
end
@declare_functions+=
local FunExpression
@expressions+=
function FunExpression(name, args)
local self = { kind = "funexp", name = name, args = args }
@fun_exp_methods
return self end
@lpar_token_methods+=
function self.infix(left)
local args = {}
while not finish() do
local exp = parse(20)
if not exp then
return nil
end
table.insert(args, exp)
local t = nextToken()
if not t then return nil end
@if_rpar_quit
@if_comma_next_arg
end
return FunExpression(left, args)
end
@if_rpar_quit+=
if t.kind == "rpar" then
break
end
@declare_functions+=
local parse_assert
@functions+=
function parse_assert(c, msg)
if not c then
errmsg = msg
return true
end
return false
end
@if_comma_next_arg+=
if parse_assert(t.kind == "comma", "expected comma in function arg list") then
return nil
end
@tokens+=
local function ExpToken() local self = { kind = "exp" }
@exp_token_methods
return self end
@tokenize_op+=
elseif c == "^" then table.insert(tokens, ExpToken()) i = i+1
@declare_functions+=
local ExpExpression
@expressions+=
function ExpExpression(left, right)
local self = { kind = "expexp", left = left, right = right }
@exp_exp_methods
return self end
@exp_token_methods+=
function self.infix(left)
local exp = parse(self.priority())
if not exp then
return nil
end
return ExpExpression(left, exp)
end
function self.priority() return priority_list["exp"] end
@priority_list+=
["exp"] = 70,
@tokenize_bracket+=
elseif c == "[" then table.insert(tokens, LBraToken()) i = i+1
elseif c == "]" then table.insert(tokens, RBraToken()) i = i+1
@tokenize_comma+=
elseif c == "," then table.insert(tokens, CommaToken()) i = i+1
@tokenize_semicolon+=
elseif c == ";" then table.insert(tokens, SemiToken()) i = i+1
@tokens+=
-- right bracket
local function LBraToken() local self = { kind = "lbra" }
@lbra_token_methods
return self end
-- left bracket
local function RBraToken() local self = { kind = "rbra" }
@rbra_token_methods
return self end
-- comma
local function CommaToken() local self = { kind = "comma" }
@comma_token_methods
return self end
-- semi-colon
local function SemiToken() local self = { kind = "semi" }
@semi_token_methods
return self end
@lbra_token_methods+=
function self.prefix()
local i, j = 1, 1
rows = {}
rows[1] = {}
while true do
local exp = parse(10)
if not exp then
return nil
end
rows[i][j] = exp
local t = nextToken()
@if_rbra_quit
@if_comma_next_col
@if_semi_next_row
end
@verify_all_lines_have_same_length
@make_matrix_expression
return exp
end
@rbra_token_methods+=
function self.priority() return priority_list["rbra"] end
@priority_list+=
["rbra"] = 5,
@comma_token_methods+=
function self.priority() return priority_list["comma"] end
@priority_list+=
["comma"] = 5,
@semi_token_methods+=
function self.priority() return priority_list["semi"] end
@priority_list+=
["semi"] = 5,
@if_rbra_quit+=
if t.kind == "rbra" then
break
end
@if_comma_next_col+=
if t.kind == "comma" then
j = j+1
end
@if_semi_next_row+=
if t.kind == "semi" then
rows[#rows+1] = {}
i = i+1
j = 1
end
@verify_all_lines_have_same_length+=
local curlen
for _,row in ipairs(rows) do
if not curlen then
curlen = #row
end
if parse_assert(#row == curlen, "matrix dimension incorrect") then
return nil
end
end
@expressions+=
function MatrixExpression(rows, m, n)
local self = { kind = "matexp", rows = rows, m = m, n = n }
@mat_exp_methods
return self end
@make_matrix_expression+=
local exp = MatrixExpression(rows, #rows, curlen)
@mat_exp_methods+=
function self.priority()
return priority_list["mat"]
end
@priority_list+=
["mat"] = 110,
@tokenize_equalsign+=
elseif c == "=" or c == ">" or c == "<" or c == "~" or c == "!" then
local cn = string.sub(str, i+1, i+1)
if cn == "=" or cn == ">" or cn == "<" then
table.insert(tokens, EqualToken(c .. cn))
i = i+2
else
table.insert(tokens, EqualToken(c))
i = i+1
end
@tokens+=
-- right bracket
local function EqualToken(sign) local self = { kind = "equal", sign = sign }
@equal_token_methods
return self end
@equal_token_methods+=
function self.infix(left)
local t = parse(self.priority())
if not t then
return nil
end
return EqualExpression(left, t, self.sign)
end
function self.priority() return priority_list["eq"] end
@priority_list+=
["eq"] = 1,
@expressions+=
function EqualExpression(left, right, sign)
local self = { kind = "eqexp", left = left, right = right, sign = sign }
@eq_exp_methods
return self end
@add_exp_methods+=
function self.toString()
if self.right.kind == "presubexp" then
return putParen(self.left, self.priority()) .. "-" .. putParen(self.right.left, self.right.priority())
elseif self.right.kind == "numexp" and self.right.num < 0 then
return putParen(self.left, self.priority()) .. "-" .. putParen(NumExpression(math.abs(self.right.num)), self.priority())
else
assert(self.priority, vim.inspect(self))
return putParen(self.left, self.priority()) .. "+" .. putParen(self.right, self.priority())
end
end
@sub_exp_methods+=
function self.toString()
return putParen(self.left, self.priority()) .. "-" .. putParen(self.right, self.priority())
end
@presub_exp_methods+=
function self.toString()
return "-" .. putParen(self.left, self.priority()) .. ""
end
@mul_exp_methods+=
function self.toString()
if self.left.kind == "numexp" and self.right.getLeft().kind ~= "numexp" then
return putParen(self.left, self.priority()) .. putParen(self.right, self.priority())
else
return putParen(self.left, self.priority()) .. "*" .. putParen(self.right, self.priority())
end
end
@div_exp_methods+=
function self.toString()
return putParen(self.left, self.priority()) .. "/" .. putParen(self.right, self.priority())
end
@exp_exp_methods+=
function self.toString()
return putParen(self.left, self.priority()) .. "^" .. putParen(self.right, self.priority())
end
@sym_exp_methods+=
function self.toString()
return self.sym
end
@num_exp_methods+=
function self.toString()
return tostring(self.num)
end
@fun_exp_methods+=
function self.toString()
local fargs = {}
for _,arg in ipairs(self.args) do
table.insert(fargs, arg.toString())
end
return self.name .. "(" .. table.concat(fargs, ", ") .. ")"
end
@mat_exp_methods+=
function self.toString()
local rowsString = {}
for _,row in ipairs(self.rows) do
local cells = {}
for _,cell in ipairs(row) do
table.insert(cells, cell.toString())
end
local cellsString = table.concat(cells, ",")
table.insert(rowsString, cellsString)
end
return "[" .. table.concat(rowsString, ";") .. "]"
end
@eq_exp_methods+=
function self.toString()
local t1 = self.left.toString()
local t2 = self.right.toString()
return t1 .. " " .. self.sign .. " " .. t2
end
@add_exp_methods+=
function self.priority()
return priority_list["add"]
end
@sub_exp_methods+=
function self.priority()
return priority_list["sub"]
end
@presub_exp_methods+=
function self.priority()
return priority_list["presub"]
end
@priority_list+=
["presub"] = 90,
@mul_exp_methods+=
function self.priority()
return priority_list["mul"]
end
@div_exp_methods+=
function self.priority()
return priority_list["div"]
end
@exp_exp_methods+=
function self.priority()
return priority_list["exp"]
end
@priority_list+=
["exp"] = 90,
@sym_exp_methods+=
function self.priority()
return priority_list["sym"]
end
@priority_list+=
["sym"] = 110,
@num_exp_methods+=
function self.priority()
return priority_list["num"]
end
@priority_list+=
["num"] = 110,
@fun_exp_methods+=
function self.priority()
return priority_list["fun"]
end
@priority_list+=
["fun"] = 100,
@declare_functions+=
local putParen
@functions+=
function putParen(exp, p)
if exp.priority() < p then
return "(" .. exp.toString() .. ")"
else
return exp.toString()
end
end
@clear_error_msg+=
errmsg = nil
@if_any_error_msg_return_it+=
if errmsg then
return nil, errmsg
end
@add_exp_methods+=
function self.getLeft()
return self.left.getLeft()
end
@sub_exp_methods+=
function self.getLeft()
return self.left.getLeft()
end
@presub_exp_methods+=
function self.getLeft()
return self
end
@mul_exp_methods+=
function self.getLeft()
return self.left.getLeft()
end
@div_exp_methods+=
function self.getLeft()
return self.left.getLeft()
end
@exp_exp_methods+=
function self.getLeft()
return self.left.getLeft()
end
@sym_exp_methods+=
function self.getLeft()
return self
end
@num_exp_methods+=
function self.getLeft()
return self
end
@fun_exp_methods+=
function self.getLeft()
return self
end
@mat_exp_methods+=
function self.getLeft()
return self
end
@tokenize_op+=
elseif c == "_" then table.insert(tokens, IndToken()) i = i+1
@tokens+=
local function IndToken() local self = { kind = "ind" }
@ind_token_methods
return self end
@declare_functions+=
local IndExpression
@expressions+=
function IndExpression(left, right)
local self = { kind = "indexp", left = left, right = right }
@ind_exp_methods
return self end
@ind_token_methods+=
function self.infix(left)
local exp = parse(self.priority())
if not exp then
return nil
end
return IndExpression(left, exp)
end
function self.priority() return priority_list["ind"] end
@priority_list+=
["ind"] = 110,
@ind_exp_methods+=
function self.priority()
return priority_list["ind"]
end
function self.getLeft()
return self.left.getLeft()
end
@sym_token_methods+=
function self.priority()
return 5
end
@tokenize_apostrophe+=
elseif c == "'" then
local parsed = string.match(string.sub(str, i), "[']+")
i = i + string.len(parsed)
table.insert(tokens, DerToken(string.len(parsed)))
@tokens+=
-- derivate
local function DerToken(order) local self = { kind = "der", order = order }
@derivate_token_methods
return self end
@derivate_token_methods+=
function self.infix(left)
return DerExpression(left, self.order)
end
function self.priority() return priority_list["der"] end
@priority_list+=
["der"] = 85,
@expressions+=
function DerExpression(left, order)
local self = { kind = "derexp", left = left, order = order }
@der_exp_methods
return self end
@der_exp_methods+=
function self.priority()
return priority_list["der"]
end
<file_sep>@../lua/nabla.lua=
@requires
@script_variables
@expressions
@tokens
@declare_functions
@functions
@parse
@init_nabla_mode
@replace_current_line
@replace_all_lines
return {
@export_symbols
}
@init_nabla_mode+=
local function init()
@create_scratch_buffer
@setup_scratch_buffer
@attach_on_lines_callback
@create_split_with_scratch_buffer
end
@export_symbols+=
init = init,
@create_scratch_buffer+=
local scratch = vim.api.nvim_create_buf(false, true)
@create_split_with_scratch_buffer+=
local prewin = vim.api.nvim_get_current_win()
local height = vim.api.nvim_win_get_height(prewin)
local width = vim.api.nvim_win_get_width(prewin)
if width > height*2 then
vim.api.nvim_command("vsp")
else
vim.api.nvim_command("sp")
end
vim.api.nvim_win_set_buf(prewin, scratch)
@attach_on_lines_callback+=
local curbuf = vim.api.nvim_get_current_buf()
local attach = vim.api.nvim_buf_attach(curbuf, true, {
on_lines = function(_, buf, _, _, _, _, _)
vim.schedule(function()
@erase_scratch_buffer
@clear_all_virtual_text
@read_whole_buffer
@foreach_nonempty_line_parse_and_output_to_scratch
end)
end
})
@erase_scratch_buffer+=
vim.api.nvim_buf_set_lines(scratch, 0, -1, true, {})
@read_whole_buffer+=
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, true)
@foreach_nonempty_line_parse_and_output_to_scratch+=
for y, line in ipairs(lines) do
if line ~= "" then
@parse_math_expression
if exp then
@generate_ascii_art
@display_in_scratch_buffer
else
@display_error_as_virtual_text
end
end
end
@requires+=
local parser = require("nabla.parser")
@parse_math_expression+=
local exp, errmsg = parser.parse_all(line)
@script_variables+=
local vtext = vim.api.nvim_create_namespace("nabla")
@clear_all_virtual_text+=
vim.api.nvim_buf_clear_namespace( buf, vtext, 0, -1)
@display_error_as_virtual_text+=
vim.api.nvim_buf_set_virtual_text(buf, vtext, y-1, {{ vim.inspect(errmsg), "Special" }}, {})
@requires+=
local ascii = require("nabla.ascii")
@generate_ascii_art+=
local g = ascii.to_ascii(exp)
local drawing = {}
for row in vim.gsplit(tostring(g), "\n") do
table.insert(drawing, row)
end
@add_whitespace_to_ascii_art
@display_in_scratch_buffer+=
vim.api.nvim_buf_set_lines(scratch, -1, -1, true, drawing)
@replace_current_line+=
local function replace_current()
@get_current_line
@get_whilespace_before
@parse_math_expression
if exp then
@generate_ascii_art
@replace_current_line_with_ascii_art
else
if type(errmsg) == "string" then
print("nabla error: " .. errmsg)
else
print("nabla error!")
end
end
end
@export_symbols+=
replace_current = replace_current,
@get_current_line+=
local line = vim.api.nvim_get_current_line()
@replace_current_line_with_ascii_art+=
local curline, _ = unpack(vim.api.nvim_win_get_cursor(0))
vim.api.nvim_buf_set_lines(0, curline-1, curline, true, drawing)
@get_whilespace_before+=
local whitespace = string.match(line, "^(%s*)%S")
@add_whitespace_to_ascii_art+=
if whitespace then
for i=1,#drawing do
drawing[i] = whitespace .. drawing[i]
end
end
@replace_all_lines+=
local function replace_all()
@get_all_lines
result = {}
for i,line in ipairs(lines) do
if line == "" then
@if_empty_line_just_skip
else
@get_whilespace_before
@parse_math_expression
if exp then
@generate_ascii_art
@add_generated_to_result
else
if type(errmsg) == "string" then
print("nabla error: " .. errmsg)
else
print("nabla error!")
end
end
end
end
@replace_with_generated
end
@export_symbols+=
replace_all = replace_all,
@get_all_lines+=
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, true)
@replace_with_generated+=
vim.api.nvim_buf_set_lines(0, 0, -1, true, result)
@if_empty_line_just_skip+=
table.insert(result, "")
@add_generated_to_result+=
for _, newline in ipairs(drawing) do
table.insert(result, newline)
end
<file_sep>@../lua/nabla/ascii.lua=
@requires
@declare_functions
local style = {
@style_variables
}
local special_syms = {
@special_symbols
}
@grid_prototype
@script_variables
@functions
return {
@export_symbols
}
@functions+=
local function to_ascii(exp)
@init_grid_structure
@transform_exp_to_grid
@if_not_valid_exp_return_nil
return grid
end
@export_symbols+=
to_ascii = to_ascii,
@if_not_valid_exp_return_nil+=
else
return nil
end
@grid_prototype+=
local grid = {}
function grid:new(w, h, content)
@make_blank_content_if_not_provided
local o = {
w = w or 0,
h = h or 0,
content = content or {},
@grid_data
}
return setmetatable(o, {
@grid_metamethods
__index = grid,
})
end
@init_grid_structure+=
local g = grid:new()
@grid_prototype+=
function grid:join_hori(g, top_align)
local combined = {}
@align_both_for_horizontal_join
@compute_horizontal_spaces
@compute_height_horizontal_join
for y=1,h do
@get_row_or_create_empty_row
@combine_rows_and_put_in_result
end
local c = grid:new(self.w+g.w, h, combined)
@set_result_horizontal_middle
return c
end
@compute_spacers+=
local s1 = math.floor((h-self.h)/2)
local s2 = math.floor((h-g.h)/2)
@grid_prototype+=
function grid:get_row(y)
if y < 1 or y > self.h then
local s = ""
for i=1,self.w do s = s .. " " end
return s
end
return self.content[y]
end
@get_row_or_create_empty_row+=
local r1 = self:get_row(y-s1)
local r2 = g:get_row(y-s2)
@combine_rows_and_put_in_result+=
table.insert(combined, r1 .. r2)
@style_variables+=
plus_sign = " + ",
@transform_exp_to_grid+=
if exp.kind == "numexp" then
local numstr = tostring(exp.num)
return grid:new(string.len(numstr), 1, { tostring(numstr) })
elseif exp.kind == "addexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.plus_sign), 1, { style.plus_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
@style_variables+=
minus_sign = " − ",
@transform_exp_to_grid+=
elseif exp.kind == "subexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.minus_sign), 1, { style.minus_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
@style_variables+=
multiply_sign = " ∙ ",
@transform_exp_to_grid+=
elseif exp.kind == "mulexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.multiply_sign), 1, { style.multiply_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
@grid_metamethods+=
__tostring = function(g)
return table.concat(g.content, "\n")
end,
@grid_prototype+=
function grid:join_vert(g, align_left)
local w = math.max(self.w, g.w)
local h = self.h+g.h
local combined = {}
@compute_spacers_vertical
for x=1,w do
@get_column_or_get_empty_column
@combine_cols_and_put_in_result
end
@transpose_columns
return grid:new(w, h, rows)
end
@compute_spacers_vertical+=
local s1, s2
if not align_left then
s1 = math.floor((w-self.w)/2)
s2 = math.floor((w-g.w)/2)
else
s1 = 0
s2 = 0
end
@declare_functions+=
local utf8len, utf8char
@functions+=
function utf8len(str)
return vim.str_utfindex(str)
end
function utf8char(str, i)
if i >= utf8len(str) or i < 0 then return nil end
local s1 = vim.str_byteindex(str, i)
local s2 = vim.str_byteindex(str, i+1)
return string.sub(str, s1+1, s2)
end
@grid_prototype+=
function grid:get_col(x)
local s = ""
if x < 1 or x > self.w then
for i=1,self.h do s = s .. " " end
else
for y=1,self.h do
s = s .. utf8char(self.content[y], x-1)
end
end
return s
end
@get_column_or_get_empty_column+=
local c1 = self:get_col(x-s1)
local c2 = g:get_col(x-s2)
@combine_cols_and_put_in_result+=
table.insert(combined, c1 .. c2)
@transpose_columns+=
local rows = {}
for y=1,h do
local row = ""
for x=1,w do
row = row .. utf8char(combined[x], y-1)
end
table.insert(rows, row)
end
@transform_exp_to_grid+=
elseif exp.kind == "divexp" then
local leftgrid = to_ascii(exp.left)
local rightgrid = to_ascii(exp.right)
@generate_appropriate_size_fraction_bar
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
@set_middle_for_fraction
return c2
@style_variables+=
div_bar = "―",
@generate_appropriate_size_fraction_bar+=
local bar = ""
local w = math.max(leftgrid.w, rightgrid.w)
for x=1,w do
bar = bar .. style.div_bar
end
@grid_data+=
my = 0, -- middle y (might not be h/2, for example fractions with big denominator, etc )
@align_both_for_horizontal_join+=
local num_max = math.max(self.my, g.my)
local den_max = math.max(self.h - self.my, g.h - g.my)
@compute_horizontal_spaces+=
local s1, s2
if not top_align then
s1 = num_max - self.my
s2 = num_max - g.my
else
s1 = 0
s2 = 0
end
@compute_height_horizontal_join+=
local h
if not top_align then
h = den_max + num_max
else
h = math.max(self.h, g.h)
end
@set_result_horizontal_middle+=
c.my = num_max
@set_middle_for_fraction+=
c2.my = leftgrid.h
@grid_prototype+=
function grid:enclose_paren()
@create_left_paren_with_correct_height
@create_right_paren_with_correct_height
local c1 = left_paren:join_hori(self)
local c2 = c1:join_hori(right_paren)
return c2
end
@style_variables+=
left_top_par = '⎛',
left_middle_par = '⎜',
left_bottom_par = '⎝',
right_top_par = '⎞',
right_middle_par = '⎟',
right_bottom_par = '⎠',
left_single_par = '(',
right_single_par = ')',
@create_left_paren_with_correct_height+=
local left_content = {}
if self.h == 1 then
left_content = { style.left_single_par }
else
for y=1,self.h do
if y == 1 then table.insert(left_content, style.left_top_par)
elseif y == self.h then table.insert(left_content, style.left_bottom_par)
else table.insert(left_content, style.left_middle_par)
end
end
end
local left_paren = grid:new(1, self.h, left_content)
left_paren.my = self.my
@create_right_paren_with_correct_height+=
local right_content = {}
if self.h == 1 then
right_content = { style.right_single_par }
else
for y=1,self.h do
if y == 1 then table.insert(right_content, style.right_top_par)
elseif y == self.h then table.insert(right_content, style.right_bottom_par)
else table.insert(right_content, style.right_middle_par)
end
end
end
local right_paren = grid:new(1, self.h, right_content)
right_paren.my = self.my
@transform_exp_to_grid+=
elseif exp.kind == "symexp" then
local sym = exp.sym
if special_syms[sym] then
sym = special_syms[sym]
end
return grid:new(utf8len(sym), 1, { sym })
@style_variables+=
comma_sign = ", ",
@transform_exp_to_grid+=
elseif exp.kind == "funexp" then
local name = exp.name.kind == "symexp" and exp.name.sym
@transform_special_functions
else
local c0 = to_ascii(exp.name)
local comma = grid:new(utf8len(style.comma_sign), 1, { style.comma_sign })
local args
for _, arg in ipairs(exp.args) do
local garg = to_ascii(arg)
if not args then args = garg
else
args = args:join_hori(comma)
args = args:join_hori(garg)
end
end
if args then
args = args:enclose_paren()
else
args = grid:new(2, 1, { style.left_single_par .. style.right_single_par })
end
return c0:join_hori(args)
end
@style_variables+=
eq_sign = {
@relation_signs
},
@relation_signs+=
["="] = " = ",
["<"] = " < ",
[">"] = " > ",
[">="] = " ≥ ",
["<="] = " ≤ ",
[">>"] = " ≫ ",
["<<"] = " ≪ ",
["~="] = " ≅ ",
["!="] = " ≠ ",
["=>"] = " → ",
@transform_exp_to_grid+=
elseif exp.kind == "eqexp" then
if style.eq_sign[exp.sign] then
local leftgrid = to_ascii(exp.left)
local rightgrid = to_ascii(exp.right)
local opgrid = grid:new(utf8len(style.eq_sign[exp.sign]), 1, { style.eq_sign[exp.sign] })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
else
return nil
end
@special_symbols+=
["Alpha"] = "Α", ["Beta"] = "Β", ["Gamma"] = "Γ", ["Delta"] = "Δ", ["Epsilon"] = "Ε", ["Zeta"] = "Ζ", ["Eta"] = "Η", ["Theta"] = "Θ", ["Iota"] = "Ι", ["Kappa"] = "Κ", ["Lambda"] = "Λ", ["Mu"] = "Μ", ["Nu"] = "Ν", ["Xi"] = "Ξ", ["Omicron"] = "Ο", ["Pi"] = "Π", ["Rho"] = "Ρ", ["Sigma"] = "Σ", ["Tau"] = "Τ", ["Upsilon"] = "Υ", ["Phi"] = "Φ", ["Chi"] = "Χ", ["Psi"] = "Ψ", ["Omega"] = "Ω",
["alpha"] = "α", ["beta"] = "β", ["gamma"] = "γ", ["delta"] = "δ", ["epsilon"] = "ε", ["zeta"] = "ζ", ["eta"] = "η", ["theta"] = "θ", ["iota"] = "ι", ["kappa"] = "κ", ["lambda"] = "λ", ["mu"] = "μ", ["nu"] = "ν", ["xi"] = "ξ", ["omicron"] = "ο", ["pi"] = "π", ["rho"] = "ρ", ["final"] = "ς", ["sigma"] = "σ", ["tau"] = "τ", ["upsilon"] = "υ", ["phi"] = "φ", ["chi"] = "χ", ["psi"] = "ψ", ["omega"] = "ω",
["nabla"] = "∇",
@transform_special_functions+=
if name == "int" and #exp.args == 3 then
local lowerbound = to_ascii(exp.args[1])
local upperbound = to_ascii(exp.args[2])
local integrand = to_ascii(exp.args[3])
@make_integral_symbol
local res = upperbound:join_vert(int_bar)
res = res:join_vert(lowerbound)
res.my = upperbound.h + integrand.my + 1
res = res:join_hori(col_spacer)
return res:join_hori(integrand)
@style_variables+=
int_top = "⌠",
int_middle = "⎮",
int_single = "∫",
int_bottom = "⌡",
@make_integral_symbol+=
local int_content = {}
for y=1,integrand.h+1 do
if y == 1 then table.insert(int_content, style.int_top)
elseif y == integrand.h+1 then table.insert(int_content, style.int_bottom)
else table.insert(int_content, style.int_middle)
end
end
local int_bar = grid:new(1, integrand.h+1, int_content)
local col_spacer = grid:new(1, 1, { " " })
@special_symbols+=
["inf"] = "∞",
@style_variables+=
prefix_minus_sign = "‐",
@transform_exp_to_grid+=
elseif exp.kind == "presubexp" then
local minus = grid:new(utf8len(style.prefix_minus_sign), 1, { style.prefix_minus_sign })
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
return minus:join_hori(leftgrid)
@grid_prototype+=
function grid:put_paren(exp, parent)
if exp.priority() < parent.priority() then
return self:enclose_paren()
else
return self
end
end
@declare_functions+=
local hassuperscript
@functions+=
function hassuperscript(x)
if x.kind == "numexp" and math.floor(x.num) == x.num then
return x.num >= 0 and x.num <= 9
elseif x.kind == "symexp" and x.sym == "n" then
return true
end
return false
end
@transform_exp_to_grid+=
elseif exp.kind == "expexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
if exp.right.kind == "numexp" and hassuperscript(exp.right) then
@get_superscript_number
@combine_superscript_char
return result
elseif exp.right.kind == "symexp" and hassuperscript(exp.right) then
@get_superscript_n
@combine_superscript_char
return result
end
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
@combine_diagonally_for_superscript
return result
@combine_superscript_char+=
local my = leftgrid.my
leftgrid.my = 0
local result = leftgrid:join_hori(superscript)
result.my = my
@script_variables+=
local super_num = { "⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹" }
@get_superscript_number+=
local superscript = grid:new(1, 1, { super_num[exp.right.num+1] })
@get_superscript_n+=
local superscript = grid:new(1, 1, { "ⁿ" })
@make_blank_content_if_not_provided+=
if not content and w and h and w > 0 and h > 0 then
content = {}
for y=1,h do
local row = ""
for x=1,w do
row = row .. " "
end
table.insert(content, row)
end
end
@grid_prototype+=
function grid:join_super(superscript)
@make_spacer_upper_left
local upper = spacer:join_hori(superscript, true)
local result = upper:join_vert(self, true)
result.my = self.my + superscript.h
return result
end
@combine_diagonally_for_superscript+=
local result = leftgrid:join_super(rightgrid)
@make_spacer_upper_left+=
local spacer = grid:new(self.w, superscript.h)
@transform_special_functions+=
elseif name == "sqrt" and #exp.args == 1 then
local toroot = to_ascii(exp.args[1])
@make_root_symbols
local res = left_root:join_hori(toroot)
res = top_root:join_vert(res)
res.my = top_root.h + toroot.my
return res
@style_variables+=
root_vert_bar = "│",
root_bottom = "\\",
root_upper_left = "┌",
root_upper = "─",
root_upper_right = "┐",
@make_root_symbols+=
local left_content = {}
for y=1,toroot.h do
if y < toroot.h then
table.insert(left_content, " " .. style.root_vert_bar)
else
table.insert(left_content, style.root_bottom .. style.root_vert_bar)
end
end
local left_root = grid:new(2, toroot.h, left_content)
left_root.my = toroot.my
local up_str = " " .. style.root_upper_left
for x=1,toroot.w do
up_str = up_str .. style.root_upper
end
up_str = up_str .. style.root_upper_right
local top_root = grid:new(toroot.w+2, 1, { up_str })
@declare_functions+=
local hassubscript
@functions+=
function hassubscript(x)
if x.kind == "numexp" and math.floor(x.num) == x.num then
return x.num >= 0 and x.num <= 9
elseif x.kind == "symexp" and string.len(x.sym) == 1 and string.find("aeoxhklmnpst", x.sym) then
return true
end
return false
end
@transform_exp_to_grid+=
elseif exp.kind == "indexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
if exp.right.kind == "numexp" and hassuperscript(exp.right) then
@get_subscript_number
@combine_subscript_char
return result
elseif exp.right.kind == "symexp" and hassuperscript(exp.right) then
@get_subscript_letter
@combine_subscript_char
return result
end
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
@combine_diagonally_for_subscript
return result
@get_subscript_number+=
local sub_num = { "₀","₁","₂","₃","₄","₅","₆","₇","₈","₉" }
local subscript = grid:new(1, 1, { sub_num[exp.right.num+1] })
@combine_subscript_char+=
local my = leftgrid.my
leftgrid.my = 0
local result = leftgrid:join_hori(subscript)
result.my = my
@get_subscript_letter+=
local sletter = {
["a"] = "ₐ",
["e"] = "ₑ",
["o"] = "ₒ",
["x"] = "ₓ",
["h"] = "ₕ",
["k"] = "ₖ",
["l"] = "ₗ",
["m"] = "ₘ",
["n"] = "ₙ",
["p"] = "ₚ",
["s"] = "ₛ",
["t"] = "ₜ",
}
local subscript = grid:new(1, 1, { sletter[exp.right.sym] })
@grid_prototype+=
function grid:combine_sub(other)
@make_spacer_lower_left
local lower = spacer:join_hori(other)
local result = self:join_vert(lower, true)
result.my = self.my
return result
end
@combine_diagonally_for_subscript+=
local result = leftgrid:combine_sub(rightgrid)
@make_spacer_lower_left+=
local spacer = grid:new(self.w, other.h)
@transform_special_functions+=
elseif name == "lim" and #exp.args == 3 then
local variable = to_ascii(exp.args[1])
local limit = to_ascii(exp.args[2])
local formula = to_ascii(exp.args[3])
@make_limit_symbols
@combine_limit_symbols
return res
@style_variables+=
limit = "lim",
limit_arrow = " → ",
@make_limit_symbols+=
local limit_text = grid:new(utf8len(style.limit), 1, { style.limit })
local arrow_text = grid:new(utf8len(style.limit_arrow), 1, { style.limit_arrow })
local col_spacer = grid:new(1, 1, { " " })
@combine_limit_symbols+=
local lower = variable:join_hori(arrow_text)
lower = lower:join_hori(limit)
local res = limit_text:join_vert(lower)
res.my = 0
res = res:join_hori(col_spacer)
res = res:join_hori(formula)
@transform_exp_to_grid+=
elseif exp.kind == "matexp" then
if #exp.rows > 0 then
@make_grid_of_individual_cells
@combine_to_matrix_grid
@combine_matrix_brackets
res.my = math.floor(res.h/2)
return res
else
return nil, "empty matrix"
end
@make_grid_of_individual_cells+=
local cellsgrid = {}
local maxheight = 0
for _, row in ipairs(exp.rows) do
local rowgrid = {}
for _, cell in ipairs(row) do
local cellgrid = to_ascii(cell)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
end
table.insert(cellsgrid, rowgrid)
end
@combine_to_matrix_grid+=
local res
for i=1,#cellsgrid[1] do
local col
for j=1,#cellsgrid do
local cell = cellsgrid[j][i]
@add_row_spacer_to_center_cell
@add_col_spacer_to_center_cell
@add_cell_grid_to_row_grid
end
@add_row_grid_to_matrix_grid
end
@add_cell_grid_to_row_grid+=
if not col then col = cell
else col = col:join_vert(cell, true) end
@add_row_grid_to_matrix_grid+=
if not res then res = col
else res = res:join_hori(col, true) end
@add_row_spacer_to_center_cell+=
local sup = maxheight - cell.h
local sdown = 0
local up, down
if sup > 0 then up = grid:new(cell.w, sup) end
if sdown > 0 then down = grid:new(cell.w, sdown) end
if up then cell = up:join_vert(cell) end
if down then cell = cell:join_vert(down) end
@add_col_spacer_to_center_cell+=
local colspacer = grid:new(1, cell.h)
colspacer.my = cell.my
if i < #cellsgrid[1] then
cell = cell:join_hori(colspacer)
end
@style_variables+=
matrix_upper_left = "⎡",
matrix_upper_right = "⎤",
matrix_vert_left = "⎢",
matrix_lower_left = "⎣",
matrix_lower_right = "⎦",
matrix_vert_right = "⎥",
matrix_single_left = "[",
matrix_single_right = "]",
@combine_matrix_brackets+=
local left_content, right_content = {}, {}
if res.h > 1 then
for y=1,res.h do
if y == 1 then
table.insert(left_content, style.matrix_upper_left)
table.insert(right_content, style.matrix_upper_right)
elseif y == res.h then
table.insert(left_content, style.matrix_lower_left)
table.insert(right_content, style.matrix_lower_right)
else
table.insert(left_content, style.matrix_vert_left)
table.insert(right_content, style.matrix_vert_right)
end
end
else
left_content = { style.matrix_single_left }
right_content = { style.matrix_single_right }
end
local leftbracket = grid:new(1, res.h, left_content)
local rightbracket = grid:new(1, res.h, right_content)
res = leftbracket:join_hori(res, true)
res = res:join_hori(rightbracket, true)
@special_symbols+=
["..."] = "…",
@transform_exp_to_grid+=
elseif exp.kind == "derexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
@make_derivates_symbol_derexp
local result = leftgrid:join_hori(superscript, true)
result.my = leftgrid.my
return result
@make_derivates_symbol_derexp+=
local super_content = ""
for i=1,exp.order do
super_content = super_content .. "'"
end
local superscript = grid:new(exp.order, 1, { super_content })
@transform_special_functions+=
elseif name == "sum" and #exp.args == 3 then
local lowerbound = to_ascii(exp.args[1])
local upperbound = to_ascii(exp.args[2])
local sum = to_ascii(exp.args[3])
@make_sum_symbol
local res = upperbound:join_vert(sum_sym)
res = res:join_vert(lowerbound)
res.my = upperbound.h + math.floor(sum_sym.h/2)
res = res:join_hori(col_spacer)
return res:join_hori(sum)
@style_variables+=
sum_up = "⎲",
sum_down = "⎳",
@make_sum_symbol+=
assert(utf8len(style.sum_up) == utf8len(style.sum_down))
local sum_sym = grid:new(utf8len(style.sum_up), 2, { style.sum_up, style.sum_down })
local col_spacer = grid:new(1, 1, { " " })
@transform_special_functions+=
elseif name == "sum" and #exp.args == 1 then
local sum = to_ascii(exp.args[1])
@make_sum_symbol
local res = sum_sym:join_hori(col_spacer)
return res:join_hori(sum)
@transform_special_functions+=
elseif name == "d" and #exp.args == 2 then
local var = to_ascii(exp.args[1])
local fun = to_ascii(exp.args[2])
@make_numerator_derivative
@make_denominator_derivative
@generate_appropriate_size_fraction_bar
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
@set_middle_for_fraction
return c2
@style_variables+=
derivative = "d",
@make_numerator_derivative+=
local d = grid:new(utf8len(style.derivative), 1, { style.derivative })
local leftgrid = d:join_hori(fun)
@make_denominator_derivative+=
local d = grid:new(utf8len(style.derivative), 1, { style.derivative })
local rightgrid = d:join_hori(var)
@transform_special_functions+=
elseif name == "dp" and #exp.args == 2 then
local var = to_ascii(exp.args[1])
local fun = to_ascii(exp.args[2])
@make_numerator_partial_derivative
@make_denominator_partial_derivative
@generate_appropriate_size_fraction_bar
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
@set_middle_for_fraction
return c2
@style_variables+=
partial_derivative = "∂",
@make_numerator_partial_derivative+=
local d = grid:new(utf8len(style.derivative), 1, { style.partial_derivative })
local leftgrid = d:join_hori(fun)
@make_denominator_partial_derivative+=
local d = grid:new(utf8len(style.derivative), 1, { style.partial_derivative })
local rightgrid = d:join_hori(var)
@transform_special_functions+=
elseif name == "abs" and #exp.args == 1 then
local arg = to_ascii(exp.args[1])
@make_vertical_bar_absolute
local c1 = vbar_left:join_hori(arg, true)
local c2 = c1:join_hori(vbar_right, true)
c2.my = arg.my
return c2
@style_variables+=
abs_bar_left = "⎮",
abs_bar_right = "⎮",
@make_vertical_bar_absolute+=
local vbar_left_content = {}
local vbar_right_content = {}
for _=1,arg.h do
table.insert(vbar_left_content, style.abs_bar_left)
table.insert(vbar_right_content, style.abs_bar_right)
end
local vbar_left = grid:new(utf8len(style.abs_bar_left), arg.h, vbar_left_content)
local vbar_right = grid:new(utf8len(style.abs_bar_right), arg.h, vbar_right_content)
@transform_special_functions+=
elseif (name == "Delta" or name == "delta") and #exp.args == 1 then
local arg = to_ascii(exp.args[1])
local delta = to_ascii(exp.name)
local res = delta:join_hori(arg)
res.my = arg.my
return res
<file_sep>-- Generated from ascii.lua.tl using ntangle.nvim
local utf8len, utf8char
local hassuperscript
local hassubscript
local style = {
plus_sign = " + ",
minus_sign = " − ",
multiply_sign = " ∙ ",
div_bar = "―",
left_top_par = '⎛',
left_middle_par = '⎜',
left_bottom_par = '⎝',
right_top_par = '⎞',
right_middle_par = '⎟',
right_bottom_par = '⎠',
left_single_par = '(',
right_single_par = ')',
comma_sign = ", ",
eq_sign = {
["="] = " = ",
["<"] = " < ",
[">"] = " > ",
[">="] = " ≥ ",
["<="] = " ≤ ",
[">>"] = " ≫ ",
["<<"] = " ≪ ",
["~="] = " ≅ ",
["!="] = " ≠ ",
["=>"] = " → ",
},
int_top = "⌠",
int_middle = "⎮",
int_single = "∫",
int_bottom = "⌡",
prefix_minus_sign = "‐",
root_vert_bar = "│",
root_bottom = "\\",
root_upper_left = "┌",
root_upper = "─",
root_upper_right = "┐",
limit = "lim",
limit_arrow = " → ",
matrix_upper_left = "⎡",
matrix_upper_right = "⎤",
matrix_vert_left = "⎢",
matrix_lower_left = "⎣",
matrix_lower_right = "⎦",
matrix_vert_right = "⎥",
matrix_single_left = "[",
matrix_single_right = "]",
sum_up = "⎲",
sum_down = "⎳",
derivative = "d",
partial_derivative = "∂",
abs_bar_left = "⎮",
abs_bar_right = "⎮",
}
local special_syms = {
["Alpha"] = "Α", ["Beta"] = "Β", ["Gamma"] = "Γ", ["Delta"] = "Δ", ["Epsilon"] = "Ε", ["Zeta"] = "Ζ", ["Eta"] = "Η", ["Theta"] = "Θ", ["Iota"] = "Ι", ["Kappa"] = "Κ", ["Lambda"] = "Λ", ["Mu"] = "Μ", ["Nu"] = "Ν", ["Xi"] = "Ξ", ["Omicron"] = "Ο", ["Pi"] = "Π", ["Rho"] = "Ρ", ["Sigma"] = "Σ", ["Tau"] = "Τ", ["Upsilon"] = "Υ", ["Phi"] = "Φ", ["Chi"] = "Χ", ["Psi"] = "Ψ", ["Omega"] = "Ω",
["alpha"] = "α", ["beta"] = "β", ["gamma"] = "γ", ["delta"] = "δ", ["epsilon"] = "ε", ["zeta"] = "ζ", ["eta"] = "η", ["theta"] = "θ", ["iota"] = "ι", ["kappa"] = "κ", ["lambda"] = "λ", ["mu"] = "μ", ["nu"] = "ν", ["xi"] = "ξ", ["omicron"] = "ο", ["pi"] = "π", ["rho"] = "ρ", ["final"] = "ς", ["sigma"] = "σ", ["tau"] = "τ", ["upsilon"] = "υ", ["phi"] = "φ", ["chi"] = "χ", ["psi"] = "ψ", ["omega"] = "ω",
["nabla"] = "∇",
["inf"] = "∞",
["..."] = "…",
}
local grid = {}
function grid:new(w, h, content)
if not content and w and h and w > 0 and h > 0 then
content = {}
for y=1,h do
local row = ""
for x=1,w do
row = row .. " "
end
table.insert(content, row)
end
end
local o = {
w = w or 0,
h = h or 0,
content = content or {},
my = 0, -- middle y (might not be h/2, for example fractions with big denominator, etc )
}
return setmetatable(o, {
__tostring = function(g)
return table.concat(g.content, "\n")
end,
__index = grid,
})
end
function grid:join_hori(g, top_align)
local combined = {}
local num_max = math.max(self.my, g.my)
local den_max = math.max(self.h - self.my, g.h - g.my)
local s1, s2
if not top_align then
s1 = num_max - self.my
s2 = num_max - g.my
else
s1 = 0
s2 = 0
end
local h
if not top_align then
h = den_max + num_max
else
h = math.max(self.h, g.h)
end
for y=1,h do
local r1 = self:get_row(y-s1)
local r2 = g:get_row(y-s2)
table.insert(combined, r1 .. r2)
end
local c = grid:new(self.w+g.w, h, combined)
c.my = num_max
return c
end
function grid:get_row(y)
if y < 1 or y > self.h then
local s = ""
for i=1,self.w do s = s .. " " end
return s
end
return self.content[y]
end
function grid:join_vert(g, align_left)
local w = math.max(self.w, g.w)
local h = self.h+g.h
local combined = {}
local s1, s2
if not align_left then
s1 = math.floor((w-self.w)/2)
s2 = math.floor((w-g.w)/2)
else
s1 = 0
s2 = 0
end
for x=1,w do
local c1 = self:get_col(x-s1)
local c2 = g:get_col(x-s2)
table.insert(combined, c1 .. c2)
end
local rows = {}
for y=1,h do
local row = ""
for x=1,w do
row = row .. utf8char(combined[x], y-1)
end
table.insert(rows, row)
end
return grid:new(w, h, rows)
end
function grid:get_col(x)
local s = ""
if x < 1 or x > self.w then
for i=1,self.h do s = s .. " " end
else
for y=1,self.h do
s = s .. utf8char(self.content[y], x-1)
end
end
return s
end
function grid:enclose_paren()
local left_content = {}
if self.h == 1 then
left_content = { style.left_single_par }
else
for y=1,self.h do
if y == 1 then table.insert(left_content, style.left_top_par)
elseif y == self.h then table.insert(left_content, style.left_bottom_par)
else table.insert(left_content, style.left_middle_par)
end
end
end
local left_paren = grid:new(1, self.h, left_content)
left_paren.my = self.my
local right_content = {}
if self.h == 1 then
right_content = { style.right_single_par }
else
for y=1,self.h do
if y == 1 then table.insert(right_content, style.right_top_par)
elseif y == self.h then table.insert(right_content, style.right_bottom_par)
else table.insert(right_content, style.right_middle_par)
end
end
end
local right_paren = grid:new(1, self.h, right_content)
right_paren.my = self.my
local c1 = left_paren:join_hori(self)
local c2 = c1:join_hori(right_paren)
return c2
end
function grid:put_paren(exp, parent)
if exp.priority() < parent.priority() then
return self:enclose_paren()
else
return self
end
end
function grid:join_super(superscript)
local spacer = grid:new(self.w, superscript.h)
local upper = spacer:join_hori(superscript, true)
local result = upper:join_vert(self, true)
result.my = self.my + superscript.h
return result
end
function grid:combine_sub(other)
local spacer = grid:new(self.w, other.h)
local lower = spacer:join_hori(other)
local result = self:join_vert(lower, true)
result.my = self.my
return result
end
local super_num = { "⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹" }
local function to_ascii(exp)
local g = grid:new()
if exp.kind == "numexp" then
local numstr = tostring(exp.num)
return grid:new(string.len(numstr), 1, { tostring(numstr) })
elseif exp.kind == "addexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.plus_sign), 1, { style.plus_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
elseif exp.kind == "subexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.minus_sign), 1, { style.minus_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
elseif exp.kind == "mulexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.multiply_sign), 1, { style.multiply_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
elseif exp.kind == "divexp" then
local leftgrid = to_ascii(exp.left)
local rightgrid = to_ascii(exp.right)
local bar = ""
local w = math.max(leftgrid.w, rightgrid.w)
for x=1,w do
bar = bar .. style.div_bar
end
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
c2.my = leftgrid.h
return c2
elseif exp.kind == "symexp" then
local sym = exp.sym
if special_syms[sym] then
sym = special_syms[sym]
end
return grid:new(utf8len(sym), 1, { sym })
elseif exp.kind == "funexp" then
local name = exp.name.kind == "symexp" and exp.name.sym
if name == "int" and #exp.args == 3 then
local lowerbound = to_ascii(exp.args[1])
local upperbound = to_ascii(exp.args[2])
local integrand = to_ascii(exp.args[3])
local int_content = {}
for y=1,integrand.h+1 do
if y == 1 then table.insert(int_content, style.int_top)
elseif y == integrand.h+1 then table.insert(int_content, style.int_bottom)
else table.insert(int_content, style.int_middle)
end
end
local int_bar = grid:new(1, integrand.h+1, int_content)
local col_spacer = grid:new(1, 1, { " " })
local res = upperbound:join_vert(int_bar)
res = res:join_vert(lowerbound)
res.my = upperbound.h + integrand.my + 1
res = res:join_hori(col_spacer)
return res:join_hori(integrand)
elseif name == "sqrt" and #exp.args == 1 then
local toroot = to_ascii(exp.args[1])
local left_content = {}
for y=1,toroot.h do
if y < toroot.h then
table.insert(left_content, " " .. style.root_vert_bar)
else
table.insert(left_content, style.root_bottom .. style.root_vert_bar)
end
end
local left_root = grid:new(2, toroot.h, left_content)
left_root.my = toroot.my
local up_str = " " .. style.root_upper_left
for x=1,toroot.w do
up_str = up_str .. style.root_upper
end
up_str = up_str .. style.root_upper_right
local top_root = grid:new(toroot.w+2, 1, { up_str })
local res = left_root:join_hori(toroot)
res = top_root:join_vert(res)
res.my = top_root.h + toroot.my
return res
elseif name == "lim" and #exp.args == 3 then
local variable = to_ascii(exp.args[1])
local limit = to_ascii(exp.args[2])
local formula = to_ascii(exp.args[3])
local limit_text = grid:new(utf8len(style.limit), 1, { style.limit })
local arrow_text = grid:new(utf8len(style.limit_arrow), 1, { style.limit_arrow })
local col_spacer = grid:new(1, 1, { " " })
local lower = variable:join_hori(arrow_text)
lower = lower:join_hori(limit)
local res = limit_text:join_vert(lower)
res.my = 0
res = res:join_hori(col_spacer)
res = res:join_hori(formula)
return res
elseif name == "sum" and #exp.args == 3 then
local lowerbound = to_ascii(exp.args[1])
local upperbound = to_ascii(exp.args[2])
local sum = to_ascii(exp.args[3])
assert(utf8len(style.sum_up) == utf8len(style.sum_down))
local sum_sym = grid:new(utf8len(style.sum_up), 2, { style.sum_up, style.sum_down })
local col_spacer = grid:new(1, 1, { " " })
local res = upperbound:join_vert(sum_sym)
res = res:join_vert(lowerbound)
res.my = upperbound.h + math.floor(sum_sym.h/2)
res = res:join_hori(col_spacer)
return res:join_hori(sum)
elseif name == "sum" and #exp.args == 1 then
local sum = to_ascii(exp.args[1])
assert(utf8len(style.sum_up) == utf8len(style.sum_down))
local sum_sym = grid:new(utf8len(style.sum_up), 2, { style.sum_up, style.sum_down })
local col_spacer = grid:new(1, 1, { " " })
local res = sum_sym:join_hori(col_spacer)
return res:join_hori(sum)
elseif name == "d" and #exp.args == 2 then
local var = to_ascii(exp.args[1])
local fun = to_ascii(exp.args[2])
local d = grid:new(utf8len(style.derivative), 1, { style.derivative })
local leftgrid = d:join_hori(fun)
local d = grid:new(utf8len(style.derivative), 1, { style.derivative })
local rightgrid = d:join_hori(var)
local bar = ""
local w = math.max(leftgrid.w, rightgrid.w)
for x=1,w do
bar = bar .. style.div_bar
end
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
c2.my = leftgrid.h
return c2
elseif name == "dp" and #exp.args == 2 then
local var = to_ascii(exp.args[1])
local fun = to_ascii(exp.args[2])
local d = grid:new(utf8len(style.derivative), 1, { style.partial_derivative })
local leftgrid = d:join_hori(fun)
local d = grid:new(utf8len(style.derivative), 1, { style.partial_derivative })
local rightgrid = d:join_hori(var)
local bar = ""
local w = math.max(leftgrid.w, rightgrid.w)
for x=1,w do
bar = bar .. style.div_bar
end
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
c2.my = leftgrid.h
return c2
elseif name == "abs" and #exp.args == 1 then
local arg = to_ascii(exp.args[1])
local vbar_left_content = {}
local vbar_right_content = {}
for _=1,arg.h do
table.insert(vbar_left_content, style.abs_bar_left)
table.insert(vbar_right_content, style.abs_bar_right)
end
local vbar_left = grid:new(utf8len(style.abs_bar_left), arg.h, vbar_left_content)
local vbar_right = grid:new(utf8len(style.abs_bar_right), arg.h, vbar_right_content)
local c1 = vbar_left:join_hori(arg, true)
local c2 = c1:join_hori(vbar_right, true)
c2.my = arg.my
return c2
elseif (name == "Delta" or name == "delta") and #exp.args == 1 then
local arg = to_ascii(exp.args[1])
local delta = to_ascii(exp.name)
local res = delta:join_hori(arg)
res.my = arg.my
return res
else
local c0 = to_ascii(exp.name)
local comma = grid:new(utf8len(style.comma_sign), 1, { style.comma_sign })
local args
for _, arg in ipairs(exp.args) do
local garg = to_ascii(arg)
if not args then args = garg
else
args = args:join_hori(comma)
args = args:join_hori(garg)
end
end
if args then
args = args:enclose_paren()
else
args = grid:new(2, 1, { style.left_single_par .. style.right_single_par })
end
return c0:join_hori(args)
end
elseif exp.kind == "eqexp" then
if style.eq_sign[exp.sign] then
local leftgrid = to_ascii(exp.left)
local rightgrid = to_ascii(exp.right)
local opgrid = grid:new(utf8len(style.eq_sign[exp.sign]), 1, { style.eq_sign[exp.sign] })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
else
return nil
end
elseif exp.kind == "presubexp" then
local minus = grid:new(utf8len(style.prefix_minus_sign), 1, { style.prefix_minus_sign })
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
return minus:join_hori(leftgrid)
elseif exp.kind == "expexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
if exp.right.kind == "numexp" and hassuperscript(exp.right) then
local superscript = grid:new(1, 1, { super_num[exp.right.num+1] })
local my = leftgrid.my
leftgrid.my = 0
local result = leftgrid:join_hori(superscript)
result.my = my
return result
elseif exp.right.kind == "symexp" and hassuperscript(exp.right) then
local superscript = grid:new(1, 1, { "ⁿ" })
local my = leftgrid.my
leftgrid.my = 0
local result = leftgrid:join_hori(superscript)
result.my = my
return result
end
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local result = leftgrid:join_super(rightgrid)
return result
elseif exp.kind == "indexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
if exp.right.kind == "numexp" and hassuperscript(exp.right) then
local sub_num = { "₀","₁","₂","₃","₄","₅","₆","₇","₈","₉" }
local subscript = grid:new(1, 1, { sub_num[exp.right.num+1] })
local my = leftgrid.my
leftgrid.my = 0
local result = leftgrid:join_hori(subscript)
result.my = my
return result
elseif exp.right.kind == "symexp" and hassuperscript(exp.right) then
local sletter = {
["a"] = "ₐ",
["e"] = "ₑ",
["o"] = "ₒ",
["x"] = "ₓ",
["h"] = "ₕ",
["k"] = "ₖ",
["l"] = "ₗ",
["m"] = "ₘ",
["n"] = "ₙ",
["p"] = "ₚ",
["s"] = "ₛ",
["t"] = "ₜ",
}
local subscript = grid:new(1, 1, { sletter[exp.right.sym] })
local my = leftgrid.my
leftgrid.my = 0
local result = leftgrid:join_hori(subscript)
result.my = my
return result
end
local rightgrid = to_ascii(exp.right):put_paren(exp.right, exp)
local result = leftgrid:combine_sub(rightgrid)
return result
elseif exp.kind == "matexp" then
if #exp.rows > 0 then
local cellsgrid = {}
local maxheight = 0
for _, row in ipairs(exp.rows) do
local rowgrid = {}
for _, cell in ipairs(row) do
local cellgrid = to_ascii(cell)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
end
table.insert(cellsgrid, rowgrid)
end
local res
for i=1,#cellsgrid[1] do
local col
for j=1,#cellsgrid do
local cell = cellsgrid[j][i]
local sup = maxheight - cell.h
local sdown = 0
local up, down
if sup > 0 then up = grid:new(cell.w, sup) end
if sdown > 0 then down = grid:new(cell.w, sdown) end
if up then cell = up:join_vert(cell) end
if down then cell = cell:join_vert(down) end
local colspacer = grid:new(1, cell.h)
colspacer.my = cell.my
if i < #cellsgrid[1] then
cell = cell:join_hori(colspacer)
end
if not col then col = cell
else col = col:join_vert(cell, true) end
end
if not res then res = col
else res = res:join_hori(col, true) end
end
local left_content, right_content = {}, {}
if res.h > 1 then
for y=1,res.h do
if y == 1 then
table.insert(left_content, style.matrix_upper_left)
table.insert(right_content, style.matrix_upper_right)
elseif y == res.h then
table.insert(left_content, style.matrix_lower_left)
table.insert(right_content, style.matrix_lower_right)
else
table.insert(left_content, style.matrix_vert_left)
table.insert(right_content, style.matrix_vert_right)
end
end
else
left_content = { style.matrix_single_left }
right_content = { style.matrix_single_right }
end
local leftbracket = grid:new(1, res.h, left_content)
local rightbracket = grid:new(1, res.h, right_content)
res = leftbracket:join_hori(res, true)
res = res:join_hori(rightbracket, true)
res.my = math.floor(res.h/2)
return res
else
return nil, "empty matrix"
end
elseif exp.kind == "derexp" then
local leftgrid = to_ascii(exp.left):put_paren(exp.left, exp)
local super_content = ""
for i=1,exp.order do
super_content = super_content .. "'"
end
local superscript = grid:new(exp.order, 1, { super_content })
local result = leftgrid:join_hori(superscript, true)
result.my = leftgrid.my
return result
else
return nil
end
return grid
end
function utf8len(str)
return vim.str_utfindex(str)
end
function utf8char(str, i)
if i >= utf8len(str) or i < 0 then return nil end
local s1 = vim.str_byteindex(str, i)
local s2 = vim.str_byteindex(str, i+1)
return string.sub(str, s1+1, s2)
end
function hassuperscript(x)
if x.kind == "numexp" and math.floor(x.num) == x.num then
return x.num >= 0 and x.num <= 9
elseif x.kind == "symexp" and x.sym == "n" then
return true
end
return false
end
function hassubscript(x)
if x.kind == "numexp" and math.floor(x.num) == x.num then
return x.num >= 0 and x.num <= 9
elseif x.kind == "symexp" and string.len(x.sym) == 1 and string.find("aeoxhklmnpst", x.sym) then
return true
end
return false
end
return {
to_ascii = to_ascii,
}
|
1cc1dfa5c600bc4643c1fde227e5af633c30a9c9
|
[
"Markdown",
"Lua",
"Type Language"
] | 6 |
Markdown
|
TrendingTechnology/nabla.nvim
|
201349aa8517df5d2d1bc3260583cf71c8ca2f61
|
471194777f3e0d3b1c0edc6ef6412cbc39cfe4d6
|
refs/heads/master
|
<repo_name>gregpr07/X5GON_discovery<file_sep>/.github/workflows/deploy.yml
# This is a basic workflow to help you get started with Actions
name: CI
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
release:
branches: [ master ]
types: [ published ]
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
deploy:
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
- name: Build on production
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
password: ${{ <PASSWORD> }}
script: |
cd ../../x5gon/x5gon-discovery
git pull
npm install
npm run-script build
|
12940d4c4e3999175f9d28713b434920452c28dd
|
[
"YAML"
] | 1 |
YAML
|
gregpr07/X5GON_discovery
|
b5beeec0029e6c11797581645fb7b6370ce8489b
|
d7c7d20059dccc2c363513aa9f8314903855ec28
|
refs/heads/master
|
<repo_name>horokos/Predator-Prey-mesa<file_sep>/model.py
from mesa import Agent, Model
from mesa.time import BaseScheduler
from mesa.space import Grid
from random import randint
import random
from mesa.visualization.modules import CanvasGrid
from mesa.visualization.ModularVisualization import ModularServer
class Animal(Agent):
def __init__(self, unique_id, model, pos):
super().__init__(unique_id, model)
self.pos = pos
self.group = None
def move(self):
possible_moves = self.model.grid.get_neighborhood(self.pos, moore=False)
while True:
next_move = random.choice(possible_moves)
if self.model.grid.is_cell_empty(next_move):
break
self.model.grid.move_agent(self, next_move)
def step(self, v=None):
if v is None:
self.move()
for i in self.model.grid.get_neighbors(self.pos, moore=False):
if i is not None:
if i.group is None:
self.group = self.model.schedule.groups + 1
i.group = self.model.schedule.groups + 1
self.model.schedule.groups += 1
else:
self.group = i.group
else:
self.model.grid.move_agent(self, tuple(map(lambda l, k: l + k, self.pos, v)))
class Scheduler(BaseScheduler):
def __init__(self, model):
super().__init__(model)
self.groups = 0
def step(self):
for a in self.agents:
if a.group is None:
a.step()
for g in range(1, self.groups):
v = random.choice([(0, 0), (1, 0), (0, 1), (1, 1)])
for a in self.agents:
if a.group == g:
a.step(v)
class WalkingModel(Model):
def __init__(self, agent_number):
self.agent_number = 40
self.width = agent_number
self.height = agent_number
self.schedule = Scheduler(self)
self.grid = Grid(self.width, self.height, True)
self.running = True
for i in range(self.agent_number):
while True:
x = randint(0, self.width - 1)
y = randint(0, self.height - 1)
if self.grid.is_cell_empty((x, y)):
break
a = Animal(model=self, pos=(x, y), unique_id=i)
self.schedule.add(a)
self.grid.place_agent(a, (x, y))
def step(self):
self.schedule.step()
for a in self.schedule.agents:
print(a.group)
def agent_portrayal(agent):
if agent is None:
return
portrayal = {"Shape": "rect",
"w": 0.5,
"h": 0.5,
"Filled": "true",
"Color": "blue",
"Layer": 1}
if agent.group is not None:
portrayal["text"] = round(agent.group, 10)
portrayal["text_color"] = "Black"
return portrayal
element = CanvasGrid(agent_portrayal, 100, 100, 800, 800)
server = ModularServer(WalkingModel,
[element],
"WalkingModel",
{"agent_number": 100})
server.port = 8606
server.launch()
|
2427e5cb6777d585fb90854f42fc4aeda9feb531
|
[
"Python"
] | 1 |
Python
|
horokos/Predator-Prey-mesa
|
5c37f28367064a25b4a053c6d3a3caa4eb8f26b4
|
e819d18586d438f789eeab4b963c327cdeb2ef4d
|
refs/heads/master
|
<file_sep># argocd-action
Setup ArgoCD cli, login the server you assigned, and then execute the subcommand if you assign one.
|
b1900b1aec0354e37185103129cc4232f4c92ac8
|
[
"Markdown"
] | 1 |
Markdown
|
gnat-service/argocd-action
|
a4453e0971f59cb88e887e7b26d855e92d2f9bfb
|
4e0285dfa3dbfd02b9dd34d20b9ff1ff53dc5902
|
refs/heads/master
|
<repo_name>crmtogether/Rapid-Item-Picker<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/product_inc_ajax.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_engine.js" -->
<!-- #include file ="product_inc.asp" --><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/uom_family_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="select UOMF_FamilyID,uomf_description,uomf_Active"+
",uomf_defaultvalue,uomf_name from UOMFamily where UOMF_Deleted is null";
_obj.columns=new Array();
_obj.title="UOMFamily";
_obj.columns.push('UOMF_FamilyID');
_obj.columns.push('uomf_description');
_obj.columns.push('uomf_Active');
_obj.columns.push('uomf_defaultvalue');
_obj.columns.push('uomf_name');
objar.push(_obj);
var _contentuomfam=createJSON_New(objar,CRM);
%>
<script>
var _uomfam=<%=_contentuomfam%>
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/updateQuoteItempos.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_header.js" -->
<!-- #include file ="json_engine.js" -->
<%
function _dev(msg)
{
if (false)
{
Response.Write("<br>dbg: "+msg);
}
}
var quot_orderquoteid="-1";
var QuIt_LineItemId=Request.Form("QuIt_LineItemId");
var old_QuIt_linenumber=Request.Form("from");
var new_QuIt_linenumber=Request.Form("to");
_dev("QuIt_LineItemId:"+QuIt_LineItemId);
//find QuoteItem..we are moving
var QuoteItemsrec=CRM.FindRecord("QuoteItems","QuIt_LineItemId="+QuIt_LineItemId);
quot_orderquoteid=QuoteItemsrec("QuIt_orderquoteid");
quoteid=QuoteItemsrec("QuIt_orderquoteid");
//find other item and update with the old number
var QuoteItemsrec2=CRM.FindRecord("QuoteItems","QuIt_orderquoteid="+quot_orderquoteid+" and QuIt_linenumber="+new_QuIt_linenumber);
QuoteItemsrec2("QuIt_linenumber")=old_QuIt_linenumber;
QuoteItemsrec2.SaveChangesNoTLS();
//update the item we are changing...
QuoteItemsrec("QuIt_linenumber")=new_QuIt_linenumber;
QuoteItemsrec.SaveChangesNoTLS();
_dev("update QuoteItems pos");
var OutputAsJSON=true;
%>
<!-- #include file ="quoteitems_inc.asp" -->
<!-- #include file ="json_footer.js" --><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/product_family_json.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_header.js" -->
<!-- #include file ="json_engine.js" -->
<%
var quoteid=CRM.GetContextInfo("quotes","quot_orderquoteid");
var json_note="";
if (!quoteid)
{
quoteid="514";
}
var _obj=new Object();
_obj.sql="SELECT TOP 51 prfa_productfamilyid, prfa_name FROM ProductFamily "+
"WHERE (prfa_name LIKE N'%' ESCAPE '|' OR COALESCE(prfa_name, N'') = N'') "+
"and prfa_Deleted is Null and prfa_active = N'Y'AND "+
"prfa_productfamilyid IN (select prod_productfamilyid from newproduct where prod_productid "+
"in(select pric_productid from pricing WHERE pric_deleted IS NULL AND pric_pricinglistid "+
"=(select quot_pricinglistid from quotes where quot_orderquoteid = "+quoteid+" and pricing.pric_price_cid = "+ "quotes.quot_currency))) "+
"and ((prfa_intid is null and prfa_active= N'Y' )) "+
"order by prfa_name";
_obj.columns=new Array();
_obj.title="ProductFamily";
_obj.columns.push('prfa_productfamilyid');
_obj.columns.push('prfa_name');
objar.push(_obj);
%>
<!-- #include file ="json_footer.js" --><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/ctItemPicker.asp
<!-- #include file ="sagecrm.js" -->
<%
var forReading = 1, forWriting = 2, forAppending = 8;
var newline="<br>";
var newlinetext="\n";
var CurrentUser=CRM.GetContextInfo("user", "User_logon");
CurrentUser=CurrentUser.toLowerCase();
var CurrentUserName=CRM.GetContextInfo("user", "User_firstname");
var CurrentUserEmail=CRM.GetContextInfo("user", "User_emailaddress");
Container=CRM.GetBlock("container");
Container.DisplayButton(Button_Default) =false;
Container.DisplayForm = true;
content=eWare.GetBlock('content');
content.contents = newline+"Hi "+CurrentUserName;
content.contents +=newline+"Welcome to the CRM Together Open Source page for the <b>Rapid Item Picker</b>.";
content.contents +=newline+"This will add a button to your CRM Quotes summary page.";
content.contents +=newline+"When this button is clicked it opens a modal window.";
content.contents +=newline+"This modal window provides users with a better experience in creating quotes.";
content.contents +=newline+"Regards";
content.contents +=newline+"The CRM Together Open Source Team"+newline+newline;
Container.AddBlock(content);
btnSend = eWare.Button("Email CRM Together", "", "mailto:<EMAIL>?subject=CRM Together Rapid Item Picker");
Container.AddButton(btnSend);
CRM.AddContent(Container.Execute());
Response.Write(CRM.GetPage('CRMTogetherOS'));
%>
<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/pricinglist_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="Select PrLi_PricingListID,prli_Description,prli_Active,prli_name "+
"from PricingList WITH (NOLOCK) where PrLi_Active = N'Y' "+
"and COALESCE(PrLi_DefaultValue, N'') = N''";
_obj.columns=new Array();
_obj.title="UOMFamily";
_obj.columns.push('PrLi_PricingListID');
_obj.columns.push('prli_Description');
_obj.columns.push('prli_Active');
_obj.columns.push('prli_name');
objar.push(_obj);
var _content=createJSON(objar,CRM);
%>
<script>
var _PricingList=<%=_content%>
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/deleteQuoteItem.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_header.js" -->
<!-- #include file ="json_engine.js" -->
<%
function _dev(msg)
{
if (false)
{
Response.Write("<br>dbg: "+msg);
}
}
var quot_orderquoteid=Request.Form("quot_orderquoteid");
_dev("quot_orderquoteid:"+quot_orderquoteid);
if (!quot_orderquoteid)
{
quot_orderquoteid="514";
}
var quoteid=quot_orderquoteid;
var QuIt_LineItemId=Request.Form("QuIt_LineItemId");
_dev("QuIt_LineItemId:"+QuIt_LineItemId);
if (!QuIt_LineItemId)
{
QuIt_LineItemId="1249";
}
//get the quote
var quoterec=CRM.FindRecord("Quotes","quot_orderquoteid="+quot_orderquoteid);
var oppoid=quoterec("Quot_opportunityid");
var quot_DiscountPC=quoterec("quot_DiscountPC");
//get the line item number of the record..we use this to update the line no's
var quit_linenumber=0;
var vLineItemsQuote_sql="select quit_linenumber from vLineItemsQuote WITH (NOLOCK) where QuIt_LineItemId="+QuIt_LineItemId;
var vLineItemsQuote=CRM.CreateQueryObj(vLineItemsQuote_sql);
vLineItemsQuote.SelectSQL();
if (!vLineItemsQuote.eof)
{
quit_linenumber=vLineItemsQuote("quit_linenumber");
}
_dev("quit_linenumber:"+quit_linenumber);
//delete QuoteItem
var itemid=Request.Form["quoteitemid"];
var QuoteItemsrec=CRM.FindRecord("QuoteItems","QuIt_LineItemID="+QuIt_LineItemId+" AND quit_Deleted is null");
QuoteItemsrec.DeleteRecord=true;
QuoteItemsrec.SaveChangesNoTLS();
_dev("DeleteRecord:"+QuIt_LineItemId);
//fix up the line items
//UPDATE QuoteItems SET quit_linenumber = (quit_linenumber -1)
//WHERE quit_linenumber > 8 AND quit_linenumber >= 0 AND quit_orderquoteid = 514 AND quit_DELETED IS NULL
var quit_linenumber_sql="UPDATE QuoteItems "+
"SET quit_linenumber = (quit_linenumber -1) "+
"WHERE quit_linenumber > "+quit_linenumber+" AND quit_linenumber >= 0 "+
"AND quit_orderquoteid = "+quot_orderquoteid+" AND quit_DELETED IS NULL";
CRM.ExecSql(quit_linenumber_sql);
_dev("quit_linenumber_sql:"+quit_linenumber_sql);
//get new values
var newquotetotals_sql="Select Sum(COALESCE(quit_DiscountSum, 0)) as DiscTotal,"+
"Sum(COALESCE(quit_quotedpricetotal, 0)) as NetTotal,"+
"Sum(COALESCE(quit_DiscountSum, 0))+Sum(COALESCE(quit_quotedpricetotal, 0)) as NoDiscAmt "+
"from vLineItemsQuote "+
"WITH (NOLOCK) where COALESCE(quit_deleted, 0) = 0 and quit_orderquoteID="+quot_orderquoteid;
var newquotetotals=CRM.CreateQueryObj(newquotetotals_sql);
newquotetotals.SelectSQL();
_dev("newquotetotals_sql:"+newquotetotals_sql);
//work out totals
var quot_NettAmt=0;
var quot_LineItemDisc=0;
var NoDiscAmt=0;
var quot_DiscountAMT=0;
var quot_GrossAmt=0;
if ((!newquotetotals.eof)&&(newquotetotals("NetTotal")!=null))
{
quot_LineItemDisc=newquotetotals("DiscTotal");
quot_NettAmt=newquotetotals("NetTotal");
NoDiscAmt=newquotetotals("NoDiscAmt");
quot_DiscountAMT=((quot_NettAmt/100)*quot_DiscountPC);
}
_dev("quot_NettAmt: "+quot_NettAmt);
quoterec("quot_NettAmt")=quot_NettAmt;
_dev("quot_LineItemDisc: "+quot_LineItemDisc);
quoterec("quot_LineItemDisc")=quot_LineItemDisc;
_dev("quot_DiscountAMT:"+quot_DiscountAMT);
quoterec("quot_DiscountAMT")=quot_DiscountAMT;
quot_GrossAmt=quot_NettAmt-quot_DiscountAMT;
_dev("quot_GrossAmt:"+quot_GrossAmt);
quoterec("quot_GrossAmt")=quot_GrossAmt; ;
quoterec.SaveChangesNoTLS();
var quotetotals_sql="Select COALESCE(Sum(Quot_GrossAmt), 0) as TotalForOppo, "+
"COALESCE(Sum(Quot_NoDiscAmt), 0) as NettTotalForOppo "+
"from vQuotes WITH (NOLOCK) "+
"where Quot_OpportunityID="+oppoid+
" and Quot_Status = N'Active' and COALESCE(Quot_RollUp, N'') <> N''";
var quotetotals=CRM.CreateQueryObj(quotetotals_sql);
quotetotals.SelectSQL();
_dev("quotetotals_sql:"+quotetotals_sql);
var Oppo_TotalQuotes=0;
var Oppo_Total=0;
if (!quotetotals.eof)
{
Oppo_TotalQuotes=quotetotals("TotalForOppo");
Oppo_Total=quotetotals("NettTotalForOppo");
}
_dev("Oppo_TotalQuotes:"+Oppo_TotalQuotes);
_dev("Oppo_Total:"+Oppo_Total);
//oppo totals
//UPDATE Opportunity SET Oppo_TotalOrders=16151.600000,Oppo_TotalOrders_CID=1,
//Oppo_TotalQuotes=145.000000,Oppo_TotalQuotes_CID=1,Oppo_Total=16296.600000,
//Oppo_Total_CID=1,Oppo_NoDiscAmtSum=0.000000,Oppo_NoDiscAmtSum_CID=1,oppo_UpdatedBy=1,
//oppo_TimeStamp='20190416 07:33:54',oppo_UpdatedDate='20190416 07:33:54'
//WHERE (Oppo_OpportunityID=10)
var oppores=CRM.FindRecord("Opportunity","oppo_opportunityid="+oppoid);
oppores("Oppo_TotalQuotes")=Oppo_TotalQuotes;
oppores("Oppo_Total")=Oppo_Total;
oppores.SaveChangesNoTLS();
_dev("oppores save:"+oppoid);
var OutputAsJSON=true;
%>
<!-- #include file ="quoteitems_inc.asp" -->
<!-- #include file ="json_footer.js" --><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/uom_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="select UOM_UOMID,uom_familyID,uom_description"+
",uom_units,uom_Active,uom_defaultvalue,uom_name from UOM "+
"where uom_Active='Y' and uom_deleted is null";
_obj.columns=new Array();
_obj.title="UOM";
_obj.columns.push('UOM_UOMID');
_obj.columns.push('uom_familyID');
_obj.columns.push('uom_description');
_obj.columns.push('uom_units');
_obj.columns.push('uom_Active');
_obj.columns.push('uom_defaultvalue');
_obj.columns.push('uom_name');
objar.push(_obj);
var _contentuom=createJSON_New(objar,CRM);
%>
<script>
var _uom=<%=_contentuom%>
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/product_family_inc.asp
<%
var objar=new Array();//this stores our data objects
var quoteid=CRM.GetContextInfo("quotes","quot_orderquoteid");
var json_note="";
if (!quoteid)
{
quoteid="514";
}
var _obj=new Object();
_obj.sql="SELECT TOP 51 prfa_productfamilyid, prfa_name FROM ProductFamily "+
"WHERE (prfa_name LIKE N'%' ESCAPE '|' OR COALESCE(prfa_name, N'') = N'') "+
"and prfa_Deleted is Null and prfa_active = N'Y'AND "+
"prfa_productfamilyid IN (select prod_productfamilyid from newproduct where prod_productid "+
"in(select pric_productid from pricing WHERE pric_deleted IS NULL AND pric_pricinglistid "+
"=(select quot_pricinglistid from quotes where quot_orderquoteid = "+quoteid+" and pricing.pric_price_cid = quotes.quot_currency))) "+
//COMMENTED OUT FOR uk SAGE 200 "and ((prfa_intid is null and prfa_active= N'Y' )) "+
"order by prfa_name";
_obj.columns=new Array();
_obj.title="ProductFamily";
_obj.columns.push('prfa_productfamilyid');
_obj.columns.push('prfa_name');
objar.push(_obj);
var _contentprodfam=createJSON(objar,CRM);
%>
<script>
var _productFamily=<%=_contentprodfam%>
var _productFamilySQL="<%=_obj.sql%>";
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/addQuoteItem.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_header.js" -->
<!-- #include file ="json_engine.js" -->
<%
function _dev(msg)
{
if (false)
{
Response.Write("<br>dbg: "+msg);
}
}
function getField(fname){
if (fname.indexOf("_CID")>0)
{
return currencyCID;
}
return Request.Form(fname);
}
var quot_orderquoteid=Request.Form("QuIt_orderquoteid");
_dev("quot_orderquoteid:"+quot_orderquoteid);
if (!quot_orderquoteid)
{
quot_orderquoteid="514";
}
var quoteid=quot_orderquoteid;
//get the quote
var quoterec=CRM.FindRecord("Quotes","quot_orderquoteid="+quot_orderquoteid);
var oppoid=quoterec("Quot_opportunityid");
var currencyCID=quoterec("Quot_currency");
var quot_DiscountPC=quoterec("quot_DiscountPC");
//get the latest line item number
var quit_linenumber=0;
var vLineItemsQuote_sql="select top 1 (quit_linenumber+1) as newno from vLineItemsQuote "+
" WITH (NOLOCK) where QuIt_orderquoteid="+quot_orderquoteid+
" order by quit_linenumber desc";
var vLineItemsQuote=CRM.CreateQueryObj(vLineItemsQuote_sql);
vLineItemsQuote.SelectSQL();
if (!vLineItemsQuote.eof)
{
quit_linenumber=vLineItemsQuote("newno");
}else{
quit_linenumber=1;
}
_dev("quit_linenumber:"+quit_linenumber);
//insert QuoteItem
var QuoteItemsrec=CRM.CreateRecord("QuoteItems");
QuoteItemsrec("QuIt_orderquoteid")=quot_orderquoteid;
var QuIt_quantity=new Number(getField("QuIt_quantity"));
var QuIt_quotedprice=new Number(getField("QuIt_quotedprice"));
var QuIt_listprice=new Number(getField("QuIt_listprice"));
QuoteItemsrec("quit_linenumber")=quit_linenumber;
QuoteItemsrec("QuIt_UOMID")=getField("QuIt_UOMID");
if (QuoteItemsrec("QuIt_UOMID")+""=="undefined")
QuoteItemsrec("QuIt_UOMID")='';
QuoteItemsrec("QuIt_productid")=getField("QuIt_productid");
QuoteItemsrec("QuIt_productfamilyid")=getField("QuIt_productfamilyid");
QuoteItemsrec("QuIt_quantity")=getField("QuIt_quantity");
QuoteItemsrec("QuIt_description")=getField("QuIt_description");
QuoteItemsrec("QuIt_quotedprice_CID")=getField("QuIt_quotedprice_CID");
QuoteItemsrec("QuIt_quotedprice")=getField("QuIt_quotedprice");
QuoteItemsrec("QuIt_LineType")=getField("QuIt_LineType");
QuoteItemsrec("QuIt_listprice_CID")=getField("QuIt_listprice_CID");
QuoteItemsrec("QuIt_listprice")=QuIt_listprice;
QuoteItemsrec("QuIt_discount_CID")=getField("QuIt_discount_CID");
var QuIt_discount=QuIt_listprice - QuIt_quotedprice;
QuoteItemsrec("QuIt_discount")=QuIt_discount;//list-quoted
QuoteItemsrec("QuIt_discountsum_CID")=getField("QuIt_discountsum_CID");
QuoteItemsrec("QuIt_discountsum")=QuIt_discount*QuIt_quantity;
QuoteItemsrec("QuIt_quotedpricetotal_CID")=getField("QuIt_quotedpricetotal_CID");
QuoteItemsrec("QuIt_quotedpricetotal")=QuIt_quantity*QuIt_quotedprice;
QuoteItemsrec("QuIt_tax_CID")=getField("QuIt_tax_CID");
QuoteItemsrec.SaveChangesNoTLS();
_dev("CreateRecord QuoteItems");
//get new values
var newquotetotals_sql="Select Sum(COALESCE(quit_DiscountSum, 0)) as DiscTotal,"+
"Sum(COALESCE(quit_quotedpricetotal, 0)) as NetTotal,"+
"Sum(COALESCE(quit_DiscountSum, 0))+Sum(COALESCE(quit_quotedpricetotal, 0)) as NoDiscAmt "+
"from vLineItemsQuote "+
"WITH (NOLOCK) where COALESCE(quit_deleted, 0) = 0 and quit_orderquoteID="+quot_orderquoteid;
var newquotetotals=CRM.CreateQueryObj(newquotetotals_sql);
newquotetotals.SelectSQL();
_dev("newquotetotals_sql:"+newquotetotals_sql);
//work out totals
var quot_NettAmt=0;
var quot_LineItemDisc=0;
var NoDiscAmt=0;
var quot_DiscountAMT=0;
var quot_GrossAmt="";
if (!newquotetotals.eof)
{
quot_LineItemDisc=newquotetotals("DiscTotal");
quot_NettAmt=newquotetotals("NetTotal");
NoDiscAmt=newquotetotals("NoDiscAmt");
quot_DiscountAMT=((quot_NettAmt/100)*quot_DiscountPC);
}
_dev("quot_NettAmt: "+quot_NettAmt);
quoterec("quot_NettAmt")=quot_NettAmt;
_dev("quot_LineItemDisc: "+quot_LineItemDisc);
quoterec("quot_LineItemDisc")=quot_LineItemDisc;
_dev("quot_DiscountAMT:"+quot_DiscountAMT);
quoterec("quot_DiscountAMT")=quot_DiscountAMT;
quot_GrossAmt=quot_NettAmt-quot_DiscountAMT;
_dev("quot_GrossAmt:"+quot_GrossAmt);
quoterec("quot_GrossAmt")=quot_GrossAmt; ;
quoterec.SaveChangesNoTLS();
var quotetotals_sql="Select COALESCE(Sum(Quot_GrossAmt), 0) as TotalForOppo, "+
"COALESCE(Sum(Quot_NoDiscAmt), 0) as NettTotalForOppo "+
"from vQuotes WITH (NOLOCK) "+
"where Quot_OpportunityID="+oppoid+
" and Quot_Status = N'Active' and COALESCE(Quot_RollUp, N'') <> N''";
var quotetotals=CRM.CreateQueryObj(quotetotals_sql);
quotetotals.SelectSQL();
_dev("quotetotals_sql:"+quotetotals_sql);
var Oppo_TotalQuotes=0;
var Oppo_Total=0;
var Oppo_NoDiscAmtSum=0;
if (!quotetotals.eof)
{
Oppo_TotalQuotes=quotetotals("TotalForOppo");
Oppo_Total=quotetotals("NettTotalForOppo");
}
_dev("Oppo_TotalQuotes:"+Oppo_TotalQuotes);
_dev("Oppo_Total:"+Oppo_Total);
//oppo totals
//UPDATE Opportunity SET Oppo_TotalOrders=16151.600000,Oppo_TotalOrders_CID=1,
//Oppo_TotalQuotes=145.000000,Oppo_TotalQuotes_CID=1,Oppo_Total=16296.600000,
//Oppo_Total_CID=1,Oppo_NoDiscAmtSum=0.000000,Oppo_NoDiscAmtSum_CID=1,oppo_UpdatedBy=1,
//oppo_TimeStamp='20190416 07:33:54',oppo_UpdatedDate='20190416 07:33:54'
//WHERE (Oppo_OpportunityID=10)
var oppores=CRM.FindRecord("Opportunity","oppo_opportunityid="+oppoid);
oppores("Oppo_TotalQuotes")=Oppo_TotalQuotes;
oppores("Oppo_Total")=Oppo_Total;
//oppores("Oppo_NoDiscAmtSum")=Oppo_NoDiscAmtSum;
oppores.SaveChangesNoTLS();
_dev("oppores save:"+oppoid);
var OutputAsJSON=true;
%>
<!-- #include file ="quoteitems_inc.asp" -->
<!-- #include file ="json_footer.js" --><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/quoteitems_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="Select "+
"QuIt_orderquoteid,QuIt_LineItemID,QuIt_linenumber,QuIt_UOMID,"+
"QuIt_productid,QuIt_productfamilyid,"+
"QuIt_quantity,QuIt_description,Prod_ProductID,"+
"QuIt_discount,QuIt_quotedprice,QuIt_quotedpricetotal,QuIt_LineType,"+
"QuIt_taxrate, prod_name, prod_code, QuIt_listprice, "+
"uom_name,uom_description, QuIt_UOMID ";
if (productCostField != '')
_obj.sql += "," + productCostField;
_obj.sql += " FROM vLineItemsQuote WITH (NOLOCK) "+
"left join UOM on QuIt_UOMID=UOM_UOMID "+
"where "+
"quit_OrderQuoteID = "+quoteid+" and quit_deleted is null "+
"order by QuIt_linenumber";
_obj.columns=new Array();
_obj.title="QuoteItems";
_obj.columns.push('QuIt_LineItemID');
_obj.columns.push('QuIt_orderquoteid');
_obj.columns.push('QuIt_linenumber');
_obj.columns.push('QuIt_UOMID');
_obj.columns.push('QuIt_productid');
_obj.columns.push('QuIt_productfamilyid');
_obj.columns.push('QuIt_quantity');
_obj.columns.push('QuIt_description');
_obj.columns.push('Prod_ProductID');
_obj.columns.push('QuIt_discount');
_obj.columns.push('QuIt_quotedprice');
_obj.columns.push('QuIt_quotedpricetotal');
_obj.columns.push('QuIt_LineType');
_obj.columns.push('QuIt_taxrate');
_obj.columns.push('prod_name');
_obj.columns.push('prod_code');
if (productCostField != '') {
_obj.columns.push(productCostField);
}
_obj.columns.push('QuIt_listprice');
_obj.columns.push('uom_name');
_obj.columns.push('uom_description');
objar.push(_obj);
//
//if OutputAsJSON is true see json_footer.js or json_footer2.js
//
if (!OutputAsJSON){
var _content=createJSON(objar,CRM);
%>
<script>
var _quoteitems=<%=_content%>
</script>
<% } %>
<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/getQuoteTotals.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_header.js" -->
<!-- #include file ="json_engine.js" -->
<%
var OutputAsJSON=true;
%>
<!-- #include file ="quote_inc.asp" -->
<!-- #include file ="json_footer.js" --><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/readme.txt
Notes:
1. Any file ending _json.asp returns json data.
2. the js folder has the 2 files needed for the js/custom folder to allow us create modals
3. <file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/uom_byfam_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="select uom_familyID,UOM_UOMID,uom_name "+
"from UOM "+
"where uom_Active='Y' and uom_deleted is null order by uom_familyID";
_obj.columns=new Array();
_obj.title="UOMbyFam";
_obj.columns.push('uom_familyID');
_obj.columns.push('UOM_UOMID');
_obj.columns.push('uom_name');
objar.push(_obj);
var _contentuom=createJSON_New2(objar,CRM);
%>
<script>
var _uombyfam=<%=_contentuom%>
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/json_engine.js
<%
var getProperty = function (obj, propertyName) {
return obj[propertyName];
};
//was planning on putting this into a grid...
function colIncolumnsToTotal(obj, name)
{
if (obj.columnsToTotal)
{
return obj.columnsToTotal.indexOf(name) > -1;
}
return false;
}
function undefinedToBlank(val)
{
if (val+""=="undefined")
{
return " ";
}
return val;
}
function undefinedToNum(val)
{
if (val+""=="undefined")
{
return 0;
}
val=val.replace(",","");
val=val.replace(",","");
return val;
}
//change the structure....so not to use an index
function createJSON_New(objar, CRM)
{
var totalsArray=new Array();
//var allcolumns=new Array();
var grid='{"structureversion":"1",';//version of the json ..use to detemine how to parse it
for(var i=0;i<objar.length;i++)
{
var allcolumns=new Array();
var totalsArray=new Array();
var _totals="0d 0h 0m";
grid+='"'+objar[i].title+'":{';
var u=objar[i];
if (u.columnsToTotal)//currency totals
{
for(var z=0;z<u.columnsToTotal.length;z++)
{
totalsArray[u.columnsToTotal[z]]=0;
}
}
var q=CRM.CreateQueryObj(u.sql);
try{
q.SelectSQL();
}catch(e)
{
Response.Write("Error in SQL: "+u.sql);
Response.End();
}
var _rowcomma="";
while(!q.eof)
{
grid+=_rowcomma+'"'+fixupJSON(undefinedToBlank(q(objar[i].columns[0])))+'":';
grid+='{';
var _cellcomma="";
for(j=0;j<objar[i].columns.length;j++)
{
if (objar[i].columns[j].indexOf("_secterr")>0)
{
grid+=_cellcomma+'"'+objar[i].columns[j]+'":"'+getTerr(q(objar[i].columns[j]))+'"';
}else{
grid+=_cellcomma+'"'+objar[i].columns[j]+'":"'+fixupJSON(undefinedToBlank(q(objar[i].columns[j])))+'"';
}
_cellcomma=",";
}
grid+='}';
_rowcomma=',';
if (u.columnsToTotalTime)
{
_totals=addTime(_totals,undefinedToBlank(q(objar[i].columnsToTotalTime[0])));
}
q.NextRecord();
}
if (u.columnsToTotal)////add in total columns
{
grid+="{";
for (_col in allcolumns) {
if (_col=="indexOf")//..weird bug
{
break;
}
var _totl=" --";//+_col;
if (totalsArray.hasOwnProperty(_col))
{
_totl=getProperty(totalsArray,_col);
_totl=formatTotals(_totl);
}
rowClass="GRIDHEAD";
grid+=''+_totl+'';
}
grid+="}";
}
grid+="}}";
}
return grid;
}
//change the structure to create an index
function createJSON_New2(objar, CRM)
{
var totalsArray=new Array();
//var allcolumns=new Array();
var grid='{"structureversion":"1",';//version of the json ..use to detemine how to parse it
for(var i=0;i<objar.length;i++)
{
var allcolumns=new Array();
var totalsArray=new Array();
var _totals="0d 0h 0m";
grid+='"'+objar[i].title+'":{';
var u=objar[i];
var q=CRM.CreateQueryObj(u.sql);
try{
q.SelectSQL();
}catch(e)
{
Response.Write("Error in SQL: "+u.sql);
Response.End();
}
var _rowcomma="";
var _rowcomma2="";
var _prevalue='---';
while(!q.eof)
{
if (_prevalue!=q(objar[i].columns[0]))
{
if (_prevalue!='---')
{
grid+="]";
}
grid+=_rowcomma+'"'+fixupJSON(undefinedToBlank(q(objar[i].columns[0])))+'":[';
_prevalue=q(objar[i].columns[0]);
}else{
grid+=_rowcomma2;
}
grid+='{';
var _cellcomma="";
for(j=0;j<objar[i].columns.length;j++)
{
if (objar[i].columns[j].indexOf("_secterr")>0)
{
grid+=_cellcomma+'"'+objar[i].columns[j]+'":"'+getTerr(q(objar[i].columns[j]))+'"';
}else{
grid+=_cellcomma+'"'+objar[i].columns[j]+'":"'+fixupJSON(undefinedToBlank(q(objar[i].columns[j])))+'"';
}
_cellcomma=",";
}
grid+='}';
_rowcomma=',';
_rowcomma2=',';
q.NextRecord();
}
grid+="]}}";
}
return grid;
}
function createJSON(objar, CRM)
{
var totalsArray=new Array();
//var allcolumns=new Array();
var grid='{"structureversion":"1",';//version of the json ..use to detemine how to parse it
for(var i=0;i<objar.length;i++)
{
var allcolumns=new Array();
var totalsArray=new Array();
var _totals="0d 0h 0m";
grid+='"'+objar[i].title+'":[';
var u=objar[i];
if (u.columnsToTotal)//currency totals
{
for(var z=0;z<u.columnsToTotal.length;z++)
{
totalsArray[u.columnsToTotal[z]]=0;
}
}
var q=CRM.CreateQueryObj(u.sql);
try{
q.SelectSQL();
}catch(e)
{
Response.Write("Error in SQL: "+u.sql);
Response.End();
}
/*
///to do...add in list of columns
grid+="<tr>";
for(j=0;j<objar[i].columns.length;j++)
{
grid+="<td class=\"GRIDHEAD\" >"+objar[i].columns[j]+"</td>";
allcolumns[objar[i].columns[j]]="";
}
grid+="</tr>";
*/
var _rowcomma="";
while(!q.eof)
{
grid+=_rowcomma+'{';
var _cellcomma="";
for(j=0;j<objar[i].columns.length;j++)
{
if (totalsArray.hasOwnProperty (objar[i].columns[j]))
{
var _nm=new Number(undefinedToNum(q(objar[i].columns[j])));
if (!isNaN(_nm))
{
totalsArray[objar[i].columns[j]]+=_nm;
}else{
//Response.write("<br />"+objar[i].columns[j]+"="+_nm);
}
}
if (objar[i].columns[j].indexOf("_secterr")>0)
{
grid+=_cellcomma+'"'+objar[i].columns[j]+'":"'+getTerr(q(objar[i].columns[j]))+'"';
}else{
grid+=_cellcomma+'"'+objar[i].columns[j]+'":"'+fixupJSON(undefinedToBlank(q(objar[i].columns[j])))+'"';
}
_cellcomma=",";
}
grid+='}';
_rowcomma=',';
if (u.columnsToTotalTime)
{
_totals=addTime(_totals,undefinedToBlank(q(objar[i].columnsToTotalTime[0])));
}
q.NextRecord();
}
if (u.columnsToTotal)////add in total columns
{
grid+="{";
for (_col in allcolumns) {
if (_col=="indexOf")//..weird bug
{
break;
}
var _totl=" --";//+_col;
if (totalsArray.hasOwnProperty(_col))
{
_totl=getProperty(totalsArray,_col);
_totl=formatTotals(_totl);
}
rowClass="GRIDHEAD";
grid+=''+_totl+'';
}
grid+="}";
}
grid+="]}";
}
return grid;
}
function formatTotals(val)
{
var valn=new Number(val);
valn=valn.toFixed(2);
return numberWithCommas(valn);
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function _getCompanyName(id)
{
var _res="";
if (id)
{
var _x=CRM.CreateQueryObj("select comp_name from company where comp_companyid="+id);
_x.SelectSQL();
if (!_x.eof)
{
_res=_x("comp_name");
}
}
return _res;
}
function _getCurrencySign(val)
{
var _res="no currency set!!!";
var _s="select * from Currency where Curr_CurrencyID="+val;
var _q=CRM.CreateQueryObj(_s);
_q.SelectSQL();
if (!_q.eof)
{
_res=_q("Curr_Symbol");
}
return _res;
}
function getTerr(val)
{
var _res=val;;
var _s="select * from Territories where Terr_TerritoryID="+val;
var _q=CRM.CreateQueryObj(_s);
_q.SelectSQL();
if (!_q.eof)
{
_res=_q("Terr_Caption");
}
return _res;
}
function fixupJSON(val)
{
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace('"','"');
val=val.replace(/\n/g,' ');
val=val.replace(/\\/g,' ');
return val;
}
%><file_sep>/src/ctItemPicker/js/custommodal.js
/*
to implement this make a copy of the function below (dont use the same method name though) and add in a custom button (using crm's client api or buttongroups and call the method filling the model with what you want displayed.
From a buttongroup your would call this like this
javascript:custommodalmethod();
*/
var customModalCloseEvent=null;
function custommodalmethod()
{
console.log("custommodalitems");
var custommodal = document.getElementById('customModal');
//your code here......
//show the modal
custommodal.style.display = "block";
}
$(document).ready(function () {
console.log("custommodal.js loading...");
var _url = new String(document.location.href);
_url = _url.toLowerCase();
var _installName = crm.installName();
if (_installName == "interactivedashboard") {
return;
}
//366=meeting planner
if (_url.indexOf("=366&") > 0) {
return;
}
var _csspath = "../js/custom/custommodal.css";
if (_url.indexOf("custompages") > 0)//for custom asp pages
{
_csspath = "/" + crm.installName() + "/js/custom/custommodal.css";
}
console.log(_csspath);
$('head').append('<link rel="stylesheet" type="text/css" href="' + _csspath + '" >');
var modal_text='<div id="customModal" class="custommodal">'+
'<!-- Modal content -->'+
' <div class="custommodal-content">'+
' <div id="custommodalheaderid" class="custommodal-header">'+
' <span class="customclose">×</span>'+
' <h2>custommodal-header</h2>'+
' </div>'+
' <div class="custommodal-body">'+
' <p>Some text in the Modal Body</p>'+
' <p>Some other text...</p>'+
' </div>'+
' <div id="custommodalfooterid" class="custommodal-footer">'+
' <h3>custommodal-footer</h3>'+
' </div>'+
' </div>'+
'</div>';
$('body').append(modal_text);
var custommodal = document.getElementById('customModal');
var span = document.getElementsByClassName("customclose")[0];
span.onclick = function() {
custommodal.style.display = "none";
window.onclick = function(event) {
var custommodal = document.getElementById('customModal');
if (event.target == custommodal) {
var custommodal = document.getElementById('customModal');
custommodal.style.display = "none";
}
}
if (customModalCloseEvent!=null)
{
customModalCloseEvent();
}
console.log("custommodal.js unloaded");
}
});
function setcustommodalheader(val)
{
$('#custommodalheaderid h2').text(val);
}
function setcustommodalfooter(val)
{
$('#custommodalfooterid h3').text(val);
}<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/custom_sysparams_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="select parm_name, parm_value from Custom_SysParams "+
"where parm_name in "+ "('QuoteFormat','QuoteExpirations','OrderFormat','PricingCIDList','UsePricingLists','UseUOMs','OrderLevelDiscounts');";
_obj.columns=new Array();
_obj.title="Custom_SysParams";
_obj.columns.push('parm_name');
_obj.columns.push('parm_value');
objar.push(_obj);
var _content=createJSON(objar,CRM);
%>
<script>
var _Custom_SysParams=<%=_content%>
</script><file_sep>/README.md
# Rapid-Item-Picker
Modal Screen on Quotes that allows you quickly add/update and remove quote items
This is designed to make creating quotes easier and quicker from Sage CRM.
Files are installed on the following folders:
wwwroot/js/custom
and
wwwroot/custompages/ctItemPicker
A button group is created on Quotes Summary an a button added here also (after installing the component you need to reload metadata to see the button or restart IIS or recycle the CRM application pool).
Screen shot
<img src="https://github.com/crmtogether/Rapid-Item-Picker/blob/master/RapidItemPicker.png" />
The component ZIP file is available from
https://github.com/crmtogether/Rapid-Item-Picker/tree/master/src
===========================================================================
Sample SQL code used to mass populate the NewProduct table for testing ONLY
----SQL start
Declare @Id int
Set @Id = 1
While @Id <= 1000
Begin
INSERT INTO NewProduct(
prod_Active,prod_UOMCategory,prod_name,prod_code,prod_productfamilyid)
VALUES (
'Y',6002,'testb-' + CAST(@Id as nvarchar(10)),'cb' + CAST(@Id as nvarchar(10)),4)
Print @Id
Set @Id = @Id + 1
End
----SQL end
===========================================================================
Example SQL for Product Families displayed..note you must change the quot_orderquoteid value to your value
----SQL start
SELECT TOP 51 prfa_productfamilyid, prfa_name FROM ProductFamily
WHERE (prfa_name LIKE N'%' ESCAPE '|' OR COALESCE(prfa_name, N'') = N'')
and prfa_Deleted is Null and prfa_active = N'Y'AND
prfa_productfamilyid IN (select prod_productfamilyid from newproduct where prod_productid
in(select pric_productid from pricing WHERE pric_deleted IS NULL AND pric_pricinglistid
=(select quot_pricinglistid from quotes where quot_orderquoteid = 11 and pricing.pric_price_cid = quotes.quot_currency)))
order by prfa_name
----SQL end
===========================================================================
How product matching works!
How the matching works is that it checks if the string exists in the product name. At any point. That’s it. So its always a LIKE and you don’t need to put in the % or *.
<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/currency_inc.asp
<%
var objar=new Array();//this stores our data objects
var _obj=new Object();
_obj.sql="select "+
"Curr_CurrencyID,Curr_Symbol,Curr_DecimalPrecision,Curr_Rate "+
"from Currency "+
"where Curr_CurrencyID="+Quot_currency+" and Curr_Deleted is null";
_obj.columns=new Array();
_obj.title="Currency";
_obj.columns.push('Curr_CurrencyID');
_obj.columns.push('Curr_Symbol');
_obj.columns.push('Curr_DecimalPrecision');
_obj.columns.push('Curr_Rate');
objar.push(_obj);
var _content=createJSON(objar,CRM);
%>
<script>
var _currency=<%=_content%>
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/quote_inc.asp
<%
var objar=new Array();//this stores our data objects
var quoteid=CRM.GetContextInfo("quotes","quot_orderquoteid");
var Quot_currency=CRM.GetContextInfo("quotes","Quot_currency");
var json_note="";
if (!quoteid)
{
quoteid="514";
}
var _obj=new Object();
_obj.sql="select Quot_OrderQuoteID,Quot_currency,Quot_PricingListID,Quot_associatedid,"+
"Quot_discountamt,Quot_grossamt,Quot_lineitemdisc,Quot_nettamt "+
"from Quotes "+
"where Quot_OrderQuoteID="+quoteid;
_obj.columns=new Array();
_obj.title="Quote";
_obj.columns.push('Quot_OrderQuoteID');
_obj.columns.push('Quot_currency');
_obj.columns.push('Quot_PricingListID');
_obj.columns.push('Quot_associatedid');
_obj.columns.push('Quot_discountamt');
_obj.columns.push('Quot_grossamt');
_obj.columns.push('Quot_lineitemdisc');
_obj.columns.push('Quot_nettamt');
objar.push(_obj);
if (!OutputAsJSON){
var _content=createJSON(objar,CRM);
%>
<script>
var _quote=<%=_content%>
</script>
<% } %><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/content.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_engine.js" -->
<!-- #include file ="quote_inc.asp" -->
<!-- #include file ="quoteitems_inc.asp" -->
<!-- #include file ="currency_inc.asp" -->
<!-- #include file ="product_family_inc.asp" -->
<!-- #include file ="product_inc.asp" -->
<!-- #include file ="uom_inc.asp" -->
<!-- #include file ="uom_byfam_inc.asp" -->
<!-- #include file ="uom_family_inc.asp" -->
<!-- #include file ="custom_sysparams_inc.asp" -->
<!-- #include file ="pricinglist_inc.asp" -->
<!-- #include file ="pricing_inc.asp" -->
<%
var OutputAsJSON=false;//only used in quoteitems_inc
%>
<style>
.column {
float: left;
width: 25%;
}
.columnMain {
float: left;
width: 75%;
}
.columnFull {
float: left;
width: 100%;
}
.columnSpacer {
float: left;
width: 100%;
height: 5px;
background-color: #34b233;
}
.moneyRight
{
float: right;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
#quoteitemsTable{
height: 300px;
overflow:auto;
max-height: 300px;
}
#quoteitems_gentable
{
table-layout:fixed;
width:100%;
}
.customGridHead{
white-space: nowrap !important;
width: 100px;
overflow: hidden;
}
#productTable{
height: 300px;
overflow: scroll;
}
.familyDisplay{
padding-left: 50px;
}
.FAMCELL{
cursor:pointer;
}
.updateButtonHide{
visibility:hidden;
}
#productfamilyTable{
height: 300px;
overflow: scroll;
}
</style>
<div class="row">
<div class="column">
<span id="_Captproductfamily" class="VIEWBOXCAPTION">Product Family:</span><br><span id="_Dataproductfamily" class="VIEWBOX"><input type="text" class="EDIT" id="productfamily" name="productfamily" value="" maxlength="20" size="20" onkeyup="productfamily_change(this)" ></span>
<div id="productfamilyTable">
</div>
</div>
<div class="columnMain">
<table>
<tr>
<td>
<span id="_Captproduct" class="VIEWBOXCAPTION">Product:</span><br><span id="_Dataproduct" class="VIEWBOX"><input type="text" class="EDIT" id="product" name="product" value="" maxlength="20" size="20" onkeyup="product_change(this)" ></span><button id="btnproductfilter" onclick="product_change(this)" >Go</button>
</td>
<td>
<span id="_CaptproductMarkup" class="VIEWBOXCAPTION">Markup:</span><br><span id="_DataproductMargin" class="VIEWBOX">
<input type="text" class="EDIT" id="productMarkup" name="productMarkup" value="" maxlength="20" size="20"></span>
<button id="btnproductMarkup" onclick="product_applyMarkup()" >Apply</button>
</td>
<td>
<span id="familyDisplay" class="VIEWBOXCAPTION familyDisplay">loading...</span>
</td>
<td>
<span id="edits_clear" style="float:right" >
<button onclick="edits_clear_click(this)" >Clear</button>
</span>
<span id="edits_use_cache" style="float:right" >
<input type="checkbox" id="usecache" name="usecache" checked />Use Local Cache
</span>
</td>
</tr>
</table>
<div id="productTable">
</div>
</div>
</div>
<div class="row">
<div class="columnSpacer">
</div>
</div>
<div class="row">
<div class="columnFull">
<div id="quoteitemsTable">
</div>
</div>
</div>
<script>
var productCostField = '<%=productCostField%>';
var G_SelectedProductFamily=-1;
var _quoteitem_template='{'+
'"QuIt_orderquoteid":"'+_quote.Quote[0]["Quot_OrderQuoteID"]+'",'+
'"QuIt_LineItemID":"-1",'+
'"QuIt_linenumber":"",'+
'"QuIt_UOMID":"",'+
'"QuIt_productid":"",'+
'"QuIt_productfamilyid":"",'+
'"QuIt_quantity":"",'+
'"Prod_ProductID":"",'+
'"QuIt_discount":"",'+
'"QuIt_quotedprice":"",'+
'"QuIt_quotedpricetotal":"",'+
'"QuIt_LineType":"i",'+
'"QuIt_taxrate":"",'+
'"QuIt_listprice":"",'+
'"QuIt_description":"",'+
'"prod_name":""}';
function getQITemplate()
{
return JSON.parse(_quoteitem_template);
}
function edits_clear_click(sender)
{
$('#productfamily').val('');
$('#product').val('');
$('#producttableobj tbody').empty();
popupdateProductTable(G_SelectedProductFamily);
}
function productfamily_change(sender)
{
createProductFamilyTable(sender.value);
}
function product_change(sender)
{
console.log('product_change');
if ((event.keyCode === 13) || (sender.id=='btnproductfilter')) {
popupdateProductTable(G_SelectedProductFamily, $('#product').val());
}
}
var updateLineItemsMarkup = [];
function product_applyMarkup() {
updateLineItemsMarkup = [];
var markupInput = $("#productMarkup");
var markup = parseFloat(markupInput.val());
if (isNaN(markup)) {
alert("Not a number");
markupInput.focus();
return;
}
if (markup > 100) {
alert("Should not be greater than 100");
markupInput.focus();
return;
}
if (productCostField != '') {
console.log(productCostField);
var lpArr = $("td[rel='prodCost']");
console.log(lpArr);
$.each(lpArr, function(i, el) {
var pId = $(el).attr("pId");
console.log(pId);
var prodCost = parseFloat($(el).attr("data"));
console.log(prodCost);
var newPrice = prodCost + (prodCost * markup)/100;
console.log(newPrice);
$("#quit_quotedprice__line_item_" + pId).val(newPrice);
__onchangeQuoteItem(document.getElementById('quit_uomid__line_item_' + pId), pId);
updateLineItemsMarkup.push(pId);
});
} else {
//when using list price for markup caluclations
var lpArr = $("span[rel='listPrice']");
$.each(lpArr, function(i, el) {
var pId = $(el).attr("pId");
console.log(pId);
var listPrice = parseFloat($(el).attr("data"));
//console.log(listPrice);
var newPrice = listPrice + (listPrice * markup)/100;
//console.log(newPrice);
$("#quit_quotedprice__line_item_" + pId).val(newPrice);
__onchangeQuoteItem(document.getElementById('quit_uomid__line_item_' + pId), pId);
updateLineItemsMarkup.push(pId);
});
}
$("#btn_markupUpdateAll").show();
}
/*
updates all line items with the calculated price sum after markup has been applied
*/
function markupUpdateAll() {
if (updateLineItemsMarkup.length >0) {
for (var i=0; i< updateLineItemsMarkup.length;i++) {
_update_quoteitem(null,updateLineItemsMarkup[i]);
}
$("#btn_markupUpdateAll").hide();
}
}
function createProductFamilyTable(filter)
{
$('#productfamilyTable').empty();
var data=_productFamily.ProductFamily;
var html = '<table class="CONTENTGRID" id="ProductFamilyTable" width="100%">';
html += '<tr>';
html += '<th class="GRIDHEAD">Product Family</th>';
html += '</tr>';
var _row="ROW1";
console.log("createProductFamilyTable **** PRELOOP :"+data.length);
for (var i = 0; i < data.length; i++){
var obj = data[i];
if ((!filter)|| ((obj["prfa_name"]).toLowerCase().indexOf(filter.toLowerCase())>=0))
{
html += '<tr><td class="'+_row+' FAMCELL" id="prfa_productfamilyid_'+obj["prfa_productfamilyid"]+'" onclick="_product_family_click(this,\''+obj["prfa_productfamilyid"]+'\');" >';
html += obj["prfa_name"];
html += '</td></tr>';
if (_row=="ROW1")
{
_row="ROW2";
}else{
_row="ROW1";
}
}
}
html += '</table>';
document.getElementById("productfamilyTable").insertAdjacentHTML( 'beforeend', html );
getProductFamilyTitle(data[0]["prfa_productfamilyid"]);
}
function getProductFamilyTitle(id)
{
$('#familyDisplay').empty();
var data=_productFamily.ProductFamily;
console.log("getProductFamilyTitle **** PRELOOP :"+data.length);
for (var i = 0; i < data.length; i++){
var obj = data[i];
if(obj["prfa_productfamilyid"]==id)
{
document.getElementById("familyDisplay").insertAdjacentHTML( 'beforeend', obj["prfa_name"] );
break;
}
}
}
//family is the product family
function createProductTable(family, filter)
{
$('#productTable').empty();
var data=_products.Products;
var html = '<table class="CONTENTGRID" width="100%">';
html += '<tr>';
html += '<th class="GRIDHEAD">Products</th>';
html += '<th class="GRIDHEAD">Code</th>';
html += '<th class="GRIDHEAD">UOM</th>';
html += '<th class="GRIDHEAD">Quantity</th>';
html += '<th class="GRIDHEAD">List Price</th>';
html += '<th class="GRIDHEAD">Quoted Price</th>';
html += '<th class="GRIDHEAD">Selected</th>';
html += '</tr>';
var _row="ROW1";
console.log("createProductTable **** PRELOOP :"+data.length);
for (var i = 0; i < data.length; i++){
var obj = data[i];
if (family==obj["prod_productfamilyid"])
{
if ((!filter)||(obj["prod_name"].toLowerCase().indexOf(filter.toLowerCase())>=0)
||(obj["prod_code"].toLowerCase().indexOf(filter.toLowerCase())>=0))
{
if (obj["prod_Active"].toLowerCase()=='y')
{
html += '<tr>';
//product
html += '<td class="'+_row+'" id="'+obj["prod_productid"]+'" >';
html += obj["prod_name"];
html += '</td>';
//productcode
html += '<td class="'+_row+'" id="prod_code_'+obj["prod_productid"]+'" >';
html += obj["prod_code"];
html += '</td>';
//product cost
if (productCostField != '') {
html += '<td class="'+_row+'" id="'+productCostField+'_'+obj["prod_productid"]+'" >';
html += obj[productCostField];
html += '</td>';
}
//uom
html += '<td class="'+_row+'">';
var obj = data[i];
html += getUOMSelect(obj);
html += '</td>';
//quantity
html += '<td class="'+_row+'">';
var obj = data[i];
html += getQuantity(obj);
html += '</td>';
//list price
html += '<td class="'+_row+'" id="td_quit_listprice_'+obj["prod_productid"]+'" >';
html += getListPrice(obj);
html += '</td>';
//quoted price
html += '<td class="'+_row+'" id="td_quit_quotedprice_'+obj["prod_productid"]+'" >';
html += getQuotedPrice(obj);
html += '</td>';
//selected
html += '<td class="'+_row+'">';
var obj = data[i];
html += '<button class="EDIT" style="float: right;" id="prod_productid_selected_'+obj["prod_productid"]+'" name="prod_productid_selected_'+obj["prod_productid"]+'" onclick="_add_quoteitem(this,'+obj["prod_productid"]+')" >Add</button>';
html += '</td>';
html += '</tr>';
if (_row=="ROW1")
{
_row="ROW2";
}else{
_row="ROW1";
}
}
}
}
}
html += '</table>';
document.getElementById("productTable").insertAdjacentHTML( 'beforeend', html );
}
//family is the product family
async function popupdateProductTable(family, filter)
{
console.log('popupdateProductTable:'+family);
$('#producttableobj tbody').empty();
var _prod=window['products_prfa_productfamilyid_'+family].Products;
if ((filter=="")||(filter+""=="undefined"))
{
//clever...have we stored the html?...only use when no filter
var _prodhtml=window['html_products_prfa_productfamilyid_'+family];
if (_prodhtml==null)
{
if (useLocalCache())
{
console.log('popupdateProductTable: localStorage fetch');
window['html_products_prfa_productfamilyid_'+family]=localStorage.getItem("html_products_prfa_productfamilyid_"+family);
_prodhtml=window['html_products_prfa_productfamilyid_'+family];
}
}
if (_prodhtml!=null)
{
$("#producttableobj tbody").append(window['html_products_prfa_productfamilyid_'+family]);
console.log('popupdateProductTable FROM HTML CACHE');
return;
}
}
var data=Object.values(_prod);
var _row="ROW1";
var html="";
console.log("popupdateProductTable **** PRELOOP :"+data.length);
if (filter+""== "undefined") filter = ""; //costi 8 sept fix for when filter is undefined
filter = filter.replace(/"/g, '"');
for (var i = 0; i < data.length; i++){
var obj = data[i];
console.log("popupdateProductTable search :"+filter+"="+obj["prod_name"].toLowerCase());
if ((!filter)||(obj["prod_name"].toLowerCase().indexOf(filter.toLowerCase())>=0)
||(obj["prod_code"].toLowerCase().indexOf(filter.toLowerCase())>=0))
{
html += '<tr>';
//product
html += '<td class="'+_row+'" id="'+obj["prod_productid"]+'" >';
html += obj["prod_name"];
html += '</td>';
//productcode
html += '<td class="'+_row+'" id="prod_code_'+obj["prod_productid"]+'" >';
html += obj["prod_code"];
html += '</td>';
//product cost
if (productCostField != '') {
html += '<td class="'+_row+'" id="'+productCostField+'_'+obj["prod_productid"]+'" >';
html += obj[productCostField];
html += '</td>';
}
//uom
html += '<td class="'+_row+'">';
var obj = data[i];
html += getUOMSelect(obj);
html += '</td>';
//quantity
html += '<td class="'+_row+'">';
var obj = data[i];
html += getQuantity(obj);
html += '</td>';
//list price
html += '<td class="'+_row+'" id="td_quit_listprice_'+obj["prod_productid"]+'" >';
html += getListPrice(obj);
html += '</td>';
//quoted price
html += '<td class="'+_row+'" id="td_quit_quotedprice_'+obj["prod_productid"]+'" >';
html += getQuotedPrice(obj);
html += '</td>';
//selected
html += '<td class="'+_row+'">';
var obj = data[i];
html += '<button class="EDIT" style="float: right;" id="prod_productid_selected_'+obj["prod_productid"]+'" name="prod_productid_selected_'+obj["prod_productid"]+'" onclick="_add_quoteitem(this,'+obj["prod_productid"]+')" >Add</button>';
html += '</td>';
html += '</tr>';
if (_row=="ROW1")
{
_row="ROW2";
}else{
_row="ROW1";
}
}
}
if ((filter=="")||(filter+""=="undefined"))
{
window['html_products_prfa_productfamilyid_'+family]=html;
if (useLocalCache())
{
localStorage.setItem("html_products_prfa_productfamilyid_"+family, html);
}
}
$("#producttableobj tbody").append(html);
}
//family is the product family
function createProductTableNEW()
{
var html = '<table id="producttableobj" class="CONTENTGRID" width="100%"><thead>';
html += '<tr id="producttableheaderrowobj" >';
html += '<th class="GRIDHEAD">Products</th>';
html += '<th class="GRIDHEAD">Code</th>';
if (productCostField!= '') {
html += '<th class="GRIDHEAD">Cost</th>';
}
html += '<th class="GRIDHEAD">UOM</th>';
html += '<th class="GRIDHEAD">Quantity</th>';
html += '<th class="GRIDHEAD">List Price</th>';
html += '<th class="GRIDHEAD">Quoted Price</th>';
html += '<th class="GRIDHEAD">Selected</th>';
html += '</tr></thead>';
html += '<tbody></tbody><table>';
document.getElementById("productTable").insertAdjacentHTML( 'beforeend', html );
}
function getUOMSelect(productobj, defaultUOM, quoteitemobj)
{
console.log("getUOMSelect productobj:"+JSON.stringify(productobj));
console.log("getUOMSelect defaultUOM:"+defaultUOM);
var uomobj=null;
if (defaultUOM)
{
uomobj=getUOM_UOMObj2(defaultUOM);
console.log("getUOMSelect uomobj:"+JSON.stringify(uomobj));
}
var _id=productobj["prod_productid"];
var _selectname=_id;
var _productid=productobj["prod_productid"];
var qilist="false";
if (quoteitemobj)
{
_id=quoteitemobj["QuIt_LineItemID"];
_selectname="_line_item_"+_id;
_productid=quoteitemobj["QuIt_productid"];
qilist="true";
}
console.log("getUOMSelect getQuantity _id:"+_id);
var pricingdata=_Pricing.Pricing[_productid];
console.log("getUOMSelect pricingdata:"+JSON.stringify(pricingdata));
var html = '';
if (pricingdata!=null)
{
html = '<select class="EDIT" style="float: right;" size="1" name="quit_uomid_'+_selectname+'" id="quit_uomid_'+_selectname+'" onchange="UOMDisplayPricesCustom(this,'+_productid+','+qilist+','+_id+');">';
console.log("getUOMSelect **** PRELOOP :"+pricingdata.length);
for (var i = 0; i < pricingdata.length; i++){
var obj=_uom.UOM[pricingdata[i]["pric_UOMID"]];
var selected="";
html += '<option value="'+obj["UOM_UOMID"]+'"'+selected+' >'+obj["uom_name"]+'</option>';
}
html += '</select>';
}else{
html = '';
}
return html;
}
function getUOMText(quoteobj)
{
if (_uom.UOM[quoteobj["QuIt_UOMID"]]!=null)
{
return _uom.UOM[quoteobj["QuIt_UOMID"]];
}
return '';
}
//qilist is the quote item list
// qiid quote item id
function UOMDisplayPricesCustom(sender, productid,qilist, qiid)
{
console.log("UOMDisplayPricesCustom uom="+sender.value+":productid:"+productid);
//update list price
var productobj=getProductObj(productid);
if (!qilist)
{
$('#quit_listprice_'+productid).text(getListPriceval(productobj, sender.value));
$('#quit_quotedprice_'+productid).val(getListPriceval(productobj, sender.value));
}else{
var _lval=getListPriceval(productobj, sender.value);
if (!isNaN(_lval))
{
_lval=0;
}
$('#quit_quotedprice__line_item_'+ qiid).val(_lval);
__onchangeQuoteItem(sender,qiid,productobj);
}
}
function anyItembeingEdited(){
var res=false;
var table = document.getElementById("quoteitems_gentable");
for (var i = 1, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
col = row.cells[0];
console.log(col.style.backgroundColor);
if (col.style.backgroundColor=="khaki"){
res=true;
break;
}
}
return res;
}
function flagQIChange(qiid)
{
itemBeingEdited=true;
document.getElementById("QuIt_LineItemID_"+qiid).style="background-color: khaki";
$('#QuIt_orderquoteid_update_'+qiid).removeClass("updateButtonHide");
}
function unflagQIChange(qiid)
{
document.getElementById("QuIt_LineItemID_"+qiid).style="";
$('#QuIt_orderquoteid_update_'+qiid).addClass("updateButtonHide");
}
//sender=
//qiid=
//
function __onchangeQuoteItem(sender, qiid)
{
setcustommodalfooter("Commit all changes to see an updated price");
var _qty=$('#quit_quantity__line_item_'+ qiid).val();
var _qprice=$('#quit_quotedprice__line_item_'+ qiid).val();
$('#QuIt_quotedpricetotal_'+ qiid).html(_formatMoney(_qprice*_qty));
var _lp=0;
//remove?
// if (sender!=null)
// _lp=getListPriceval(productobj, sender.value);
// $('#QuIt_listprice_'+ qiid).text(_lp);
// QuIt_discount_1294
$('#QuIt_discount_'+ qiid).html(_formatMoney(_lp-_qprice));
flagQIChange(qiid);
}
function __onchangeQuoteItemOLD(sender, qiid,productobj)
{
setcustommodalfooter("Commit all changes to see an updated price");
var _qty=$('#quit_quantity__line_item_'+ qiid).val();
var _qprice=$('#quit_quotedprice__line_item_'+ qiid).val();
$('#QuIt_quotedpricetotal_'+ qiid).html(_formatMoney(_qprice*_qty));
var _lp=0;
if (sender!=null)
_lp=getListPriceval(productobj, sender.value);
$('#QuIt_listprice_'+ qiid).text(_lp);
// QuIt_discount_1294
$('#QuIt_discount_'+ qiid).html(_formatMoney(_lp-_qprice));
flagQIChange(qiid);
}
function getListPrice(productobj,uomval){
console.log("getListPrice:"+productobj["prod_productid"]);
var html = '<span id="quit_listprice_'+productobj["prod_productid"]+'" class="VIEWBOX">';
html += _formatMoney(getListPriceval(productobj,uomval));
html += '</span>';
return html;
}
function getListPriceval(productobj,uomval){
console.log("getListPriceval productobj:"+JSON.stringify(productobj));
console.log("getListPriceval uomval:"+uomval);
var val = '0';
var data=_Pricing.Pricing[productobj["prod_productid"]];
if (data!=null)
{
console.log("getListPriceval **** PRELOOP :"+data.length);
for (var i = 0; i < data.length; i++){
var obj = data[i];
var uomobj = null;
if (!uomval){
console.log("getListPriceval prod_UOMCategory:"+productobj["prod_UOMCategory"]);
uomobj=getUOM_UOMObj(productobj["prod_UOMCategory"]);
}else{
console.log("getListPriceval X prod_UOMCategory:"+productobj["prod_UOMCategory"]);
uomobj=getUOM_UOMObj2(uomval);
}
console.log("getListPriceval productobj uomobj!!:"+JSON.stringify(uomobj));
if ((obj["pric_UOMID"]==uomobj["UOM_UOMID"]) && (productobj["prod_productid"]==obj["pric_ProductID"]))
{
console.log("getListPriceval got object:"+JSON.stringify(obj));
val = obj["pric_price"];
console.log("getListPriceval got object val:"+val);
}
}
console.log("getListPriceval final val:"+val);
return val;
}
return 0;
}
function getProductObj(prod_productid)
{
console.log("getProductObj:"+prod_productid);
var _prod=window['products_prfa_productfamilyid_'+G_SelectedProductFamily].Products;
if (_prod[prod_productid]!=null)
{
return _prod[prod_productid];
}
console.log("getProductObj: no product found");
//create a dummy empty object
return {"prod_Active": "Y","prod_UOMCategory": "-1","prod_code": "","prod_name": "","prod_productfamilyid": "-1","prod_productid": "-1"}
// return null;
}
function getUOM_UOMObj(uomfamilyid)
{
console.log("getUOM_UOMObj:"+uomfamilyid);
var data=_uom.UOM;
if (_uombyfam.UOMbyFam[uomfamilyid]!=null){
return _uom.UOM[_uombyfam.UOMbyFam[uomfamilyid][0]["UOM_UOMID"]];
}
return {"UOM_UOMID": "-1","uom_Active": "Y","uom_defaultvalue": "Y","uom_description": "","uom_familyID": "-1","uom_name": "Default","uom_units": "-1"};
}
function getUOM_UOMObj2(uomid)
{
console.log("getUOM_UOMObj2:"+uomid);
if (_uom.UOM[uomid]!=null)
{
return _uom.UOM[uomid];
}
return {"UOM_UOMID": "-1","uom_Active": "Y","uom_defaultvalue": "Y","uom_description": "","uom_familyID": "-1","uom_name": "Default","uom_units": "-1"};
}
function getQuantity(productobj, defaultvalue){
console.log("getQuantity:"+JSON.stringify(productobj));
console.log("getQuantity defaultvalue:"+defaultvalue);
var _id=productobj["prod_productid"];
var _onchange="";
if (!_id)
{
_id="_line_item_"+productobj["QuIt_LineItemID"];
_onchange="__onchangeQuoteItem(document.getElementById('quit_uomid__line_item_"+productobj["QuIt_LineItemID"]+"'), "+productobj["QuIt_LineItemID"]+");";
}
console.log("getQuantity _id:"+_id);
var _val='1';
if (defaultvalue)
{
_val=defaultvalue;
}
return '<input type="number" class="EDIT" style="float: right;width:5em;text-align: right;" id="quit_quantity_'+_id+'" name="quit_quantity_'+_id+'" onchange="'+_onchange+'" value="'+_val+'" '+
' onchange="quit_quantity_change(this,'+_id+')" maxlength="10" size="5">';
}
function quit_quantity_change(sender, productid){
var qty=new Number($('#quit_quantity_'+productid).val());
}
function getQuotedPrice(productobj,defaultvalue, quoteitemobj){
if (productobj!=null)
console.log("getQuotedPrice product:"+JSON.stringify(productobj));
console.log("getQuotedPrice defaultvalue:"+defaultvalue);
var qval="";
var _onchange="";
var _id="";
if (quoteitemobj)
{
_id="_line_item_"+quoteitemobj["QuIt_LineItemID"];
_onchange="__onchangeQuoteItem(document.getElementById('quit_uomid__line_item_"+quoteitemobj["QuIt_LineItemID"]+"'), "+quoteitemobj["QuIt_LineItemID"]+");";
}else{
_id=productobj["prod_productid"];
qval=getListPriceval(productobj);
}
console.log("getQuotedPrice getQuantity _id:"+_id);
if (defaultvalue)
{
qval=defaultvalue;
}
qval=+qval;
qval=qval.toFixed(2);
return '<input rel="quotedPrice" type="text" class="EDIT" style="float: right;text-align: right;" id="quit_quotedprice_'+_id+'" name="quit_quotedprice_'+_id+'" onchange="'+_onchange+'" value="'+qval+'" maxlength="10" size="5">';
}
function _product_family_click(sender, productfamilyid)
{
//clear the filter
$('#product').val('');
//remove style from all
var data=_productFamily.ProductFamily;
console.log("_product_family_click **** PRELOOP :"+data.length);
for (var i = 0; i < data.length; i++){
var elm=document.getElementById("prfa_productfamilyid_"+data[i]["prfa_productfamilyid"]);
if (elm!=null)
{
elm.style="";
}
}
console.log('_product_family_click:'+productfamilyid);
getProductFamilyTitle(productfamilyid);
//add in style
sender.style="text-decoration: underline;";
G_SelectedProductFamily=productfamilyid;
//does the data for this family exist on the client
$('#producttableobj tbody').empty();
if (useLocalCache())
{
if ((window["products_prfa_productfamilyid_"+productfamilyid]==null) &&
(localStorage.getItem("products_prfa_productfamilyid_"+productfamilyid)!=null))
{
window["products_prfa_productfamilyid_"+productfamilyid]=JSON.parse(localStorage.getItem("products_prfa_productfamilyid_"+productfamilyid));
}
}
if ((window["products_prfa_productfamilyid_"+productfamilyid]==null)||(window["products_prfa_productfamilyid_"+productfamilyid]+""=="undefined"))
{
getProductsExtraRec(productfamilyid,false);
}else{
popupdateProductTable(productfamilyid, false);
}
}
async function getProductsExtraRec(family,filter) {
var requestCount=1;
console.log("getProductsExtraRec:"+requestCount);
var url=crm.url('ctItemPicker/product_inc_ajax.asp');
url+="&prfa_productfamilyid="+family+"&pageCount="+requestCount;
const response = await fetch(url);
var _res=await (response.json());
//draw
window["products_prfa_productfamilyid_"+family]=_res;
if (useLocalCache())
{
localStorage.setItem("products_prfa_productfamilyid_"+family, JSON.stringify(_res));
}
popupdateProductTable(family, false);
}
function getAddData(obj)
{
var res="";
for (var key in obj) {
if (res!="")
{
res+="&";
}
if (obj.hasOwnProperty(key)) {
console.log(key + " -> " + obj[key]);
var _val=encodeURIComponent(obj[key]);
res+=key+"="+_val;
}
}
return res;
}
function buildQI(newQI, id)
{
console.log('buildQI');
//get the product data
var product=getProductObj(id);
newQI.QuIt_productid =product.prod_productid;
newQI.QuIt_productfamilyid =product.prod_productfamilyid;
newQI.QuIt_description =customEscape(product.prod_name);
newQI.Prod_ProductID=product.prod_productid;
newQI.prod_name=customEscape(product.prod_name);
//get the inputs data
var QuIt_UOMID=getfieldval("quit_uomid",id);
newQI.QuIt_UOMID =QuIt_UOMID;
newQI.QuIt_listprice=getListPriceval(product, QuIt_UOMID);
newQI.QuIt_quotedprice=getfieldval("quit_quotedprice",id);
newQI.QuIt_quantity=getfieldval("quit_quantity",id);
//reset the inputs?
return newQI;
}
function getfieldval(fieldName, id)
{
return $('#'+fieldName+'_'+id).val();
}
function _add_quoteitem(sender, id)
{
console.log('_add_quoteitem:'+id);
var newQI=getQITemplate();
newQI=buildQI(newQI, id);
//send request to add the item
var _url=crm.url('../custompages/ctitempicker/addQuoteItem.asp');
console.log("_url:"+_url);
$.ajax(
{
method: "POST",
url: _url,
cache: false,
data: getAddData(newQI),
success: function( data ) {
_quoteitems=data;
createQuoteItemsTable();
},
error: function( error )
{
alert( error );
}
});
}
function getCurrency(){
return _currency.Currency[0]["Curr_Symbol"];
}
//family is the product family
function createQuoteItemsTable()
{
console.log('createQuoteItemsTable');
$('#quoteitemsTable').empty();
var data=_quoteitems.QuoteItems;
var html = '<table class="CONTENTGRID" id="quoteitems_gentable" width="100%" >';
html += '<tr>';
html += '<th class="GRIDHEAD customGridHead" style="width: 30px;" >Line #</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 140px;max-width: 160px;" >Product Name</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 70px;max-width: 80px;" >Code</th>';
if (productCostField!= '') {
html += '<th class="GRIDHEAD customGridHead" style="width: 70px;max-width: 80px;" >Cost</th>';
}
html += '<th class="GRIDHEAD customGridHead" style="width: 70px;max-width: 80px;" >UOM</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 70px;" >Quantity</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 60px;">List Price ('+getCurrency()+')</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 85px;">Quoted Price ('+getCurrency()+')</th>';
//removed 15 may 2019 on request
//html += '<th class="GRIDHEAD customGridHead" style="width: 100px;">Line Item Discount ('+getCurrency()+')</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 100px;">Quoted Price Sum ('+getCurrency()+')</th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 60px;" > </th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 60px;" ><button style="display:none" id="btn_markupUpdateAll" onclick="markupUpdateAll()">Update All</button></th>';
html += '<th class="GRIDHEAD customGridHead" style="width: 20px;" > </th>';
html += '</tr>';
var _row="ROW1";
var canEditItem=true;
data=Object.values(data);
console.log("createQuoteItemsTable **** PRELOOP :"+data.length);
for (var i = 0; i < data.length; i++){
var obj = data[i];
html += '<tr>';
//QuIt_linenumber
html += '<td class="'+_row+'" id="QuIt_LineItemID_'+obj["QuIt_LineItemID"]+'" >';
html += obj["QuIt_linenumber"];
html += '</td>';
console.log("QuIt_linenumber:"+obj["QuIt_linenumber"]);
//product name
if (obj["QuIt_LineType"]=="c")
{
html += '<td class="'+_row+'" colspan="7" >';
html += obj["QuIt_description"];
}else{
//QuIt_description
html += '<td class="'+_row+'" >';
if (obj["QuIt_LineType"]=="f")
html += obj["QuIt_description"];
else
html += obj["prod_name"];
}
html += '</td>';
//product name
if (obj["QuIt_LineType"]!="c")
{
html += '<td id="prod_code_'+obj["QuIt_LineItemID"]+'" class="'+_row+'">';
//console.log(JSON.stringify(obj));
html += obj["prod_code"];
html += '</td>';
if (productCostField != '') {
//prod_cost
html += '<td rel="prodCost" pId="'+obj["QuIt_LineItemID"]+'" data="'+ obj[productCostField]+'" id="'+ productCostField + '_'+obj["QuIt_LineItemID"]+'" class="'+_row+'">';
html += obj[productCostField];
html += '</td>';
}
//uom
html += '<td class="'+_row+'" ct_QuIt_UOMID="'+obj["QuIt_UOMID"]+'" >';
if (obj["QuIt_LineType"]!="f")
{
if (canEditItem)
{
console.log("getUOMSelect calling...:"+obj["QuIt_LineItemID"]);
html += obj["uom_name"];
console.log("getUOMSelect called");
}else{
html += obj["uom_name"];
}
}
html += '</td>';
//quantity
html += '<td class="'+_row+'">';
if (canEditItem)
{
html += getQuantity(obj, obj["QuIt_quantity"]);
}else{
html += _formatMoney(obj["QuIt_quantity"]);
}
html += '</td>';
//list price
html += '<td class="'+_row+'" >';
if (obj["QuIt_LineType"]!="f")
html += '<span rel="listPrice" pId="'+obj["QuIt_LineItemID"]+'" data="'+ obj["QuIt_listprice"]+'" id="QuIt_listprice_'+obj["QuIt_LineItemID"]+'" >'+ _formatMoney(obj["QuIt_listprice"])+"</span>";
else
html += '<span rel="listPrice" pId="'+obj["QuIt_LineItemID"]+'" data="0" id="QuIt_listprice_'+obj["QuIt_LineItemID"]+'" >'+ _formatMoney(0)+"</span>";
html += '</td>';
//quoted price
html += '<td class="'+_row+' " >';
if (canEditItem)
{
html += getQuotedPrice(null,obj["QuIt_quotedprice"],obj);
}else{
html += _formatMoney(obj["QuIt_quotedprice"]);
}
html += '</td>';
//removed 15 may 2019 on request
//line item discount
//html += '<td class="'+_row+' " >';
//html += '<span id="QuIt_discount_'+obj["QuIt_LineItemID"]+'" >'+_formatMoney(obj["QuIt_discount"])+"</span>";
//html += '</td>';
//quoted sum/total
html += '<td class="'+_row+' " >';
html += '<span id="QuIt_quotedpricetotal_'+obj["QuIt_LineItemID"]+'" >'+_formatMoney(obj["QuIt_quotedpricetotal"])+"</span>";
html += '</td>';
}
//delete
html += '<td class="'+_row+' ">';
var obj = data[i];
html += '<button class="EDIT" id="QuIt_orderquoteid_selected_'+obj["QuIt_LineItemID"]+'" name="QuIt_orderquoteid_selected_'+obj["QuIt_LineItemID"]+'" onclick="_delete_quoteitem(this,'+obj["QuIt_LineItemID"]+')" >Delete</button>';
html += '</td>';
//update
html += '<td class="'+_row+' ">';
var obj = data[i];
html += '<button class="EDIT updateButtonHide" id="QuIt_orderquoteid_update_'+obj["QuIt_LineItemID"]+'" name="QuIt_orderquoteid_selected_'+obj["QuIt_LineItemID"]+'" onclick="_update_quoteitem(this,'+obj["QuIt_LineItemID"]+')" >Update</button>';
html += '</td>';
html += '<td class="'+_row+' ">';
//var __from=new Number(obj["QuIt_linenumber"]);
var __from=new Number((i+1));
var __to_down=new Number(obj["QuIt_linenumber"]);
__to_down++;
var __to_up=new Number(obj["QuIt_linenumber"]);
__to_up--;
if (i > 0)
{
html += '<button class="EDIT updateButtonUp" id="QuIt_orderquoteid_update_'+obj["QuIt_LineItemID"]+'" name="QuIt_orderquoteid_selected_'+obj["QuIt_LineItemID"]+'" onclick="_update_quoteitem_pos(this,'+obj["QuIt_LineItemID"]+','+__from+','+__to_up+')" >↑</button>';
}
if (i < (data.length-1))
{
html += '<button class="EDIT updateButtonDown" id="QuIt_orderquoteid_update_'+obj["QuIt_LineItemID"]+'" name="QuIt_orderquoteid_selected_'+obj["QuIt_LineItemID"]+'" onclick="_update_quoteitem_pos(this,'+obj["QuIt_LineItemID"]+','+__from+','+__to_down+')" >↓</button>';
}
html += '</td>';
html += '</tr>';
if (_row=="ROW1")
{
_row="ROW2";
}else{
_row="ROW1";
}
}
html += '</table>';
document.getElementById("quoteitemsTable").insertAdjacentHTML( 'beforeend', html );
getQuoteTotals();
}
function buildQIFromQI(newQI)
{
console.log("buildQIFromQI:"+JSON.stringify(newQI));
//get the inputs data
var id=newQI["QuIt_LineItemID"];
var QuIt_UOMID=newQI["QuIt_UOMID"];
newQI.QuIt_UOMID =QuIt_UOMID;
newQI.QuIt_listprice=newQI["QuIt_listprice"];
newQI.QuIt_quotedprice=getfieldval("quit_quotedprice__line_item",id);
newQI.QuIt_quantity=getfieldval("quit_quantity__line_item",id);
newQI.prod_name=customEscape(newQI.prod_name);
newQI.QuIt_taxrate=customEscape(newQI.QuIt_taxrate);
console.log("buildQIFromQI NEW:"+JSON.stringify(newQI));
return newQI;
}
function customEscape(val)
{
return encodeURIComponent(val);
}
function _update_quoteitem(sender, id)
{
console.log('_update_quoteitem:'+id);
var newQI=getQuoteItemObj(id);
console.log(JSON.stringify(newQI));
console.log('*******************');
newQI=buildQIFromQI(newQI);
//send request to add the item
var _url=crm.url('../custompages/ctitempicker/updateQuoteItem.asp');
console.log("_url:"+_url);
console.log(JSON.stringify(getAddData(newQI)));
$.ajax(
{
method: "POST",
url: _url,
cache: false,
data: getAddData(newQI),
success: function( data ) {
unflagQIChange(id);
_quoteitems=data;
if (!anyItembeingEdited())
{
createQuoteItemsTable();
}
},
error: function( error )
{
alert( error );
}
});
}
function _update_quoteitem_pos(sender, id,_from, _to)
{
console.log('_update_quoteitem_pos:'+id+' from '+_from+' to '+_to);
//send request to add the item
var _url=crm.url('../custompages/ctitempicker/updateQuoteItempos.asp');
console.log("_url:"+_url);
$.ajax(
{
method: "POST",
url: _url,
cache: false,
data: "QuIt_LineItemId="+id+"&from="+_from+"&to="+_to,
success: function( data ) {
unflagQIChange(id);
_quoteitems=data;
if (!anyItembeingEdited())
{
createQuoteItemsTable();
}
},
error: function( error )
{
alert( error );
}
});
}
function getQuoteItemObj(QuIt_LineItemID)
{
var data=_quoteitems.QuoteItems;
for (var i = 0; i < data.length; i++){
var obj = data[i];
if (QuIt_LineItemID==obj["QuIt_LineItemID"])
{
return obj;
}
}
return null;
}
function getQuoteTotals(){
var _url=crm.url('../custompages/ctitempicker/getQuoteTotals.asp');
_url+=""_orderquoteid="+_quote.Quote[0]["Quot_OrderQuoteID"];
$.ajax(
{
method: "GET",
url: _url,
cache: false,
success: function( data ) {
_quote=data;
var footerdisplay="Gross Amount: "+getCurrency()+" "+_formatMoneyVal(_quote.Quote[0]["Quot_grossamt"]);
footerdisplay+=" - Discount Amount: "+getCurrency()+" "+_formatMoneyVal(_quote.Quote[0]["Quot_discountamt"]);
footerdisplay+=" - Net Amount: "+getCurrency()+" "+_formatMoneyVal(_quote.Quote[0]["Quot_nettamt"]);
setcustommodalfooter(footerdisplay);
},
error: function( error )
{
alert( error );
}
});
}
function _delete_quoteitem(sender,QuIt_LineItemId)
{
console.log('_delete_quoteitem:'+QuIt_LineItemId);
if (window.confirm("Are you sure you want to delete this item?"))
{
console.log("delete quote item:"+QuIt_LineItemId);
//send request to delete the item
var _url=crm.url('../custompages/ctitempicker/deleteQuoteItem.asp');
console.log("_url:"+_url);
$.ajax(
{
method: "POST",
url: _url,
cache: false,
data: "quot_orderquoteid="+_quote.Quote[0]["Quot_OrderQuoteID"]+"&QuIt_LineItemId="+QuIt_LineItemId,success: function( data ) {
_quoteitems=data;
createQuoteItemsTable();
},
error: function( error )
{
alert( error );
}
});
}
}
function _formatMoney(val)
{
val=+val; //convert to number
val=val.toFixed(2);
val=val.toLocaleString();
return '<div class="moneyRight" >'+val+'</div>';
}
function _formatMoneyVal(val)
{
val=+val; //convert to number
val=val.toFixed(2);
val=val.toLocaleString();
return val;
}
function useLocalCacheStore()
{
return (localStorage.getItem("usecache1")=="Y");
}
function useLocalCache()
{
return document.getElementById("usecache").checked;
}
if (_quote.Quote[0]["Quot_associatedid"]==" ")
{
console.log("Rapid Item Picker from CRM Together");
console.log("crmtogether.com Open Source");
//get stored cache setting
document.getElementById("usecache").checked = useLocalCacheStore();
setcustommodalheader("Quote Items");
createProductFamilyTable();
createProductTableNEW();
popupdateProductTable(_productFamily.ProductFamily[0]['prfa_productfamilyid']);
G_SelectedProductFamily=_productFamily.ProductFamily[0]['prfa_productfamilyid'];
createQuoteItemsTable();
document.getElementById("prfa_productfamilyid_"+_productFamily.ProductFamily[0]['prfa_productfamilyid']).style="text-decoration: underline;";
$("#usecache").change(function() {
console.log("usecache clicked");
if(this.checked) {
localStorage.setItem("usecache1","Y");
}else{
localStorage.setItem("usecache1","N");
}
});
}else{
setcustommodalheader("This Quote has been converted and locked");
}
setcustommodalfooter("");
function customModalCloseEventMethod()
{
console.log("customModalCloseEventMethod");
//document.location.reload(); //note : do NOT use reload as when you create a new quote this reposts the screen and you get a second quote.
document.location.href=crm.url(1469);
}
customModalCloseEvent=customModalCloseEventMethod;
</script>
<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/pricing_inc.asp
<%
var objar=new Array();//this stores our data objects
var qsql_="select Quot_OrderQuoteID,Quot_currency,Quot_PricingListID from Quotes "+
"where Quot_OrderQuoteID="+quoteid;
var qp=CRM.CreateQueryObj(qsql_);
qp.SelectSQL();
var pric_PricingListID="-1";//default
var pric_price_CID="-1";
if (!qp.eof)
{
pric_PricingListID=qp("Quot_PricingListID");
pric_price_CID=qp("Quot_currency");
}
var _obj=new Object();
_obj.sql="select "+
"Pric_PricingID,pric_UOMID,pric_ProductID,pric_price,pric_price_CID,pric_PricingListID "+
"from Pricing where pric_PricingListID="+pric_PricingListID+" and pric_Active='Y' and "+
"pric_price_CID="+pric_price_CID;
_obj.columns=new Array();
_obj.title="Pricing";
_obj.columns.push('pric_ProductID');
_obj.columns.push('Pric_PricingID');
_obj.columns.push('pric_UOMID');
_obj.columns.push('pric_price');
_obj.columns.push('pric_price_CID');
_obj.columns.push('pric_PricingListID');
objar.push(_obj);
var _content=createJSON_New2(objar,CRM);
%>
<script>
var _Pricing=<%=_content%>
</script><file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/product_inc.asp
<%
var objar=new Array();//this stores our data objects
var _famfilter="";
var prfa_productfamilyid=Request.Querystring("prfa_productfamilyid");
var pageCount=Request.Querystring("pageCount");
if (pageCount+""=="undefined")
{
pageCount=1;
}
pageCount=new Number(pageCount);
var rowsatatime=20000;
var rowsfrom=1;
if (pageCount>1)
{
var rowsfrom=((pageCount-1)*rowsatatime)+pageCount;
}
var rowsto=rowsfrom+rowsatatime;
var returndataonly=true;
if (prfa_productfamilyid+""=="undefined")
{
returndataonly=false;
}
var quoteid=CRM.GetContextInfo("quotes","quot_orderquoteid");
var json_note="";
//test line
if (!quoteid)
{
quoteid="514";
}
//Oct 2019 - Get the first families items only...
var _fam_sql="SELECT TOP 1 prfa_productfamilyid, prfa_name FROM ProductFamily "+
"WHERE (prfa_name LIKE N'%' ESCAPE '|' OR COALESCE(prfa_name, N'') = N'') "+
"and prfa_Deleted is Null and prfa_active = N'Y'AND "+
"prfa_productfamilyid IN (select prod_productfamilyid from newproduct where prod_productid "+
"in(select pric_productid from pricing WHERE pric_deleted IS NULL AND pric_pricinglistid "+
"=(select quot_pricinglistid from quotes where quot_orderquoteid = "+quoteid+" and pricing.pric_price_cid = quotes.quot_currency))) "+
"and ((prfa_intid is null and prfa_active= N'Y' )) "+
"order by prfa_name";
if (prfa_productfamilyid+""=="undefined")
{
var _fam_sqlds=CRM.CreateQueryObj(_fam_sql);
_fam_sqlds.SelectSQL();
if (!_fam_sqlds.eof)
{
prfa_productfamilyid=_fam_sqlds("prfa_productfamilyid");
}
}
_famfilter=" and prod_productfamilyid="+prfa_productfamilyid;
var _obj=new Object();
_obj.sql="SELECT * FROM (select Row_Number() OVER (ORDER BY prod_name) as rowid," +
"Prod_ProductID,prod_name,prod_code,prod_productfamilyid ,prod_UOMCategory,prod_Active ";
if (productCostField != '')
_obj.sql += "," + productCostField;
_obj.sql += " FROM NewProduct where Prod_Deleted is null and (prod_Active is null or prod_Active='Y') "+_famfilter+
") as a where rowid >= "+rowsfrom+" and rowid < "+rowsto;
//Response.Write(_obj.sql);
_obj.columns=new Array();
_obj.title="Products";
_obj.columns.push('prod_productid');
_obj.columns.push('prod_name');
_obj.columns.push('prod_code');
if (productCostField != '') {
_obj.columns.push(productCostField);
}
_obj.columns.push('prod_productfamilyid');
_obj.columns.push('prod_UOMCategory');
_obj.columns.push('prod_Active');
objar.push(_obj);
var _contentprodfam=createJSON_New(objar,CRM);
if (!returndataonly)
{
%>
<script>
var products_prfa_productfamilyid_<%=prfa_productfamilyid %>=<%=_contentprodfam%>;
//raw html...for speed purposes
var html_products_prfa_productfamilyid_<%=prfa_productfamilyid %>=null;
</script>
<% } else{
Response.ContentType = "application/json";
%>
<%=_contentprodfam%>
<% } %>
<file_sep>/src/ctItemPicker/CustomPages/ctItemPicker/updateQuoteItem.asp
<!-- #include file ="crmwizard.js" -->
<!-- #include file ="json_header.js" -->
<!-- #include file ="json_engine.js" -->
<%
function _dev(msg)
{
if (false)
{
Response.Write("<br>dbg: "+msg);
}
}
function getField(fname){
if (fname.indexOf("_CID")>0)
{
return currencyCID;
}
return Request.Form(fname);
}
var quot_orderquoteid=Request.Form("QuIt_orderquoteid");
_dev("quot_orderquoteid:"+quot_orderquoteid);
if (!quot_orderquoteid)
{
quot_orderquoteid="514";
}
var quoteid=quot_orderquoteid;
var QuIt_LineItemId=Request.Form("QuIt_LineItemId");
_dev("QuIt_LineItemId:"+QuIt_LineItemId);
if (!QuIt_LineItemId)
{
QuIt_LineItemId="1249";
}
//get the quote
var quoterec=CRM.FindRecord("Quotes","quot_orderquoteid="+quot_orderquoteid);
var oppoid=quoterec("Quot_opportunityid");
var currencyCID=quoterec("Quot_currency");
var quot_DiscountPC=quoterec("quot_DiscountPC");
//find QuoteItem
var QuoteItemsrec=CRM.FindRecord("QuoteItems","QuIt_LineItemId="+QuIt_LineItemId);
var QuIt_LineType=QuoteItemsrec("QuIt_LineType");
var QuIt_quantity=new Number(getField("QuIt_quantity"));
var QuIt_quotedprice=new Number(getField("QuIt_quotedprice"));
if (QuIt_LineType!="f")
{
var QuIt_listprice=new Number(getField("QuIt_listprice"));
var __uomid=new String(getField("QuIt_UOMID"));
if (__uomid.indexOf("&")==-1)
{
QuoteItemsrec("QuIt_UOMID")=getField("QuIt_UOMID");
}
QuoteItemsrec("QuIt_productfamilyid")=getField("QuIt_productfamilyid");
QuoteItemsrec("QuIt_listprice")=QuIt_listprice;
}
QuoteItemsrec("QuIt_quantity")=QuIt_quantity;
QuoteItemsrec("QuIt_quotedprice")=QuIt_quotedprice;
if (QuIt_LineType!="f")
{
var QuIt_discount=QuIt_listprice - QuIt_quotedprice;
QuoteItemsrec("QuIt_discount")=QuIt_discount;//list-quoted
QuoteItemsrec("QuIt_discountsum")=QuIt_discount*QuIt_quantity;
QuoteItemsrec("QuIt_quotedpricetotal")=QuIt_quantity*QuIt_quotedprice;
}
QuoteItemsrec.SaveChangesNoTLS();
_dev("update QuoteItems");
//get new values
var newquotetotals_sql="Select Sum(COALESCE(quit_DiscountSum, 0)) as DiscTotal,"+
"Sum(COALESCE(quit_quotedpricetotal, 0)) as NetTotal,"+
"Sum(COALESCE(quit_DiscountSum, 0))+Sum(COALESCE(quit_quotedpricetotal, 0)) as NoDiscAmt "+
"from vLineItemsQuote "+
"WITH (NOLOCK) where COALESCE(quit_deleted, 0) = 0 and quit_orderquoteID="+quot_orderquoteid;
var newquotetotals=CRM.CreateQueryObj(newquotetotals_sql);
newquotetotals.SelectSQL();
_dev("newquotetotals_sql:"+newquotetotals_sql);
//work out totals
var quot_NettAmt=0;
var quot_LineItemDisc=0;
var NoDiscAmt=0;
var quot_DiscountAMT=0;
var quot_GrossAmt="";
if (!newquotetotals.eof)
{
quot_LineItemDisc=newquotetotals("DiscTotal");
quot_NettAmt=newquotetotals("NetTotal");
NoDiscAmt=newquotetotals("NoDiscAmt");
quot_DiscountAMT=((quot_NettAmt/100)*quot_DiscountPC);
}
_dev("quot_NettAmt: "+quot_NettAmt);
quoterec("quot_NettAmt")=quot_NettAmt;
_dev("quot_LineItemDisc: "+quot_LineItemDisc);
quoterec("quot_LineItemDisc")=quot_LineItemDisc;
_dev("quot_DiscountAMT:"+quot_DiscountAMT);
quoterec("quot_DiscountAMT")=quot_DiscountAMT;
quot_GrossAmt=quot_NettAmt-quot_DiscountAMT;
_dev("quot_GrossAmt:"+quot_GrossAmt);
quoterec("quot_GrossAmt")=quot_GrossAmt; ;
quoterec.SaveChangesNoTLS();
var quotetotals_sql="Select COALESCE(Sum(Quot_GrossAmt), 0) as TotalForOppo, "+
"COALESCE(Sum(Quot_NoDiscAmt), 0) as NettTotalForOppo "+
"from vQuotes WITH (NOLOCK) "+
"where Quot_OpportunityID="+oppoid+
" and Quot_Status = N'Active' and COALESCE(Quot_RollUp, N'') <> N''";
var quotetotals=CRM.CreateQueryObj(quotetotals_sql);
quotetotals.SelectSQL();
_dev("quotetotals_sql:"+quotetotals_sql);
var Oppo_TotalQuotes=0;
var Oppo_Total=0;
var Oppo_NoDiscAmtSum=0;
if (!quotetotals.eof)
{
Oppo_TotalQuotes=quotetotals("TotalForOppo");
Oppo_Total=quotetotals("NettTotalForOppo");
}
_dev("Oppo_TotalQuotes:"+Oppo_TotalQuotes);
_dev("Oppo_Total:"+Oppo_Total);
//oppo totals
//UPDATE Opportunity SET Oppo_TotalOrders=16151.600000,Oppo_TotalOrders_CID=1,
//Oppo_TotalQuotes=145.000000,Oppo_TotalQuotes_CID=1,Oppo_Total=16296.600000,
//Oppo_Total_CID=1,Oppo_NoDiscAmtSum=0.000000,Oppo_NoDiscAmtSum_CID=1,oppo_UpdatedBy=1,
//oppo_TimeStamp='20190416 07:33:54',oppo_UpdatedDate='20190416 07:33:54'
//WHERE (Oppo_OpportunityID=10)
var oppores=CRM.FindRecord("Opportunity","oppo_opportunityid="+oppoid);
oppores("Oppo_TotalQuotes")=Oppo_TotalQuotes;
oppores("Oppo_Total")=Oppo_Total;
//oppores("Oppo_NoDiscAmtSum")=Oppo_NoDiscAmtSum;
oppores.SaveChangesNoTLS();
_dev("oppores save:"+oppoid);
var OutputAsJSON=true;
%>
<!-- #include file ="quoteitems_inc.asp" -->
<!-- #include file ="json_footer.js" -->
|
cbdd4625e14c7dc2be60bf62f887fa9beb736cf8
|
[
"Text",
"Markdown",
"Classic ASP",
"JavaScript"
] | 24 |
Text
|
crmtogether/Rapid-Item-Picker
|
a0d1e21c473f8c1be18a6e75f1b260a8a826b612
|
b54ac1320fbd9af5181f52d86cb29080e4962c4b
|
refs/heads/main
|
<file_sep>import {Prop, Schema, SchemaFactory} from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import {ApiResponseProperty} from '@nestjs/swagger';
import { User } from 'src/user/schemas/user.schema';
export type ProfileDocument = Profile & mongoose.Document;
@Schema()
export class Profile
{
@Prop({type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true})
user: User;
@ApiResponseProperty()
@Prop({required: true})
full_name: string;
@ApiResponseProperty()
@Prop({type: Date, default: Date.now()})
created_at: Date;
@ApiResponseProperty()
@Prop({type: Date, default: Date.now()})
updated_at: Date;
}
export const ProfileSchema = SchemaFactory.createForClass(Profile);<file_sep>import {ApiResponseProperty} from '@nestjs/swagger';
export class AuthResponseDto {
@ApiResponseProperty()
email: string;
@ApiResponseProperty()
full_name: string;
@ApiResponseProperty()
token: string;
}
<file_sep>import {ApiResponseProperty} from '@nestjs/swagger';
export class UserResponseDto {
@ApiResponseProperty()
_id: string;
@ApiResponseProperty()
email: string;
@ApiResponseProperty()
created_at: Date;
@ApiResponseProperty()
updated_at: Date;
}
<file_sep>## Description
Nakbah task was given as a task. The tech stack used is Nestjs (expresjs as base) using Typescript, swagger for api documentation and MongoDB as Database.
## Run app
### `cd hakbah_task`
### `npm install`
### Prerequisite
Rename the `.env.example` to `.env` and add mongodb credentials and JWT key.
### `npm run start:dev`
Runs the app in development environment.
### `npm run start`
Runs the app in production environment.
Open [http://localhost:3001](http://localhost:3001) to view it in the browser.
### Swagger documentation of the apis
The project also includes a swagger api documentation of all the apis and schemas
Open [http://localhost:3001/docs](http://localhost:3001/docs) to read documentation of the apis and to test the `endpoints`.
<file_sep>import { ApiProperty } from '@nestjs/swagger';
import {IsNotEmpty} from 'class-validator';
export class CreateProfileDto {
@ApiProperty()
@IsNotEmpty()
full_name: string;
}
<file_sep>import { Injectable } from '@nestjs/common';
import * as mongoose from 'mongoose';
import {InjectModel} from '@nestjs/mongoose';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User, UserDocument } from './schemas/user.schema';
@Injectable()
export class UserService {
constructor(@InjectModel(User.name) private readonly userRepository: mongoose.Model<User>) {}
async create(createUserDto: CreateUserDto): Promise<User> {
const newUser: UserDocument = new this.userRepository(createUserDto);
return await newUser.save();
}
async update(userId: string, updateProfileDto: UpdateUserDto): Promise<UserDocument> {
const user: UserDocument = await this.userRepository.findOneAndUpdate({_id: userId}, updateProfileDto).exec();
return user;
}
async findOneByEmail(email: string): Promise<User>
{
const user: User = await this.userRepository.findOne({email}).exec();
return user;
}
async findOne(userId: string): Promise<User>
{
const user: User = await this.userRepository.findOne({_id: userId}).exec();
return user;
}
}
<file_sep>import { Module } from '@nestjs/common';
import {ConfigModule} from '@nestjs/config';
import {MongooseModule} from '@nestjs/mongoose';
import { UserModule } from './user/user.module';
import { ProfileModule } from './profile/profile.module';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [ConfigModule.forRoot({isGlobal: true}), MongooseModule.forRoot(`mongodb://${process.env.DATABASE_HOST}/${process.env.DATABASE_NAME}`, {retryWrites: false, useFindAndModify: false}), UserModule, ProfileModule, AuthModule],
controllers: [],
providers: []
})
export class AppModule {}
<file_sep>import { NestFactory } from '@nestjs/core';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
app.setGlobalPrefix('api');
const config = new DocumentBuilder()
.setTitle('Hakbah Apis')
.setDescription('Set of apis for usage for mobile and frotend frameworks')
.setVersion('1.0')
.addTag('Signup, login, CRUDS')
.addBearerAuth({type: 'http', scheme: 'bearer', bearerFormat: 'jwt'}, 'JWT')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
await app.listen(3001);
}
bootstrap();
<file_sep>DATABASE_USER=
DATABASE_NAME=
DABABASE_PASSWORD=
DATABASE_HOST=localhost
JWT_KEY=THE_JWT_KEY<file_sep>import { Injectable } from '@nestjs/common';
import {InjectModel} from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { User } from 'src/user/schemas/user.schema';
import { UserService } from 'src/user/user.service';
import { CreateProfileDto } from './dto/create-profile.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { Profile, ProfileDocument } from './schemas/profile.schema';
@Injectable()
export class ProfileService {
constructor(
@InjectModel(Profile.name) private readonly profileRepository: mongoose.Model<Profile>
) {}
async create(userId: string, createProfileDto: CreateProfileDto): Promise<Profile> {
const saveObject = {user: userId, ...createProfileDto};
const profileDocument: ProfileDocument = new this.profileRepository(saveObject);
return await profileDocument.save();
}
async getProfile(userId: string): Promise<Profile>
{
const profile: Profile = await this.profileRepository.findOne({user: userId} as mongoose.FilterQuery<User>)
.populate('user', 'email created_at updated_at')
.exec();
return profile;
}
}
<file_sep>import { Controller, Get, Post, Body, Request, Put, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SignUpDto } from './dto/sign-up.dto';
import { LoginDto} from './dto/login.dto';
import { AuthResponseDto } from './dto/auth-response.dto';
import { ApiBearerAuth, ApiCreatedResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ChangePasswordDto } from './dto/change-password.dto';
import { User } from 'src/user/schemas/user.schema';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { UserResponseDto } from 'src/user/dto/user-response.dto';
@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@ApiOperation({description: "Signup new user"})
@ApiCreatedResponse({type: AuthResponseDto, description: "Auth Response Object"})
@Post('signup')
async signup(@Body() signUpDto: SignUpDto): Promise<AuthResponseDto> {
return this.authService.signup(signUpDto);
}
@ApiOperation({description: "Login user"})
@ApiCreatedResponse({type: AuthResponseDto, description: "Auth Response Object"})
@Post('login')
async login(@Body() loginDto: LoginDto): Promise<AuthResponseDto> {
return this.authService.login(loginDto);
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth('JWT') //swagger
@ApiOperation({description: "Change password user"})
@ApiCreatedResponse({type: AuthResponseDto, description: "Auth Response Object"})
@Put('password/change')
async changePassword(@Request() req: any, @Body() changePasswordDto: ChangePasswordDto): Promise<UserResponseDto> {
const {userId} = req.user;
return this.authService.changePassword(userId, changePasswordDto);
}
}
<file_sep>import { Controller, Get, NotFoundException, Request, UseGuards } from '@nestjs/common';
import { ProfileService } from './profile.service';
import { CreateProfileDto } from './dto/create-profile.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Profile } from './schemas/profile.schema';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
@ApiTags('Profile')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth('JWT') //swagger
@Controller('profile')
export class ProfileController {
constructor(private readonly profileService: ProfileService) {}
@ApiOperation({summary: "Returns user profile"})
@ApiOkResponse({type: Profile, description: "User Profile Object"})
@Get()
async getProfile(@Request() req: any): Promise<Profile> {
const {userId} = req.user;
const profile = this.profileService.getProfile(userId);
if(!profile)
{
throw new NotFoundException();
}
return profile;
}
}
<file_sep>import { ApiProperty } from '@nestjs/swagger';
import {IsNotEmpty, IsEmail} from 'class-validator';
export class ChangePasswordDto {
@ApiProperty()
@IsNotEmpty() current_password: string;
@ApiProperty()
@IsNotEmpty() new_password: string;
}
<file_sep>import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { SignUpDto } from './dto/sign-up.dto';
import { LoginDto } from './dto/login.dto';
import { AuthResponseDto } from './dto/auth-response.dto';
import { UserService } from 'src/user/user.service';
import { ProfileService } from 'src/profile/profile.service';
import * as bcrypt from 'bcrypt';
import { CreateUserDto } from 'src/user/dto/create-user.dto';
import { User, UserDocument } from 'src/user/schemas/user.schema';
import { CreateProfileDto } from 'src/profile/dto/create-profile.dto';
import { Profile } from 'src/profile/schemas/profile.schema';
import {JwtService} from '@nestjs/jwt';
import { ChangePasswordDto } from './dto/change-password.dto';
import { UpdateUserDto } from 'src/user/dto/update-user.dto';
import { UserResponseDto } from 'src/user/dto/user-response.dto';
@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private readonly profileService: ProfileService,
private readonly jwtService: JwtService
) { }
async signup(signUpDto: SignUpDto): Promise<AuthResponseDto>
{
const {email, password, full_name} = signUpDto;
const userExists = await this.userService.findOneByEmail(email);
if(userExists)
{
throw new BadRequestException("Account already exists");
}
const hashedPassword = await this.createHash(password);
const createUserDto: CreateUserDto = {email, password: hashedPassword};
const user: User = await this.userService.create(createUserDto);
const createProfileDto: CreateProfileDto = {full_name};
const profile: Profile = await this.profileService.create(user['_id'], createProfileDto);
const result: AuthResponseDto = this.getAuthUserResponse(user, profile);
return result;
}
async login(loginDto: LoginDto): Promise<AuthResponseDto>
{
const {email, password} = loginDto;
const user: User = await this.userService.findOneByEmail(email);
if(!user)
{
throw new NotFoundException("User not found");
}
const isPasswordMatched = await bcrypt.compare(password, user.password);
if(!isPasswordMatched)
{
throw new BadRequestException("The password you have entered is incorrect");
}
const profile: Profile = await this.profileService.getProfile(user['_id']);
const result: AuthResponseDto = this.getAuthUserResponse(user, profile);
return result;
}
async changePassword(userId: string, changePasswordDto: ChangePasswordDto): Promise<UserResponseDto>
{
const {current_password, new_password} = changePasswordDto;
const user: User = await this.userService.findOne(userId);
if(!user)
{
throw new NotFoundException("The user was not found");
}
const isPasswordMatched = await bcrypt.compare(current_password, user.password);
if(!isPasswordMatched)
{
throw new BadRequestException("The password you have entered is incorrect");
}
const hashedPassword = await this.createHash(new_password);
const updateUserDto: UpdateUserDto = {password: <PASSWORD>Password};
const updateUser = await this.userService.update(user['_id'], updateUserDto);
const result: UserResponseDto = this.getUserResponse(updateUser);
return result;
}
private async createHash(password: string): Promise<string>
{
const hash = await bcrypt.hash(password, 10);
return hash;
}
private getUserResponse(user: UserDocument): UserResponseDto
{
const {email, created_at, _id, updated_at} = user;
return {_id, email, created_at, updated_at};
}
private getAuthUserResponse(user: User, profile?: Profile): AuthResponseDto
{
const {email, created_at} = user;
const token = this.createToken(user['_id']);
const {full_name} = profile;
const result: AuthResponseDto = {email, full_name, token};
return result;
}
private createToken(userId: string): string
{
const payload = {sub: userId};
return this.jwtService.sign(payload);
}
}
|
8ca450c317f1198622f135bc6a433998705f760d
|
[
"Markdown",
"TypeScript",
"Shell"
] | 14 |
Markdown
|
ahtasham637/hakbah_task
|
41fe9072311d405acc4636a2e21aac20eaa7d017
|
235fdb72f7acc677cd2d4baa6a44e15a394f424e
|
refs/heads/master
|
<file_sep>## 接口如何防刷
#### 措施
+ 网关控制流量洪峰
+ 对在一个时间段内出现流量异常,可以拒绝请求
+ 源ip请求个数限制
+ 对请求来源的ip请求个数做限制
+ http请求头信息校验
+ host、User-Agent、Referer
+ 对用户唯一身份uid进行限制和校验
+ 基本的长度,组合方式,有效性进行判断
+ uid具有一定的时效性
+ 前后端协议采用二进制方式进行交互或者协议采用签名机制
+ 验证码等
+ 人机验证
+ 验证码
+ 短信验证码
+ 滑动图片形式
+ 12306形式(找不同)
+ 返回"操作频繁"的错误提示<file_sep># 爬楼梯问题变种
# 题目描述
> 假设你正在爬楼梯,每次你可以爬***1***个、***2***个或***3***个台阶,
> 那么在***相邻步数不能相同***的条件下,
> 你有多少种不同的方法可以爬到第n阶呢?
#### 解法:动态规划
+ 类似题型
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/solution/70-pa-lou-ti-by-alexer-660/)
+ 图解
+ 
+ 思路
+ 去掉限制条件,即此题和**70题**几乎一摸一样
+ 到达第i阶走法有三种
+ ***前1阶走1步***来到终点**或**
+ **如图I 第N-1台阶**,走***1步***来到**end**台阶
+ **如图I 第N-2台阶**,走***1步***来到**N-1**台阶
+ **如图I 第N-3台阶**,走***2步***来到**N-1**台阶
+ **如图I 第N-4台阶**,走***3步***来到**N-1**台阶
+ **依次类推......**
+ ***前2阶走2步***来到终点**或**
+ **如图II 第N-2台阶**,走***2步***来到**end**台阶
+ **如图II 第N-3台阶**,走***1步***来到**N-2**台阶
+ **如图II 第N-4台阶**,走***2步***来到**N-2**台阶
+ **如图II 第N-5台阶**,走***3步***来到**N-2**台阶
+ **依次类推......**
+ ***前3阶走3步***来到终点
+ **如图III 第N-3台阶**,走***3步***来到**end**台阶
+ **如图III 第N-4台阶**,走***1步***来到**N-3**台阶
+ **如图III 第N-5台阶**,走***2步***来到**N-3**台阶
+ **如图III 第N-6台阶**,走***3步***来到**N-3**台阶
+ **依次类推......**
+ 那么走法总数是以上3种情况之和
+ 递推公式:**dp[i] = dp [i-3]+ dp[i-2] + dp[i-1];**
+ 加上限制条件即为本题
+ 意思是如果当前台阶是走n(n=[1,2,3])步来到的
+ 那么它的前一步**不能走相同的n步**
+ 如图I、II、III,就是在当前台阶N-1、N-2、N-3三种情况下,把从左往右第一个绿色的箭头去掉
+ 也就是把上面不加限制条件的三种情况下其中一种情况去掉即可
+ 子问题:
+ dp[i]:从0走到第i阶台阶的走法总数
+ dp[i] = dp [i-3]+ dp[i-2] + dp[i-1];
+ 状态定义:
+ 第i个台阶表示最后一步走n步过来的前i个台阶所用步数总和
+ dp[i][1]:增加维度,二维1代表走到最后一个台阶前一步用了1步
+ dp[i][2]:增加维度,二维2代表走到最后一个台阶前一步用了2步
+ dp[i][3]:增加维度,二维3代表走到最后一个台阶前一步用了3步
+ 边界条件:
+ 走到前一台阶用的步数 != 走到当前台阶用的步数
+ 设B[x]代表走到第x级台阶所用步数
+ 则**B[n] != B[n-1]**
+ 合并到状态公式当中去就是
+ **dp[i][n]走法时,dp[i-n][n]走法不能走**
+ 递推公式:
+ **dp[i][1] = dp[i-1][2] + dp[i-1][3]**
+ **dp[i][2] = dp[i-2][1] + dp[i-2][3]**
+ **dp[i][3] = dp[i-3][1] + dp[i-3][2]**
+ 建立状态表:
+ 
+ 结合上述两个图解可知
```javascript
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
if(n < 3){
return 1;
}
var dp = Array.from(new Array(n+1),() => new Array(4).fill(0));
// 第i级台阶走n步前i个台阶所用步数总和且第i-n台阶不能走
dp[1][1] = 1;
dp[2][2] = 1;
dp[3][1] = 1;
dp[3][2] = 1;
dp[3][3] = 1;
for(var i = 4;i <= n;i++){
dp[i][1] = dp[i-1][2]+dp[i-1][3];
dp[i][2] = dp[i-2][1]+dp[i-2][3];
dp[i][3] = dp[i-3][1]+dp[i-3][2];
}
// 合并三种情况
return dp[n][1] + dp[n][2] + dp[n][3];
};
```
#### [更多leetCode题解敬请戳看👇](https://github.com/Alex660/leetcode)<file_sep># 摘要
+ 数据结构
+ 时间复杂度
+ 算法
+ 脑图
+ 化繁为简
+ 面试技巧
+ 经典习题
+ 几点感想
### 数据结构
+ 一维
+ 基础
+ 数组 array (string), 链表 linked list
+ 高级
+ 栈 stack, 队列 queue, 双端队列 deque, 集合 set, 映射 map (hash or map)
+ 二维
+ 基础
+ 树 tree, 图 graph
+ 高级
+ 二叉搜索树 binary search tree (red-black tree, AVL), 堆 heap, 并查集 disjoint set, 字典树 Trie
+ 特殊
+ 位运算 Bitwise, 布隆过滤器 BloomFilter
+ LRU Cache
### 时间复杂度
+ 
### 算法
+ If-else, switch —> branch
+ for, while loop —> Iteration
+ 递归 Recursion (Divide & Conquer, Backtrace)
+ 搜索 Search: 深度优先搜索 Depth first search, 广度优先搜索 Breadth first search, A*, etc
+ 动态规划 Dynamic Programming
+ 二分查找 Binary Search
+ 贪心 Greedy
+ 数学 Math , 几何 Geometry
### 脑图
+ [数据结构](https://naotu.baidu.com/file/b832f043e2ead159d584cca4efb19703?token=7a6a56eb2630548c)
+ [算法](https://naotu.baidu.com/file/0a53d3a5343bd86375f348b2831d3610?token=<PASSWORD>)
### 化繁为简【寻找重复性 —> 计算机指令集】
+ 人肉递归低效、很累
+ 找到最近最简方法,将其拆解成可重复解决的问题
+ 数学归纳法思维
### 面试技巧
+ Clarification:明确题⽬意思、边界、数据规模
+ Possible solutions:穷尽所有可能的解法
+ compare time/space
+ optimal solution
+ Coding:代码简洁、⾼性能、美感
+ Test cas
### 经典习题
+ 爬楼梯、硬币兑换
+ 括号匹配、括号⽣、成直⽅图最⼤⾯积、滑动窗⼝
+ ⼆叉树遍历、分层输出树、判断⼆叉排序树
+ 股票买卖、偷房⼦、字符串编辑距离、最⻓上升⼦序列、最⻓公共⼦序列
+ 异位词(判断和归类)、回⽂串(最⼤回⽂串)、regex和通配符匹配
+ ⾼级数据结构(Trie、BloomFilter、LRU cache、etc)
### 几点感想
1. 路漫漫其修远兮,吾将上下而求索
2. 师父领进门,修行在个人
3. 人类的本质是重复性,要想达到某个行业的翘楚,十年如一日的枯燥乏味坚持才是王道<file_sep># position属性的理解
+ static
+ 对象遵循常规流
+ 此时4个定位偏移属性不会被应用
+ 默认元素都是静态的定位
+ relative
+ 对象遵循常规流
+ 相对定位
+ 并且参照自身在常规流中的位置通过top,right,bottom,left属性进行偏移时不影响常规流中的任何元素。
+ absolute
+ 对象脱离常规流
+ 绝对定位
+ 使用top,right,bottom,left等属性进行绝对定位,盒子的偏移位置不影响常规流中的任何元素
+ 其margin不与其他任何margin折叠。
+ 元素定位参考的是离自身最近的定位祖先元素,要满足两个条件,
+ 第一个是自己的祖先元素,可以是父元素也可以是父元素的父元素,一直找,如果没有则选择body为对照对象。
+ 第二个条件是要求祖先元素必须定位,通俗说就是position的属性值为非static都行。
+ fixed
+ 与absolute一致,但偏移定位是以窗口为参考。当出现滚动条时,对象不会随着滚动。
+ 固定定位
+ center
+ **CSS3新增**
+ 与absolute一致,但偏移定位是以定位祖先元素的中心点为参考。
+ 盒子在其包含容器垂直水平居中。
+ page
+ **CSS3新增**
+ 与absolute一致。元素在分页媒体或者区域块内,元素的包含块始终是初始包含块,否则取决于每个absolute模式。
+ sticky
+ **CSS3新增**
+ 对象在常态时遵循常规流。
+ 它就像是 relative 和 fixed 的合体,
+ 当在屏幕中时按常规流排版,
+ 当卷动到屏幕外时则表现如fixed。
+ 该属性的表现是现实中你见到的吸附效果。<file_sep>## ***The stock issue With Javascript***
### 动态规划:***一法破万法*** 之 歼灭6道股票问题
#### 参考文章:[一个通用方法团灭 6 道股票问题](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/solution/yi-ge-tong-yong-fang-fa-tuan-mie-6-dao-gu-piao-wen/)
#### 1、[121. 买卖股票的最佳时机](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/)
#### 2、[122. 买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
#### 3、[123. 买卖股票的最佳时机 III](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/submissions/)
#### 4、[309. 最佳买卖股票时机含冷冻期](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/submissions/)
#### 5、[188. 买卖股票的最佳时机 IV](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/submissions/)
#### 6、[714. 买卖股票的最佳时机含手续费](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/submissions/)
#### 寻找共同特征
| 题号 | 交易日期/i | 交易次数/k | 操作 | 限制区别 |
| --- | -----: | :----: | -----:| -----: |
| 1 | any | 1 |buy/sell | —— |
| **2**| any | +infinity |buy/sell | —— |
| 3 | any | 2 |buy/sell | —— |
| **4**|**sell之后要等一天**| +infinity |buy/sell | —— |
| 5 | any | k = any |buy/sell | —— |
| **6**| any | +infinity |buy/sell |**每次交易去除手续费**|
#### 表格分析
+ +infinity为正无穷,代表当题不限制交易次数,可以进行n笔交易
+ 交易日期:sell之后要等一天
+ 为当题中的交易冷冻期
+ 意即,今天买入buy,那么昨天就不能卖出sell,只能前天sell
+ 交易次数
+ **不影响状态转移方程**
+ +infinity
+ 当题不限制交易次数,不影响交易利润
+ 例如我交易k次或者k+1次或者k+n次都可以,只要我能达到那个相对固定的最大利润值即可
+ 类似于爬楼梯、斐波那契数列问题
+ 无论你是爬一步或者每次两步上来都无所谓,能到达终点即可
+ 相当于0次或1次
+ 1
+ 无论是躺着还是睡着交易都是1次,可以多次买卖一支股票
+ 相当于0次
+ **影响状态转移方程**
+ 2
+ 交易1次和交易2次对于股票交易之利润的获取,肯定是不同的
+ 和交易次数为k次且k < n/2 情况相同
+ k
+ 一次交易 = 买入 + 卖出,至少需要2天
+ prices数组的长度即为最大交易天数n
+ 当 k < n/2 时
+ 为有效限制,即和上述交易限制次数为2的解法一样,只不过换成了动态数据
+ 当 k > n/2 时
+ 相当于 其它几题的可以多次买卖一支股票
+ 因而,此种情况是**不影响状态转移方程**的,所以解法也就回到了上面 k = +infinity 的情况,如出一辙
+ 又因为是**不影响状态转移方程**的,所以解法跟k = 0 或者 k = 1 次一样,是殊途同归的
+ 限制区别:每次交易去除手续费
+ 每一笔交易都要从获得利润中减去
+ 等价于
+ 买入股票时,价格升高了**或者**
+ 卖出股票时,价格降低了
#### 归纳总结
+ **状态定义**
+ 三要素
+ 1、交易日期:i
+ 2、交易次数:k
+ 每一次buy,交易次数必然减一:k-1
+ 3、交易操作:buy/sell <=> 持有/抛售
+ sell:利润中加prices[i]
+ buy:利润中减去prices[i]
+ dp[i][k][0,1]:三维DP
+ **dp[i][k][0]**:第i天本人至今最多交易了k次,并且手上**没有持有**股票
+ 之前(**dp[i-1]**)就没有持有**或者**之前(**dp[i-1]**)已经sell抛售了
+ **dp[i][k][1]**:第i天本人至今最多交易了k次,并且手上**持有**股票
+ 之前(**dp[i-1]**)已经持有,并选择继续持有**或者**之前(**dp[i-1]**)就没有持有,今天选择buy持有
+ **转移方程**
+ **dp[i][k][0] = Max(dp[i-1][k][1][0],dp[i-1][k][1] + prices[i])**
+ **dp[i][k][1] = Max(dp[i-1][k][1][1],dp[i-1][k-1][0] - prices[i])**
+ **边界条件**
+ dp[-1][k][0] = 0
+ 第一天是i = 0,而i = -1 时意即还未开始,利润为0
+ 同理:dp[-n][k][0] = 0
+ dp[-1][k][1] = -Infinity
+ 还没开始时是不可能持有或买入股票的,用负无穷代表买入的是非正常不可能的负数的的股票
+ 同理:dp[-n][k][0] = -Infinity
+ dp[i][0][0] = 0
+ 交易次数最少为1才有可能产生利润,为0时,意味还没开始交易,利润为0
+ dp[i][0][1] = -Infinity
+ 还未交易时,是不可能持有股票的,用负无穷表示这种不可能
+ **结果**
+ **dp[n-1][k][0]**
+ 最后一个手上没有股票的利润要比手上还有没被抛售的股票的利润更大
+ **dp代码框架**
+ 设三维数组 dp[n][k+1][2],n,k+1,2均为当前维度数组元素个数
+ i为天数,m为最大交易次数,0或1为交易状态;且0 <= i < n ,1 <= m <= k
```javascript
var maxProfit = function(k, prices) {
// 交易天数
let n = prices.length;
// 最大交易次数
//-----如果当题k不影响状态转移方程,此处去掉
let maxTime = k;
if(n == 0){
return 0;
}
// 初始化三维数组
//-----如果当题k不影响状态转移方程,此处初始化去掉
let dp = Array.from(new Array(n),() => new Array(maxTime+1));
for(let i = 0;i < n;i++){
for(let r = 0;r <= maxTime;r++){
dp[i][r] = new Array(2);
}
}
//-----如果当题k不影响状态转移方程,则只需二维数组
// let dp = Array.from(new Array(n),() => new Array(2));
// 遍历递推
for(let i = 0;i < n;i++){
//-----如果当题k不影响状态转移方程,内循环去掉
for(let k = maxTime;k >= 1;k--){
if(i == ...){
// 边界条件处理
//
continue;
}
// 递推公式
dp[i][k][0] = Max(前一天交易次数k:买,卖,不买也不卖);
dp[i][k][1] = Max(前一天交易次数k-1:买,卖,不买也不卖);
}
}
// 返回结果
return dp[n-1][maxTime][0];
//-----如果当题k不影响状态转移方程
// return dp[n-1][0];
};
```
#### 卍解
+ 1、***121***
+ **状态转移方程**
+ ***k = 1***
```javascript
dp[i][1][0] = Max(dp[i-1][1][0],dp[i-1][1][1] + prices[i])
dp[i][1][1] = Max(dp[i-1][1][1],dp[i-1][1-1][0] - prices[i])
= Max(dp[i-1][1][1],0-prices[i])
= Max(dp[i-1][1][1],-prices[i])
```
+ 正如表格分析可知,k都是1,对整个三维状态转移方程毫无影响,可以化掉
```javascript
dp[i][0] = Max(dp[i-1][0],dp[i-1][1] + prices[i])
dp[i][1] = Max(dp[i-1][1],-prices[i])
```
+ **解法一**
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp = Array.from(new Array(n),() => new Array(2));
for(let i = 0;i < n;i++){
if(i == 0){
dp[i][0] = 0;
dp[i][1] = -prices[i];
continue;
}
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
dp[i][1] = Math.max(-prices[i],dp[i-1][1]);
}
return dp[n-1][0];
};
```
+ **解法二 - 降维**
+ 新的状态只和相邻的一个状态有关,所以只需要两个相邻状态的变量进行递归即可
+ 正如[70. 爬楼梯-解法一](https://leetcode-cn.com/problems/climbing-stairs/solution/70-pa-lou-ti-by-alexer-660/)问题一样
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
var dp_i_0 = 0;
var dp_i_1 = -Infinity;
for(let i = 0;i < n;i++){
dp_i_0 = Math.max(dp_i_0,dp_i_1 + prices[i]);
dp_i_1 = Math.max(-prices[i],dp_i_1);
}
return dp_i_0;
};
```
___
+ 2、***122***
+ **状态转移方程**
+ ***k = +infinity***
```javascript
dp[i][k][0] = Max(dp[i-1][k][0],dp[i-1][k][1] + prices[i])
dp[i][k][1] = Max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i])
= Max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i])
= Max(dp[i-1][k][1],dp[i-1][k][0] - prices[i])
```
+ 正如表格分析可知,k为正无穷时,k和k-1都可以到达最大利润,对整个三维状态转移方程无影响,可以化掉
```javascript
dp[i][0] = Max(dp[i-1][0],dp[i-1][1] + prices[i])
dp[i][1] = Max(dp[i-1][1],dp[i-1][0] - prices[i])
```
+ **解法一**
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp = Array.from(new Array(n),() => new Array(2));
for(let i = 0;i < n;i++){
if(i == 0){
dp[0][0] = 0;
dp[0][1] = -prices[0];
continue;
}
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
dp[i][1] = Math.max(dp[i-1][0]-prices[i],dp[i-1][1]);
}
return dp[n-1][0];
};
```
+ **解法二 - 降维**
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp_i_0 = 0;
let dp_i_1 = -Infinity;
for(let i = 0;i < n;i++){
var tmp = dp_i_0;
dp_i_0 = Math.max(dp_i_0,dp_i_1+prices[i]);
dp_i_1 = Math.max(tmp-prices[i],dp_i_1);
}
return dp_i_0;
};
___
+ 3、***123***
+ **状态转移方程**
+ ***k = 2***
```javascript
dp[i][k][0] = Max(dp[i-1][k][0],dp[i-1][k][1] + prices[i])
dp[i][k][1] = Max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i])
```
+ 正如表格分析可知,k为2,对整个三维状态转移方程有影响,不能化掉k和k-1
+ **解法一**
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let maxTime = 2;
let dp = Array.from(new Array(n),() => new Array(maxTime+1));
for(let i = 0;i < n;i++){
for(let r = 0;r <= maxTime;r++){
dp[i][r] = new Array(2).fill(0);
}
}
for(let i = 0;i < n;i++){
for(let k = maxTime;k >= 1;k--){
if(i == 0){
dp[i][k][0] = 0;
dp[i][k][1] = -prices[i];
continue;
}
dp[i][k][0] = Math.max(dp[i-1][k][0],dp[i-1][k][1] + prices[i]);
dp[i][k][1] = Math.max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i]);
}
}
return dp[n-1][maxTime][0];
};
```
+ **解法二 - 降维**
+ k = 2
+ 只有两种情况,直接列举出所有的4种状态即可
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp_i_1_0 = 0;
let dp_i_1_1 = -prices[0];
let dp_i_2_0 = 0;
let dp_i_2_1 = -prices[0];
for(let i = 0;i < n;i++){
dp_i_1_0 = Math.max(dp_i_1_0,dp_i_1_1 + prices[i]);
dp_i_1_1 = Math.max(dp_i_1_1,0 - prices[i]);
dp_i_2_0 = Math.max(dp_i_2_0,dp_i_2_1+prices[i]);
dp_i_2_1 = Math.max(dp_i_2_1,dp_i_1_0-prices[i]);
}
return dp_i_2_0;
};
```
___
+ 4、***309***
+ **状态转移方程**
+ ***k = +infinity***
+ i:每次交易后要隔一天才能继续交易,即冷冻期
+ 即第i天选择1即buy时,
+ 第i-2天才是上一步交易的开始状态,第i-1天不能交易保持原来持有状态
```javascript
dp[i][k][0] = Max(dp[i-1][k][0],dp[i-1][k][1] + prices[i])
dp[i][k][1] = Max(dp[i-1][k][1],dp[i-2][k-1][0] - prices[i])
= Max(dp[i-1][k][1],dp[i-2][k-1][0] - prices[i])
= Max(dp[i-1][k][1],dp[i-2][k][0] - prices[i])
```
+ 和第2、题一样,k 对整个三维状态转移方程毫无影响,可以化掉
```javascript
dp[i][0] = Max(dp[i-1][0],dp[i-1][1] + prices[i])
dp[i][1] = Max(dp[i-1][1],dp[i-2][0] - prices[i])
```
+ **解法一**
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp = Array.from(new Array(n),() => new Array(2));
for(var i = 0;i < n;i++){
if(i == 0){
dp[0][0] = 0;
dp[0][1] = -prices[i];
continue;
}else if(i == 1){
dp[1][0] = Math.max(dp[0][0],dp[0][1]+prices[i]);
dp[1][1] = Math.max(dp[0][1], - prices[i]);
continue;
}
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1] + prices[i]);
dp[i][1] = Math.max(dp[i-1][1],dp[i-2][0] - prices[i]);
}
return dp[n-1][0];
};
```
+ **解法二 - 降维**
```javascript
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp_i_0 = 0;
let dp_i_1 = -Infinity;
let dp_pre = 0;
for(var i = 0;i < n;i++){
let tmp = dp_i_0;
dp_i_0 = Math.max(dp_i_0,dp_i_1 + prices[i]);
dp_i_1 = Math.max(dp_i_1,dp_pre - prices[i]);
dp_pre = tmp;
}
return dp_i_0;
};
```
+ 5、***188***
+ **状态转移方程**
+ ***k = any***
+ **k > n/2 时,<=> k = +infinity**
```javascript
dp[i][k][0] = Max(dp[i-1][k][0], dp[i-1][k][1] + prices[i])
dp[i][k][1] = Max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])
= Max(dp[i-1][k][1], dp[i-1][k][0] - prices[i])
```
+ 和第2、题一样,k 对整个三维状态转移方程毫无影响,可以化掉
```javascript
dp[i][0] = Max(dp[i-1][0],dp[i-1][1] + prices[i])
dp[i][1] = Max(dp[i-1][1],dp[i-1][0] - prices[i])
```
+ **k < n/2 时,<=> k = 2**
```javascript
dp[i][k][0] = Max(dp[i-1][k][0],dp[i-1][k][1] + prices[i])
dp[i][k][1] = Max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i])
```
+ 正如表格分析可知,k为2,对整个三维状态转移方程有影响,不能化掉k和k-1
+ **解法一**
+ 超时
+ k输入过大,导致dp数组申请内存超出限制
+ 所以要分情况
```javascript
/**
* @param {number} k
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(k, prices) {
let n = prices.length;
let maxTime = k;
if(n == 0){
return 0;
}
let dp = Array.from(new Array(n),() => new Array(maxTime+1));
for(let i = 0;i < n;i++){
for(let r = 0;r <= maxTime;r++){
dp[i][r] = new Array(2);
}
}
for(let i = 0;i < n;i++){
for(let k = maxTime;k >= 1;k--){
if(i == 0){
dp[i][k][0] = 0;
dp[i][k][1] = - prices[i];
continue;
}
dp[i][k][0] = Math.max(dp[i-1][k][0],dp[i-1][k][1] + prices[i]);
dp[i][k][1] = Math.max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i]);
}
}
return dp[n-1][maxTime][0];
};
```
+ 分情况优化版
+ k > n/2 <=> k = +infinity
+ k < n/2 <=> k = 2
+ 合并两种情况解法即为此题解法
```javascript
/**
* @param {number} k
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(k, prices) {
let n = prices.length;
let maxTime = k;
if(n == 0){
return 0;
}
let maxProfitInfinity = (prices) => {
let n = prices.length;
if(n == 0){
return 0;
}
let dp = Array.from(new Array(n),() => new Array(2));
for(let i = 0;i < n;i++){
if(i == 0){
dp[0][0] = 0;
dp[0][1] = -prices[0];
continue;
}
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
dp[i][1] = Math.max(dp[i-1][0]-prices[i],dp[i-1][1]);
}
return dp[n-1][0];
};
if(maxTime > n/2){
return maxProfitInfinity(prices);
}
let dp = Array.from(new Array(n),() => new Array(maxTime+1));
for(let i = 0;i < n;i++){
for(let r = 0;r <= maxTime;r++){
dp[i][r] = new Array(2).fill(0);
}
}
for(let i = 0;i < n;i++){
for(let k = maxTime;k >= 1;k--){
if(i == 0){
dp[i][k][0] = 0;
dp[i][k][1] = - prices[i];
continue;
}
dp[i][k][0] = Math.max(dp[i-1][k][0],dp[i-1][k][1] + prices[i]);
dp[i][k][1] = Math.max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i]);
}
}
return dp[n-1][maxTime][0];
};
```
+ **解法二 - 降维**
```javascript
/**
* @param {number} k
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(k, prices) {
let n = prices.length;
let maxTime = k;
if(n == 0){
return 0;
}
// 此处降维-复用第2题k=infinity的方法
// 但不能复用第4题的,因为第4天仍有交易天数的限制
let maxProfitInfinity = (prices) => {
let n = prices.length;
if(n == 0){
return 0;
}
let dp_i_0 = 0;
let dp_i_1 = -Infinity;
for(let i = 0;i < n;i++){
var tmp = dp_i_0;
dp_i_0 = Math.max(dp_i_0,dp_i_1+prices[i]);
dp_i_1 = Math.max(tmp-prices[i],dp_i_1);
}
return dp_i_0;
};
if(maxTime > n/2){
return maxProfitInfinity(prices);
}
// 此处不能能像第3题k=2那样降维
// 因为:第三题k值较小,它第解法是直接列举处所有可能的情况出来
// 但是:此题当k<n/2的情况下,k依然可能很大,如果k=10,11,12
// 那这样就不像爬楼梯和斐波那契数列那样只有两种情况了可以直接列举降维了
// 因此只能用for循环枚举所有k可能的状态,三维无可避免。
let dp = Array.from(new Array(n),() => new Array(maxTime+1));
for(let i = 0;i < n;i++){
for(let r = 0;r <= maxTime;r++){
dp[i][r] = new Array(2).fill(0);
}
}
for(let i = 0;i < n;i++){
for(let k = maxTime;k >= 1;k--){
if(i == 0){
dp[i][k][0] = 0;
dp[i][k][1] = - prices[i];
continue;
}
dp[i][k][0] = Math.max(dp[i-1][k][0],dp[i-1][k][1] + prices[i]);
dp[i][k][1] = Math.max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i]);
}
}
return dp[n-1][maxTime][0];
};
```
___
+ 6、***714***
+ **状态转移方程**
+ ***k = +infinity***
```javascript
dp[i][k][0] = Max(dp[i-1][k][0],dp[i-1][k][1] + prices[i])
dp[i][k][1] = Max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i] - fee)
= Max(dp[i-1][k][1],dp[i-1][k-1][0] - prices[i] - fee)
= Max(dp[i-1][k][1],dp[i-1][k][0] - prices[i] - fee)
```
+ 和第2、题一样,k 对整个三维状态转移方程毫无影响,可以化掉
```javascript
dp[i][0] = Max(dp[i-1][0],dp[i-1][1] + prices[i])
dp[i][1] = Max(dp[i-1][1],dp[i-1][0] - prices[i] - fee)
```
+ **解法一**
```javascript
/**
* @param {number[]} prices
* @param {number} fee
* @return {number}
*/
var maxProfit = function(prices, fee) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp = Array.from(new Array(n),() => new Array(2));
for(let i = 0;i < n;i++){
if(i == 0){
dp[0][0] = Math.max(0,-Infinity+prices[0]);
dp[0][1] = Math.max(-Infinity,0 - prices[0] - fee);
continue;
}
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1] + prices[i]);
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0] - prices[i] - fee);
}
return dp[n-1][0];
};
```
+ **解法二 - 降维**
```javascript
/**
* @param {number[]} prices
* @param {number} fee
* @return {number}
*/
var maxProfit = function(prices, fee) {
let n = prices.length;
if(n == 0){
return 0;
}
let dp_i_0 = 0;
let dp_i_1 = -Infinity;
for(let i = 0;i < n;i++){
let tmp = dp_i_0;
dp_i_0 = Math.max(dp_i_0,dp_i_1 + prices[i]);
dp_i_1 = Math.max(dp_i_1,tmp - prices[i] - fee);
}
return dp_i_0;
};
```
#### [更多leetCode题解敬请戳看👇](https://github.com/Alex660/leetcode)<file_sep>### 定义
+ 略
### 创建
+ let arr = new Array()
+ let arr = []
### 方法
+ [Array.from()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
+ 从类数组对象或者可迭代对象中创建一个新的数组实例
+ [Array.isArray()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
+ 用来判断某个变量是否是一个数组对象。
+ [Array.of()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/of)
+ 根据一组参数来创建新的数组实例,支持任意的参数数量和类型
+ [Array.prototype.copyWithin()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin)
+ 在数组内部,将一段元素序列拷贝到另一段元素序列上,覆盖原有的值
+ [Array.prototype.fill()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/fill)
+ 将数组中指定区间的所有元素的值,都替换成某个固定的值
+ [Array.prototype.pop()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)
+ 删除数组的最后一个元素,并返回这个元素
+ [Array.prototype.push()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
+ 在数组的末尾增加一个或多个元素,并返回数组的新长度
+ [Array.prototype.reverse()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)
+ 颠倒数组中元素的排列顺序
+ shift()
+ sort()
+ splice()
+ unshift()
+ concat()
+ includes()
+ join()
+ slice()
+ toString()
+ toLocaleString()
+ indexOf()
+ lastIndexOf()
+ forEach()
+ entries()
+ every()
+ some()
+ filter()
+ find()
+ findIndex()
+ keys()
+ map()
+ reduce()
+ reduceRight()
+ values()
+ [更多解释敬请参考MDN官方文档](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array)<file_sep>## 回溯算法--求解八皇后问题
```javascript
// 8X8的棋盘上要求放满符合这样条件的棋子:
// 1、每个棋子的横行、竖列和左右对角线上不能有其它任何一颗棋子【皇后】
// 2、求这样的棋子有多少个
// 设结果数组:result 索引代表行,值代代表列 值可以存在时即为所求
// 初始化8个元素的数组
var result = new Array(8);
// 主函数
function cal8queens(row) {
// 8 行都放满了 退出
if(row == 8){
printQueens(result);
return;
}
for(var column = 0;column<8;column++){
// 符合要求的就落子
if(isOk(row,column)){
result[row] = column;
cal8queens(row+1);
}
}
}
// 判断 row 行 column 列放置是否合适
function isOk(row,column) {
// 当前列的左右两列
var leftColumn = column -1;
var rightColumn = column +1;
// 逐上判断每一行是否能放棋子
for(var i = row - 1;i>=0;i--){
// 第i行第column列是否有棋子【上一行同一列不能有棋子】
if(result[i] == column){
return false;
}
// 当左列存在 && 考虑左上对角线【递减斜向上】 第i行第leftColumn列是否有棋子
if(leftColumn>=0){
if(result[i] == leftColumn){
return false;
}
}
// 当右列存在 && 考虑右上对角线【递减斜向上】 第i行第rightColumn列是否有棋子
if(rightColumn<8){
if(result[i] == rightColumn){
return false;
}
}
leftColumn--;
rightColumn++;
}
return true;
}
// 打印结果
function printQueens(result) {
console.log(result);
var str = '';
for(var i=0;i<8;i++){
for(var r=0;r<8;r++){
if(result[i] == r){
str+='Q ';
}else{
str+='* ';
}
}
str+='\n'
}
console.log(str)
}
```<file_sep>## 垂直居中的卍种方法
#### 解法一
+ 对单行元素进行居中垂直(文本+图片)
+ 设置行内元素的父元素:height == line-height
+ 设置行内元素:vertical-align:middle,line-height
#### 解法二
+ 定位
+ position:absolute + margin-top(元素高度一半)
+ position:absolute + top:0 + bottom:0 + left:0 + right:0 + marign:auto
+ position:absolute + top:calc(50% - 元素height/2) + left:calc(50% - 元素width/2)
+ position:absolute + top:50% + left:50% + transform:translate(-50%,-50%)
#### 解法三
+ 居于视口单位的解决方案
+ margin-top:50vh + transform:translateY(-50%)
#### 解法四
+ table
+ 父元素
+ display:table;
+ 子元素
+ display:table-cell + vertival-align:middle
#### 解法五
+ flex
+ 父元素
+ display:flex
+ 子元素
+ margin:auto
+ algin-items:center<file_sep>## 薅羊毛
```javascript
// 满200减50元 假设购物车有n个商品
// 在凑够满减条件的前提下 让选出来的商品价格总和接近 满减值 是为 薅羊毛
// 类似01背包问题动态规划求解方法
// n个商品每个商品买或不买,决策之后对应不同的状态集合;用二维数组 states[n][x]记录决策后的状态
// 0-1背包问题中,找的是 <=w 的最大值 x = 背包的最大承载重量 = w+1
// 对于这个问题 x 为大于等于 200【满减条件】值中最小的
// 求X后 倒推出被选择的商品序列
// items 商品价格
// n 商品个数
// w 满减条件
var items = [100,50,60,50,110,106];
var n = items.length;
var w = 200;
var needBuy = [];
function getNeedShop() {
// 设置满减值的3倍为薅羊毛的最大利益化 && 初始化二维数组
var result = Array(n);
for(var i = 0;i<n;i++){
result[i] = Array(3*w+1);
}
// 第一行数据特殊处理 作为哨兵优化
result[0][0] = true;
if(items[0] <= 3*w){
result[0][items[0]] = true;
}
// 动态规划状态转移
for(var i = 1;i<n;i++){
// 不购买第 i 个商品
for(var j = 0;j<= 3*w;j++){
if(result[i-1][j] == true){
result[i][j] = result[i-1][j];
}
}
// 购买第 i 个商品
for(var j = 0;j<=3*w - items[i];j++){
if(result[i-1][j] == true){
result[i][j+items[i]] = true;
}
}
}
// 确认结果大于等于w的最小值
var minMaxJ;
for(minMaxJ = w;j<3*w+1;j++){
if(result[n-1][minMaxJ] == true){
break;
}
}
// 不存在利益最大化的解
if(minMaxJ == 3*w+1){
return;
}
// 有解 倒推出选择的商品
// 分析
// (i,j) <= (i-1,j) 或 (i-1,j-items[i])
// => 检查result[i-1][j] 或者 result[i-1][j-itmes[i]]是否为true
// => result[i-1][j]可达 => 没有选择购买第 i 个 商品
// => result[i-1][j-items[i]] 可达 => 购买了第 i 个 商品
// 继续迭代其它商品是否选择购买
for(var i = n-1;i>=1;i--){
if(j-items[i] >= 0 && result[i-1][j-items[i]] == true){
needBuy.push(itmes[i]);
// 更新列
j = j -itmes[i];
}//else 没有购买这个商品,j不变
}
// 动态规划初始值由此推动而来所以要加上
if(j!=0){
needBuy.push(itmes[0])
}
return needBuy;
}
```<file_sep># 定义
+ 前序
+ 根-左-右
+ 中序
+ 左-根-右
+ 后序
+ 左-右-根
## 例题
+ [144. 二叉树的前序遍历](https://leetcode-cn.com/problems/binary-tree-preorder-traversal/)
+ [94. 二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/)
+ [145. 二叉树的后序遍历](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/)
## 图解
+ 
## 三序遍历解法
+ 递归
+ 模拟栈/迭代
+ I
+ II
+ III
+ IV
+ 转换
+ 只针对前、后序遍历
+ 线索二叉树/莫里斯遍历
+ 忙,待更
#### 递归
+ 思路
+ 前序遍历 preOrder(r)
+ print r
+ preOrder(r->left)
+ preOrder(r->right)
+ 中序遍历 inOrder(r)
+ inOrder(r->left)
+ print r
+ inOrder(r->right)
+ 后序遍历 postOrder(r)
+ postOrder(r->left)
+ postOrder(r->right)
+ print r
+ 求解
+ 前序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
var result = [];
function pushRoot(node){
if(node != null){
result.push(node.val);
if(node.left != null){
pushRoot(node.left);
}
if(node.right != null){
pushRoot(node.right);
}
}
}
pushRoot(root);
return result;
};
```
+ 中序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
var result = [];
function pushRoot(root){
if(root != null){
if(root.left != null){
pushRoot(root.left);
}
result.push(root.val);
if(root.right !=null){
pushRoot(root.right);
}
}
}
pushRoot(root);
return result;
};
```
+ 后序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
var result = [];
function pushRoot(node){
if(node != null){
if(node.left != null){
pushRoot(node.left);
}
if(node.right != null){
pushRoot(node.right);
}
result.push(node.val);
}
}
pushRoot(root);
return result;
};
```
#### 模拟栈-I
+ 思路
+ 由三序定义和其图解操作可知
+ 对于二叉树任何一个节点而言,我们对它只有两种操作
+ 一是将它作为根节点,在三序相应的遍历顺序中,取出其中的值作为结果集的一部分
+ 二是继续探索它的左、右子树,按照三序的定义顺序来操作
+ 因而在此
+ 我们对任意一个节点附加一个标识
+ true:表示当前节点是三序遍历中相应顺序的根节点,碰到需要加入结果集
+ false:表示此节点属于三序遍历中的左、右子树的操作,需要压入栈中
+ 栈
+ 先进后出
+ 总结
+ **通过栈编写三序遍历中时,代码编写顺序是其倒序**
+ 前序
+ 右-左-根
+ 中序
+ 右-根-左
+ 后序
+ 根-右-左
+ 求解
+ 前序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [[root,false]];
while(stack.length > 0){
let node = stack.pop();
let curr = node[0];
let isTrue = node[1];
if(isTrue){
res.push(curr.val);
}else{
if(curr.right){
stack.push([curr.right,false]);
}
if(curr.left){
stack.push([curr.left,false]);
}
stack.push([curr,true]);
}
}
return res;
};
```
+ 中序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [[root,false]];
while(stack.length > 0){
let node = stack.pop();
let curr = node[0];
let isTrue = node[1];
if(isTrue){
res.push(curr.val);
}else{
if(curr.right){
stack.push([curr.right,false]);
}
stack.push([curr,true]);
if(curr.left){
stack.push([curr.left,false]);
}
}
}
return res;
};
```
+ 后序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [[root,false]];
while(stack.length > 0){
let node = stack.pop();
let curr = node[0];
let isTrue = node[1];
if(isTrue){
res.push(curr.val);
}else{
stack.push([curr,true]);
if(curr.right){
stack.push([curr.right,false]);
}
if(curr.left){
stack.push([curr.left,false]);
}
}
}
return res;
};
```
#### 模拟栈-II
+ 思路
+ 前序
+ 1、申请一个stack,将当前遍历节点保存在栈中
+ 2、对当前节点的左子树重复过程1,直到左子树为空
+ 3、出栈当前节点,对当前节点的右子树重复过程1
+ 4、直到遍历完所有节点
+ 中序
+ 略
+ 后序
+ 另一种写法
+ 参考-转换-后序-解法二
+ 求解
+ 前序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [];
let curr = root
while(curr != null || stack.length > 0){
if(curr){
res.push(curr.val);
stack.push(curr);
curr = curr.left;
}else{
let node = stack.pop();
curr = node.right;
}
}
return res;
};
```
+ 中序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [];
let curr = root
while(curr != null || stack.length > 0){
if(curr){
stack.push(curr);
curr = curr.left;
}else{
let node = stack.pop();
res.push(node.val);
curr = node.right;
}
}
return res;
};
```
+ 后序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [];
let curr = root
while(curr != null || stack.length > 0){
if(curr){
res.unshift(curr.val);
stack.push(curr);
curr = curr.right;
}else{
let node = stack.pop();
curr = node.left;
}
}
return res;
};
```
#### 模拟栈-III
+ 思路
+ 前序
+ 根-左-右 + 栈
+ 遇到根,直接入结果集
+ 先入栈右边,这样【后】出栈右边,到时入结果集
+ 后入栈左边,这样【先】出栈左边,到时入结果集
+ 中序
+ 略
+ 后序
+ 另一种写法
+ 参考-转换-后序-解法一
+ 求解
+ 前序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [root];
while(stack.length > 0){
let curr = stack.pop();
// 遇到根,直接入结果集
res.push(curr.val);
// 先入栈右边,这样后出栈
if(curr.right){
stack.push(curr.right);
}
// 后入栈左边,这样先出栈左边
if(curr.left){
stack.push(curr.left);
}
}
return res;
};
```
+ 中序
+ 略
+ 后序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [root];
while(stack.length > 0){
let curr = stack.pop();
if(curr.left){
stack.push(curr.left);
}
if(curr.right){
stack.push(curr.right);
}
res.unshift(curr.val);
}
return res;
};
```
#### 模拟栈-IV
+ 思路
+ 前序 + 栈
+ 遍历顺序
+ 根-右-左
+ 结果顺序
+ 根-左-右
+ 中序
+ 遍历顺序
+ 右-根-左
+ 结果顺序
+ 左-根-右
+ 后序
+ 另一种解法
+ 将前序转换(翻转)一下就可
+ 前序遍历顺序 - 根-右-左
+ 转换(翻转)顺序 - 左-右-根
+ 即为后序遍历
+ 参考-转换-后序-解法三
+ 求解
+ 前序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let res = [];
let stack = [];
let curr = root;
while(stack.length > 0 || curr){
while(curr){
res.push(curr.val);
stack.push(curr);
curr = curr.left;
}
let node = stack.pop();
curr = node.right;
}
return res;
};
```
+ 中序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
let res = [];
let stack = [];
let curr = root;
while(stack.length > 0 || curr){
while(curr){
stack.push(curr);
curr = curr.left;
}
let node = stack.pop();
res.push(node.val);
curr = node.right;
}
return res;
};
```
+ 后序
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
let stack = [];
let curr = root;
while(stack.length > 0 || curr){
while(curr){
stack.push(curr);
res.unshift(curr.val);
curr = curr.right;
}
let node = stack.pop();
curr = node.left;
}
return res;
};
```
#### 转换
+ 思路
+ 前序
+ 略
+ 中序
+ 略
+ 后序
+ 相对于前序遍历,反转结果即可
+ 求解
+ 后序
+ 解法一:参考模拟栈-III
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [root];
while(stack.length > 0){
let curr = stack.pop();
if(curr.left){
stack.push(curr.left);
}
if(curr.right){
stack.push(curr.right);
}
res.push(curr.val);
}
return res.reverse();
};
```
+ 解法二:参考模拟栈-II
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
if(!root){
return res;
}
let stack = [];
let curr = root
while(curr != null || stack.length > 0){
if(curr){
res.push(curr.val);
stack.push(curr);
curr = curr.right;
}else{
let node = stack.pop();
curr = node.left;
}
}
return res.reverse();
};
```
+ 解法三:参考模拟栈-IV
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let res = [];
let stack = [];
let curr = root;
while(stack.length > 0 || curr){
while(curr){
res.push(curr.val);
stack.push(curr);
curr = curr.right;
}
let node = stack.pop();
curr = node.left;
}
return res.reverse();
};
```
#### 线索二叉树/莫里斯遍历
+ 忙,待更<file_sep># iframe的优缺点
#### 优点
+ iframe能够把嵌入的网页原样展现出来;
+ 模块分离,便于更改,如果有多个网页引用iframe,只需要修改iframe的内容,就可以实现调用的每一个页面内容的更改,方便快捷;
+ 网页如果为了统一风格,头部和版本都是一样的,就可以写成一个页面,用iframe来嵌套,增加代码的可重用;
+ 如果遇到加载缓慢的第三方内容如图标和广告,这些问题可以由iframe来解决;
+ 重载页面时不需要重载整个页面,只需要重载页面中的一个框架页;
+ 方便制作导航栏。
#### 缺点
+ iframe会阻塞主页面的 Onload 事件,影响网页加载速度;
+ 搜索引擎的检索程序无法解读这种页面,不利于 SEO;
+ iframe和主页面共享连接池,而浏览器对相同域的连接有限制,所以会影响页面的并行加载。
+ 如果需要使用 iframe ,最好是通过 javascript动态给iframe添加 src 属性值,这样可以绕开以上两个问题。
+ 多数小型的移动设备(PDA 手机)无法完全显示框架,设备兼容性差
#### 应用场景
+ 分析
+ iframe的页面和父页面(parent)是分开的,所以它意味着,这是一个独立的区域,不受 parent的CSS或者全局的JavaScript的影响。
+ 应用
+ 网页编辑器;
+ 跨域通信。JavaScript跨域总结与解决办法 ,类似的还有浏览器多页面通信,比如音乐播放器,用户如果打开了多个tab页,应该只有一个在播放;
+ 历史记录管理,解决ajax化网站响应浏览器前进后退按钮的方案,在html5的history api不可用时作为一种替代;
+ 纯前端的utf8和gbk编码互转。比如在utf8页面需要生成一个gbk的encodeURIComponent字符串,可以通过页面加载一个gbk的iframe,然后主页面与子页面通信的方式实现转换;
+ 用iframe实现无刷新文件上传,在FormData不可用时作为替代方案;
+ 创建一个全新的独立的宿主环境。iframe还可以用于创建新的宿主环境,用于隔离或者访问原始接口及对象,比如有些前端安全的防范会覆盖一些原生的方法防止恶意调用,通过创建一个iframe,然后从iframe中取回原始对象和方法来破解这种防范;
+ 用来加载广告;
+ 一般邮箱使用iframe,如QQ邮箱;
+ 一些简单的后台页面。<file_sep>## 不使用NEW运算符如何创建JS对象
#### 解法
+ 利用字面量
```javascript
let a = [],b = {},c = /abc/g;
```
+ 利用 dom api
```javascript
let d = document.createElement('p');
```
+ 利用JavaScript内置对象api
```javascript
let e = Object.create(null);
let f = Object.assign({x:2},{y:3});
let g = JSON.parse('{}');
```
+ 利用装箱转换
```javascript
let h = Object(undefined);
let i = Object(null);
let j = Object(1);
let k = Object('a');
let l = Object(true);
let m = (function() {return this}).call(1)
```
+ 利用 ES6构造器
```javascript
class myObj{
constructor(a) {this.a = a;}
}
``` <file_sep># 摘要
+ 数组
+ 链表
+ 栈
+ 队列
+ 源码分析
+ 图示

### 数组
+ 数组是一个线性表,是一组连续的存储空间
+ 支持随机访问
+ 低效的“插入”和“删除”
+ 警惕数组的访问越界问题
+ 下标从0开始
+ 从数组存储的内存模型上来看,“下标”最确切的定义应该是“偏移(offset)”,
+ 如果用a来表示数组的首地址,a[0]就是偏移为0的位置,也就是首地址,
+ a[k]就表示偏移k个type_size的位置,
+ 所以计算a[k]的内存地址只需要
+ a[k]_address = base_address + k * type_size
+ 若是数组从1开始计数,那么我们计算数组元素a[k]的内存地址就是
+ a[k]_address = base_address + (k-1) * type_size
+ 从1开始编号,每次随机访问数组元素都多了一次减法运算,对于cpu来说,就是多了一次减法指令。
+ 容器类实现
+ Java的 ArrayList
+ 支持动态扩容
+ 操作时间复杂度
+ prepend O(1)
+ append O(1)
+ lookup O(1)
+ insert O(n)
+ delete O(n)
### 链表 Linked list
+ 是一种在内存中通过节点记录内存地址而互相链接形成一条链的存储方式
+ 区别数组图示

+ 操作时间复杂度
+ prepend O(1)
+ append O(1)
+ lookup O(n)
+ insert O(1)
+ delete O(1)
+ 解题技巧
+ 警惕指针丢失和内存泄露
+ 插入结点时,注意操作的顺序
>new_node->next = p->next;
p->next = new_node;
+ 删除链表结点时,记得手动释放内存空间
> p->next = p->next->next;
+ 不用哨兵结点插入首结点、删除尾结点
> if (head == null) {
head = new_node;
}
>if (head->next == null) {
head = null;
}
+ 利用哨兵简化实现难度
+ 头结点为哨兵结点

+ 重点留意边界条件处理
+ 举例画图,辅助思考

+ 多写多练
+ 常考题
+ 单链表反转
+ 链表中环的检测
+ 两个有序的链表合并
+ 删除链表倒数第n个结点
+ 经典应用场景
+ LRU 缓存淘汰算法
+ 缓存
+ 是一种提高数据读取性能的技术
+ 常见策略
+ LFU(Least Frequently Used) 最少使用策略
+ LRU(Least Recently Used) 最近最少使用策略
+ 常用链表结构
+ 单链表

+ 插入与删除

+ 循环链表
+ 是一种特殊的单链表
+ 典型应用
+ 约瑟夫问题
+ 双链表

+ 双向循环链表

#### 栈
+ 是一种受限的线性表
+ 先进后出
+ 表现
+ 数组实现叫 顺序栈
+ 链表实现叫 链式栈
+ 应用
+ 函数调用
```java
int main() {
int a = 1;
int ret = 0;
int res = 0;
ret = add(3, 5);
res = a + ret;
printf("%d", res);
reuturn 0;
}
int add(int x, int y) {
int sum = 0;
sum = x + y;
return sum;
}
```

+ 表达式求值
>34+13*9+44-12/3

+ 括号匹配
+ 用栈来保存未匹配的左括号,从左到右依次扫描字符串。当扫描到左括号时,则将其压入栈中;
+ 当扫描到右括号时,从栈顶取出一个左括号。
+ 如果能够匹配,比如“(”跟“)”匹配,“[”跟“]”匹配,“{”跟“}”匹配,则继续扫描剩下的字符串。
+ 如果扫描的过程中,遇到不能配对的右括号,或者栈中没有数据,则说明为非法格式。
+ 浏览器前进后退功能
#### 队列
+ 是一种操作受限的线性表
+ 先进先出
+ 与栈区分
+ 栈只需维护一个 栈顶指针

+ 队列需要维护两个指针
+ 队首 Head 永远指向队首元素索引位置
+ 队尾 Tail 永远指向队尾元素下一个索引位置
+ 表现
+ 用数组实现的队列叫 顺序队列

+ 用链表实现的队列叫 链式队列

+ 循环队列

+ 队空
+ tail == head
+ 队满

+ (tail+1)%n == head
```java
public class CircularQueue {
// 数组:items,数组大小:n
private String[] items;
private int n = 0;
// head 表示队头下标,tail 表示队尾下标
private int head = 0;
private int tail = 0;
// 申请一个大小为 capacity 的数组
public CircularQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
// 入队
public boolean enqueue(String item) {
// 队列满了
if ((tail + 1) % n == head) return false;
items[tail] = item;
tail = (tail + 1) % n;
return true;
}
// 出队
public String dequeue() {
// 如果 head == tail 表示队列为空
if (head == tail) return null;
String ret = items[head];
head = (head + 1) % n;
return ret;
}
}
```
+ 阻塞队列
+ 在队列的基础上增加阻塞操作
+ 应用
+ 生产者 - 消费者 模型

+ 并发队列
+ 线程安全的队列
+ 最简单直接的实现方式是直接在 enqueue()、dequeue() 方法上加锁,但是锁粒度大并发度会比较低,同一时刻仅允许一个存或者取操作。
+ 实际上,基于数组的循环队列,利用 CAS 原子操作,可以实现非常高效的并发队列。这也是循环队列比链式队列应用更加广泛的原因。
+ 实现无锁并发队列
+ cas + 数组
+ 其它应用
+ 分布式应用中的消息队列 如 kafka
+ 源码分析
+ [Java](http://fuseyism.com/classpath/doc/java/util/Queue-source.html)

+ Queue
+ java.util.Collection接口的子类型
+ 方法
+ add
+ 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
+ remove
+ 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
+ element
+ 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
+ offer
+ 添加一个元素并返回true 如果队列已满,则返回false
+ poll
+ 移除并返问队列头部的元素 如果队列为空,则返回null
+ peek
+ 返回队列头部的元素 如果队列为空,则返回null
+ PriorityQueue <file_sep># 如何实现浏览器内多个标签页之间的通信?
#### websocket
+ 建立在 TCP 协议之上,服务器端的实现比较容易。
+ 与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
+ 数据格式比较轻量,性能开销小,通信高效。
+ 可以发送文本,也可以发送二进制数据。
+ 没有同源限制,客户端可以与任意服务器通信。
+ 协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。
#### setInterval+cookie
+ 在页面A设置一个使用 setInterval 定时器不断刷新,检查 Cookies 的值是否发生变化,如果变化就进行刷新的操作。
#### localstorage
+ code
```javascript
window.onstorage = (e) => {console.log(e)}
// 或者这样
window.addEventListener('storage', (e) => console.log(e))
```
+ 注意
+ onstorage以及storage事件,针对都是非当前页面对localStorage进行修改时才会触发,当前页面修改localStorage不会触发监听函数。
+ 在对原有的数据的值进行修改时才会触发,比如原本已经有一个key会a值为b的localStorage,你再执行:localStorage.setItem('a', 'b')代码,同样是不会触发监听函数的。
#### html5浏览器的新特性SharedWorker
+ 普通的webworker直接使用new Worker()即可创建,这种webworker是当前页面专有的。
+ 还有种共享worker(SharedWorker),这种是可以多个标签页、iframe共同使用的。
+ SharedWorker可以被多个window共同使用,但必须保证这些标签页都是同源的(相同的协议,主机和端口号)<file_sep>### 定义
+ 略
### 链表操作摘要
+ 单链表插入、删除、查找
+ 单链表反转
+ 单链表反转从位置 m 到 n 的部分
+ 链表中环的检测
+ 合并两个有序的链表
+ 合并K个排序链表
+ 删除链表倒数第n个节点
+ 求链表的中间结点
+ 求链表环的入口节点
+ 两两交换链表中的节点
+ K 个一组翻转链表
### 对比
+ 
### 单链表
+ 图解
+ 
+ 插入/删除
+ 
### 循环链表
+ 
### 双向链表
+ 
### 双向循环链表
+ 
### **代码实现【结合图解看】**
#### 单链表插入、删除、查找
```javascript
class Node {
constructor (val){
this.val = val
this.next = null
}
}
class LinkedList {
constructor () {
this.head = new Node('head')
}
// 查找当前节点 - 根据val值
// 适用于链表中无重复节点
findNodeByVal (val) {
let curr = this.head
while(curr != null && curr.val != val){
curr = curr.next
}
return curr ? curr : -1
}
// 查找当前节点 - 根据索引/index
// 适用于链表中有重复节点
findNodeByIndex (index) {
let curr = this.head
let pos = 1
while(curr != null && pos !== index){
curr = curr.next
pos++
}
return curr != null ? curr : -1
}
// 插入
insert (newVal,val) {
let curr = this.findNodeByVal(val)
if(crr == -1) return false;
let newNode = new Node(newVal)
newNode.next = curr.next
curr.next = newNode
}
// 查找当前节点的前一个节点 - 根据val值
// 适用于链表中无重复节点
findNodePreByVal (nodeVal) {
let curr = this.head
while(curr.next != null && curr.next.val != nodeVal){
curr = curr.next
}
return curr != null ? curr : -1
}
// 查找当前节点的前一个节点 - 根据索引/index
// 适用于链表中无重复节点
// 同 findNodeByIndex,只要index传的是前一个节点的索引就对了
// 删除节点
remove (nodeVal) {
let needRemoveNode = findNodeByVal(nodeVal)
if(needRemoveNode == -1) return false;
let prevNode = this.findNodePre(nodeVal)
prevNode.next = needRemoveNode.next
}
// 遍历节点
display (){
let res = []
let curr = this.head
while(curr != null){
res.push(curr.val)
curr = curr.next
}
return res
}
}
```
#### 单链表反转
+ 解法一:迭代
+ 时间复杂度:O(n)
+ 空间复杂度:O(1)
+ 图解
+ 
+ 思路
+ 关键
+ 将当前节点的指针指向上一个节点
+ 然后更新当前节点和下一个节点的值即顺移
+ 技巧
+ 设置哨兵节点 null,初始化时将head节点指向null,下一步将next指向head
+ 重复以上动作直到当前节点为尾节点的节点null
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let prev = null;
let curr = head;
while(curr != null){
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
};
```
+ 解法二:尾递归
+ 思路
+ 其实就是解法一的简化版
+ >prev = curr;
curr = next;
+ 此解法将 上面放在递归里返回
+ 同理都是做将当前节点指向前一个节点的操作之后,来顺移更新前一个、当前、和下一个节点的操作
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let reverse = (prev,curr) => {
if(!curr)return prev;
let next = curr.next;
curr.next = prev;
return reverse(curr,next);
}
return reverse(null,head);
};
```
+ 解法三:递归
+ 思路
+ 关键是反转操作
+ 当前节点 head,下一个节点 head.next
+ head.next.next = head
+ 此处将原 head.next 指向head,即是反转
+ head.next = null
+ 此处将原 head 指向head.next的指针断开
+ 递归
+ 由编译器函数调用执行栈原理可知
+ **最先调用的函数会在递归过程中最后被执行,而最后调用的会最先执行**
+ 因此此题,**最先返回最后两个节点开始反转操作**
+ 依次从后面两两节点开始反转
+ 图解
+ 
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
// 如果测试用例只有一个节点 或者 递归到了尾节点,返回当前节点
if(!head || !head.next) return head;
// 存储当前节点的下一个节点
let next = head.next;
let reverseHead = reverseList(next);
// 断开 head ,如图闪电⚡️标记处
head.next = null;
// 反转,后一个节点连接当前节点
next.next = head;
return reverseHead;
};
```
+ 解法四:栈解
+ 思路
+ 既然是反转,那么符合栈先进后出的特点
+ 将原节点依次入栈
+ 出栈时,重新构造链表改变指向
+ 同样设置哨兵节点
+ 最后返回哨兵的next即为所求
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let tmp = head;
let tHead = new ListNode(0);
let pre = tHead;
let stack = [];
while(tmp){
stack.push(tmp.val);
tmp = tmp.next;
}
while(stack.length != 0){
pre.next = new ListNode(stack.pop());
pre = pre.next;
}
return tHead.next;
};
```
#### 单链表反转从位置 m 到 n 的部分
+ 解法一:迭代
+ 思路同单链表反转 - 解法一
+ 即将需要反转的 m到n 区间的链表反转,再重新连接首尾即可
```javascript
var reverseBetween = function(head, m, n) {
let dummy = new ListNode(0);
dummy.next = head;
let tmpHead = dummy;
// 找到第m-1个链表节点
for(let i = 0;i < m - 1;i++){
tmpHead = tmpHead.next;
}
// 206题解法一
let prev = null;
let curr = tmpHead.next;
for(let i = 0;i <= n - m;i++){
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// 将翻转的部分链表 和 原链表拼接
tmpHead.next.next = curr;
tmpHead.next = prev;
return dummy.next;
};
```
+ 解法二:迭代II
+ 解法一的 for -> while 版本
```javascript
var reverseBetween = function(head, m, n) {
if(head == null) return null;
let curr = head,prev = null;
while(m > 1){
prev = curr;
curr = curr.next;
m--;
n--;
}
let con = prev,tail = curr;
while(n > 0){
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
n--;
}
if(con != null){
con.next = prev;
}else{
head = prev;
}
tail.next = curr;
return head;
};
```
+ 解法三:迭代III
+ 思路
+ 关键是插入操作,每次将当前尾节点插入到全链表中第一个节点和第二个节点之间
+ 每次只手动更新tail节点,一次插入完成会自动更新第二个节点
+ 因此需要 pre、start、tail三个节点
+ 举个栗子
+ 1->2->3->4->null,m = 2,n = 4
+ 将节点 3 插入到 节点1和节点2 之间
+ 1->3->2->4->null
+ 将节点 4 插入到 节点1和节点3 之间
+ 1->4->3->2->null
+ 图解
+ 
```javascript
var reverseBetween = function(head, m, n) {
let dummy = new ListNode(0);
dummy.next = head;
let tmpHead = dummy;
for(let i = 0;i < m - 1;i++){
tmpHead = tmpHead.next;
}
let start = tmpHead.next;
let tail = start.next;
for(let i = 0;i < n - m;i++){
start.next = tail.next;
tail.next = tmpHead.next;
tmpHead.next = tail;
tail = start.next;
}
return dummy.next;
};
```
+ 解法四:递归
+ 参考题解
+ [步步拆解:如何递归地反转链表的一部分](https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/bu-bu-chai-jie-ru-he-di-gui-di-fan-zhuan-lian-biao/)
+ 题解原型
+ 思路同单链表反转 - 解法三
+ 解法三
+ 当n为链表长度时
+ 相当于反转链表 从1到n 个节点
```javascript
var reverseList = function(head) {
// 如果测试用例只有一个节点 或者 递归到了尾节点,返回当前节点
if(!head || !head.next) return head;
// 存储当前节点的下一个节点
let next = head.next;
let reverseHead = reverseList(next);
// 断开 head
head.next = null;
// 反转,后一个节点连接当前节点
next.next = head;
return reverseHead;
};
```
+ 或者这样写
+ 此时 tail 恒为 null
```javascript
var reverseList = function(head,n) {
if(!head || !head.next) return head;
let tail = null;
if(n == 1){
tail = head.next;
return head;
}
let next = head.next;
let reverseHead = reverseList(next,n-1);
head.next = tail;
next.next = head;
return reverseHead;
};
```
+ 当 n 小于链表长度时
+ 此时 tail 为 第 n+1 个节点
```javascript
var reverseList = function(head,n) {
if(!head || !head.next) return head;
let tail = null;
if(n == 1){
tail = head.next;
return head;
}
let next = head.next;
let reverseHead = reverseList(next,n-1);
head.next = tail;
next.next = head;
return reverseHead;
};
```
+ 上面两种情况均是默认从第1个节点开始反转,即题意中的 m == 1 时
+ tail 相当于 反转前的头节点反转后不一定是最后一个节点,因为此时n != 链表长度
+ 所以要记录最后一处反转的位置,用以连接被反转的部分
+ 如果是整条链表都反转,head就成了最后一个节点,它的next自然恒为null
+ 图解
+ 
+ 思路
+ 既然默认m=1,n未知的解法出来了
+ 那么如题,m 未知的话,每次减1递归就好了
```javascript
var reverseBetween = function(head, m, n) {
let nextTail = null;
let reverseN = (head,n) => {
if(n == 1){
nextTail = head.next;
return head;
}
let last = reverseN(head.next,n-1);
head.next.next = head;
head.next = nextTail;
return last;
}
if(m == 1){
return reverseN(head,n);
}
head.next = reverseBetween(head.next,m-1,n-1);
return head;
};
```
#### 链表中环的检测
+ 解法一:数组判重
+ 环中两个节点相遇,说明在不同的时空内会存在相遇的那一刻,过去与未来相遇,自己和前世回眸,即是重复
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
let res = [];
while(head != null){
if(res.includes(head)){
return true;
}else{
res.push(head);
}
head = head.next;
}
return false;
};
```
+ 解法二:标记法
+ 思路
+ 一路遍历,走过的地方,标识走过,当下次再遇到,说明鬼打墙了,在绕圈子!!!妈呀,吓死宝宝👶了,😭
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
while(head && head.next){
if(head.flag){
return true;
}else{
head.flag = 1;
head = head.next;
}
}
return false;
};
```
+ 解法三:双指针
+ 思路
+ 在一个圆里,运动快的点在跑了n圈后,一定能相遇运动慢的点
+ 对应链表,就是两个指针重合
+ 如果不是圆,哪怕是非闭合的圆弧,快点一定先到达终点🏁,则说明不存在环
+ 对应链表,就是结尾指针指向null
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if(!head || !head.next) return false;
let fast = head.next;
let slow = head;
while(fast != slow){
if(!fast || !fast.next){
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
};
```
#### 合并两个有序的链表
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
```
+ 解法一:双指针
+ 思路:归并排序的核心
```javascript
let mergeTwoLists = (l1,l2) => {
let preHead = new ListNode(-1);
let prevNode = preHead;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
prevNode.next = l1;
l1 = l1.next;
}else{
prevNode.next = l2;
l2 = l2.next;
}
prevNode = prevNode.next;
}
prevNode.next = l1 ? l1 : l2;
return preHead.next;
}
```
+ 解法二:分治
```javascript
let mergeTwoLists = (l1,l2) => {
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val <= l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
```
#### 合并K个排序链表
+ [戳看👇](https://github.com/Alex660/leetcode/blob/master/leetCode-0-023-merge-k-sorted-lists.md)
#### 删除链表倒数第n个节点
+ 解法一:单链表经典操作
```javascript
var removeNthFromEnd = function(head, n) {
// 反转链表
let prev = null;
let curr = head;
var reverse = (prev,curr) => {
while(curr){
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev
}
let newHead = reverse(prev,curr);
// 边界条件处理
if(n == 1){
return reverse(null,newHead.next);
}
// 查询节点
let findNodeByIndex = (currSearchTmp,n) => {
let pos = 1;
while(currSearchTmp && pos != n){
currSearchTmp = currSearchTmp.next
pos++
}
return currSearchTmp
}
let currSearch = findNodeByIndex(newHead,n);
// 查找前一个节点
let pre = findNodeByIndex(newHead,n-1);
// 删除节点
pre.next = currSearch.next;
let prevNeed = null;
let currNeed = newHead;
// 反转回来
return reverse(prevNeed,currNeed)
};
```
+ 解法二:两次遍历
+ 时间复杂度:O(n)
+ 空间复杂度:O(1)
+ 思路
+ 删除正数第n个节点
+ 遍历链表,直到第n-1个节点,将第n-1个节点指向第n个节点即完成了删除操作
+ 通过索引位置自减,直到0,就可以找到
+ 删除倒数第n个节点
+ 如解法一
+ 我们通过反转链表来删除第n个节点,即是删除了倒数第n个节点
+ 查找节点
+ 通过遍历位置得到
+ 此处不需反转
+ 举个栗子
+ 1 -> 2 -> 3 -> 4 -> 5
+ 删除倒数第2个节点
+ 等价于
+ 删除正数第4(5 - 2 + 1)个节点
+ **因此此题转换成了删除正数第(L - n + 1)个节点**
+ L为链表长度,需要通过遍历算得
+ 然后解法同正数的相同即可
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let preHead = new ListNode(-1);
preHead.next = head;
let len = 0;
let first = head;
while(first){
len++;
first = first.next;
}
len -= n;
first = preHead;
while(len != 0){
len--;
first = first.next;
}
first.next = first.next.next;
return preHead.next;
};
```
+ 解法三:双指针
+ 时间复杂度:O(n)
+ 空间复杂度:O(1)
+ 思路
+ 设快慢两个指针
+ 1、快指针先移n个节点
+ 2、快、慢指针一起移动,使得两指针之间一直保持n个节点
+ 2.1、当指针到达链表底了,将慢指针的指针指向它的下下一个指针
+ 2.2、慢指针的下一个指针即为要删除的节点
+ 边界
+ 当要删除的节点是head时,需要设置哨兵节点,即增设一个位于当前头部节点的前一个值为null的哨兵节点
+ 最后返回哨兵节点的next即为所求
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let preHead = new ListNode(-1);
preHead.next = head;
let fast = preHead;
let slow = preHead;
while(n != 0){
fast = fast.next;
n--;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return preHead.next;
};
```
#### 求链表的中间结点
+ 求第二个中间节点,如[1,2,3,4],返回3
+ 解法一:双指针
```javascript
var middleNode = function(head) {
let fast = head;
let slow = head;
while(fast && fast.next){
fast = fast.next.next;
slow = slow.next;
}
return slow;
};
```
+ 解法二:两次遍历
+ 参看删掉链表倒数第n个节点 - 解法二
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
let len = 0;
let tmpHead = head;
while(tmpHead){
len++;
tmpHead = tmpHead.next;
}
let center = (len >> 1);
let pos = 0;
tmpHead = head;
while(center--){
tmpHead = tmpHead.next;
}
return tmpHead;
};
```
+ 解法三:数组
+ 解法二的简化版
+ 找到了中间节点的位置,那么可以想到利用数组下标取值实现
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
let len = 0;
let tmpHead = head;
let res = [];
while(tmpHead){
res[len++] = tmpHead;
tmpHead = tmpHead.next;
}
return res[len >> 1];
};
```
+ 求第一个中间节点,如[1,2,3,4],返回2
+ 解法一:双指针
```javascript
var middleNode = function(head) {
let fast = head;
let slow = head;
while(fast.next && fast.next.next){
fast = fast.next.next;
slow = slow.next;
}
return slow;
};
```
#### 求链表环的入口节点
+ 解法一:标记法
+ 思路同链表中环的检测 - 解法二
```javascript
var detectCycle = function(head) {
while(head && head.next){
if(head.flag){
return head;
}else{
head.flag = 1;
head = head.next;
}
}
return null;
};
```
+ 解法二:数组判重
+ 思路同链表中环的检测 - 解法一
```javascript
var detectCycle = function(head) {
let res = [];
while(head != null){
if(res.includes(head)){
return head;
}else{
res.push(head);
}
head = head.next;
}
return null;
};
```
+ 解法三:双指针
+ 思路
+ 图解
+ 
+ 公式
+ S:初始点到环的入口点A的距离
+ m:环的入口点到快慢双指针在环内的相遇点B的距离
+ L:环的周长
+ 如果 S == L - m
+ 那么可以设置两个步数相同的指针分别从,链表入口节点和快慢双指针相遇节点同时出发
+ 当他们第一次相遇时,即是环的入口节点A所在
+ 因此,我们需要证明 S == L - m
+ 已知快指针的行走距离是慢指针行走距离的两倍
+ 那么他们在环内第一次相遇时
+ 慢指针走过了:S + xL
+ 快指针走过了:S + yL
+ 那么,设C为指针走过的距离
+ C(快) - C(慢) = (y-x)L = nL
+ C(慢) = S + m
+ 因为C(快) == 2C(慢)
+ 所以C(快) - C(慢) == C(慢)
+ S + m = nL
+ S = nL - m
+ 而L为环的周长 ,n为任意正整数
+ 所以 S == L - m 成立
+ 解即为反证法的操作
+ 判断链表是否有环
+ 思路同链表中环的检测 - 解法三
```javascript
var detectCycle = function(head) {
if(!head || !head.next) return null;
let slow = head;
let fast = head;
let start = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
while (start != slow) {
slow = slow.next;
start = start.next;
}
return slow;
}
}
return null;
};
```
#### 两两交换链表中的节点
+ 解法一:非递归
+ 时间复杂度:O(n)
+ 空间复杂度:O(1)
+ 思路
+ 添加一个哨兵节点
+ 三个节点外加一个哨兵节点之间作指针指向变换操作
+ 图解
+ 
```javascript
var swapPairs = function(head) {
let thead = new ListNode(0);
thead.next = head;
let tmp = thead;
while(tmp.next != null && tmp.next.next != null){
let start = tmp.next;
let end = start.next;
tmp.next = end;
start.next = end.next;
end.next = start;
tmp = start;
}
return thead.next;
};
```
+ 解法二:递归
+ 时间复杂度:O(n)
+ 空间复杂度:O(n)
+ 思路
+ 终止
+ 同解法一:至少三个节点之间才可以互换
+ 只有一个节点或没有节点,返回此节点
+ 交换
+ 设需要交换的两个节点为head、next
+ head -> next -> c -> ...
+ head -> c -> ... && next -> head
+ next -> head -> c -> ...
+ head 连接( -> )后面交换完成的子链表
+ next 连接( -> )head 完成交换
+ 对子链表重复上述过程即可
```javascript
var swapPairs = function(head) {
if(head == null || head.next == null){
return head;
}
// 获得第 2 个节点
let next = head.next;
// next.next = head.next.next
// 第1个节点指向第 3 个节点,并从第3个节点开始递归
head.next = swapPairs(next.next);
// 第2个节点指向第 1 个节点
next.next = head;
// 或者 [head.next,next.next] = [swapPairs(next.next),head]
return next;
};
```
#### K 个一组翻转链表
+ 解法一:迭代
+ 思路同单链表反转 - 解法一
+ 区别
+ 限制k个
+ 用计数实现,实时更新链表需要反转部分的头、尾节点
```javascript
var reverseKGroup = function(head, k) {
let cur = head;
let count = 0;
// 求k个待反转元素的首节点和尾节点
while(cur != null && count != k){
cur = cur.next;
count++;
}
// 足够k个节点,去反转
if(count == k){
// 递归链接后续k个反转的链表头节点
cur = reverseKGroup(cur,k);
while(count != 0){
count--;
// 反转链表
let tmp = head.next;
head.next = cur;
cur = head;
head = tmp;
}
head = cur;
}
return head;
};
```
+ 解法二:递归 II
+ 同解法一
+ 区别
+ while改成for
```javascript
var reverseKGroup = function(head, k) {
if(!head) return null;
// 反转链表
let reverse = (a,b) => {
let pre;
let cur = a;
let next = b;
while(cur != b){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
// 反转区间a-b的k个待反转的元素
let a = head;
let b = head;
for(let i = 0;i < k;i++){
// 不足k个,不需要反转
if(!b) return head;
b = b.next;
}
// 反转前k个元素
let newHead = reverse(a,b);
// 递归链接后续反转链表
a.next = reverseKGroup(b,k);
return newHead;
};
```
+ 解法三:栈解
+ 思路同单链表反转 - 解法四
+ 反转k个
```javascript
var reverseKGroup = function(head, k) {
let stack = [];
let preHead = new ListNode(0);
let pre = preHead;
// 循环链接后续反转链表
while(true){
let count = 0;
let tmp = head;
while(tmp && count < k){
stack.push(tmp);
tmp = tmp.next;
count++;
}
// 不够k个,直接链接剩下链表返回
if(count != k){
pre.next = head;
break;
}
// 出栈即是反转
while(stack.length > 0){
pre.next = stack.pop();
pre = pre.next;
}
pre.next = tmp;
head = tmp;
}
return preHead.next;
};
```<file_sep>## webpack 热更新原理
### 参考文献
+ [Webpack HMR 原理解析](https://zhuanlan.zhihu.com/p/30669007)
+ [彻底搞懂并实现webpack热更新原理](https://segmentfault.com/a/1190000020310371)
+ [Webpack 热更新实现原理分析](https://zhuanlan.zhihu.com/p/30623057)
#### 参考答案
+ 图解一
+ 
+ 1、第一步,在 webpack 的 watch 模式下,文件系统中某一个文件发生修改,webpack 监听到文件变化,
+ 根据配置文件对模块重新编译打包,并将打包后的代码通过简单的 JavaScript 对象保存在内存中。
+ 2、第二步是 webpack-dev-server 和 webpack 之间的接口交互,
+ 而在这一步,主要是 dev-server 的中间件 webpack-dev-middleware 和 webpack 之间的交互,webpack-dev-middleware 调用 webpack 暴露的 API对代码变化进行监控,并且告诉 webpack,将代码打包到内存中。
+ 3、第三步是 webpack-dev-server 对文件变化的一个监控,这一步不同于第一步,并不是监控代码变化重新打包。
+ 当我们在配置文件中配置了devServer.watchContentBase 为 true 的时候,Server 会监听这些配置文件夹中静态文件的变化,变化后会通知浏览器端对应用进行 live reload。
+ 注意,这儿是浏览器刷新,和 HMR 是两个概念。
+ 4、第四步也是 webpack-dev-server 代码的工作,该步骤主要是通过 sockjs(webpack-dev-server 的依赖)在浏览器端和服务端之间建立一个 websocket 长连接,将 webpack 编译打包的各个阶段的状态信息告知浏览器端,同时也包括第三步中 Server 监听静态文件变化的信息。
+ 浏览器端根据这些 socket 消息进行不同的操作。
+ 当然服务端传递的最主要信息还是新模块的 hash 值,后面的步骤根据这一 hash 值来进行模块热替换。
+ 5、webpack-dev-server/client 端并不能够请求更新的代码,也不会执行热更模块操作,而把这些工作又交回给了 webpack,
+ webpack/hot/dev-server 的工作就是根据 webpack-dev-server/client 传给它的信息以及 dev-server 的配置决定是刷新浏览器呢还是进行模块热更新。
+ 当然如果仅仅是刷新浏览器,也就没有后面那些步骤了。
+ 6、HotModuleReplacement.runtime 是客户端 HMR 的中枢,它接收到上一步传递给他的新模块的 hash 值,它通过 JsonpMainTemplate.runtime 向 server 端发送 Ajax 请求,
+ 服务端返回一个 json,该 json 包含了所有要更新的模块的 hash 值,获取到更新列表后,
+ 该模块再次通过 jsonp 请求,获取到最新的模块代码。这就是上图中 7、8、9 步骤。
+ 7、而第 10 步是决定 HMR 成功与否的关键步骤,在该步骤中,HotModulePlugin 将会对新旧模块进行对比,决定是否更新模块,
+ 在决定更新模块后,检查模块之间的依赖关系,更新模块的同时更新模块间的依赖引用。
+ 8、最后一步,当 HMR 失败后,回退到 live reload 操作,
+ 也就是进行浏览器刷新来获取最新打包代码。
+ 图解二
+ 
+ webpack-dev-server 解析
+ 使用express启动本地服务,当浏览器访问资源时对此做响应。
+ express负责搭建请求路由服务。
+ 服务端和客户端使用websocket实现长连接
+ webpack监听源文件的变化,即当开发者保存文件时触发webpack的重新编译。
+ 每次编译都会生成hash值、已改动模块的json文件、已改动模块代码的js文件
+ 编译完成后通过socket向客户端推送当前编译的hash戳
+ 客户端的websocket监听到有文件改动推送过来的hash戳,会和上一次对比
+ 一致则走缓存
+ 不一致则通过ajax和jsonp向服务端获取最新资源
+ 使用内存文件系统去替换有修改的内容实现局部刷新
+ webpack-dev-middleware
+ 主要负责构建内存文件系统,把webpack的 OutputFileSystem 替换成 InMemoryFileSystem。
+ 同时作为Express的中间件拦截请求,从内存文件系统中把结果拿出来。
+ 参考解答一:
+ 1、当修改了一个或多个文件;
+ 2、文件系统接收更改并通知webpack;
+ 3、webpack重新编译构建一个或多个模块,并通知HMR服务器进行更新;
+ 4、HMR Server 使用webSocket通知HMR runtime 需要更新,HMR运行时通过HTTP请求更新jsonp;
+ 5、HMR运行时替换更新中的模块,如果确定这些模块无法更新,则触发整个页面刷新。
+ 调用 module.hot.accept() 完成热更新
+ 参考解答二:
+ 1、启动dev-server,webpack开始构建,在编译期间会向 entry 文件注入热更新代码;
+ 2、Client 首次打开后,Server 和 Client 基于Socket建立通讯渠道;
+ 3、修改文件,Server 端监听文件发送变动,webpack开始编译,直到编译完成会触发"Done"事件;
+ 4、Server通过socket 发送消息告知 Client;
+ 5、Client根据Server的消息(hash值和state状态),通过ajax请求获取 Server 的manifest描述文件;
+ 6、Client对比当前 modules tree ,再次发请求到 Server 端获取新的JS模块;
+ 7、Client获取到新的JS模块后,会更新 modules tree并替换掉现有的模块;
+ 8、最后调用 module.hot.accept() 完成热更新;<file_sep>## JS编程实现简单模板引擎变量替换
### 解题关键
+ replace/正则
### 参考文献
+ [js简单前端模板引擎实现](https://segmentfault.com/a/1190000010366490)
+ [JavaScript模板引擎实现原理实例详解](https://www.jb51.net/article/152760.htm)
#### code
```javascript
let render = (str) => {
return (obj) => {
str = str.replace('YY',obj.YY);
str = str.replace('MM',obj.MM);
str = str.replace('DD',obj.DD);
return str;
}
}
// 栗子
const YY = '2020';
const MM = '02';
const DD = '04';
const str = render('YY-MM-DD')({YY,MM,DD});
console.log(str);// 2020-02-04
```<file_sep>#### 实现ES6的class语法
```javascript
function inherit(subType,superType) {
subType.prototype = Object.create(superType.prototype,{
constructor: {
enumerable:false,
configurable:true,
writable:true,
value:subType
}
})
Object.setPrototypeOf(subType,superType)
}
``` <file_sep>## http1.0、1.1、2.0 协议的区别
### 参考文献
+ [阮一峰http协议入门](http://www.ruanyifeng.com/blog/2016/08/http.html)
#### 前言
+ HTTP 是基于 TCP/IP 协议的应用层协议;它不涉及数据包(packet)传输,主要规定了客户端和服务器之间的通信格式,默认使用80端口。
#### http0.9
+ 只支持一个命令GET
+ 服务器只能返回HTML格式的字符串,不能回应别的格式。
#### http1.0
+ 支持GET、POST、HEAD命令
+ 任何格式的内容都可以发送
+ 文字
+ 图像
+ 视频
+ 二进制文件
+ 每次通信必须包括头信息(HTTP header)
+ 其它新增功能
+ 状态码(status code)
+ 多字符集支持
+ 多部分发送(multi-part type)
+ 权限(authorization)
+ 缓存(cache)
+ 内容编码(content encoding)
+ 缺点
+ 无连接
+ 每个TCP连接只能发送一个请求,浏览器再请求必须再新建一个连接
+ 影响
+ 无法复用连接
+ 网络利用率非常低,每次请求都要三次握手四次挥手(一次tcp连接)
+ 队头阻塞
+ 前一个请求响应之前,后一个请求不能发送,如果阻塞,后面也会阻塞
+ 无状态
+ 服务器不跟踪不记录请求过的状态
+ 改进
+ 可以借助cookie/session机制来做身份认证和状态记录
#### http1.1
+ 引入持久连接
+ 默认不关闭,不用声明Connection:keep-alive
+ 管道机制(pipelining)
+ 在同一个TCP连接里可以发送多个请求
+ 缓存处理
+ 新增字段cache-control
+ 断点传输
+ 上传/下载
+ 在 Header 里两个参数实现的,客户端发请求时对应的是 Range 服务器端响应时对应的是 Content-Range
+ 其它功能
+ PUT
+ PATCH
+ HEAD
+ OPTIONS
+ DELETE
+ 客户端请求头信息增加了Host字段,用来制定服务器的域名
+ 可以将请求发往同一台服务器上的不同网站,为虚拟主机的兴起打下了基础。
+ 缺陷
+ 即使多个请求可以在同一个TCP连接里,但是所有数据通信都是按次序进行的;服务器处理完前一个回应,才会进行下一个回应,依旧会造成队头阻塞
+ 改进
+ 减少请求数
+ 同时多开持久连接
#### http2
+ SPDY协议,谷歌2009年自主研发的主要解决1.1效率不高的问题;在2.0中得到继承
+ 二进制协议
+ 1.1头信息必须是文本(ASCII编码)
+ 2版头信息和数据体都是二进制,统称为桢(frame)
+ 多工(Multiplexing)/多路复用
+ HTTP/2 复用TCP连接,在一个连接里,客户端和浏览器都可以同时发送多个请求或回应,而且不用按照顺序一一对应,这样就避免了"队头堵塞"。
+ 数据流
+ HTTP/2 将每个请求或回应的所有数据包,称为一个数据流(stream)。每个数据流都有一个独一无二的编号。数据包发送的时候,都必须标记数据流ID,用来区分它属于哪个数据流。另外还规定,客户端发出的数据流,ID一律为奇数,服务器发出的,ID为偶数。
+ 客户端还可以指定数据流的优先级。优先级越高,服务器就会越早回应。
+ 头信息压缩
+ 服务器推送
#### 区别纵览
+ 缓存
+ 1.0
+ header:if-Modified-Since/Last-Modefied
+ 使用绝对时间戳,精确到秒
+ 304:Not Modified
+ Expires
+ Pragma:no-cache
+ 1.1
+ Entity tag
+ If-Unmodified-Since
+ If-Match
+ If-None-Match
+ Cache-Control
+ max-age
+ 支持相对时间戳
+ private/no-store
+ no-transform
+ 阻止Proxy进行任何改变响应的行为
+ 长连接
+ 1.0
+ 需要设置keep-alive,且各大浏览器实现有所不同
+ 1.1
+ 默认支持
+ 2
+ 默认支持
+ HOST域、状态码
+ 1.0
+ 不支持、无状态
+ 1.1
+ 支持、新增24个状态码
+ 2
+ 支持、继承
+ 多路复用/首部数据压缩/服务器推送
+ 2
+ 支持<file_sep># div里包img图片下方有空白的问题
```javascript
<div class="banner">
<img src="https://profile.csdnimg.cn/7/0/4/3_qq_34400736"/>
</div>
```
### 原理
+ 图片的display属性默认是inline,
+ 而这个属性的vertical-align的默认值是baseline。
+ 所以就会出现上图的情况(图片底部出现一个小留白区域)。
#### 解法
+ 把img变成块状元素,所以是否需要留白,可以用过padding来设置。
```css
img {
display: block;
}
```
+ 直接修改vertical-align属性值
```css
img {
vertical-align: middle/bottom;
}
```
+ 把img元素的底部外边距改成负值
```css
img {
margin-bottom: -4px;
}
```
+ 出现留白的原因是因为垂直对齐的方式所导致的,所以可以修改父元素的font-size,把父元素的字体大小改为0,所以就没什么垂直对齐所言
```css
.banner {
font-size: 0;
}
```
+ 把img的父元素行高设成0
```css
.banner {
line-height: 0;
}
```<file_sep># 函数防抖与节流
## 摘要
+ 定义
+ 思路
+ 实现
### 防抖
+ 定义
+ 触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间
+ 思路
+ 每次触发事件时都取消之前的延时调用方法
+ 实现
```javascript
let debounce = (fn,wait = 500) => {
let timeout = null;
return (arguments) => {
// 每次触发清除上一个执行的函数
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this,arguments);
},wait)
}
}
let sayHi = () => {
console.log('防抖成功');
}
let inp = document.getElementById('inp');
// 防抖
inp.addEventListener('input',debounce(sayHi));
```
#### 节流
+ 定义
+ 高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
+ 思路
+ 每次触发事件时都判断当前是否有等待执行的延时函数
+ 实现
```javascript
let throttle = (fn,gapTime = 2000) => {
let lastTime = null;
return (arguments) => {
let nowTime = Date.now();
if(nowTime - lastTime > gapTime || !lastTime){
fn.apply(this,arguments);
lastTime = nowTime;
}
}
}
let sayHi = (e) => {
console.log('节流成功:'+document.documentElement.clientHeight)
}
window.addEventListener('resize',throttle(sayHi));
``` <file_sep># 摘要
+ Trie树
+ 并查集
+ 高级搜索
+ 高级树
+ 课后思考
### Trie
+ Trie 树,也叫“字典树”,“单词查找树”或“键树”。顾名思义,它是一个树形结构。
+ 它是一种专门处理字符串匹配的数据结构,用来解决在一组字符串集合中快速查找某个字符串的问题。
+ 优点
+ 最大限度地减少无谓的字符串比较,查找效率比哈希表高。
+ 实现题型
+ [208. 实现 Trie (前缀树)](https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/208-shi-xian-trie-qian-zhui-shu-by-alexer-660/)
+ 应用题型
+ [212. 单词搜索 II](https://leetcode-cn.com/problems/word-search-ii/solution/212-dan-ci-sou-suo-ii-by-alexer-660/)
+ [其它应用](https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shi-xian-trie-qian-zhui-shu-by-leetcode/)
+ 地址或其它搜索栏的自动补全功能
+ 拼写检查
+ IP路由(最长前缀匹配)
+ T9(九宫格)打字预测
+ 单词游戏
+ 核心思想
+ 空间换时间
+ 利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的
+ 代码模板
```python
class Trie(object):
def __init__(self):
self.root = {}
self.end_of_word = "#"
def insert(self, word):
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end_of_word] = self.end_of_word
def search(self, word):
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return self.end_of_word in node
def startsWith(self, prefix):
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
```
### 并查集
+ 适用场景
+ 组团、配对问题
+ 并查集
+ 是一种树型的数据结构,用来**处理一些不相交集合(Disjoint Sets)的合并及查询问题**
+ 联合-查找算法(union-find algorithm),规范了对此数据结构的操作
+ Find:**确定元素属于哪一个子集**
+ 方法是不断向上查找它的根节点
+ 因而可以**被用来确定两个元素是否属于同一子集**的问题
+ Union:**将两个子集合并成同一个集合**
+ 初始化:
+ 每个元素是自己的集合代表,即自己是一个集合,我为自己代言;
+ 
+ 设当前元素为**代表**
+ Find(x)返回x所属集合的代表
+ Union(Find(x<sub>1</sub>),Find(x<sub>2</sub>))
+ **按秩合并两个不相交集合**
+ **求连通分量**
+ 求解
+ 并查集森林
+ 是一种**将每一个集合以树表示的数据结构**,**每一个节点保存着它的父节点引用地址**
+ **每个集合的代表即是集合的根节点**
+ **查找**
+ 根据父节点引用向上进行搜索直到root根节点
+ **联合**
+ 将两棵树合并到一起,即将其中一棵树的根连接到另一棵树的根的操作
+ **方法模板**
```javascript
let MakeSet = (x) => {
parent[x] = x;
}
let find = (x) => {
if(parent[x] == x){
return x;
}
return find(parent[x])
}
let union = (x,y) => {
let rootX = find(x);
let rootY = find(y);
if(rootX == rootY){
return;
}
parent[rootX] = rootY;
}
```
+ 优化方法
+ **按秩合并**
+ 
+ 这里的**秩**可以理解为**树的深度**
+ **总是将更小的树连接到更大的树上,即改变小根节点到大根节点上**
+ 初始化
+ 单元素大树秩定义为0
+ 当两棵秩相同时,均+1
+ 效率
+ 提升至O(logn)
+ **优化方法模板A**
```javascript
let MakeSet = (x) => {
parent[x] = x;
rank[x] = 1;
}
let find = (x) => {
if(parent[x] == x){
return x;
}
return find(parent[x])
}
let union = (x,y) => {
let rootX = find(x);
let rootY = find(y);
if(rank[rootX] > rank[rootY]){
parent[rootY] = rootP;
}else if(rank[rootX] < rank[rootY]){
parent[rootX] = rootY;
}else{
parent[rootY] = rootX;
rank[rootX]++;
}
}
```
+ **路径压缩**
+ 
+ **处于同一路径上的节点都直接连接到根节点上**
+ **优化方法模板B**
```javascript
let MakeSet = (x) => {
parent[x] = x;
}
let find = (x) => {
while(parent[x] != x){
parent[x] = Find(parent[x]);
}
return parent[x];
}
let union = (x,y) => {
let rootX = find(x);
let rootY = find(y);
if(rootX == rootY){
return;
}
parent[rootX] = rootY;
}
```
+ 总结:将以上两种优化方法合并,执行时间提升客观
+ 这两种方法的优势互补,同时使用二者的程序每个操作的平均时间仅为
+ $$O(\alpha (n))$$
+ 实际上,这是渐近最优算法
+ 总结下包含**路径压缩**和**按秩合并**两种优化的最优代码模板来求解并查集问题
```javascript
/**
* @param {number[][]} M
* @return {number}
*/
var findCircleNum = function(M) {
let n = M.length;
if(n == 0){
return 0;
}
// 求连通分量
let count = n;
// 给每个元素单集建立秩
let rank = new Array(n);
let find = (p) => {
while( p != parent[p]){
// 路径压缩
// 区别与上述模版,很巧妙,通过直接将当前节点的父节点直接指向爷爷节点
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
// 查询两个相交集合
let union = (p,q) => {
let rootP = find(p);
let rootQ = find(q);
// 集合相交则不合并
if(rootP == rootQ){
return;
}
// 按秩合并
if(rank[rootP] > rank[rootQ]){
parent[rootQ] = rootP;
}else if(rank[rootP] < rank[rootQ]){
parent[rootP] = rootQ;
}else{
parent[rootQ] = rootP;
// 相同的秩都加1
rank[rootP]++;
}
// 求连通分量,每合并两个集合,即整体减少一个独立集合
count--;
}
let parent = new Array(n);
for(let i = 0;i < n;i++){
parent[i] = i;
// 初始化秩
rank[i] = 1;
}
// 并查集搜索开始
for(let i = 0;i < n;i++){
for(let j = 0; j < n;j++){
if(M[i][j] == 1){
union(i,j);
}
}
}
// 返回连通分量结果
return count;
};
```
+ 三要素
+ makeSet(s):建立一个新的并查集,其中包含n个单元素集合
+ unionSet(x,y):将元素x和元素y所在的集合合并
+ 若不相交则不合并
+ 若相交
+ 按秩合并为优化手段
+ 可用于求连通分量
+ find(x):
+ 找到元素x所在的集合的代表
+ 路径压缩为优化手段
+ 可用于判断两个元素是否在同一个子集
+ 练习题型
+ [200. 岛屿数量-解法三](https://leetcode-cn.com/problems/number-of-islands/solution/200-dao-yu-shu-liang-by-alexer-660/)
+ [547. 朋友圈](https://leetcode-cn.com/problems/friend-circles/solution/547-peng-you-quan-by-alexer-660/)
### 高级搜索
+ 减枝
+ 斐波那契数列问题
+ 双向BFS
+ 从过到右的BFS+从右到左的BFS
+ 启发式搜索(A<sup>*</sup>)
+ 估价函数
+ 启发式函数: h(n),它用来评价哪些结点最有希望的是一个我们要找的结点,
+ h(n) 会返回一个非负实数,也可以认为是从结点n的目标结点路径的估计成本。
+ 启发式函数是一种告知搜索方向的方法。
+ 它提供了一种明智的方法来猜测哪个邻居结点会导向一个目标。
+ 基于 BFS 代码
```python
def BFS(graph, start, end):
queue = []
queue.append([start])
visited.add(start)
while queue:
node = queue.pop() # can we add more intelligence here ?
visited.add(node)
process(node)
nodes = generate_related_nodes(node)
queue.push(nodes)
```
+ A* search
```python
def AstarSearch(graph, start, end):
pq = collections.priority_queue() # 优先级 —> 估价函数
pq.append([start])
visited.add(start)
while pq:
node = pq.pop() # can we add more intelligence here ?
visited.add(node)
process(node)
nodes = generate_related_nodes(node)
unvisited = [node for node in nodes if node not in visited]
pq.push(unvisited)
```
### 高级树
+ 树
+ 父、子节点
+ 根节点、兄弟节点、叶子节点或叶节点
+ 高度、深度、层
+ 二叉树
+ 根节点、左子节点、右子节点
+ 满二叉树
+ 叶子节点全部在最底层
+ 除叶子节点外,每个节点都有左右两个子节点
+ 完全二叉树
+ 叶子节点都在最底下两层
+ 最后一层的叶子节点都靠左排列
+ 且除了最后一层,其它层的节点个数都要达到最大
+ 存储
+ 链式存储法
+ 顺序存储法
+ 遍历
+ 图解

+ 模板
```python
def preorder(self, root):
if root:
self.traverse_path.append(root.val)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
if root:
self.inorder(root.left)
self.traverse_path.append(root.val)
self.inorder(root.right)
def postorder(self, root):
if root:
self.postorder(root.left)
self.postorder(root.right)
self.traverse_path.append(root.val)
```
+ 二叉搜索树【Binary Search Tree】
+ 也叫有序二叉树、排序二叉树
+ 是一颗空树
+ 也是一颗这样的树
+ 1、左子树上所有子节点均小于它的根节点的值
+ 2、右子树上所有子节点均大于它的根节点的值
+ 3、左、右子树也分别为二叉查找树
+ 应用
+ 中序遍历即升序排列
+ AVL树
+ 平衡因子(Balance Factor)
+ 是它的左子树和右子树的高度差的绝对值不能超过1
+ balacnce factor = {-1,0,1}
+ 一颗平衡的二叉搜索树
+ 通过四种基础的旋转操作来进行平衡
+ 左旋【右右子树】

+ 右旋【左左子树】

+ 左右旋【左右子树】
+ 左旋+右旋


+ 右左旋【右左子树】
+ 右旋+左旋


+ 复杂示例

+ 缺点
+ 结点需要存储额外信息、且调整次数频繁
+ 红黑树
+ Red-black Tree
+ 一种近似平衡的二叉搜索树(Binary Search Tree)
+ 性质
+ **每个结点的左右子树的高度差小于两倍**
+ ***从根到叶子的最长的可能路径不多于最短的可能路径的两倍长***
+ 根节点是黑色
+ 每个叶节点(这里指左右子节点的最后的空节点)是看不到的黑色
+ 两个相邻节点不能都是红色
+ 从任一节点到其每个叶子节点的所有路径都包含相同数目的黑色节点
+ AVL树和红黑树的区别
+ AVL trees provide faster lookups than Red Black Trees because they are more strictly balanced.
+ AVL树有更加快速的查询(lookups) ,因为它是严格按照平衡的(子树高度差绝对值为1)
+ Red Black Trees provide faster insertion and removal operations than AVL trees as fewer rotations are done due to relatively relaxed balancing.
+ 红黑树提供了更快的插入和删除操作,因为AVL旋转操作更多,红黑树相对少一点,是一颗近似平衡树
+ AVL trees store balance factors or heights with each node, thus requires storage for an integer per node whereas Red Black Tree requires only 1 bit of information per node.
+ AVL每个节点要存 factors 和 heights额外信息,需要更多内存,红黑树只要1个bit 0或1 表示红色还是黑色节点
+ Red Black Trees are used in most of the language libraries like map, multimap, multisetin C++ whereas AVL trees are used in databases where faster retrievals are required.
+ 读操作多,写入操作少时,用AVL
+ 写入操作大于等于一半时,用红黑树好
### 课后思考
+ [212. 单词搜索 II](https://leetcode-cn.com/problems/word-search-ii/solution/212-dan-ci-sou-suo-ii-by-alexer-660/)用Trie树实现的时间复杂度
+ 暴力法时间复杂度分析(看视频)
+ O(N*m*m*4<sup>k</sup>)
+ Trie树时间复杂度分析
+ 递归四连通判断:O(m * n * 4<sup>k</sup>)
+ 构建Trie树:O(n * k)
+ 外层遍历:O(n)
+ 内存单词字符循环建立子节点:O(k)
+ 合计:O(n * k + m * n * 4<sup>k</sup>)
+ 即为O(m * n * 4<sup>k</sup>)
+ 双端BFS模板总结
+ 单端模版
```python
def BFS(graph, start, end):
queue = []
queue.append([start])
while queue:
node = queue.pop()
visited.add(node)
process(node)
nodes = generate_related_nodes(node)
queue.push(nodes)
# other processing work
...
```
+ 双端模版
+ Set 替换 Queue
```javascript
let double_bfs = (start,end) => {
let startSet = new Set();
let endSet = new Set();
startSet.add(start);
endSet.add(end);
while(startSet.size > 0){
let next_startSet = new Set();
for(let key of startSet){
// process(node)
let new_key = process(key);
if(endSet.has(new_key)){
return something;
}
next_startSet.add(new_key);
}
startSet = next_startSet;
if(startSet.size > endSet.size){
[beginSet,endSet] = [endSet,beginSet]
}
}
}
``` <file_sep>+ 定义
+ 增加了向前指针的链表叫作跳表。跳表全称叫做跳跃表,简称跳表。
+ 跳表是一个随机化的数据结构,实质就是一种可以进行二分查找的有序链表。
+ 跳表在原有的有序链表上面增加了多级索引,通过索引来实现快速查找。
+ 跳表不仅能提高搜索性能,同时也可以提高插入和删除操作的性能。
+ 时间复杂度
+ 查找、插入、删除均为O(logn),最坏为O(n)
+ 空间复杂度
+ O(n)
+ 实践
+ Redis、LevelDB
+ 性能
+ 和红黑树、AVL树不相上下
+ 图解实现
+ 跳表在原有的有序链表上面增加了多级索引,通过索引来实现快速查找。
+ 首先在最高级索引上查找最后一个小于当前查找元素的位置,
+ 然后再跳到次高级索引继续查找,直到跳到最底层为止
+ 
+ 高效的动态插入和删除
+ 插入
+ 查询:二分( O(logn) )
+ 
+ 删除
+ 查询节点,因为是链表,获取它的前驱节点,最后进行链表删除节点操作
+ 跳表索引动态更新
+ 随机函数
+ 相关文章
+ [Redis源码学习之跳表](https://cloud.tencent.com/developer/article/1353762)
+ 代码实现
```javascript
```
# -------未完待续-------<file_sep>## 避免重排和重绘的小技巧
+ 浏览器渲染网页过程
+ 解析HTML(HTML Parser)
+ 构建DOM树(DOM Tree)
+ 渲染树构建(Render Tree)
+ 绘制渲染树(Painting)
+ 
+ reflow:重排/回流
+ 改变窗口大小
+ 改变文字大小
+ 添加/删除样式表
+ 内容的改变,(用户在输入框中写入内容也会)
+ 激活伪类,如:hover
+ 操作class属性
+ 脚本操作DOM
+ 计算offsetWidth和offsetHeight
+ 设置style属性
+ repaint:重绘
+ 在一个元素的外观被改变,但没有改变布局的情况下发生的,
+ 如改变了visibility、outline、background等。
+ 当repaint发生时,浏览器会验证DOM树上所有其他节点的visibility属性。
+ 优化
+ translate属性值来替换top/left/right/bottom的切换
+ scale属性值替换width/height
+ opacity属性替换display/visibility
+ 创建文档片段,一次性添加所有动态元素
+ document.createDocumentFragment()
+ 将需要多次重排的元素,position属性设为absolute或fixed,这样此元素就脱离了文档流,它的变化不会影响到其他元素。
+ 例如有动画效果的元素就最好设置为绝对定位。<file_sep># 摘要
+ 深度优先搜索 与 广度优先搜索(depth first search,breadth first search)
+ 贪心算法
+ 二分查找
+ 课后思考
### DFS 和 BFS
+ 均基于数据机构-图
+ BFS
+ 借助队列实现
+ DFS
+ 借助栈实现
+ 实践用应用
+ BFS
+ 找出社交网络中某个用户的三度好友关系
+ DFS
+ 走迷宫
+ 代码
+ 图的广度优先遍历

```java
public void bfs(int s, int t) {
if (s == t) return;
boolean[] visited = new boolean[v];
visited[s]=true;
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
int[] prev = new int[v];
for (int i = 0; i < v; ++i) {
prev[i] = -1;
}
while (queue.size() != 0) {
int w = queue.poll();
for (int i = 0; i < adj[w].size(); ++i) {
int q = adj[w].get(i);
if (!visited[q]) {
prev[q] = w;
if (q == t) {
print(prev, s, t);
return;
}
visited[q] = true;
queue.add(q);
}
}
}
}
private void print(int[] prev, int s, int t) { // 递归打印 s->t 的路径
if (prev[t] != -1 && t != s) {
print(prev, s, prev[t]);
}
System.out.print(t + " ");
}
```
+ 走迷宫深度优先搜索
```java
boolean found = false; // 全局变量或者类成员变量
public void dfs(int s, int t) {
found = false;
boolean[] visited = new boolean[v];
int[] prev = new int[v];
for (int i = 0; i < v; ++i) {
prev[i] = -1;
}
recurDfs(s, t, visited, prev);
print(prev, s, t);
}
private void recurDfs(int w, int t, boolean[] visited, int[] prev) {
if (found == true) return;
visited[w] = true;
if (w == t) {
found = true;
return;
}
for (int i = 0; i < adj[w].size(); ++i) {
int q = adj[w].get(i);
if (!visited[q]) {
prev[q] = w;
recurDfs(q, t, visited, prev);
}
}
}
```
+ 模板
+ BFS
```python
def BFS(graph, start, end):
queue = []
queue.append([start])
visited.add(start)
while queue:
node = queue.pop()
visited.add(node)
process(node)
nodes = generate_related_nodes(node)
queue.push(nodes)
# other processing work
...
```
+ DFS
+ 递归写法
```python
visited = set()
def dfs(node, visited):
if node in visited: # terminator
# already visited
return
visited.add(node)
# process current node here.
...
for next_node in node.children():
if not next_node in visited:
dfs(next_node, visited)
```
+ 非递归写法
```python
def DFS(self, tree):
if tree.root is None:
return []
visited, stack = [], [tree.root]
while stack:
node = stack.pop()
visited.add(node)
process (node)
nodes = generate_related_nodes(node)
stack.push(nodes)
# other processing work
...
```
### 贪心算法
+ 定义
+ 是一种在每一步选择中都采取在当前状态下最好或最优(即最有利)的选择,从而希望导致结果是全局最好或最优的算法
+ 注意
+ 贪心算法并不能每次都能给出最优解
+ 例如最短路径问题,从顶点S开始,找到一条到顶点T的最短路径问题

+ 贪心算法算得:S->A->E->T,1+4+4=9
+ 实际上最短路径是:S->B->D->T,2+2+2+2=6
+ 区别
+ 和动态规划的不用在于它对每个子问题的解决方案都做出选择,不能回退
+ 动态规划则会保存以前的运算结果,并根据以前的结果对当前进行选择,有回退功能
+ 适用场景
+ 问题能分成子问题来解决
+ 子问题的最优解能递推到最终问题的最优解
+ 这种子问题最优解被称为最优子结构
+ 实践应用
+ 图的最小生成树
+ 哈夫曼编码
+ 分糖果问题
+ 钱币找零
+ 区间覆盖

> 假设我们有n个区间,区间的起始端点和结束端点分别是[l1,r1],[l2,r2],[l3,r3],...,[ln,rn]。
我们从这n个区间中选出一部分区间,这部分区间满足两两不相交(端点不相交的情况不算相交),最多能选出多少个区间呢?
+ 思路
+ 假设这n个区间中最左端点是lmin,最右端点是rmax。
+ 这个问题等价于,我们选择几个不相交的区间,从左到右将[lmin,rmax]覆盖上。
+ 解题技巧
+ 按照起始端点从小到大的顺序对这n个区间排序
+ 贪心选择
+ 遍历时,当且仅当左端点区间跟前面的已经覆盖的区间不重合,且右端点尽量小时,剩下的右边的未覆盖区间才能尽可能大,整体才可以放置更多的空间

+ 任务调度
+ 区间覆盖相同处理思想问题
+ 教师排课
+ 区间覆盖相同处理思想问题
+ 单源最短路径算法
### 二分查找(Binary Search)
+ 定义
+ 一种针对有序数据集合的查找算法,也叫折半查找算法
+ 时间复杂度:O(logn)
+ 每次查找后数据都会缩小原来的一半,即除以2
+ 最坏情况下,直到查找区间被缩小为空,才停止

+ 如图,当空间缩小为1时,n/2^k == 1;k 为总共缩小的次数
+ k = log2n ,即O(logn)
+ 相同时间复杂度的数据结构
+ 堆
+ 二叉树
+ 实现
+ 警惕
+ 循环退出条件
+ low<=high ,而不是
+ mid的取值
+ mid = (low+high)/2 有可能会出问题
+ 当low和high很大的时候,和会溢出
+ 优化
+ low+(high-low)/2
+ 进一步优化
+ low+((high-low)>>1)
+ 模版
+ java
```java
public int bsearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == value) {
return mid;
} else if (a[mid] < value) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
```
+ python
```python
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) / 2
if array[mid] == target:
# find the target!!
break or return result
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
```
+ 递归
```java
// 二分查找的递归实现
public int bsearch(int[] a, int n, int val) {
return bsearchInternally(a, 0, n - 1, val);
}
private int bsearchInternally(int[] a, int low, int high, int value) {
if (low > high) return -1;
int mid = low + ((high - low) >> 1);
if (a[mid] == value) {
return mid;
} else if (a[mid] < value) {
return bsearchInternally(a, mid+1, high, value);
} else {
return bsearchInternally(a, low, mid-1, value);
}
}
```
+ 非递归
+ 局限性
+ 依赖于顺序表结构,即数组
+ 利用数组的下标随机访问特性,时间复杂度O(1)
+ 其它数据结构如链表,时间复杂度为O(n)
+ 针对的是有序数据
+ 二分查找要求数据必须有序
+ 如果数据无序,则需要先排序,排序的时间复杂度最低为O(nlogn)
+ 尤其不实用于动态的数据集合
+ 数量太小不实用
+ 直接顺序遍历来得快
+ 数量太大也不实用
+ 因为底层依赖数组,假设有1GB大小的数据,则需要申请1GB的连续存储空间,不现实
+ 常考变形问题
+ 数组中重复元素,且是给定值
+ 查找第一个值等于给定值的元素
```java
public int bsearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (a[mid] >= value) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (low < n && a[low]==value) return low;
else return -1;
}
```
+ 查找最后一个值等于给定值的元素
```java
public int bsearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (a[mid] > value) {
high = mid - 1;
} else if (a[mid] < value) {
low = mid + 1;
} else {
if ((mid == n - 1) || (a[mid + 1] != value)) return mid;
else low = mid + 1;
}
}
return -1;
}
```
+ 查找第一个大于等于给定值的元素
```java
public int bsearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (a[mid] >= value) {
if ((mid == 0) || (a[mid - 1] < value)) return mid;
else high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
```
+ 查找最后一个小于等于给定值的元素
+ 如何快速定位出一个IP地址的归属地?
```java
public int bsearch7(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (a[mid] > value) {
high = mid - 1;
} else {
if ((mid == n - 1) || (a[mid + 1] > value)) return mid;
else low = mid + 1;
}
}
return -1;
}
```
### 课后思考
+ 如果一个有序数组是一个循环有序数组,比如4,5,6,1,2,3;如何实现一个求"值等于给定值"的二分算法呢?
+ 此题解答可参考[我的题解](https://github.com/Alex660/leetcode/blob/master/leetCode-33-search-in-rotated-sorted-array.md)
+ 解法思路
+ 一、
1. 找到分界下标,分成两个有序数组
2. 判断目标值在哪个有序数据范围内,做二分查找
+ 二、
1. 找到最大值的下标 x;
2. 所有元素下标 +x 偏移,超过数组范围值的取模;
3. 利用偏移后的下标做二分查找;
4. 如果找到目标下标,再作 -x 偏移,就是目标值实际下标。两种情况最高时耗都在查找分界点上,所以时间复杂度是 O(N)。复杂度有点高,能否优化呢?
+ 三、
1. 我们发现循环数组存在一个性质:以数组中间点为分区,会将数组分成一个有序数组和一个循环有序数组。
2. 如果首元素小于 mid,说明前半部分是有序的,后半部分是循环有序数组;
3. 如果首元素大于 mid,说明后半部分是有序的,前半部分是循环有序的数组;
4. 如果目标元素在有序数组范围中,使用二分查找;
5. 如果目标元素在循环有序数组中,设定数组边界后,使用以上方法继续查找。时间复杂度为 O(logN)。
+ 使用二分查找,寻找一个半有序数组 [4, 5, 6, 7, 0, 1, 2] 中间无序的地方?
+ 分析
+ 设置low,high左右边界,算出中间数nums[mid]
+ 当nums[mid] > nums[high]时,说明出现了无序的地方在右边
+ low = mid+1
+ 否则无序点在左侧
+ high = mid
+ 两边夹逼直到low == high ,剩下的一个元素即为无序点
+ 代码实现
```javascript
// 查找无序地方即半有序数组的最小元素的索引
function findMinElementI(nums){
var low = 0;
var high = nums.length -1;
while(low<high){
var mid = low + ((high - low)>>1);
if(nums[mid] > nums[high]){
low = mid +1;
}else{
high = mid;
}
}
return low;
}
``` <file_sep># js基本数据类型
#### ES5
+ 简单数据类型
+ String、Boolean
+ Null、Undefined
+ Undefined类型表示未定义,它只有一个值为undefined
+ undefined是一个变量,并非关键字,在局部作用域下,会被篡改
+ 因此判断是否为undefined,可以用
+ x !== void 0
+ void 0 返回undefined
+ Null类型只有一个值,为null
+ null是一个关键字
+ Number
+ 有 18437736874454810627(即 2^64-2^53+3) 个值
+ 额外场景
+ NaN,占用了 9007199254740990,这原本是符合 IEEE 规则的数字;
+ Infinity,无穷大;
+ -Infinity,负无穷大。
+ 精度问题
+ 根据双精度浮点数的定义,Number 类型中有效的整数范围是 -0x1fffffffffffff 至 0x1fffffffffffff,所以 Number 无法精确表示此范围外的整数。
+ console.log( 0.1 + 0.2 == 0.3); // false
+ 改正
+ console.log( Math.abs(0.1 + 0.2 - 0.3) <= Number.EPSILON); // true
+ 复杂数据类型
+ Object
+ 其它规范类型
+ List 和 Record: 用于描述函数传参过程。
+ Set:主要用于解释字符集等。
+ Completion Record:用于描述异常、跳出等语句执行过程。
+ Reference:用于描述对象属性访问、delete 等。
+ Property Descriptor:用于描述对象的属性。
+ Lexical Environment 和 Environment Record:用于描述变量和作用域。
+ Data Block:用于描述二进制数据。
#### ES6
+ 新增
+ [Symbol](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol)<file_sep>### 数组、链表、跳表
+ [11. 盛最多水的容器](https://leetcode-cn.com/problems/container-with-most-water/)
+ [283. 移动零](https://leetcode-cn.com/problems/move-zeroes/)
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/?utm_source=LCUS&utm_medium=ip_redirect_q_uns&utm_campaign=transfer2china)
+ [15. 三数之和](https://leetcode-cn.com/problems/3sum/)
+ [1. 两数之和](https://leetcode-cn.com/problems/two-sum/)
+ [206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)
+ [24. 两两交换链表中的节点](https://leetcode-cn.com/problems/swap-nodes-in-pairs/)
+ [141. 环形链表](https://leetcode-cn.com/problems/linked-list-cycle/)
+ [142. 环形链表 II](https://leetcode-cn.com/problems/linked-list-cycle-ii/)
+ [25. K 个一组翻转链表](https://leetcode-cn.com/problems/reverse-nodes-in-k-group/)
+ [26. 删除排序数组中的重复项](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/)
+ [189. 旋转数组](https://leetcode-cn.com/problems/rotate-array/)
+ [21. 合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/)
+ [88. 合并两个有序数组](https://leetcode-cn.com/problems/merge-sorted-array/)
+ [66. 加一](https://leetcode-cn.com/problems/plus-one/)
### 栈、队列、优先队列、双端队列
+ [20. 有效的括号](https://leetcode-cn.com/problems/valid-parentheses/)
+ [155. 最小栈](https://leetcode-cn.com/problems/min-stack/)
+ [84. 柱状图中最大的矩形](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/)
+ [239. 滑动窗口最大值](https://leetcode-cn.com/problems/sliding-window-maximum/)
+ [641. 设计循环双端队列](https://leetcode-cn.com/problems/design-circular-deque/)
+ [42. 接雨水](https://leetcode-cn.com/problems/trapping-rain-water/)
### 哈希表、映射、集合
+ [242. 有效的字母异位词](https://leetcode-cn.com/problems/valid-anagram/)
+ [49. 字母异位词分组](https://leetcode-cn.com/problems/group-anagrams/)
+ [1. 两数之和](https://leetcode-cn.com/problems/two-sum/)
### 树、二叉树、二叉搜索树
+ [94. 二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/)
+ [144. 二叉树的前序遍历](https://leetcode-cn.com/problems/binary-tree-preorder-traversal/)
+ [590. N叉树的后序遍历](https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/)
+ [589. N叉树的前序遍历](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/)
+ [429. N叉树的层序遍历](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/)
+ [145. 二叉树的后序遍历](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/)
### 泛型递归、树的递归
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/)
+ [22. 括号生成](https://leetcode-cn.com/problems/generate-parentheses/)
+ [226. 翻转二叉树](https://leetcode-cn.com/problems/invert-binary-tree/)
+ [98. 验证二叉搜索树](https://leetcode-cn.com/problems/validate-binary-search-tree/)
+ [104. 二叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
+ [111. 二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
+ [297. 二叉树的序列化与反序列化](https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/)
+ [236. 二叉树的最近公共祖先](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/)
+ [105. 从前序与中序遍历序列构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
+ [77. 组合](https://leetcode-cn.com/problems/combinations/)
+ [46. 全排列](https://leetcode-cn.com/problems/permutations/)
+ [47. 全排列 II](https://leetcode-cn.com/problems/permutations-ii/)
### 分治、回溯
+ [50. Pow(x, n)](https://leetcode-cn.com/problems/powx-n/)
+ [78. 子集](https://leetcode-cn.com/problems/subsets/)
+ [169. 多数元素](https://leetcode-cn.com/problems/majority-element/)
+ [17. 电话号码的字母组合](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/)
+ [51. N皇后](https://leetcode-cn.com/problems/n-queens/)
### 深度优先搜索和广度优先搜索
+ [102. 二叉树的层次遍历](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)
+ [433. 最小基因变化](https://leetcode-cn.com/problems/minimum-genetic-mutation/)
+ [22. 括号生成](https://leetcode-cn.com/problems/generate-parentheses/)
+ [515. 在每个树行中找最大值](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/)
+ [127. 单词接龙](https://leetcode-cn.com/problems/word-ladder/)
+ [126. 单词接龙 II](https://leetcode-cn.com/problems/word-ladder-ii/description/)
+ [200. 岛屿数量](https://leetcode-cn.com/problems/number-of-islands/)
+ [529. 扫雷游戏](https://leetcode-cn.com/problems/minesweeper/description/)
### 贪心算法
+ [322. 零钱兑换](https://leetcode-cn.com/problems/coin-change/)
+ [860. 柠檬水找零](https://leetcode-cn.com/problems/lemonade-change/)
+ [122. 买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
+ [455. 分发饼干](https://leetcode-cn.com/problems/assign-cookies/)
+ [874. 模拟行走机器人](https://leetcode-cn.com/problems/walking-robot-simulation/)
+ [55. 跳跃游戏](https://leetcode-cn.com/problems/jump-game/)
+ [45. 跳跃游戏 II](https://leetcode-cn.com/problems/jump-game-ii/)
### 二分查找
+ [69. x 的平方根](https://leetcode-cn.com/problems/sqrtx/)
+ [367. 有效的完全平方数](https://leetcode-cn.com/problems/valid-perfect-square/)
+ [33. 搜索旋转排序数组](https://leetcode-cn.com/problems/search-in-rotated-sorted-array/)
+ [74. 搜索二维矩阵](https://leetcode-cn.com/problems/search-a-2d-matrix/)
+ [153. 寻找旋转排序数组中的最小值](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/)
### 动态规划
+ [1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/description/)
+ [746. 使用最小花费爬楼梯](https://leetcode-cn.com/problems/min-cost-climbing-stairs/)
+ [300. 最长上升子序列](https://leetcode-cn.com/problems/longest-increasing-subsequence/)
+ [120. 三角形最小路径和](https://leetcode-cn.com/problems/triangle/)
+ [53. 最大子序和](https://leetcode-cn.com/problems/maximum-subarray/)
+ [152. 乘积最大子序列](https://leetcode-cn.com/problems/maximum-product-subarray/)
+ [322. 零钱兑换](https://leetcode-cn.com/problems/coin-change/)
+ [518. 零钱兑换 II](https://leetcode-cn.com/problems/coin-change-2/)
+ [198. 打家劫舍](https://leetcode-cn.com/problems/house-robber/)
+ [213. 打家劫舍 II](https://leetcode-cn.com/problems/house-robber-ii/description/)
+ [121. 买卖股票的最佳时机](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/)
+ [122. 买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
+ [123. 买卖股票的最佳时机 III](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/)
+ [309. 最佳买卖股票时机含冷冻期](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)
+ [188. 买卖股票的最佳时机 IV](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/)
+ [714. 买卖股票的最佳时机含手续费](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)
+ [32. 最长有效括号](https://leetcode-cn.com/problems/longest-valid-parentheses/)
+ [64. 最小路径和](https://leetcode-cn.com/problems/minimum-path-sum/)
+ [72. 编辑距离](https://leetcode-cn.com/problems/edit-distance/)
+ [91. 解码方法](https://leetcode-cn.com/problems/decode-ways/)
+ [221. 最大正方形](https://leetcode-cn.com/problems/maximal-square/)
+ [363. 矩形区域不超过 K 的最大数值和](https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k/)
+ [403. 青蛙过河](https://leetcode-cn.com/problems/frog-jump/)
+ [410. 分割数组的最大值](https://leetcode-cn.com/problems/split-array-largest-sum/)
+ [552. 学生出勤记录 II](https://leetcode-cn.com/problems/student-attendance-record-ii/)
+ [621. 任务调度器](https://leetcode-cn.com/problems/task-scheduler/)
+ [647. 回文子串](https://leetcode-cn.com/problems/palindromic-substrings/)
+ [76. 最小覆盖子串](https://leetcode-cn.com/problems/minimum-window-substring/)
+ [312. 戳气球](https://leetcode-cn.com/problems/burst-balloons/)
+ [279. 完全平方数](https://leetcode-cn.com/problems/perfect-squares/)
+ [55. 跳跃游戏](https://leetcode-cn.com/problems/jump-game/)
+ [45. 跳跃游戏 II](https://leetcode-cn.com/problems/jump-game-ii/)
+ [62. 不同路径](https://leetcode-cn.com/problems/unique-paths/)
+ [63. 不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/)
+ [980. 不同路径 III](https://leetcode-cn.com/problems/unique-paths-iii/)
+ [85. 最大矩形](https://leetcode-cn.com/problems/maximal-rectangle/)
+ [115. 不同的子序列](https://leetcode-cn.com/problems/distinct-subsequences/)
+ [818. 赛车](https://leetcode-cn.com/problems/race-car/)
### 字典树和并查集
+ [208. 实现 Trie (前缀树)](https://leetcode-cn.com/problems/implement-trie-prefix-tree/)
+ [212. 单词搜索 II](https://leetcode-cn.com/problems/word-search-ii/)
+ [547. 朋友圈](https://leetcode-cn.com/problems/friend-circles/)
+ [200. 岛屿数量](https://leetcode-cn.com/problems/number-of-islands/)
+ [130. 被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions/)
### 高级搜索
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/)
+ [22. 括号生成](https://leetcode-cn.com/problems/generate-parentheses/)
+ [51. N皇后](https://leetcode-cn.com/problems/n-queens/)
+ [36. 有效的数独](https://leetcode-cn.com/problems/valid-sudoku/description/)
+ [37. 解数独](https://leetcode-cn.com/problems/sudoku-solver/#/description)
+ [127. 单词接龙](https://leetcode-cn.com/problems/word-ladder/)
+ [433. 最小基因变化](https://leetcode-cn.com/problems/minimum-genetic-mutation/)
+ [1091. 二进制矩阵中的最短路径](https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/)
+ [773. 滑动谜题](https://leetcode-cn.com/problems/sliding-puzzle/)
### 位运算
+ [191. 位1的个数](https://leetcode-cn.com/problems/number-of-1-bits/)
+ [231. 2的幂](https://leetcode-cn.com/problems/power-of-two/)
+ [190. 颠倒二进制位](https://leetcode-cn.com/problems/reverse-bits/)
+ [51. N皇后](https://leetcode-cn.com/problems/n-queens/description/)
+ [52. N皇后 II](https://leetcode-cn.com/problems/n-queens-ii/description/)
+ [338. 比特位计数](https://leetcode-cn.com/problems/counting-bits/description/)
### 布隆过滤器和LRU缓存
+ [146. LRU缓存机制](https://leetcode-cn.com/problems/lru-cache/#/)
### 排序算法
+ [1122. 数组的相对排序](https://leetcode-cn.com/problems/relative-sort-array/)
+ [242. 有效的字母异位词](https://leetcode-cn.com/problems/valid-anagram/)
+ [1244. 力扣排行榜](https://leetcode-cn.com/problems/design-a-leaderboard/)
+ [56. 合并区间](https://leetcode-cn.com/problems/merge-intervals/)
+ [493. 翻转对](https://leetcode-cn.com/problems/reverse-pairs/)
#### 字符串算法
+ [709. 转换成小写字母](https://leetcode-cn.com/problems/to-lower-case/)
+ [58. 最后一个单词的长度](https://leetcode-cn.com/problems/length-of-last-word/)
+ [771. 宝石与石头](https://leetcode-cn.com/problems/jewels-and-stones/)
+ [387. 字符串中的第一个唯一字符](https://leetcode-cn.com/problems/first-unique-character-in-a-string/)
+ [8. 字符串转换整数 (atoi)](https://leetcode-cn.com/problems/string-to-integer-atoi/)
+ [14. 最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/description/)
+ [344. 反转字符串](https://leetcode-cn.com/problems/reverse-string/)
+ [541. 反转字符串 II](https://leetcode-cn.com/problems/reverse-string-ii/)
+ [151. 翻转字符串里的单词](https://leetcode-cn.com/problems/reverse-words-in-a-string/)
+ [557. 反转字符串中的单词 III](https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/)
+ [917. 仅仅反转字母](https://leetcode-cn.com/problems/reverse-only-letters/)
+ [242. 有效的字母异位词](https://leetcode-cn.com/problems/valid-anagram/)
+ [49. 字母异位词分组](https://leetcode-cn.com/problems/group-anagrams/)
+ [438. 找到字符串中所有字母异位词](https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/)
+ [125. 验证回文串](https://leetcode-cn.com/problems/valid-palindrome/)
+ [680. 验证回文字符串 Ⅱ](https://leetcode-cn.com/problems/valid-palindrome-ii/)
+ [5. 最长回文子串](https://leetcode-cn.com/problems/longest-palindromic-substring/)
+ [1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)
+ [72. 编辑距离](https://leetcode-cn.com/problems/edit-distance/)
+ [5. 最长回文子串](https://leetcode-cn.com/problems/longest-palindromic-substring/)
+ [10. 正则表达式匹配](https://leetcode-cn.com/problems/regular-expression-matching/)
+ [44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/)
+ [115. 不同的子序列](https://leetcode-cn.com/problems/distinct-subsequences/)
+ [917. 仅仅反转字母](https://leetcode-cn.com/problems/reverse-only-letters/)
+ [205. 同构字符串](https://leetcode-cn.com/problems/isomorphic-strings/)
+ [32. 最长有效括号](https://leetcode-cn.com/problems/longest-valid-parentheses/)<file_sep># Javascript的继承与多态
+ ES5
+ ES6
+ 概述
+ JS引入了prototype的概念,可以让我们以另一种方式模仿类,并通过原型链的方式实现了父类子类之间共享属性的继承以及身份确认机制。
### ES6之前的继承
+ 原型赋值方式
+ 直接将父类的一个实例赋给子类的原型
+ code
```javascript
function Person(name) {
this.name = name;
this.className = 'person';
}
Person.prototype.getClassName = function(){
console.log(this.className);
}
function Man(){
}
Man.prototype = new Person();
var man = new Man();
man.getClassName() // "person"
man instanceof Person // true
```
+ 分析
+ 实现
+ 通过new一个父类的实例,赋值给子类的原型,使得
+ 父类原型中的方法属性及挂在this上的各种方法属性全赋给了子类的原型
+ 问题
+ 子类无法通过父类创建私有属性
+ 此种方法,每次继承来的人名都是同一个
+ 调用构造函数方式
+ 子类的在构造函数里用子类实例的this去调用父类的构造函数,
+ 从而达到继承父类属性的效果
+ call
+ apply
+ code
```javascript
function Person(name){
this.name=name;
this.className="person"
}
Person.prototype.getName=function(){
console.log(this.name)
}
function Man(name){
Person.apply(this,arguments)
}
var man1=new Man("Davin");
var man2=new Man("Jack");
man1.name // "Davin"
man2.name // "Jack"
man1.getName() // 报错
man1 instanceof Person // false
```
+ 分析
+ 只能继承父类构造函数中声明的实例属性,并没有继承父类原型的属性和方法
+ 组合继承
+ 原型继承 + 调用构造函数
+ code
```javascript
function Person(name){
this.name=name||"default name";
this.className="person"
}
Person.prototype.getName=function(){
console.log(this.name)
}
function Man(name){
// 第一次调用Person()
Person.apply(this,arguments)
}
//继承原型
Man.prototype = new Person(); // 第二次调用Person()
var man1=new Man("Tom");
man1.name // "Tom"
man1.getName() //"Tom"
Man.prototype // Person {name: "default name", className: "person"}
```
+ 分析
+ 由Man.prototype可知实例中的name属性和原型不同,
+ 每次创建相当于覆盖原型的name属性,原型的依旧在
+ 无论在什么情况下,都会调用两次构造函数:
+ 一次是在创建子类型原型时,
+ 另一次是在子类型构造函数内部。
+ 寄生式继承
+ 和工厂模式类似,创建一个仅用于封装继承过程的函数,
+ 该函数在内部以某种方式来增强对象,最后返回对象。
+ code
```javascript
function Person(name){
this.name=name; //1
this.className="person"
}
function createAnother(origin){
// 浅拷贝原型对象,继承方法
var clone = Object(origin);
// 以某种方式来增强这个对象
clone.sayHi = function(){
console.log("hi");
};
return clone; // 返回这个对象
}
var anotherPeople = createAnother(Person);
anotherPeople.sayHi(); // hi
```
+ 寄生组合继承(ES5主流继承方式)
+ 去除原型直接赋值方式,改用[Object.creat(obj)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create)浅拷贝原型对象
+ code
```javascript
function Person(name){
this.name=name; //1
this.className="person"
}
Person.prototype.getName=function(){
console.log(this.name)
}
function Man(name){
// 继承属性
Person.apply(this,arguments)
}
// 浅拷贝原型对象 - 继承方法
Man.prototype = Object.create(Person.prototype);
// 增强对象
Man.prototype.constructor = Man
var man1=new Man("Tom");
man1.name // "Tom"
man1.getName() // "Tom"
```
+ 分析
+ 将父类的原型复制给了子类原型
+ constructor属性
```javascript
Person.prototype.constructor
Person(name){
this.name=name; //1
this.className="person"
}
Man.prototype.constructor
Person(name){
this.name=name; //1
this.className="person"
}
man1 instanceof Person // true
man1 instanceof Man // true
```
+ constructor是类的构造函数
+ 上述Man的构造函数应该是Man,所以一般需要重置,
+ 也叫增强对象
+ **Man.prototype.constructor = Man**
+ 总结
+ 
+ 组合寄生:一条实现属性继承,一条实现方法的继承
### ES6继承
+ [Class](http://es6.ruanyifeng.com/#docs/class-extends#%E5%8E%9F%E7%94%9F%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%9A%84%E7%BB%A7%E6%89%BF)
+ extends
+ super
+ code
```javascript
class A {}
// B通过extends关键字继承了A类的所有属性和方法
class B extends A {
constructor(x,y,color){
// 调用父类的constructor(x,y)
// 相当于 A.prototype.constructor.call(this)
super(x,y);
this.color = color
}
toString(){
//调用父类的方法
return this.color + ' ' + super.toString();
}
}
```
+ 分析
+ 一个继承语句同时存在两条继承链:属性继承 + 方法的继承
```javascript
class B extends A{}
B.__proto__ === A; //继承属性
B.prototype.__proto__ === A.prototype;//继承方法
```
+ 总结
+  <file_sep>## 动态规划理论
```javascript
// “一模三特”
// 一、模型【多阶段决策最优解模型】
// ----解决问题过程经历n个决策阶段 && 分别对应一组状态
// 二、特征【最优子结构、无后效性、重复子问题】
// ----<1>、最优子结构
// 问题的最优解包含子问题的最优解 => 子问题的最优解推导出问题的最优解
// 后面阶段的状态可以通过前面阶段的状态推导出来
// ----<2>、无后效性
// 1⃣️:不关心当前状态的推导,只关心前面阶段的状态值
// 2⃣️:前一阶段的状态一旦确定就不受之后阶段的决策影响
// ----<3>、重复子问题
// 不同的决策序列,到达某个相同的阶段时,可能会产生重复的状态
// 实例
// 一个 n*n 的矩阵 w[n][n]
// 求从左上角出发到右下角最短距离【路经的数字和为路径长度】
// 每次只能向右或向下移动一位
// [i,j] 0 1 2 3
// 0 1 3 5 9
// 1 2 1 3 4
// 2 5 2 6 7
// 3 6 8 4 3
// (0,0)->(n-1,n-1) 共 2*(n-1)步 => 2*(n-1)个阶段状态集合 <= 向右走/向下走
// min_dist(i,j) <= (0,0)->(i,j)的最短路径长度
// (0,0)->(i-1,j)/(i,j-1)->(i,j)
// ==>
// min_dist(i,j) == Math.min(min_dist(i-1,j),min_dist(i,j-1)) + w[i][j]
// 动态规划题目解题思路
// 一、状态转移表法
// 二、状态转移方程法
// 一:
// 回溯算法->回溯加“备忘录”
// 代码实现
var minDist = 0;//最短路径
// 当前状态最短路径
var dist = 0;
// 定义n*n
var n = 4;
// 初始化随机二维整数【1~10】数组
var w = [];
while (w.length<n) {
// 1~10随机数
w.push(Math.floor(Math.random(0,1)*10)+1);
}
function minDistBacktracing(i,j,dist) {
// 路过所有节点/到达了n-1,n-1这个位置了【有多个集合】
if(i == n && j == n){
if(dist<minDist){
minDist = dist;
}
}
// 往下走
if(i<n){//边界
minDistBacktracing(i+1,j,dist)
}
// 往右走
if(j<n){//边界
minDistBacktracing(i,j+1,dist)
}
}
// [i,j] 0 1 2 3
// 0 1 3 5 9
// 1 2 1 3 4
// 2 5 2 6 7
// 3 6 8 4 3
// ||
// ||
// \/
// [i,j] 0 1 2 3
// 0 1 4 9 18
// 1 3 4 7 11
// 2 8 6 12 18
// 3 14 14 16 19
// 状态规划->
// 状态转移表
// 一般情况下二维【数组】 (高维时就不适合这种方法了太复杂)
// [i,j] = value 行,列,数组值
// 代码实现
// n*n
var n = 4;
// 初始化二维数组
var result = Array(n);
result[0] = [1,3,5,9];
result[1] = [2,1,3,4];
result[2] = [5,2,6,7];
result[3] = [6,8,4,3];
function getMinDist(result) {
// 临时最短路径
var minDist = 0;
// 初始化第一行n列数据
for(var i = 0;i<n;i++){
minDist += result[0][i];
result[0][i] = minDist;
// 此处也可以再定义一个数组,利于分析 下面第状态转移表亦是如此
// example[0][i] = minDist;
// 但递归时用备忘录的话在原数组上修改就不好判断了就需要另外创建一个数组
}
// 初始化第一列n行数据
minDist = 0;
for(var i = 0;i<n;i++){
minDist += result[i][0];
result[i][0] = minDist;
}
// 状态转移表推进
for(var i = 1;i<n;i++){
for(j = 1;j<n;j++){
result[i][j] = result[i][j] + Math.min(result[i-1][j],result[i][j-1]);
}
}
// 返回最后一个也就是结果
return result[n-1][n-1];
}
// 状态转移方程
// 由一系列的分析可知状态转移方程:
// min_dist(i,j) = w[i][j] + min(min_dist(i,j-1),min_dist(i-1,j))
//递归加“备忘录”
// 代码实现
// 路线数组
var matrix = [
[1,3,5,9],
[2,1,3,4],
[5,2,6,7],
[6,8,4,3]
];
// 初始化最短路径数组
var result = [
[-1,-1,-1,-1],
[-1,-1,-1,-1],
[-1,-1,-1,-1],
[-1,-1,-1,-1],
]
var n = 4;
function minDist(i,j) {
// 递推到第一个状态停止递推
if(i == 0 && j == 0){
return matrix[0][0]
}
var leftUp = 0;
var topUp = 0;
// 求向右走后的上一步最短路径 && 考虑边界情况
j-1>=0 && (leftUp = minDist[i][j-1])
// 求向下走后的上一步最短路径 && 考虑边界情况
i-1>=0 && (topUp = minDist[i-1][j])
// 求上两种情况的最新上一步路径+当前路径 = 当前结点最小路径
result[i][j] = matrix[i][j] + Math.min(leftUp,topUp);
return result[i][j];
}
//迭代递推
// ......
```<file_sep>## 0-1背包问题 【变体】
#### 解法一:回溯
```javascript
// 一个背包总承载重量为:W kg
// 有 n 个物品 ,不可分割
// 求选择哪几样物品放入背包且不超过 W 的情况下,背包物品总价值最大
// 分析:对于每个物品来说有 装和不装 两种选择 => 对于 n 个物品来说 总的装法就有 2^n 种,
// 去掉总量超过 W 的,选取最大总价值。
// 回溯:n个物品依次排列 => n个阶段 ,每个阶段对应一个物品选择装与不装 && 装则总重必须不大于 W
// 递归处理剩下的物品
// 选择的物品相同重量可能一样但价值不一定一样所以回溯算法下用不了备忘录模式去掉重复
//cw 已装物品的重量和
//cv 已装物品的价值和
// i 表示第 i 个物品
// w 背包重量
// n 物品个数
// items 物品重量数组
// value 物品价值数组
// 存储背包物品中总价值的最大值
var maxV = 0;
function getMaxV(i,cw,cv,items,value,n,w) {
// cw == w 背包装满 ; i == n 遍历完所有物品
if(cw == w || i == n){
// 背包装满或扫描完所有物品
if(cv > maxV){
maxV = cv;
}
// 每一轮要退出当前函数否则会造成堆栈溢出
return;
}
// 选择不把当前物品装入背包直接进入下一个
getMaxV(i+1,cw,cv,items,value,n,w);
// 符合背包承受总重时
if(cw+items[i]<=w){
// 选择把当前物品i放入背包 【加当前物品重量和价值】
getMaxV(i+1,cw+items[i],cv+value[i],items,value,n,w);
}
}
getMaxV(0,0,0,[1,2,4,6,7],[1,2,3,4,5],5,10);
```
#### 解法二:动态规划
```javascript
// states[n][cw=w+1] n:第n个物品 cw=w+1:递增第背包承受重量
// states[i][j] = maxV 表示大于等于1种情况的总价值【合计同等重量的物品总价值不一定一样】
var weight = [2,2,4,6,3];//可选装物品重量数组
var value = [1,2,3,4,5];//可选装物品价值数组
var w = 9;//背包可承载重量
function knapsack() {
var n = weight.length;
// 初始化一个二维数组
var result = Array(n)
for(var i = 0;i<n;i++){
result[i] = Array(w);
for(var r =0 ;r<w;r++){
result[i][r] = -1;
}
}
// 第一行的数据要特殊处理,可以利用哨兵优化
result[0][0] = 0;
// 动态规划状态转移
for(var i = 1;i<n;i++){
// 选择不把第 i 个物品装入背包
for(var j = 0;j<w;j++){
if(result[i-1][j]>=0){
result[i][j] = result[i-1][j]
}
}
// 选择把第 i 个物品装入背包 【加当前物品重量和价值】
for(var j = 0;j<=w-weight[i];j++){
// 合并同等重量情况下价值不一的情况,只留一种价值最大的情况
if(result[i-1][j]>=0){//上一行同列
var tmpV = result[i-1][j]+value[i];//增加i种物品价值
if(tmpV>result[i][j+weight[i]]){//当前行下一列
result[i][j+weight[i]] = tmpV;
}
}
}
}
// 输出最大价值结果【结果一定位于最后一行但不一定是最后有有效值的一位】
var maxV = -1;
for(var i = 0;i<=w;i++){
if(result[n-1][i]>maxV){
maxV = result[n-1][i]
}
}
return maxV;
}
// 第22行代码 j如果按照从大到小遍历 则会少重复很多
// 分析代码可知 时间复杂度为O(n*w),空间复杂度为O(n*w)【二维数组】
// 不装背包的动作似乎可以忽略 => 优化为一维数组
var weight = [2,2,4,6,3];//可选装物品重量数组
var value = [1,2,3,4,5];//可选装物品价值数组
var w = 9;//背包可承载重量
function knapsack() {
var n = weight.length;
// 初始化一个一维数组
var result = Array(w)
for(var i = 0;i<w;i++){
result[i] = -1;
}
// 第一行的数据要特殊处理,可以利用哨兵优化
result[0] = 0;
// 动态规划状态转移
// 选择把第 i 个物品装入背包 【加当前物品重量和价值】
for(var i = 1;i<n;i++){
// 装入第 i 个物品入背包
for(var j = w - weight[i];j>=0;j--){
// 合并同等重量情况下价值不一的情况,只留一种价值最大的情况
if(result[j]>=0){//同列
var tmpV = result[j]+value[i];//增加i种物品价值
if(tmpV>result[j+weight[i]]){//下一列
result[j+weight[i]] = tmpV;
}
}
}
}
// 输出最大价值结果【结果一定位于最后一行但不一定是最后有有效值的一位】
var maxV = -1;
for(var i = 0;i<=w;i++){
if(result[i]>maxV){
maxV = result[i]
}
}
return maxV;
}
// 分析代码可知 时间复杂度为O(w),空间复杂度为O(w)【一维数组】
```<file_sep>## 实现Bind函数
#### 解法
```javascript
if(!Function.prototype.bind)(function(){
Function.prototype.bind = () => {
let that = this;
let arg = arguments[0];
let args = [].prototype.slice.call(arguments,1);
if(typeof that !== 'function'){
throw new TypeError('Fucntion.prototype.bind -'+'what is trying to be bound is not callable');
}
return function (){
return that.apply(arg,args.concat([].prototype.slice.call(arguments)))
}
}
})();
```
+ 或者这样写
```javascript
Function.prototype.bind = function () {
let self = this;
let cxt = arguments[0];
let args = [].slice.call(arguments,1);
return function (){
self.apply(cxt,args.concat([].slice.call(arguments)));
}
}
```<file_sep># 超大数相加
#### 解法
```javascript
let addBigNum = (a,b) => {
let res = '',tmp = 0;
a = a.split('');
b = b.split('');
while(a.length || b.length || tmp){
tmp += ~~a.pop() + ~~b.pop();
res = (tmp %10)+res;
tmp = tmp > 9;
}
return res.replace(/^0+/,'');
}
```<file_sep>## 盒模型
#### W3C标准模型和IE模型
+ 包含:margin、border、padding、content
+ 区别
+ 标准:width = content
+ IE:width = content + padding + border
#### CSS3转换
+ box-sizing
+ content-box
+ 元素的 width = content
+ border-box
+ 元素的 width = border + padding + content
#### 番外
+ margin
+ margin-top/margin-bottom
+ 行内元素无效
+ margin-left/margin-right才有效
+ 相邻块级元素
+ 都是整数,margin值取两者最大值
+ 都是负数,margin值取最小值
+ 两者正负相反,margin值取两者之和<file_sep>// 这是一个空文件!<file_sep>## cookie 和 token 在什么情况下会被劫持?
### 常见攻击
+ CSRF
+ Cross-site request forgery(跨站请求伪造)
+ 原理是利用用户的身份,执行非用户本身意愿的操作
+ 图解
+ 
+ 形式
+ 图片URL
+ 超链接
+ Form提交
+ 嵌入第三方论坛、文章中
+ 防御
+ 验证码
+ 检验头部Refer字段
+ Refer用来记录该HTTP请求的来源地址
+ Token
+ 浏览器不会自带token
+ 过程
+ 服务器生成随机数Token
+ 并将该随机Token保存在用户Session(或Cookie中)
+ 用户在提交(如表单)数据时,该Token会提交到服务器
+ 服务器检测提交的Token是否与用户Session(或Cookie)中的是否一致
+ XSS攻击
+ Cross site script,即跨站脚本
+ 形式
+ 用户输入没有进行限制或过滤,从而被黑客嵌入恶意代码提交
+ 防御
+ 设置Cookie的属性为Http only,这样js就无法获取Cookie值
+ 对用户输入做过滤和限制
+ 提交数据做 Html encode处理
+ 去掉 <script>、<iframe>等特殊标签
+ 过滤js事件标签 onclick=、on...
+ 后端也要做过滤限制
### 参考解答
+ XSS下
+ Cookie、Token都有可能被劫持
+ CSRF下
+ Cookie会被劫持
+ Token不会,因为浏览器不会携带
+ 浏览器会自动带上Cookie,因为HTTP是无状态的
+ AJAX不会自动携带cookie<file_sep>## promise的简单实现
+ 图解
+ 
+ code
+ 写法一:
```javascript
let i = 1;
var Promise = (fn) => {
this.id = i++;
this.status = 'PENDING';
this.value = null;
this.deffered = [];
fn.call(this,this.resolve.bind(this),this.reject.bind(this));
}
Promise.prototype = {
constructor:Promise,
then(onfulfilled,onrejected){
let obj = {
onfulfilled:onfulfilled,
onrejected:onrejected
}
obj.promise = new this.constructor(() => {});
console.log(this.status);
if(this.status === 'PENDING'){
this.deffered.push(obj);
}
console.log(this.deffered);
return obj.promise;
},
resolve(data){
this.status = 'FULFILLED';
this.value = data;
this.deffered.forEach(item => {
let p = item.onfulfilled(this.value);
if(p && p.constructor === Promise){
p.deffered = item.promise.deffered;
}
});
},
reject(err){
this.status = 'REJECTED';
this.value = err;
this.deffered.forEach(item => {
let p = item.onrejected(this.value);
if(p && p.constructor === Promise){
p.deffered = item.promise.deffered;
}
})
}
}
```
+ 写法二:
```javascript
```<file_sep>## Vue 的响应式原理中 Object.defineProperty 有什么缺陷?
### 为什么在 Vue3.0 采用了 Proxy,抛弃了 Object.defineProperty?
#### 参考文献
+ [Vue为什么不能检测数组变动](https://segmentfault.com/a/1190000015783546#comment-area)
+ [抱歉,学会 Proxy 真的可以为所欲为](https://zhuanlan.zhihu.com/p/35080324)
+ [阮一峰 - Proxy详解](http://es6.ruanyifeng.com/#docs/proxy)
+ [面试官: 实现双向绑定Proxy比defineproperty优劣如何?](https://juejin.im/post/5acd0c8a6fb9a028da7cdfaf)
#### 参考答案
+ Object.defineProperty无法监控到数组下标的变化,导致通过数组下标添加元素,不能实时响应;
+ Vue通过修改数组的八种方法进行了hack处理
+ push()
+ pop()
+ shift()
+ unshift()
+ splice()
+ sort()
+ reverse()
+ Object.defineProperty只能劫持对象的属性,从而需要对每个对象,每个属性进行遍历,如果,属性值是对象,还需要深度遍历。
+ Proxy可以劫持整个对象,并返回一个新的对象。
+ Proxy有13种劫持操作
+ Proxy不仅可以代理对象,还可以代理数组。还可以代理动态增加的属性。<file_sep>## 0-1背包问题
#### 解法一:回溯
```javascript
// 一个背包总承载重量为:W kg
// 有 n 个物品 ,不可分割
// 求选择哪几样物品放入背包且不超过 W 的情况下,背包物品总重量最大
// 分析:对于每个物品来说有 装和不装 两种选择 => 对于 n 个物品来说 总的装法就有 2^n 种,
// 去掉总量超过 W 的,选取总重量最接近 W 的。
// 回溯:n个物品依次排列 => n个阶段 ,每个阶段对应一个物品选择装与不装 && 装则总重必须不大于 W
// 递归处理剩下的物品
//cw 已装物品的重量和
// i 表示第 i 个物品
// w 背包重量
// n 物品个数
// items 物品重量数组
// 存储背包物品中总重量的最大值
var maxW = 0;
var hasScaned = {};//【备忘录】模式
function getMax(i,cw,items,n,w) {
// cw == w 背包装满 ; i ==n 遍历完所有物品
if(cw === w || i == n){
// 背包装满或扫描完所有物品
if(cw > maxW){
maxW = cw;
}
// 每一轮要退出当前函数否则会造成堆栈溢出
return;
}
// 【备忘录】中有 重复计算 返回
if(hasScaned){
return
}
// 记录【备忘录】里面 下次不再计算
hasScaned[i] = cw;
// 选择不把当前物品放入背包直接进入下一个
getMax(i+1,cw,items,n,w);
// 符合背包承受总重时
if(cw+items[i]<=w){
//选择把当前物品i放入背包 【加当前物品重量】
getMax(i+1,cw+items[i],items,n,w);
}
}
getMax(0,0,[1,2,4,6,7],5,10);
// ==> 优化+增加备忘录模式[很多getMax()重复计算了]]如上题所加
// 函数调用栈 从下往上压栈,从上往下出栈执行
// getMax(5,7) return
// 0+1+2+4+6>w && 终止
// getMax(4,0+1+2+4) i=3 getMax(4,7) ==> getMax(5,7) return
// ==> 7+7>w
// getMax(3,0+1+2+4) getMax(3,7) ==> getMax(4,7) ==> getMax(5,7) return
// <==
// 0+1+2+4<=w 7+6>w
// ==>
// getMax(3,1+2)
// <== getMax(3,3) ==> getMax(4,3+6)
// 0+1+2<=w i=2 <==
// 3+6<=w ==> getMax(5,9) return
// ==> getMax(4,3) getMax(5,3) return
// getMax(2,1) getMax(2,1) ==> 5+6>w
// getMax(4,5) getMax(5,5) return
// <==
// getMax(3,1+4) ==> getMax(3,5) ==> 5+6>w ==> getMax(5,5) return
// <==
// 1+4<=w getMax(4,5)
// getMax(3,1)
// 7+6>w
// getMax(4,7) ===> getMax(5,7) return
// <==
// 1+6<=w getMax(5,1) return
// getMax(4,1)
// getMax(1,1) i=1 ..........
// <==
// 0+1<=w
// getMax(1,0) i=0
// <==
// getMax(0,0) i=0
```
#### 解法二:动态规划
```javascript
// states[n][cw=w+1] n:第n个物品 cw=w+1:递增第背包承受重量
// states[i][j] = true 表示存在
var weight = [2,2,4,6,3];//可选装物品重量数组
var w = 9;//背包可承载重量
function knapsack() {
var n = weight.length;
// 初始化一个二维数组
var result = Array(n)
for(var i = 0;i<n;i++){
result[i] = Array(w);
}
// 第一行的数据要特殊处理,可以利用哨兵优化
result[0][0] = true;
// 动态规划状态转移
for(var i = 1;i<n;i++){
// 选择不把第 i 个物品装入背包
for(var j =0 ;j<w;j++){
if(result[i-1][j] == true){
result[i][j] = result[i-1][j]
}
}
// 选择把第 i 个物品装入背包 【加当前物品重量】
for(var j = 0;j<=w-weight[i];j++){
if(result[i-1][j]==true){
result[i][j+weight[i]] =true
}
}
}
// 输出结果【结果一定位于最后一行最后有有效值的一位】
for(var i = w;i>=0;i--){
if(result[n-1][i] == true){
return i;
}
}
return 0;
}
// 第22行代码 j如果按照从大到小遍历 则会少重复很多
// 分析代码可知 时间复杂度为O(n*w),空间复杂度为O(n*w)【二维数组】
// 不装背包的动作似乎可以忽略 => 优化为一维数组
var weight = [2,2,4,6,3];//可选装物品重量数组
var w = 9;//背包可承载重量
function knapsack() {
var n = weight.length;
// 初始化一个一维数组
var result = Array(w)
// 第一行的数据要特殊处理,可以利用哨兵优化
result[0] = true;
// 动态规划状态转移
for(var i = 1;i<n;i++){
// 装入第 i 个物品入背包
for(var j = w - weight[i];j>=0;j--){
if(result[j]==true){
result[j+weight[i]] = true
}
}
}
// 输出结果
for(var i = w;i>=0;i--){
if(result[i]){
return i;
}
}
return 0 ;
}
// 分析代码可知 时间复杂度为O(w),空间复杂度为O(w)【一维数组】
// 分析:
// 2 2 4 6 3 w=9
// j 0 1 2 3 4 5 6 7 8 9 j<=9
// i
// 0 1 0 1 0 0 0 0 0 0 0 2 arr[i]<=9
// 1 1 0 1 0 1 0 1 0 0 0 2 arr[i]+cw<=9
// 2 1 0 1 0 1 0 1 0 1 0 4
// 3 1 0 1 0 1 0 1 0 1 0 6
// 4 . . . i<=5
// w:背包总承受重量
// states[n][cw=w+1] n:第n个物品 cw=w+1:递增第背包承受重量
// states[i][j] = true
// 0,2 => 0+0,0+2 => 0,2 =>
// 不装 states[0][0]
// 装 states[0][2]
// 1,2 => 0+0,0+2 2+0,2+2 => 0,2,4 =>
// 不装 states[1][0] states[1][2]
// 装 states[1][4]
// 2,4 => 0+0,0+4 2+0,2+4 4+0,4+4 => 0,2,4,6,8 =>
// 不装 states[2][0] states[2][2]
// 装 states[2][4] states[2][6] states[2][8]
// 3,6 => 0+0,0+6 2+0,2+6 4+0,4+6 6+0,6+6 8+0,8+6 => 0,2,4,6,8
// 不装 states[3][0] states[3][2] states[3][4] states[3][6] states[3][8]
// 装 states[3][6] states[3][8] states[3][10](不符合不再加6即不再装入)
// 4,3 => 0+0,0+3 2+0,2+3 4+0,4+3 6+0,6+3 8+0,8+3 => 0,2,3,4,5,6,7,8,9
// 不装 states[4][0] states[4][2] states[4][4] states[4][6] states[4][8]
// 装 states[4][3] states[4][5] states[4][7] states[4][9] states[4][11](不符合不再加6即不再装入))
// ===>
// 不装 states[i-1][j] == states[i][j] == true
// 装 states[i-1][j] == true && j+weight[i]<=w && states[i][j+weight[i]]
// 最后一行最后一个ture的二维数组元素的二维元素j 即为所求
```<file_sep># 摘要
+ 实现
+ 练习
### 实现
+ 需要解决的问题
+ 输入一个数m,输出数组中下标1~m的前缀和
+ 某个指定下标的数进行值的修改
+ 多次执行上述两种操作
+ 一般方法
+ 求数组1~m的前缀和,n次操作,时间复杂度为O(n^2)
+ 单值修改,n次也为O(n)
+ 优化
+ 额外设置一个数组B同步保存原操作数组假设为A的前i个和,那么求和就直接取B中下标的值即可,n次操作,时间复杂度降为O(n)
+ 缺点
+ 每次单值修改后,必然要重新修改B中每一项存储的A中前i个和,n次操作,效率降低为O(n^2)
+ 树状数组
+ 时间复杂度:O(nlogn)
+ 整合了一般方法中的两种解决手段的优点
+ 图解
+ 
+ 
+ 思路
+ 如图所示
+ 数组A存放原数组(每项都是初始值)
+ 引入一个辅助数组C,建立数组数组
+ C1 = A1
+ C2 = C1 + A2 = A1 + A2
+ C3 = A3
+ C4 = C2 + C3 + A4 = A1 + A2 + A3 + A4
+ C5 = A5
+ C6 = C5 + A6 = A5 + A6
+ C7 = A7
+ C8 = C4 + C6 + C7 = A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8
+ 设**C[i]的值为下标为i的数所管辖的数的和**
+ C[8]存放的是编号为8所管辖的n个数的和(有8个)
+ n == 2^k
+ k为i的二进制的末尾0的个数
+ 例如
+ m == 8
+ C[8]管了8个数,8的二进制为 1000
+ 8 == 2^3,恰好末尾3个0,k == 3
+ m == 5
+ C[5]管了1个数,5的二进制为 0101
+ 1 == 2^0,恰好末尾1个0,k == 0
+ 求和 O(nlogn)
+ 求A1~Am即前m个数的和
+ m == 7
+ sum(7) == C7 + C6 + C4 == A7 + A5 + A6 + A1 + A2 + A3 + A4
+ m == 6
+ sum(6) == C6 + C4 == A5 + A6 + A1 + A2 + A3 + A4
+ 原理
1. 每次将输入的m转为二进制,加上转换十进制后的m,+ C(m)
2. 将m二进制末尾的1删掉一个替换为0,并再转换为十进制即为C(j), + C[j]
3. 重复第2步,直到m二进制中没有1 即 m == 0 时终止
4. 结束
1. 返回C(m) + C(j) + ... + C(n) = sum(m)
2. 而C数组的数已经可以通过下标直接访问
+ 示例
+ m == 7 => sum(7) == C7 + C6 + C4
+ 7 => 0111 => 7,+C(7)
+ 0111 => 0110 => 6,+C(6)
+ 0110 => 0100 => 4,+C(4)
+ 0100 => 0000 => 0,终止
+ m == 6 => sum(6) == C6 + C4
+ 6 => 0110 => 6,+C(6)
+ 0110 => 0100 => 4,+C(4)
+ 0100 => 0000 => 0,终止
+ 解题技巧
+ 对于移除二进制数当前最后一个1的操作可以用位运算
+ 最后一个1表示的数
+ m & -m
+ 如 7(0111)最后一个1的位置为0,所以十进制数为2^0 = 1
+ 7 & -7 = 1
+ 那么如示例中,每次清除二进制末尾1的操作等价于,每次当前十进制m减去当前二进制数m最后一个1的位置所表示的十进制数
+ 求二进制最后一个1所代表的十进制数
+ m & -m
+ 原理
+ 负数在计算机中是以补码的形式存储的
+ 举个栗子
+ 13 => 1101
+ -13 转换二进制:将13按位取反,然后末尾+1
+ 0010 + 0001 = 0011
+ 13 & -13
+ 1101 & 0011 = 0001
+ 得到了13的二进制数的末尾1的二进制
+ 由题意,减去末尾1:
+ 1101 - 0001 = 13 - 2^0 = 12
+ 对12再次执行末尾清1的操作
+ 12 & -12
+ 1100 & 0100 = 0100
+ 由上述,减去末尾1:
+ 1100 - 0100 = 12 - 2^2 = 8
+ 对8再次执行末尾清1的操作
+ 8 & -8
+ 0100 & 1100 = 0100
+ 由上述,减去末尾1:
+ 0100 - 0100 = 8 - 2^2 = 0
+ 0,末尾没有1可清了,终止
+ 循环上述操作
+ sum(13) = C(13) + C(12) + C(8)
+ 求末尾二进制1的十进制
```javascript
// m为输入的求数组A中前m个数的和
let lowbit = (m) => {
return m & (-m)
}
```
+ 综上所述
```javascript
let sum = 0;
let getSum = (m) => {
while(m > 0){
// 求和
sum += C[m];
// 清1
m -= lowbit(m);
}
}
```
+ 单点更新(值修改) O(nlogn)
+ 
+ 设A[2],我们要对A[2]执行加一个数的修改值的操作:+value(6)
+ 简单修改A[2]值,可以直接A[2]+=value实现
+ 但是由求和实现可知,是通过C[i]+...+C[n]实现的
+ 而C[i]的值为下标为i的数所管辖的数的和,更新了管辖的数,涉及到的C[i]数自然也必须更新,不然求和会不正确
+ C[2],C[4],C[8]均管辖了A[2]的值
+ 那么如何从2得知管辖它的C[j]中j有哪些呢
+ 由求和中lowbit原理可知
+ 求sum[m],可以通过lowbit得到相关的C[m](m为每次末尾清1后得到的数)
+ 变更了A[x],那么管辖它的多个C[m]均要加value
+ 同理,我们每次对x的二进制加一再转成十进制即为,下一个C[m]中m的值
+ 终止条件自然为m的33最大值,即输入值
+ 同样可以复用求和中,求当前二进制m中最后一个1所代表的十进制数
+ 每次执行+1操作即可
+ 综上所述
```javascript
let update = (x,value) => {
// 先更新要修改的节点
A[x] += value;
// 再更新会影响求前缀和的C[m]的值
while(x <= m){
C[x] += value;
x += lowbit(x);
}
}
```
+ 初始化C
+ 设一个元素均为0长度为输入长度m的数组C,原数组A
+ 每次输入值的过程即为更新C的过程
```javascript
// 初始化并更新树状数组C
let C = new Array(m+1).fill(0);
for(let i = 1;i <= m;i++){
update(i,A[i]);
}
```
+ 代码总结
```javascript
let treeArray = (m) => {
// 初始化树状数组
let update = (x,value) => {
// 先更新要修改的节点
A[x] += value;
// 再更新会影响求前缀和的C[m]的值
while(x <= m){
C[x] += value;
x += lowbit(x);
}
}
// 求前缀和
let sum = 0;
let getSum = (m) => {
while(m > 0){
sum += C[m];
m -= lowbit(m);
}
}
// 求当前二进制数m最后一位1所代表的十进制数
let lowbit = (m) => {
return m & (-m)
}
// 单点更新
let update = (x,value) => {
// 先更新要修改的节点
A[x] += value;
// 再更新会影响求前缀和的C[m]的值
while(x <= m){
C[x] += value;
x += lowbit(x);
}
}
}
```
### 练习
+ [493. 翻转对-解法三](https://leetcode-cn.com/problems/reverse-pairs/solution/493-fan-zhuan-dui-by-alexer-660/)<file_sep># 摘要
+ 高级动态规划
+ 字符串算法
+ 课后思考
### 高级动态规划
+ “Simplifying a complicated problem by breaking it down into simpler sub-problems”(in a recursive manner)
+ Divide & Conquer + Optimal substructure
+ 分治 + 最优子结构
+ 顺推形式: 动态递推
+ 顺推模板
```javascript
function DP():
// ⼆维情况
dp = [][]
for i = 0 .. M {
for j = 0 .. N {
dp[i][j] = _Function(dp[i’][j’]…)
}
}
return dp[M][N];
```
+ 关键点
+ 有无最优的子结构
+ 找到重复子问题
+ 最优子结构、中途可以淘汰次优解
+ 实例
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/solution/70-pa-lou-ti-by-alexer-660/)
+ [746. 使用最小花费爬楼梯](https://leetcode-cn.com/problems/min-cost-climbing-stairs/solution/746-shi-yong-zui-xiao-hua-fei-pa-lou-ti-by-alexer-/)
+ [爬楼梯问题变种:图文-详解](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/demos/climbing-stairs3.md)
+ [62. 不同路径](https://leetcode-cn.com/problems/unique-paths/solution/62-bu-tong-lu-jing-by-alexer-660/)
+ [63. 不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/solution/63-bu-tong-lu-jing-ii-by-alexer-660/)
+ [198. 打家劫舍](https://leetcode-cn.com/problems/house-robber/solution/198-da-jia-jie-she-by-alexer-660/)
+ [213. 打家劫舍 II](https://leetcode-cn.com/problems/house-robber-ii/solution/213-da-jia-jie-she-ii-by-alexer-660/)
+ [64. 最小路径和](https://leetcode-cn.com/problems/minimum-path-sum/solution/64-zui-xiao-lu-jing-he-by-alexer-660/)
+ [编辑距离](https://leetcode-cn.com/problems/edit-distance/solution/72-bian-ji-ju-chi-by-alexer-660/)
+ 股票6道
+ 1、[121. 买卖股票的最佳时机](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/)
+ 2、[122. 买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
+ 3、[123. 买卖股票的最佳时机 III](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/submissions/)
+ 4、[309. 最佳买卖股票时机含冷冻期](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/submissions/)
+ 5、[188. 买卖股票的最佳时机 IV](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/submissions/)
+ 6、[714. 买卖股票的最佳时机含手续费](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/submissions/)
### 字符串算法
+ 最长子序列
+ [1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/solution/1143-zui-chang-gong-gong-zi-xu-lie-by-alexer-660/)
+ s1[i-1] == s2[j-1] && dp[i][j] = dp[i-1][j-1] + 1
+ s1[i-1] != s2[j-1] && dp[i][j] = Max(dp[i-1][j],dp[i][j-1])
+ 最长子串
+ 最长子序列的变体
+ 即子序列必须在原字符串中连续
+ s1[i-1] == s2[j-1] && dp[i][j] = dp[i-1][j-1] + 1
+ s1[i-1] != s2[j-1] && dp[i][j] = 0
+ 编辑距离
+ [72. 编辑距离](https://leetcode-cn.com/problems/edit-distance/solution/72-bian-ji-ju-chi-by-alexer-660/)
+ s1[i-1] == s2[j-1] && dp[i][j] = dp[i-1][j-1]
+ s1[i-1] != s2[j-1] && dp[i][j] = Min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]+1)
+ 最长回文串
+ [5. 最长回文子串](https://leetcode-cn.com/problems/longest-palindromic-substring/solution/5-zui-chang-hui-wen-zi-chuan-by-alexer-660/)
+ dp[i][j] = s[i] == s[j] && (j - i < 2 || dp[i+1][j-1])
+ 字符串匹配算法KMP
+ 暴力法(brute force) - O(mn)
+ Rabin-Karp 算法
+ KMP 算法
+ KMP算法(Knuth-Morris-Pratt)的思想就是,当子串与目标字符串不匹配时,
+ 其实你已经知道了前面已经匹配成功那 一部分的字符(包括子串与目标字符串)。
+ 以阮一峰的文章为例,当空格与 D 不匹配时,你其实 知道前面六个字符是“ABCDAB”。
+ KMP 算法的想法是,设法利用这个已知信息,不要把“搜索位置” 移回已经比较过的位置,继续把它向后移,这样就提高了效率。
+ 暴力法
```java
public static int forceSearch(String txt, String pat) {
int M = txt.length();
int N = pat.length();
for (int i = 0; i <= M - N; i++) {
int j;
for (j = 0; j < N; j++) {
if (txt.charAt(i + j) != pat.charAt(j))
break;
}
if (j == N) {
return i;
}
// 更加聪明?
// 1. 预先判断– hash(txt.substring(i, M)) == hash(pat)
// 2. KMP
}
return -1;
}
```
+ 文献
+ [文献A](https://www.bilibili.com/video/av11866460?from=search&seid=17425875345653862171)
+ [文献B](http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html)
+ 学习资料
+ [Boyer-Moore 算法](https://www.ruanyifeng.com/blog/2013/05/boyer-moore_string_search_algorithm.html)
+ 在朴素算法中,我们需要挨个比较所有字符,才知道目标字符串中是否包含子串。
+ 那么, 是否有别的方法可以用来判断目标字符串是否包含子串呢?
+ 答案是肯定的,确实存在一种更快的方法。为了避免挨个字符对目标字符串和子串进行比较,
+ 我们可以尝试一次性判断两者是否相等。因此,我们需要一个好的哈希函数(hash function)。
+ 通过哈希函数,我们可以算出子串的哈希值,然后将它和目标字符串中的子串的哈希值进行比较。
+ 这个新方法在速度上比暴力法有显著提升。
+ 核心思想
1. 假设子串的长度为 M (pat),目标字符串的长度为 N (txt)
2. 计算子串的 hash 值 has_pat
3. 计算目标字符串txt中每个长度为 M 的子串的 hash 值(共需要计算 N-M+1次)
4. 比较 hash 值:如果 hash 值不同,字符串必然不匹配; 如果 hash 值相同,还需要使用朴素算法再次判断
> KMP算法(Knuth-Morris-Pratt)的思想就是,当子串与目标字符串不匹配时,其实你已经知道了前面已经匹配成功那 一部分的字符(包括子串与目标字符串)。
以阮一峰的文章为例,当空格与 D 不匹配时,你其实 知道前面六个字符是“ABCDAB”。
KMP 算法的想法是,设法利用这个已知信息,不要把“搜索位置” 移回已经比较过的位置,继续把它向后移,这样就提高了效率。
+ code
```java
public final static int D = 256;
public final static int Q = 9997;
static int RabinKarpSerach(String txt, String pat) {
int M = pat.length();
int N = txt.length();
int i, j;
int patHash = 0, txtHash = 0;
for (i = 0; i < M; i++) {
patHash = (D * patHash + pat.charAt(i)) % Q;
txtHash = (D * txtHash + txt.charAt(i)) % Q;
}
int highestPow = 1; // pow(256, M-1)
for (i = 0; i < M - 1; i++)
highestPow = (highestPow * D) % Q;
for (i = 0; i <= N - M; i++) {
// 枚举起点
if (patHash == txtHash) {
for (j = 0; j < M; j++) {
if (txt.charAt(i + j) != pat.charAt(j))
break;
}
if (j == M)
return i;
}
if (i < N - M) {
txtHash = (D * (txtHash - txt.charAt(i) * highestPow) + txt.charAt(i + M)) % Q;
if (txtHash < 0)
txtHash += Q;
}
}
return -1;
}
```
+ [Sunday 算法](https://blog.csdn.net/u012505432/article/details/52210975)
### 课后思考
+ [62. 不同路径](https://leetcode-cn.com/problems/unique-paths/solution/62-bu-tong-lu-jing-by-alexer-660/)
+ 状态定义
+ dp[i][j]:来到当前格子的最短路径总数
+ 状态转移方程
+ **dp[i][j] = dp[i-1][j] + dp[i][j-1]**
+ [63. 不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/solution/63-bu-tong-lu-jing-ii-by-alexer-660/)
+ 状态定义
+ dp[i][j] == 0 ,此路不通
+ dp[i][j] != 0 ,最短路径总数
+ 状态转移方程
+ **obstacleGrid[i][j] != 1 && dp[i][j] = dp[i-1][j] + dp[i][j-1]**
<file_sep>#### 两个栈实现一个队列
```javascript
let stack1 = [];
let stack2 = [];
function push(node){
while(stack2.length !== 0){
stack1.push(stack2.pop());
}
return stack1.push(node);
}
function pop(){
while(stack1.length !== 0){
stack2.push(stack1.pop())
}
return stack2.pop()
}
```
#### 两个队列实现一个栈
```javascript
let queue1 = [];
let queue2 = [];
function push (node){
if(queue1.length === 0){
queue2.push(node);
}else{
queue1.push(node);
}
}
function pop (){
if(queue1.length === 0){
while(queue2.length !== 1){
queue1.push(queue2.pop())
}
return queue2.pop();
}else{
while(queue1.length !=== 1){
queue2.puush(queue1.pop());
}
return queue1.pop();
}
}
``` <file_sep>## 实现一个 sum(1)(2)(4,1).valueOf() sum(1,2,3,4).valueOf()
#### 解法一:add(1)(2)(3) 6
```javascript
function add(x) {
var sum = x;
var tmp = function(y) {
sum = sum + y;
return tmp;
}
tmp.toString = function (){
return sum;
}
return tmp;
}
```
#### 解法二:sum(1)(2)(3)、sum(1,2,3)
```javascript
function sum(...arguments){
if([...arguments].length == 1){
var sum = [...arguments][0];
var tmp = function(y){
sum += y;
return tmp;
}
// valueOf
tmp.toString = function (){
return sum;
}
return tmp;
}else{
var sum2 = 0;
var tmpArr = [...arguments];
for(var i = 0;i < tmpArr.length;i++){
sum2 += tmpArr[i];
}
return sum2;
}
}
```
#### 解法三:通用的函数柯里化构造方法
```javascript
// 通用的函数柯里化构造方法
function curry(func){
//新建args保存参数,注意,第一个参数应该是要柯里化的函数,所以args里面去掉第一个
var args = [].slice.call(arguments,1);
//新建_func函数作为返回值
var _func = function(){
//参数长度为0,执行func函数,完成该函数的功能
if(arguments.length === 0){
return func.apply(this,args);
}else {
//否则,存储参数到闭包中,返回本函数
[].push.apply(args,arguments);
return _func;
}
}
return _func;
}
function add(){
return [].reduce.call(arguments,function(a,b){return a+b});
}
console.log(curry(add,1,2,3)(1)(2)(3,4,5,5)(5,6,6,7,8,8)(1)(1)(1)());//69
```<file_sep># 摘要
+ 动态规划
+ 分治、回溯、递归
+ demos
+ 解法总结
+ 课后思考
### 模板
+ 递归
```java
public void recur(int level,int param){
// terminator
if(level > MAX_LEVEL){
// process result
return;
}
// process current logic
process(level,param);
// drill down
recur(level:level+1,newParam);
}
```
+ 分治 Divide & Conquer
```python
def divide_conquer(problem,param1,param2,...):
# recursion terminator
if problem is None:
print_result
return
# prepare data
data = prepare_data(problem)
subproblems = split_problem(problem,data)
# conquer subproblems
subresult1 = self.divide_conquer(subproblems[0],p1,...)
subresult2 = self.divied_conquer(Subproblems[1],p1,...)
subresult3 = self.divied_conquer(Subproblems[2],p1,...)
""
# process and generate the final result
result = process_result(subresult1,subresult2,subresult3,...)
# revert the current level states
```
### 差异
+ 动态规划 和 递归或者分治 没有根本上的区别
+ 关键是看有无最优的子结构
+ 共性
+ 找到重复子问题
+ 差异性
+ 最优子结构、中途可以被淘汰次优解
### dp关键点
1. 最优子结构
1. opt[n] = best_of(opt[n-1],opt[n-2],...)
2. 储存中间状态
1. opt[i]
3. 递推公式
1. Fib: opt[n] = opt[n-1]+opt[n-2]
2. 二维路径:opt[i,j] = opt[i+1][j] + opt[i][j+1]
1. 需判断a[i,j]是否可达,如障碍物
### demos
+ 斐波那契数列
```java
int fib(int n){
if(n <= 1){
return n;
}
return fib(n-1) + fib(n-2);
}
int fib(int n){
return n <= 1 ? n : fib(n-1) + fib(n-2)
}
int fib(int n,int [] meno){
if(n <= 1){
return n;
}
if(memo[n] == 0){
meno = fib(n-1) + fib(n-2);
}
return memo[n];
}
// Bottom Up
F[n] = F[n-1]+F[n-2]
a[0] = 0,a[1] = 1;
for(int i = 2;i <= n;i++){
a[i] = a[i-1] + a[i-2]
}
a[n]
```
+ 路径计数
+ 图解


```java
int countParts(boolean[][]grid,int row,int col){
if(!validSquare(grid,row,col)) return 0;
if(isAtEnd(grid,row,col)) return 1;
return countPaths(grid,row+1,col) + countPaths(grid,row,col+1);
}
```




+ 求状态转移方程(DP方程)
+ opt[i,j] = opt[i+1,j] + opt[i,j+1]
+ if a[i,j] = '空地';
+ opt[i,j] = opt[i+1,j]+opt[i,j+1]
+ else
+ opt[i,j] = 0
+ 其它dp题型
+ [62. 不同路径](https://leetcode-cn.com/problems/unique-paths/solution/62-bu-tong-lu-jing-by-alexer-660/)
+ [63. 不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/solution/63-bu-tong-lu-jing-ii-by-alexer-660/)
+ [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/solution/70-pa-lou-ti-by-alexer-660/)
### 解法总结
+ 1、define subproblems
+ 进行分治:总问题分解为子问题
+ 2、guess(part of solution)
+ 猜递归方程形式
+ 3、relate subproblem solutions
+ 将n个子问题的解联系起来 <=> 合并子问题的解
+ 4、recurse && memorize 或者 build DP table bottom-up
+ 递归+备忘录搜索 或者 建立一个自底向上的表来递推
#### 课后思考
+ [爬楼梯问题变种:图文-详解](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/demos/climbing-stairs3.md)<file_sep># 摘要
+ 位运算
+ 布隆过滤器
+ LRU Cache
+ 排序算法
+ 算法区别
### 位运算
+ 意义
+ 机器里的数字表示方式和存储格式就是 二进制
+ 算数移位与逻辑移位
+ 左移
+ "<<":0011 => 0110
+ 右移
+ ">>":0110 => 0011
+ 位运算符
+ “|”
+ 按位或
+ 0011,1011 => 1011
+ “ & ”
+ 按位与
+ 0011,1011 => 0011
+ “ ~ ”
+ 按位取反
+ 0011 => 1100
+ “ ^ ”
+ 按位异或(相同为零、不同为一)
+ 0011,1011 => 1000
+ 常用
+ x ^ 0 = x
+ x ^ 1s = ~x (注意 1s = ~)
+ x ^ (~x) = 1s
+ x ^ x = 0
+ c = a ^ b => a ^c = b,b ^c =a(交换两个数)
+ a ^ b ^ c = a ^ (b ^ c) = (a ^ b)^c //associative
+ 指定位置的位运算
1. 将 x 最右边的 n 位清零:x & (~0 <<
2. 获取 x 的第 n 位值(0 或者 1): (x >> n) &
3. 获取 x 的第 n 位的幂值:x & (1 << (n -1))
4. 仅将第 n 位置为 1:x | (1 << n)
5. 仅将第 n 位置为 0:x & (~ (1 << n))
6. 将 x 最高位至第 n 位(含)清零:x & ((1 << n) - 1)
7. 将第 n 位至第 0 位(含)清零:x & (~ ((1 << (n + 1)) - 1))
+ 实战常用
+ x % 2 == 1 —> (x & 1) == 1
+ x % 2 == 0 —> (x & 1) == 0
+ x >> 1 —> x / 2
+ X = X & (X-1) 清零最低位的 1
+ X & -X => 得到最低位的 1
+ X & ~X => 0
+ 转换整数
+ parseInt(string,radix)
+ Math.trunc()
+ ~~n
+ n | n
+ n | 0
+ n << 0
+ n >> 0
+ n & n
### 布隆过滤器
+ 布隆过滤器可以用于检索一个元素是否在一个集合中。
+ 一个很长的二进制向量
+ 和一系列随机映射函数。
+ 是一个占用空间很小、效率很高的随机数据结构,它由一个bit数组和一组Hash算法构成。
+ 可用于判断一个元素是否在一个集合中,查询效率很高(1-N,最优能逼近于1)
+ 图示

+ 优点
+ 空间效率和查询时间都远远超过一般的算法
+ 缺点
+ 有一定的误识别率和删除困难
+ 实际应用
+ 比特币网络
+ 分布式系统(Map-Reduce) — Hadoop、search engine
+ Redis 缓存
+ 垃圾邮件、评论等的过滤
+ 网页爬虫对URL的去重,避免爬取相同的URL地址(一个网址是否被访问过)
+ 反垃圾邮件,从数十亿个垃圾邮件列表中判断某邮箱是否垃圾邮箱(同理,垃圾短信)
+ 缓存击穿,将已存在的缓存放到布隆中,当黑客访问不存在的缓存时迅速返回避免缓存及DB挂掉
+ 字处理软件中,需要检查一个英语单词是否拼写正确
+ 在 FBI,一个嫌疑人的名字是否已经在嫌疑名单上
### LRU Cache
+ 缓存手段
+ LFU - least frequently used
+ LRU - least recently used
+ 实现
+ Hash Table + Double LinkedList
+ 时间复杂度
+ O(1) 查询
+ O(1) 修改、更新
+ 实现
+ [146. LRU缓存机制](https://leetcode-cn.com/problems/lru-cache/solution/146-lruhuan-cun-ji-zhi-by-alexer-660/)
+ 模板
+ Python
```Python
class LRUCache(object):
def __init__(self, capacity):
self.dic = collections.OrderedDict()
self.remain = capacity
def get(self, key):
if key not in self.dic:
return -1
v = self.dic.pop(key)
self.dic[key] = v # key as the newereturn v
return v
def put(self, key, value):
if key in self.dic:
self.dic.pop(key)
else:
if self.remain > 0:
self.remain -= 1
else: # self.dic is full
self.dic.popitem(last=False)
self.dic[key] = value
```
+ java
```java
public class LRUCache {
private Map<Integer, Integer> map
public LRUCache(int capacity) {
map = new LinkedCappedHashMap<>(capacity);
}
public int get(int key) {
if(!map.containsKey(key)) { return -1; }
return map.get(key);
}
public void put(int key, int value) {
map.put(key,value);
}
private static class LinkedCappedHashMap<K,V> extends LinkedHashMap<K,V> {
int maximumCapacity;
LinkedCappedHashMap(int maximumCapacity) {
super(16, 0.75f, true);
this.maximumCapacity = maximumCapacity;
}
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > maximumCapacity;
}
}
}
```
+ javascript
```javascript
// 链表节点
class Node{
constructor(key,val){
this.key = key;
this.val = val;
}
}
// 双链表
class DoubleList{
// 初始化头、尾节点、链表最大容量
constructor(){
this.head = new Node(0,0);
this.tail = new Node(0,0);
this.size = 0;
this.head.next = this.tail;
this.tail.prev = this.head;
}
// 在链表头部添加节点
addFirst(node){
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
this.size++;
}
// 删除链表中存在的node节点
remove(node){
node.prev.next = node.next;
node.next.prev = node.prev;
this.size--;
}
// 删除链表中最后一个节点,并返回该节点
removeLast(){
// 链表为空
if(this.tail.prev == this.head){
return null;
}
let last = this.tail.prev;
this.remove(last);
return last;
}
}
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.cap = capacity;
this.map = new Map();
this.cache = new DoubleList();
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
let map = this.map;
if(!map.has(key)){
return -1;
}
let val = map.get(key).val;
// 最近访问数据置前
this.put(key,val);
return val;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
let cache = this.cache;
let map = this.map;
let node = new Node(key,value);
if(map.has(key)){
// 删除旧的节点,新的插到头部
cache.remove(map.get(key));
}else{
if(this.cap == cache.size){
// 删除最后一个
let last = cache.removeLast();
map.delete(last.key);
}
}
// 新增头部
cache.addFirst(node);
// 更新 map 映射
map.set(key,node);
};
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
```
### 排序算法
+ 非比较类排序
+ 计数排序
+ 基数排序
+ 桶排序
+ 比较类排序
+ 交换排序
+ 冒泡排序
+ **快速排序**
+ 插入排序
+ 简单插入排序
+ 希尔排序
+ 选择排序
+ 简单选择排序
+ **堆排序**
+ **归并排序**
+ 二路归并排序
+ 多路归并排序
+ 图解
+ 
+ 
+ 算法稳定性
+ 稳定
+ 相同的两个元素,经过排序后位置顺序没有变化
+ 不稳定
+ 相同的两个元素,经过排序后位置顺序发生变化
+ 以下排序算法所用测试用例
```javascript
// 生成n个1~scope的随机数字
let randomArr = (n,scope) => {
let arr = [];
for(let i = 0;i < n;i++){
arr.push(~~(Math.random()*scope) + 1)
}
return arr;
}
// 交换两个数字[注意是两个数字,且如果自己异或自己,结果为0]
// 1、位运算
a ^= b;
b ^= a;
a ^= b;
// 2、中间变量
let tmp = a;
a = b;
b = a;
// 3、ES6语法糖
[a,b] = [b,a]
```
+ 初级排序 - O( n^2 )
+ 选择排序 - (Selection Sort)
+ **每次找到最小值,然后放到待排序数组的起始位置**
+ **找最小值的索引**
+ **经过n-1趟**
+ 
+ code
```javascript
let selectionSort = (arr) => {
let len = arr.length;
let minIndex;
for(let i = 0;i < len - 1;i++){
minIndex = i;
for(let j = i + 1;j < len;j++){
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
// 自己异或自己 == 0
if( (minIndex ^ i) !== 0){
arr[i] ^= arr[minIndex];
arr[minIndex] ^= arr[i];
arr[i] ^= arr[minIndex];
}
}
return arr;
}
```
+ 插入排序 - (Insertion Sort)
+ **从前到后逐步构建有序序列**
+ **对于未排序序列,在已排序序列中从后向前扫描,找到相应位置并插入**
+ 
+ code
```javascript
let insertionSort = (arr) => {
let len = arr.length;
let preIndex,current;
for(let i = 1;i < len;i++){
preIndex = i - 1;
current = arr[i];
while(preIndex >= 0 && arr[preIndex] > current){
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = current;
}
return arr;
}
```
+ 希尔排序 - (Shell Sort)
+ 简单插入排序的进阶版,又叫缩小增量排序
+ 区别
+ 与插入排序不同的是,会优先比较距离较远的元素
+ **将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序**
+ **选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1**
+ **按增量序列个数k,对序列进行k 趟排序**
+ **每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列,分别对各子表进行直接插入排序。**
+ **仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度**
+ 
+ code
```javascript
let shellSort = (arr) => {
let len = arr.length;
for(let gap = (len >> 1);gap > 0;gap >>= 1){
for(let i = gap;i < len;i++){
let j = i;
let curr = arr[i];
while(j - gap >= 0 && curr < arr[j - gap]){
arr[j] = arr[j - gap];
j = j - gap;
}
arr[j] = curr;
}
}
return arr;
}
```
+ 冒泡排序 - (Bubble Sort)
+ **嵌套排序,每次查看相邻的元素如果逆序,则交换**
+ 
+ code
```javascript
let bubbleSort = (arr) => {
let n = arr.length - 1;
for(let i = 0;i < n;i++){
for(let j = 0;j < n;j++){
if(arr[j] > arr[j+1]){
arr[j] ^= arr[j+1];
arr[j+1] ^= arr[j];
arr[j] ^= arr[j+1];
}
}
}
return arr;
}
```
+ 改进版
+ 1、设置两个个标志位,pos用于标识最后一次交换的位置,flag用于当前数组是否已经有序的标志
```javascript
let bubblesort = (arr) => {
let i = arr.length - 1;
while(i > 0){
let flag = true;
let pos = 0;
for(let j = 0;j < i;j++){
if(arr[j] > arr[j+1]){
pos = j;
flag = false;
[arr[j],arr[j+1]] = [arr[j+1],arr[j]];
}
}
if(flag) break;
i = pos;
}
return arr;
}
```
+ 2、一次排序同时找出最大值和最小值,查询次数减少一半
```javascript
let bubblesort = (arr) => {
let high = arr.length - 1;
let low = 0;
while(low < high){
for(let i = 0;i < high;i++){
if(arr[i] > arr[i+1]){
[arr[i],arr[i+1]] = [arr[i+1],arr[i]];
}
}
--high;
for(let j = high;j > low;j--){
if(arr[j] < arr[j-1]){
[arr[j],arr[j-1]] = [arr[j-1],arr[j]];
}
}
++low;
}
return arr;
}
```
+ 高级排序 - O( N*LogN )
+ 快速排序 - (Quick Sort)
+ **数组取标杆 pivot**
+ **将小元素放 pivot 左边,大元素放右侧**
+ **然后依次对右边和右边对子数组继续快排**
+ 
+ 借助额外空间
+ 
+ 此种思路和快排思想很吻合,缺点是空间复杂度高
+ code
```javascript
let quickSort = (arr) => {
if(arr.length <= 1) return arr;
let pivot = arr[arr.length-1];
let left = [];
let right = [];
for(let i = 0;i < arr.length;i++){
if(arr[i] < pivot){
left.push(arr[i]);
}else if(arr[i] > pivot){
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot],quickSort(right));
}
```
+ 或者这样写
```javascript
let quickSort = (arr) => {
if(arr.length <= 1) return arr;
const pivot = arr.pop();
let left = arr.filter(item => item < pivot);
let right = arr.filter(item => item >= pivot);
return quickSort(left).concat([pivot], quickSort(right));
}
```
+ 原地替换
+ 
+ 此种思路,利用交换方法避免每次都创建左右两个数组,不是很好理解,多看图
+ code
```javascript
// 分区函数 + 原地替换
let partition = (arr,start,end) => {
let pivot = end;
let newPivot = start;
for(let i = start;i < end;i++){
// 遵循小的替换到左边,大的顺延或者被替换到后面
if(arr[i] < arr[pivot]){
[arr[i],arr[newPivot]] = [arr[newPivot],arr[i]];
newPivot++;
}
}
// 更新基准值,小的在左,大的在后
[arr[newPivot],arr[pivot]] = [arr[pivot],arr[newPivot]];
return newPivot;
}
let quick_sort = (arr,start,end) => {
if(start >= end){
return;
}
let pivot = partition(arr,start,end);
quick_sort(arr,start,pivot-1);
quick_sort(arr,pivot+1,end);
}
```
+ 归并排序 - (Merge Sort) ~ 分治
+ **把长度为n的输入序列分成两个长度为n/2的子序列**
+ **对这两个子序列分别采用归并排序**
+ **将两个排序好的子序列合并成一个最终的排序序列**
+ 
+ 递归版
+ 
+ code
```javascript
let mergeArr = (left,right) => {
let result = [];
let left_i = 0,right_j = 0;
while(left_i < left.length && right_j < right.length){
if(left[left_i] <= right[right_j]){
result.push(left[left_i]);
left_i++;
}else{
result.push(right[right_j]);
right_j++
}
}
return [...result,...left.slice(left_i),...right.slice(right_j)];
}
let mergeSort = (arr) => {
if(arr.length <= 1){
return arr;
}
let mid = arr.length >> 1;
let left = arr.slice(0,mid);
let right = arr.slice(mid);
return mergeArr(mergeSort(left),mergeSort(right));
}
```
+ 或者
```javascript
let mergeArr = (arr,left,mid,right) => {
let temp = [];
let i = left,j = mid + 1,sortedIndex = 0;
while(i <= mid && j <= right){
temp[sortedIndex++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
}
while(i <= mid){
temp[sortedIndex++] = arr[i++];
}
while(j <= right){
temp[sortedIndex++] = arr[j++];
}
for(let r = 0;r < temp.length;r++){
arr[left + r] = temp[r];
}
}
let mergeSort = (arr,left,right) => {
if(left >= right){
return;
}
let mid = (left + right) >> 1;
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);
mergeArr(arr,left,mid,right);
}
```
+ 非递归版
+ 思路
+ 对于给定数组,每次归并2*i个元素
+ 初始化每次归并1 个元素,即i = 1
+ 
+ code
+ javascript
```javascript
let mergeArr = (left,mid,right) => {
let tmp = [];
let i = left;
let j = mid + 1;
let sortedIndex = 0;
while(i <= mid && j <= right){
if(arr[i] <= arr[j]){
tmp[sortedIndex++] = arr[i++];
}else{
tmp[sortedIndex++] = arr[j++];
}
}
while(i <= mid){
tmp[sortedIndex++] = arr[i++];
}
while(j <= right){
tmp[sortedIndex++] = arr[j++];
}
for(let i = 0;i < tmp.length;i++){
arr[left + i] = tmp[i];
}
}
let mergeSort = (arr) => {
let n = arr.length;
for(let i = 1;i < n;i *= 2){
for(let j = 0;j + i < n;j += i*2){
let left = j;
let mid = i + j - 1;
let right = Math.min(j + 2*i - 1,n - 1);
mergeArr(left,mid,right);
}
}
}
```
+ java
+ 
+ 堆排序 - (Heap Sort)
+ 是一种特殊的树
+ 是一个完全二叉树
+ 除了最后一层,其他层的节点个数都是满的
+ 最后一层的节点都靠左排列
+ 比较适合用数组来存储
+ 
+ 堆中每个节点的值大于等于或小于等于其左右子树中(或者说左右子节点)每个节点的值
+ 原地排序
+ 大顶堆:
+ 每个节点的值都大于或等于其子节点的值,在堆排序算法中用于升序排列
+ 小顶堆:
+ 每个节点的值都小于或等于其子节点的值,在堆排序算法中用于降序排列
+ 部分操作时间复杂度
+ 插入:O(logN)
+ 取最大、小值:O(1)
+ **1、数组元素依次建立小顶堆**
+ **2、依次取堆顶元素,并删除**
+ 
+ code
```javascript
let len;
let swap = (arr,i,j) => {
[arr[i],arr[j]] = [arr[j],arr[i]];
}
// 建立大顶堆
let buildMaxHeap = (arr) => {
len = arr.length;
for(let i = (len >> 1);i >= 0;i--){
heapify(arr,i);
}
}
// 堆节点调整
let heapify = (arr,i) => {
let left = 2 * i + 1;
let right = 2 * i + 2;
let largest = i;
if(left < len && arr[left] > arr[largest]){
largest = left;
}
if(right < len && arr[right] > arr[largest]){
largest = right;
}
if(largest != i){
swap(arr,i,largest);
heapify(arr,largest);
}
}
// 主函数
let heapSort = (arr) => {
buildMaxHeap(arr);
for(let i = arr.length - 1;i > 0;i--){
swap(arr,0,i);
len--;
heapify(arr,0);
}
return arr;
}
```
+ 特殊排序 - O(n)
+ 计数排序(Counting Sort)
+ 计数排序要求输入的数据必须是有确定范围的整数。
+ 将输入的数据值转化为键存储在额外开辟的数组空间中;
+ 然后依次把计数大于 1 的填充回原数组
+ 
+ 经典版 - 借助额外空间
+ code
```javascript
let countingSort = (arr,maxValue) => {
let bucket = new Array(maxValue+1).fill(0);
let sortedIndex = 0;
let arrLen = arr.length;
let bucketLen = maxValue + 1;
for(let i = 0;i < arrLen;i++){
bucket[arr[i]]++;
}
for(let j = 0;j < bucketLen;j++){
while(bucket[j] > 0){
arr[sortedIndex++] = j;
bucket[j]--;
}
}
return arr;
}
```
+ 原地交换版 - 不借助额外空间
+ 思路解析
+ 重复对当前值大于0的元素进行
+ 当前值 != 当前值为索引的元素
+ 当前值和当前值为索引的元素进行交换
+ 模仿经典版进行计数
+ 对于有重复元素的数组进行频繁交换会和下面这个交换条件冲突
+ 当前值 != 当前值为索引的元素
+ 因为你不知道 当前值为索引的元素是原来的值还是被替换过来的
+ 处理很麻烦,就不如经典版容易理解了
+ [例题 - 缺失的第一个正数 - 解法四](https://github.com/Alex660/leetcode/blob/master/leetCode-0-041-first-missing-positive.md)
+ **此解法只适用于原数组中没有重复元素时**
+ code
```javascript
let countingSort = (arr) => {
let n = arr.length;
let sortedIndex = 0;
for(let i = 0;i <= n;i++){
while(arr[i] > 0 && arr[arr[i]] != arr[i]){
[arr[arr[i]],arr[i]] = [arr[i],arr[arr[i]]];
}
}
arr.filter((el) => el != undefined);
};
```
+ 桶排序(Bucket Sort)
+ 假设输入数据服从均匀分布,将数据分到有限数量的桶里,
+ 每个桶再分别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)
+ **设置默认数组当作空桶**
+ **设置映射函数,将遍历的数组元素均匀的分配到映射的桶内**
+ **对每个非空桶进行排序(可以选择其它排序方法)**
+ **将所有有序桶中的元素拼接返回即为所求**
+ 图解
+ 
+ code
```javascript
let bucketSort = (arr,bucketSize = 5) => {
// 桶的数量默认为5
if(arr.length === 0) return arr;
let res = [];
let minVal = arr[0];
let maxVal = arr[0];
for(let i = 0;i < arr.length;i++){
if(arr[i] < minVal){
minVal = arr[i];
}else if(arr[i] > maxVal){
maxVal = arr[i];
}
}
// 初始化n个桶
let bucketCount = Math.floor((maxVal - minVal)/bucketSize) + 1;
let buckets = new Array(bucketCount);
for(let i = 0;i < buckets.length;i++){
buckets[i] = [];
}
// 映射函数,均匀的将遍历的元素分配到n个中对应的桶内
for(let j = 0;j < arr.length;j++){
buckets[Math.floor((arr[j]-minVal)/bucketSize)].push(arr[j]);
}
for(let r = 0;r < buckets.length;r++){
// 对每个桶进行排序,这里选择插入排序
insertionSort(buckets[r]);
res = res.concat(buckets[r]);
}
return res;
}
```
+ 基数排序(Radix Sort)
+ 按照低位先排序,然后收集;再按照高位排序,然后再收集;依次类推,直到最高位。
+ 有时候有些属性是有优先级顺序的,先按低优先级排序,再按高优先级排序。

+ 思路
+ 从数组低位开始比较
+ 每个数以个位为主进行计数排序:
+ [32,14,41,5,621] => [41,621,32,14,5]
+ 从十位开始进行计数排序
+ [41,621,32,14,5] => [5,14,621,32,41]
+ 从百位开始进行计数排序
+ [5,14,621,32,41] => [5,14,32,41,621]
+ 数组中最大数有n位,则需要计数比较各位n次
+ code
```javascript
let radixSort = (arr,maxDigit) => {
let digit = 1;
let mod = 10;
let bucket = new Array(10);
for(let i = 0;i < maxDigit;i++){
for(let j = 0;j < arr.length;j++){
// 这里不能用parseInt
// parseInt(1/10000000) == 1,当栗子为[1,10000000]时,有问题
let index = Math.floor(arr[j]/digit) % mod;
if(bucket[index] == null) bucket[index] = [];
bucket[index].push(arr[j]);
}
let pos = 0;
for(let r = 0;r < bucket.length;r++){
let val = null;
if(bucket[r]){
while((val = bucket[r].shift()) != null){
arr[pos++] = val;
}
}
}
digit *= 10;
}
}
```
### 算法区别
+ 快排与归并
+ 
+ 归并:
+ 
+ 分治
+ 先排序,数组只剩一个元素即为有序
+ 再合并,双指针比较合并两个子分区数组
+ 快排:
+ 先分区,小的放基准左边,大的放基准右边
+ 再排序,将两个以基准划分的子数组合并成完全有序的一个数组
+ 计数排序、桶排序、基数排序
+ 这三种排序算法都利用了桶的概念,但对桶的使用方法上有明显差异:
+ 基数排序:根据键值的每位数字来分配桶;
+ 计数排序:每个桶只存储单一键值;
+ 桶排序:每个桶存储一定范围的数值。
<file_sep># html5的优缺点
#### 优点
+ 网络标准统一、HTML5本身是由W3C推荐出来的。
+ 多设备、跨平台
+ 即时更新。
+ 提高可用性和改进用户的友好体验;
+ 有几个新的标签,这将有助于开发人员定义重要的内容;
+ 可以给站点带来更多的多媒体元素(视频和音频);
+ 可以很好的替代Flash和Silverlight;
+ 涉及到网站的抓取和索引的时候,对于SEO很友好;
+ 被大量应用于移动应用程序和游戏。
#### 缺点
+ 安全:像之前Firefox4的web socket和透明代理的实现存在严重的安全问题,同时web storage、web socket 这样的功能很容易被黑客利用,来盗取用户的信息和资料。
+ 完善性:许多特性各浏览器的支持程度也不一样。
+ 技术门槛:HTML5简化开发者工作的同时代表了有许多新的属性和API需要开发者学习,像web worker、web socket、web storage 等新特性,后台甚至浏览器原理的知识,机遇的同时也是巨大的挑战
+ 性能:某些平台上的引擎问题导致HTML5性能低下。
+ 浏览器兼容性:最大缺点,IE9以下浏览器几乎全军覆没。<file_sep># 对象拷贝实现
### 深拷贝
#### 解法一:JSON全局对象
```javascript
JSON.parse.JSON.stringfy(obj)
```
+ 分析
+ 只能正确处理Number、String、Boolea、Array、扁平对象及那些能够被json直接表示的数据结构
+ 会忽略 undefined
+ 会忽略 symbol
+ 不能序列化函数
+ 不能解决循环引用的对象
+ obj.property = obj
+ JSON.parse(JSON.stringify(obj)) // TypeError:Converting circular structure to JSON
#### 解法二:框架
+ jQuery
+ $.extend(true,{},x)($.extend({},x)就是浅拷贝)
+ lodash
+ .clone(obj,true) == .cloneDeep(obj)
#### 解法三:浅拷贝 + 递归
+ code
```javascript
// 判断不为null的对象
let isObject = (obj) => {
return typeof obj === 'object' && obj !== null;
}
let deepCopy = (obj) => {
if(!isObject) return obj;
let newObj = Array.isArray(obj) ? [] : {};
for(let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = isObject(obj[key]) ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
```
+ 分析
+ 对传入参数校验。传人null返回null
+ typeof null === 'object'
+ Array.isArray(),兼容数组
+ 对象的属性还是对象,则递归
+ 循环引用无法深拷贝,即环检测:当检测到访问过该对象时,直接取出该值返回即可
+ 使用哈希表
+ code
```javascript
// 判断不为null的对象
let isObject = (obj) => {
return typeof obj === 'object' && obj !== null;
}
let cloneDeep = (obj,hash = new WeakMap()) =>{
if(!isObject(obj)) return obj;
if(hash.has(obj)) return hash.get(obj);
let newObj = Array.isArray(obj) ? [] : {};
hash.set(obj,newObj);
for(let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = isObject(obj[key]) ? cloneDeep(obj[key],hash) : obj[key];
}
}
return newObj;
}
```
+ 使用数组
+ code
```javascript
// 判断不为null的对象
let isObject = (obj) => {
return typeof obj === 'object' && obj !== null;
}
// 查找方法
let find = (arr,item) => {
for(let i = 0;i < arr.length;i++){
if(arr[i].source === item){
return arr[i];
}
}
return null;
}
let cloneDeep2 = (obj,hash = []) => {
if(!isObject(obj)) return obj;
let newObj = Array.isArray(obj) ? [] : {};
let tmp = find(hash,obj);
if(tmp){
return tmp.newObj;
}
hash.push({
source:obj,
newObj:newObj
})
for(let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = isObject(obj[key]) ? cloneDeep2(obj[key],hash) : obj[key];
}
}
return newObj;
}
```
+ 进阶
+ 拷贝Symbol
+ [Symbol介绍](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol)
+ 分析
+ Symbol用普通方法遍历不到
+ 解法一:Object.getOwnPropertySymbols()
```javascript
// 判断不为null的对象
let isObject = (obj) => {
return typeof obj === 'object' && obj !== null;
}
let cloneDeep = (obj,hash = new WeakMap()) =>{
if(typeof obj !== 'object' || obj === null) return obj;
if(hash.has(obj)) return hash.get(obj);
let newObj = Array.isArray(obj) ? [] : {};
hash.set(obj,newObj);
// 处理Symbol
let symKeys = Object.getOwnPropertySymbols(obj);
if(symKeys.length){
symKeys.forEach(symKey => {
newObj[symKey] = isObject(obj[symKey]) ? cloneDeep(obj[symKey],hash) : obj[symKey];
})
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = isObject(obj[key]) ? cloneDeep(obj[key],hash) : obj[key];
}
}
return newObj;
}
```
+ 解法二:Reflect.ownKeys()
+ 它的返回值等同于
+ Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))
+ code
```javascript
// 判断不为null的对象
let isObject = (obj) => {
return typeof obj === 'object' && obj !== null;
}
let cloneDeep = (obj,hash = new WeakMap()) =>{
if(!isObject(obj)) return obj;
if(hash.has(obj)) return hash.get(obj);
let newObj = Array.isArray(obj) ? [] : {};
hash.set(obj,newObj);
Reflect.ownKeys(obj).forEach(key => {
newObj[key] = isObject(obj[key]) ? cloneDeep(obj[key],hash) : obj[key];
})
return newObj;
}
```
+ 或者这样写
```javascript
// 判断不为null的对象
let isObject = (obj) => {
return typeof obj === 'object' && obj !== null;
}
let cloneDeep = (obj,hash = new WeakMap()) =>{
if(!isObject(obj)) return obj;
if(hash.has(obj)) return hash.get(obj);
let newObj = Array.isArray(obj) ? [...obj] : {...obj};
hash.set(obj,newObj);
Reflect.ownKeys(newObj).forEach(key => {
newObj[key] = isObject(obj[key]) ? cloneDeep(obj[key],hash) : obj[key];
})
return newObj;
}
```
+ 进击的巨人
+ 破解递归爆栈
```javascript
// 保持引用关系
function cloneForce(x) {
// =============
const uniqueList = []; // 用来去重
// =============
let root = {};
// 循环数组
const loopList = [
{
parent: root,
key: undefined,
data: x,
}
];
while(loopList.length) {
// 深度优先
const node = loopList.pop();
const parent = node.parent;
const key = node.key;
const data = node.data;
// 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素
let res = parent;
if (typeof key !== 'undefined') {
res = parent[key] = {};
}
// =============
// 数据已经存在
let uniqueData = find(uniqueList, data);
if (uniqueData) {
parent[key] = uniqueData.target;
break; // 中断本次循环
}
// 数据不存在
// 保存源数据,在拷贝数据中对应的引用
uniqueList.push({
source: data,
target: res,
});
// =============
for(let k in data) {
if (data.hasOwnProperty(k)) {
if (typeof data[k] === 'object') {
// 下一次循环
loopList.push({
parent: res,
key: k,
data: data[k],
});
} else {
res[k] = data[k];
}
}
}
}
return root;
}
function find(arr, item) {
for(let i = 0; i < arr.length; i++) {
if (arr[i].source === item) {
return arr[i];
}
}
return null;
}
```
### 浅拷贝
#### 解法:Object.assign()/ES6解构.../字面量赋值
```javascript
Object.assign({},obj)
{...obj}
let newObj = obj
```
+ 局限
+ 只能复制一层<file_sep># 算法与数据结构等 - 知识荟萃 「长期更新中」
## 摘要
+ demos
+ otherShare
+ theoreticalKnowledge
+ algo
### demos
+ 一些算法问题求解
### otherShare
+ 知识分享
+ 服务器知识点总结
+ 前端知识点总结
+ 数据结构分享
+ ......
### theoreticalKnowledge
+ 数据结构大部分知识点讲解
+ [Array数组、LinkedList链表、Stack栈、Queue队列](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/Array%E6%95%B0%E7%BB%84%E3%80%81LinkedList%E9%93%BE%E8%A1%A8%E3%80%81Stack%E6%A0%88%E3%80%81Queue%E9%98%9F%E5%88%97.md)
+ [Hash table哈希表、Map映射、Set集合 、Tree 树、Binary tree二叉树、Binary search tree二叉搜索树、图(Graph) 、 recursive递归 、divide分治 、recall 回溯](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/Hash%20table%E5%93%88%E5%B8%8C%E8%A1%A8%E3%80%81Map%E6%98%A0%E5%B0%84%E3%80%81Set%E9%9B%86%E5%90%88%20%E3%80%81Tree%20%E6%A0%91%E3%80%81Binary%20tree%E4%BA%8C%E5%8F%89%E6%A0%91%E3%80%81Binary%20search%20tree%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E3%80%81%E5%9B%BE(Graph)%20%E3%80%81%20recursive%E9%80%92%E5%BD%92%20%E3%80%81divide%E5%88%86%E6%B2%BB%20%E3%80%81recall%20%E5%9B%9E%E6%BA%AF.md)
+ [DFS深度优先搜索、BFS广度优先搜索、Greedy algorithm贪心算法、Binary search二分查找](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/DFS%E6%B7%B1%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2%E3%80%81BFS%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2%E3%80%81Greedy%20algorithm%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95%E3%80%81Binary%20search%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.md)
+ [DynamicProgramming动态规划](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/DynamicProgramming%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92.md)
+ [BitOperation位运算、Bloom Filter布隆过滤器、LRU Cache缓存、Sorting algorithm排序算法](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/BitOperation%E4%BD%8D%E8%BF%90%E7%AE%97%E3%80%81Bloom%20Filter%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8%E3%80%81LRU%20Cache%E7%BC%93%E5%AD%98%E3%80%81Sorting%20algorithm%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95.md)
+ [Trie树、Union-Find并查集、search搜索、tree树](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/Trie%E6%A0%91%E3%80%81Union-Find%E5%B9%B6%E6%9F%A5%E9%9B%86%E3%80%81search%E6%90%9C%E7%B4%A2%E3%80%81tree%E6%A0%91.md)
+ [HighClassDynamicProgramming高级动态规划、字符串算法](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/HighClassDynamicProgramming%E9%AB%98%E7%BA%A7%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E3%80%81%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%AE%97%E6%B3%95.md)
+ [总结 - CommencementIsJustStart毕业也是开始](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/CommencementIsJustStart%E6%AF%95%E4%B8%9A%E4%B9%9F%E6%98%AF%E5%BC%80%E5%A7%8B.md)
+ 各类算法模板总结
+ [AlgorithmTemplate算法模板](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/AlgorithmTemplate%E7%AE%97%E6%B3%95%E6%A8%A1%E6%9D%BF.md)
+ leetCode习题分类练习
+ [ProblemClassificationCut习题分类斩](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/ProblemClassificationCut%E4%B9%A0%E9%A2%98%E5%88%86%E7%B1%BB%E6%96%A9.md)
+ [题解](https://github.com/Alex660/leetcode)
### algo
+ 数据结构和算法必知必会的代码实现
+ 数组
+ 链表
+ 跳表
+ 栈
+ 队列
+ 递归
+ 排序
+ [十大经典排序 - theoreticalKnowledge - 排序算法一节处](https://github.com/Alex660/Algorithms-and-data-structures/blob/master/theoreticalKnowledge/BitOperation%E4%BD%8D%E8%BF%90%E7%AE%97%E3%80%81Bloom%20Filter%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8%E3%80%81LRU%20Cache%E7%BC%93%E5%AD%98%E3%80%81Sorting%20algorithm%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95.md)
+ 
+ 二分查找
+ 散列表
+ 字符串
+ 二叉树
+ 堆
+ 图
+ 回溯
+ 分治
+ 动态规划
<file_sep># 摘要
+ 哈希表、映射、集合
+ 树、二叉树、二叉搜索树、图(Graph)
+ 递归
+ 分治
+ 回溯
+ 课后思考
+ 源码分析
### 哈希表、映射、集合
+ Hash table 也叫散列表
+ 核心问题
+ 散列函数设计
+ 散列冲突解决
+ 其实是数组对一种扩展
+ Hash Function 也叫散列函数

+ 散列冲突
+ 解决方法
+ 开放寻址法
+ 手段
+ 线性探测
+ 二次探测
+ 双重散列
+ 优化
+ 装载因子
+ 保证散列表空间中一定比例对空闲槽
+ 装载因子越大,说明空闲位置越少,冲突越多,散列表的性能会下降。
> 散列表的装载因子 = 填入表中的元素个数 / 散列表的长度
+ 链表法

+ 工程实践
+ 电话号码簿
+ 用户信息表
+ 缓存(LRU Cache)
+ 键值对存储
+ Word文档单词拼写检查功能
+ 用散列表来存储整个英文单词词典。
+ 如果查到,则说明拼写正确;
+ 如果没有查到,则说明拼写可能有误
+ 假设我们有 10 万条 URL 访问日志,如何按照访问次数给 URL 排序?
+ 遍历 10 万条数据,以 URL 为 key,访问次数为 value,存入散列表,
+ 同时记录下访问次数的最大值 K,时间复杂度 O(N)。
+ 如果 K 不是很大,可以使用桶排序,时间复杂度 O(N)。
+ 如果 K 非常大(比如大于 10 万),就使用快速排序,复杂度 O(NlogN)。
+ 有两个字符串数组,每个数组大约有 10 万条字符串,如何快速找出两个数组中相同的字符串?
+ 以第一个字符串数组构建散列表,key 为字符串,value 为出现次数。
+ 再遍历第二个字符串数组,以字符串为 key 在散列表中查找,
+ 如果 value 大于零,说明存在相同字符串。时间复杂度 O(N)。
### 树
+ 一种非线性表结构
+ 高度(Height)
+ 深度(Depth)
+ 层 (Level)


+ 二叉树
+ 满二叉树
+ 叶子节点全部在最底层
+ 除了叶子节点之外,每个节点都有左右两个子节点
+ 也是完全二叉树的一种特殊情况
+ 完全二叉树
+ 叶子节点都在最底下两层
+ 最后一层的叶子节点都靠左排列
+ 除了最后一层,其它层的节点个数都要达到最大
+ 二叉树的存储
+ 基于指针或引用的二叉链式存储法
+ 每个节点有三个字段
+ 存储数据
+ 存储左右子节点的指针

+ 基于数组的顺序存储法
+ 根节点 i=1
+ 左子节点 2*i
+ 右子节点 2*i+1
+ 完全二叉树的存储

+ 非完全二叉树的存储

+ 结论
+ 完全二叉树 用数组存储是最节省内存的一种方式
+ 不需要像链式存储法那样额外存储左右子节点的指针
+ 也是完全二叉树要求最后一层的子节点都靠左的原因
+ 应用
+ 堆
+ 思考
+ 给定一组数据,比如 1,3,5,6,9,10。你来算算,可以构建出多少种不同的二叉树?
+ n! 阶乘 即 卡塔兰数
+ 二叉树的遍历
+ 时间复杂度 O(n) 因为每个节点最多被访问两次,跟节点的个数 n 成正比
+ 以下根代表 任意节点
+ 前序(Pre-order):根-左-右
+ 中序(In-order):左-根-右
+ 一种升序排列
+ 后序(Post-order):左-右-根
+ 均是一种递归的过程
+ 前序遍历的递推公式:
+ preOrder(r) = print r->preOrder(r->left)->preOrder(r->right)
+ 中序遍历的递推公式:
+ inOrder(r) = inOrder(r->left)->print r->inOrder(r->right)
+ 后序遍历的递推公式:
+ postOrder(r) = postOrder(r->left)->postOrder(r->right)->print r

+ 层序遍历
+ 可以看作以根节点为起点,图的广度优先遍历的问题
+ 二叉树的高度
+ 根节点的高度 = max(左子树高度,右子树高度) + 1
+ 二叉搜索树 Binary Search Tree
+ 也叫二叉搜索排序树、有序二叉树(Ordered Binary Tree)、排序二叉树(Sorted Binary Tree)
+ 是指一颗空树 或 具有下列性质的二叉树
+ 左子树上 所有结点 的值均小于它的根节点的值
+ 右子树上 所有结点 的值均大于它的根节点的值
+ 以此类推:左、右子树也分别为二叉查找树(即重复性)
+ 常见操作
+ 查询
+ 插入新结点(创建)
+ 删除
+ [操作图示](https://visualgo.net/zh/bst)
### 递归
+ 解题关键
+ 写出递推公式
+ 递归模版
```java
// recur 递归
public void recur(int level, int param) {
// terminator 终结条件
if (level > MAX_LEVEL) {
// process result 流程结果
return;
}
// process current logic 当前逻辑过程
process(level, param);
// drill down 向下递归
recur( level: level + 1, newParam);
// restore current status 恢复现状
}
```
+ 警惕堆栈溢出
+ 警惕重复计算
+ 可以使用备忘录模式

+ 应用实践
+ DFS深度优先搜索
+ 前中后序二叉树遍历
### 分治
+ 原问题分解成的子问题可以独立求解,子问题之间没有相关性,是和动态规划的明显区别
+ 实践应用
+ Google的 MapReduce
+ 代码模版
+ 递归的代码模版加上合并所有子问题操作
1. terminator
2. process(split your big problem)
3. drill down subproblems
4. merge(subsult)
5. if need reverse states
### 回溯
+ 用来解决广义的搜索问题
+ 从一组可能的解中,选择出一个满足要求的解
+ 本质是枚举,即投石问路
+ 解题方法
+ 递归
+ 搜索减枝
+ 实践应用
+ 蝴蝶效应
+ DFS 深度优先搜索算法
+ 正则表达式匹配
+ 编译原理总的语法分析
+ 数独
+ 八皇后问题
+ 0-1 背包
+ 图的着色
+ 旅行商问题
+ 全排列问题
+ 代码示例
+ 八皇后

```javascript
// 下标为row,其值为column
var result = new Array(8);
// 主函数
function cal8Queens(row){
if(row == 8){
return result;
}
// 每一行有 column 种放法
for(var column = 0;column < 8;column++){
// 判断合法性
if(isOK(row,column)){
// 第row行第column列 可以放一个棋子
result[row] = column;
// 考察下一行
cal8Queens(row+1);
}
}
}
// 核心放法
// 判断上面每一行至其他列有值的地方是否与将要放的棋子相冲突
function isOk(row,column){
var leftColumn = column - 1;
var rightColumn= column + 1;
// 逐上考察每一行
for(var i =row-1;i >= 0;i--){
// 上面某一行当前列有值
if(result[i] == column){
return false;
}
// 左对角线有值
if(result[i] == leftColumn){
return false;
}
// 右对角线有值
if(result[i] == rightColumn){
return false;
}
// 两侧扩散
leftColumn--;
rightColumn++;
}
// 上面每一行都通过
return true;
}
```
+ 0-1背包问题
> 一个背包 总重为 Wkg
现有 n 个物品 每个物品重量不等且不可分割
求在不超过背包重量的前提下,选择哪几样物品装载到背包中能使得物品的总重量最大?
求解思路:回溯
将物品依次排列,整个问题就分解成了N个阶段
每个阶段只有两种选择:装 与 不装
再递归处理剩下的物品
```javascript
// w 背包重量
// cw 表示已经装进去的物品重量和
// items 每个物品的重量集合数组
// n 物品个数
// fn(n,cw)
var maxW = 0;// 可以存储进入背包中的物品总重量的最大值
function getMaxV(i,cw){
// 递归终止条件
if(cw == w || i == n){
// cw == w 表示装满了,不判断大于0的情况是因为下面选择装的时候做了准入判断
// i == n 表示已经考察完所有的物品
// 更新结果最大值
if( cw > maxW){
maxW = cw;
}
return;
}
// 不装 && 进入下一个物品选择阶段
getMaxV(i+1,cw)
// 装 && 进入下一个物品选择阶段
// 加上搜索减枝
if(cw + items[i] <= w){
getMaxV(i+1,cw + items[i])
}
}
```
+ 正则匹配
> "*" 匹配任意多个(>=0)任意字符
"?" 匹配零个 或者 一个任意字符
求用回溯算法,判断一个给定的文本,能否跟给点的正则表达式匹配?
+ 思路 当依次考察正则表达式中的每个字符时
+ 当是非通配符时
+ 直接跟文本的字符进行匹配
+ 相同:递归进入下一个字符的一对一匹配
+ 不同:回溯 即回到当....时
+ 当是通配符时
+ 当是“*”时
+ 符合匹配规则则继续考察下一个字符
+ 不符合则回溯 即回到 当是"*"时 并进入下一个匹配规则
+ 当是“?”时
+ 同上处理
+ 代码
```javascript
function patternStr(pattern,text){
var matched = false;
var plen = pattern.length;
var tlen = text.length;
rematch(0,0);
// 核心方法
// ti text每个字符的当前索引位置
// pj pattern 每个字符的当前位置索引
function rmatch(ti,pj){
// 递归过程中 匹配成功 则不需要继续了 直接返回结果
if(matched){
return;
}
if(pj == plen){//正则表达式匹配到结尾了
if(ti == tlen){//文本串也到结尾了
return;
}
}
//* 匹配任意个字符
if(pattern[pj] == '*'){
for(var k = 0;k <= tlen - ti;k++){
rematch(ti + k,pj+1);
}
}
// ?匹配 0个 或 1个字符
else if(pattern[j] == '?'){
rematch(ti,pj+1);
rematch(ti+1,pj+1);
}
//纯字符匹配 一对一
else{
rematch(ti+1,pj+1);
}
}
// 返回结果
return matched;
}
```
### 课后思考
+ 树的面试题解法一般都是递归,为什么?
+ 树一般都是左右子树遍历查找 重复性质 可以递归调用
### 源码分析
+ Java Hash Map
+ 由数组、链表、红黑树组成

+ 判断两个对象是否相等 ==(地址)
```java
public boolean equals(Object obj) {
return (this == obj);
}
```
+ 自反性
+ 对称性
+ 传递性
+ 一致性
+ 非空性
+ 获取节点的 hashCode
+ 用于查找的快捷性
+ 对象上就有 但可以覆写如String
```java
static final int hash(Object key) {
int h;
// h = key.hashCode() 为第一步 取hashCode值
// h ^ (h >>> 16) 为第二步 高位参与运算
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
static int indexFor(int h, int length) {
return h & (length-1); //第三步 取模运算
}
```
+ 在JDK1.8的实现中,优化了高位运算的算法,
+ 通过hashCode()的高16位异或低16位实现的:(h = k.hashCode()) ^ (h >>> 16),
+ 主要是从速度、功效、质量来考虑的,这么做可以Node数组table的length比较小的时候,
+ 也能保证考虑到高低Bit都参与到Hash的计算中,同时不会有太大的开销。

+ get 查找通过 getNode实现
```java
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
// 变量说明:tab用于存储table引用,first用于存储数组中第一个节点,e为目标节点
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 在hash值相等的情况下,进行key值匹配
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 判断散列冲突 检测节点是链表还是红黑树,然后分别调用不同的方法进行匹配
if ((e = first.next) != null) {
// 红黑树
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 链表
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
```
+ put 函数 插入操作实现
```java
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table 为空的检测
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 对hash进行映射,并检测数组头是否为空,为空则直接创建新的节点
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 数组头不为空,则进行碰撞的值的检测
else {
Node<K,V> e; K k;
// 若当前数组头匹配,则直接返回数组头节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 对节点类型进行检测,若为红黑树,则调用红黑树的插入逻辑
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 否则为链表
else {
// 对链表进行匹配
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 对匹配成功对节点进行值的更新
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
```
+ 操作示意图

+ 判断是否是红黑树即树形节点时 调用 TreeNode
+ 表扩容通过 resize函数实现
+ table的长度保持在2^n次方
+ 在不超过最大容量限制的前提下进行2倍扩容操作
+ 将旧的table迁移到新的table中去
> 旧元素的位置 == 新元素的位置索引
新插入的位置 == 偏移oldCap + index 的索引位置上去
+ => 位运算 优化模运算
>这个方法非常巧妙,它通过h & (table.length -1)来得到该对象的保存位,
而HashMap底层数组的长度总是2的n次方,这是HashMap在速度上的优化。
当length总是2的n次方时,h& (length-1)运算等价于对length取模,
也就是h%length, 但是&比%具有更高的效率。
+ 假设原来的table大小为4,那么扩容之后会变为8,
+ 那么对于一个元素A来说,如果他的hashCode值为3,
+ 那么他在原来的table上的位置为(3 & 3) = 3,
+ 那么新位置呢?(3 & 7) = 3,
+ 这种情况下元素A的index和原来的index是一致的不用变。
+ 再来看一个元素B,他的hashCode值为47,那么在原来table中的位置为(47 & 3) = 3
+ 在新table中的位置为(47 & 7) = 7,也就是(3 + 4),正好偏移了oldCap个单位。
+ 因为我们的计算方法为:(hashCode & (length - 1))
+ 所以扩容之后新插入=元素比原来多判断一步 边插边判断是否需要移动元素到新的table中去
+ if (oldTab != null)

+ 还是上面的两个元素A和B,哈希值分别为3和47,在table长度为4的情况下,因为(3) = (11),
+ 所以A和B会有两位参与运算来获得index,A和B的二进制分别为:
+ 3 : 11
+ 47: 101111
+ 在table的length为4的前提下:
+ 3-> 11 & 11 = 3
+ 47-> 000011 & 101111 = 3
+ 在扩容后,length变为8:
+ 3-> 011 & 111 = 3
+ 47-> 10111 & 00111 = 7
+ 对于3来说,新增的参与运算的位为0,所以index不变,
+ 而对于47来说,新增的参与运算的位为1,所以index需要变为(index + oldCap)
+ newTab[e.hash & (newCap - 1)] = e; <file_sep># json和xml的区别
#### json
+ 定义
+ 一种轻量级的数据交换格式,具有更好的可读性和便于快速编写的特性
+ 优点
+ 数据格式比较简单,易于读写,格式都是压缩的,占用带宽小;
+ 易于解析,客户端JavaScript可以简单的通过eval()进行JSON数据的读取;
+ 支持多种语言,包括ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby等服务器端语言,便于服务器端的解析;
+ 在PHP世界,已经有PHP-JSON和JSON-PHP出现了,偏于PHP序列化后的程序直接调用,PHP服务器端的对象、数组等能直接生成JSON格式,便于客户端的访问提取;
+ 因为JSON格式能直接为服务器端代码使用,大大简化了服务器端和客户端的代码开发量,且完成任务不变,并且易于维护。
+ 缺点
+ 没有XML格式这么推广的深入人心和喜用广泛,没有XML那么通用性;
+ JSON格式目前在Web Service中推广还属于初级阶段。
#### xml
+ 定义
+ 扩展标记语言 (Extensible Markup Language,XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据、定义数据类型,
+ 是一种允许用户对自己的标记语言进行定义的源语言。
+ XML是标准通用标记语言 (SGML) 的子集,非常适合 Web 传输。
+ XML 提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。
+ 优点
+ 格式统一,符合标准;
+ 容易与其他系统进行远程交互,数据共享比较方便。
+ 缺点
+ XML文件庞大,文件格式复杂,传输占带宽;
+ 服务器端和客户端都需要花费大量代码来解析XML,导致服务器端和客户端代码变得异常复杂且不易维护;
+ 客户端不同浏览器之间解析XML的方式不一致,需要重复编写很多代码;
+ 服务器端和客户端解析XML花费较多的资源和时间。
#### 区别
+ 在可读性方面,JSON和XML的数据可读性基本相同。JSON和XML的可读性可谓不相上下,一边是建议的语法,一边是规范的标签形式,很难分出胜负。
+ 可扩展性方面,XML天生有很好的扩展性,JSON当然也有,没有什么是XML能扩展,JSON不能的。
+ 在编码难度方面,XML有丰富的编码工具,比如Dom4j、JDom等,JSON也有json.org提供的工具,但是JSON的编码明显比XML容易许多,即使不借助工具也能写出JSON的代码,可是要写好XML就不太容易了。
+ 在解码难度方面,XML的解析得考虑子节点父节点,让人头昏眼花,而JSON的解析难度几乎为0。这一点XML输的真是没话说。
+ 在流行度方面,XML已经被业界广泛的使用,而JSON才刚刚开始,但是在Ajax这个特定的领域,未来的发展一定是XML让位于JSON。到时Ajax应该变成Ajaj(AsynchronousJavascript and JSON)了。
+ JSON和XML同样拥有丰富的解析手段。
+ JSON相对于XML来讲,数据的体积小。
+ JSON与JavaScript的交互更加方便。
+ JSON对数据的描述性比XML较差。
+ json的速度要远远快于XML。
|
ffa0ff4d38071b5080aa0ebf8b1eae6a50faadc3
|
[
"Markdown",
"JavaScript"
] | 49 |
Markdown
|
zhuxinyu-znb/Algorithms-and-data-structures
|
fa0f15eac8ca373aa8b97cd239c7234c32dae99c
|
138761836a04069d7b5f720535d5f8f27a7caf36
|
refs/heads/master
|
<repo_name>wicho1001/blog<file_sep>/.github/PULL_REQUEST_TEMPLATE.md
## ISSUE
Describe your issue
## SOLUTION
* [x]
## TEST
* GCO current branch
* run npm run dev
* Enjoy 🚀 <file_sep>/src/components/shared/Layout.tsx
import React from 'react';
import Navbar from './Navbar';
import Footer from './Footer';
import Header from './Header';
const Layout = (props) => {
return (
<div>
<Header children={props.props}></Header>
<section className="w-full flex flex-col">
<Navbar></Navbar>
<div className="flex flex-col flex-grow">
{props.children}
<section className="w-full self-end">
<Footer></Footer>
</section>
</div>
</section>
</div>
)
}
export default Layout;<file_sep>/src/pages/_app.tsx
import 'tailwindcss/tailwind.css';
import '../styles/style.css';
import '../styles/general.css';
import Router from 'next/router';
import withGa from 'next-ga';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default withGa('UA-169353371-1', Router)(MyApp);<file_sep>/src/pages/index.tsx
import React from 'react';
import Layout from '../components/shared/Layout';
import Link from 'next/link'
import fs from 'fs';
import matter from 'gray-matter';
function IndexPage(props) {
return (
<Layout props={props}>
<section className="flex flex-col xs:w-10/12 2xl:w-8/12 mx-auto">
{/* home */}
<section className="flex md:flex-row xs: flex-col justify-between items-center">
<div className="flex flex-col md:items-start md:w-1/3 xs:w-full">
<p className="font-bold text-4xl font-duru text-surface-800">{props.title}</p>
<p className="text-lg font-rubik text-surface-800 mt-10">{props.description}</p>
<a href={'https://api.whatsapp.com/send?phone=%2B525612993621&text=Hola%2C+quisiera+saber+m%C3%A1s+acerca+de+sus+servicios.+Gracias%21'}
target="_blank"
className="px-6 py-4 font-bold font-duru bg-primary-700 text-white text-center rounded-2 mt-10 xs:w-full md:w-10/12 outline-none"
>
Contáctanos
</a>
</div>
<div className="self-end relative xs:mt-10 md:mt-0">
<img className="z-3 h-150 w-150 rounded-2 object-cover" src={props.image} alt="" />
<div className="h-150 w-150 xs:hidden md:block md:absolute bg-secondary-500 right-0 bottom-0 -mr-20 -z-1 -mb-10 rounded-2"></div>
</div>
</section>
{/* End home */}
<section className="flex flex-col mt-30">
<p className="text-4xl font-bold self-center">Acerca de nosotros</p>
<section className="grid xs:grid-cols-1 md:grid-cols-3 gap-6 justify-around w-full mt-10">
{
props.stages.map((stage, index) => (
<Link href={stage.permaLink} key={index}>
<div className="flex flex-col px-7 py-5 rounded-2 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-105 cursor-pointer hover:bg-surface-100">
<div className="flex flex-col flex-grow">
<img className="w-full xs:h-70 md:h-60 rounded-2" src={stage.image} alt="" />
<p className="text-lg font-duru font-bold text-surface-800 mt-6">{stage.title}</p>
<p className="text-lg font-rubik text-surface-800 mt-6 break-words">{stage.description}</p>
</div>
<i className="icon-arrow-right2 mt-6 self-end text-xl"></i>
</div>
</Link>
))
}
</section>
</section>
</section>
</Layout>
)
};
export default IndexPage;
export async function getStaticProps(params: any) {
const file = fs.readFileSync('public/static/content/index.md', 'utf-8');
const {content, data}: any = matter(file);
const props = {
props: {
...data,
content,
}
}
return props
}
<file_sep>/src/components/shared/Header.tsx
import React from 'react'
import Head from 'next/head'
const Header = ({children}) => {
return (
<Head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<title>{children.seo.title}</title>
<meta name="keywords" content={children.seo.keywords.join(',')}></meta>
<meta name="language" content="Spanish"/>
<meta name="description" content={children.seo.description} />
<meta property="og:title" content={children.seo.title}/>
<meta property="og:type" content="website"/>
<meta property="og:image" content={children.seo.image}/>
<meta property="og:image:secure_url" content={children.seo.image}/>
<meta property="og:image:width" content="1200"/>
<meta property="og:image:height" content="630"/>
<meta property="og:site_name" content="Nemiliz Diagnostics"/>
<meta property="og:description" content={children.seo.description}></meta>
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"/>
<link rel="icon" type="image/png" sizes="32x32" href="portada.png"/>
<link rel="icon" type="image/png" sizes="16x16" href="portada.png"/>
</Head>
)
}
export default Header;<file_sep>/public/static/content/laboratorio.md
---
title: SARS CoV-2
description: Virus que causa una enfermedad respiratoria llamada enfermedad por coronavirus
de 2019 (COVID-19). El SARS-CoV-2 es un virus de la gran familia de los coronavirus,
un tipo de virus que infecta a seres humanos y algunos animales. La infección por
el SARS-CoV-2 en las personas se identificó por primera vez en 2019. Se piensa que
este virus se transmite de una persona a otra en las gotitas que se dispersan cuando
la persona infectada tose, estornuda o habla.
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_4.jpeg
stages:
- title: Toma de la muestra.
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_3.jpeg
description: Se realiza por medio un hisopado nasofaringeo, el hisopo debe ser estéril
,debe ser de fibras sintéticas para evitar inhibición de la PCR, cuando la técnica
es bien ejecutada se puede provocar una molestia pero nunca una lesión. El personal
lleva equipo completo de protección y se toman las más altas normas de seguridad
e higiene.
- title: Conservación y transporte de la muestra.
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_8.jpeg
description: Se utiliza un medio de transporte viraal diseñado para conservar la
muestra de la mejor manera se procura que las células lleguen óptimas al laboratorio
para poder extraer correctamente la información genética de cada célula. Se recomienda
transportar en refrigeración para que la muestra llegué con buenas condiciones
al laboratorio, este paso es sumamente importante ya que de esto depende el buen
material genético que se obtenga
- title: Procesamiento de la muestra.
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_3.jpeg
description: En la primera etapa se extraen los ácidos nucleicos y se obtienen purificados
para su posterior marcaje y amplificación en el equipo de termociclado Detectamos
regiones genicas del virus con mayor tasa de conservación y menor tasa ve mutación
o variabilidad genicas, lo que nos ayuda a tener Diagnosticos más certeros y de
mejor utilidad para el profesional de la salud. Debido a que los.sintomas son
similares a otros virus respiratorios nuestra prueba detecta en simultáneo SARS-CoV
2 e Influenza A y B. Esto nos habilita para beneficio de nuestros clientes y pacientes.
seo:
title: SARS CoV-2
description: Nemiliz Diagnostics es una empresa que brinda una experiencia de calidad
a nuestros clientes con un servicio profesional en Biología Molecular
image: nemiliz.png
keywords:
- Biología molecular
- Pruebas SARS CoV-2
---
<file_sep>/src/lib/author-api.ts
import fs from 'fs';
import matter from 'gray-matter';
import {join} from 'path';
import remark from 'remark';
import html from 'remark-html';
//const authorDirectory=null;
//static/content/authors/+${author}
export const getAllAuthors = () => {
const path = join(process.cwd(),'static/content/authors');
return fs.readdirSync(path);
}
export const getAuthor = (author:string) => {
//const authorDirectory =join(process.cwd(), author);
const fullPath = join(process.cwd(),author);
const file= fs.readFileSync(fullPath,'utf-8');
const { content, data }:any= matter(file);
return { content, ...data }
}
export default async function markdownToHtml(markdown) {
const result = await remark().use(html).process(markdown)
return result.toString()
}
<file_sep>/public/static/content/authors/wicho.md
---
name: '<NAME>'
bio: 'Esta es una descripcion'
social:
facebook: 'https://www.facebook.com/ELW1CH0'
profile_image: 'https://www.silversites.es/wp-content/uploads/2019/02/html-javascript.jpg'
seo:
title: Yo soy wicho
description: Soy un frontend developer que ama programar
image: 'https://www.silversites.es/wp-content/uploads/2019/02/html-javascript.jpg'
---<file_sep>/src/components/shared/Footer.tsx
import React from 'react'
const Footer = () => {
return (
<section className="flex justify-between bg-surface-400 px-11 py-9 mt-10 h-70">
<div>
<p className="text-4xl font-exo text-surface-800">Horario</p>
</div>
<div className="flex flex-col items-start">
<p className="text-4xl font-exo text-surface-800">Contactanos</p>
<div className="flex justify-between items-center mt-6 w-full">
<i className="icon-facebook text-xl text-surface-700"></i>
<i className="icon-instagram text-xl text-surface-700"></i>
<i className="icon-mail text-xl text-surface-700"></i>
<i className="icon-whatsapp text-xl text-surface-700"></i>
</div>
</div>
</section>
)
}
export default Footer;<file_sep>/.forestry/front_matter/templates/stage-fields.yml
---
label: Cards de info
hide_body: true
fields:
- name: stage
type: field_group
config: {}
fields:
- name: title
type: text
config:
required: true
label: Title
- name: description
type: textarea
default: ''
config:
required: true
label: Descripcion
- name: image
type: file
config:
maxSize: 2
label: Image
label: Card
<file_sep>/.forestry/settings.yml
---
new_page_extension: md
auto_deploy: false
admin_path: public/static/admin
webhook_url:
sections:
- type: document
path: public/static/content/index.md
label: Inicio
templates:
- index
- type: document
path: public/static/content/laboratorio.md
label: laboratorio
templates:
- index
upload_dir: ''
public_path: https://nemiliz.s3-us-west-2.amazonaws.com
front_matter_path: ''
use_front_matter_path:
file_template: ":filename:"
build:
preview_output_directory: public
install_dependencies_command: npm install
preview_docker_image: forestryio/node:12
mount_path: "/srv"
working_dir: "/srv"
instant_preview_command: npm run dev
<file_sep>/.forestry/front_matter/templates/social-media.yml
---
label: Social
hide_body: false
fields:
- name: twitter
type: text
label: Twitter
- name: facebook
type: text
label: Facebook
- name: instagram
type: text
label: Instagram
- name: github
type: text
label: Github
<file_sep>/.forestry/front_matter/templates/blog.yml
---
label: Blog
hide_body: false
fields:
- name: type
type: text
config:
required: true
label: Type
hidden: true
default: blog
- name: title
type: text
config:
required: true
label: Title
default: ''
- name: minutes
type: text
config:
required: true
label: MinutesToRead
default: 3
- name: date
type: datetime
description: ''
config:
required: true
date_format:
time_format:
display_utc: false
label: Date
default: now
- name: featured_image
type: file
config:
maxSize: 2
label: Featured Image
- name: author
type: select
default: []
config:
required: true
options: []
source:
type: pages
section: authors
file:
path:
label: Author
- name: seo
type: include
config: {}
template: seo-fields
label: SEO
<file_sep>/public/static/content/_posts/php-is-the-worst-copy.md
---
title: Mi super mega titulo copy
featured_image: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJHnFru3UsC2AHddso0JPrKs6JVtQOpv5KjQ&usqp=CAU
slug: php-is-the-worst-copy
fecha: 10-05-2020
author: static/content/authors/jorge.md
---
### Hello world!
## Hello world!
# Hello world!
* Hello world!
* Hello world!
* Hello world!
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.
## Hello world!
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.Lorem ipsum dolor sit, amet consectetur adipisicing elit. Ullam corrupti veritatis cumque ratione dignissimos culpa perspiciatis at, molestiae porro, blanditiis eius, adipisci itaque sequi aut voluptatibus quia quam veniam? Odit.
<file_sep>/public/static/content/authors/jorge.md
---
name: '<NAME>'
bio: 'Esta es una descripcion'
social:
facebook: 'https://www.facebook.com/ELW1CH0'
profile_image: 'https://www.silversites.es/wp-content/uploads/2019/02/html-javascript.jpg'
seo:
title: Yo soy wicho
description: Soy un frontend developer que ama programar
image: 'https://www.silversites.es/wp-content/uploads/2019/02/html-javascript.jpg'
---
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Neque id quae consequuntur, distinctio, quam voluptatibus debitis quis nemo vero rem reiciendis expedita maiores amet ut! Dolore quia laborum vel itaque.Lorem ipsum dolor, sit amet consectetur adipisicing elit. Neque id quae consequuntur, distinctio, quam voluptatibus debitis quis nemo vero rem reiciendis expedita maiores amet ut! Dolore quia laborum vel itaque.
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Neque id quae consequuntur, distinctio, quam voluptatibus debitis quis nemo vero rem reiciendis expedita maiores amet ut! Dolore quia laborum vel itaque.<file_sep>/.forestry/front_matter/templates/seo-fields.yml
---
label: SEO Fields
hide_body: true
fields:
- name: seo
type: field_group
config: {}
fields:
- name: title
type: text
config:
required: true
label: Title
- name: description
type: textarea
default: ''
config:
required: true
wysiwyg: false
schema:
format: markdown
label: Description
- name: image
type: file
config:
maxSize: 2
label: Image
- name: keywords
type: tag_list
default: []
label: Keywords
- name: language
type: select
default: ES
config:
required: false
options:
- ES
source:
type: simple
section:
file:
path:
label: Language
hidden: true
label: SEO
<file_sep>/src/pages/laboratorio/index.tsx
import React from 'react'
import Layout from '../../components/shared/Layout';
import fs from 'fs';
import matter from 'gray-matter';
const Index = (props) => {
return (
<Layout props={props}>
<section className="flex flex-col xs:w-10/12 2xl:w-8/12 mx-auto">
<section className="flex md:flex-row xs: flex-col justify-between items-center">
<div className="flex flex-col md:items-start md:w-1/3 xs:w-full">
<p className="font-bold text-4xl font-duru text-primary-600">{props.title}</p>
<p className="text-lg font-rubik text-primary-600 mt-10">{props.description}</p>
<a href={'https://api.whatsapp.com/send?phone=%2B525612993621&text=+Hola+que+tal%2C+quiero+obtener+mi+prueba+para+SARS+CoV-2'}
target="_blank"
className="px-6 py-4 font-bold font-duru bg-primary-700 text-white text-center rounded-2 mt-10 xs:w-full md:w-10/12 outline-none"
>
Obten tu prueba
</a>
</div>
<div className="self-end relative xs:mt-10 md:mt-0">
<img className="z-3 h-150 w-150 object-cover rounded-2" src={props.image} alt="" />
</div>
</section>
<section className="flex flex-col mt-30">
<p className="font-bold text-4xl font-duru text-primary-600 pb-4">Etapas</p>
<hr className="border-b-4 border-primary-50 rounded-2 w-1/2"/>
<div className="flex flex-col mt-10">
{
props.stages.map((stage, index) => (
<div className="flex xs:flex-col md:flex-row items-center xs:my-10 md:my-5" key={index}>
<img className="z-3 xs:h-60 md:h-45 md:w-45 xs:w-full rounded-2" src={stage.image} alt="" />
<div className="flex flex-col md:ml-6 w-full">
<p className="font-bold text-2xl font-duru text-primary-600">Etapa {index + 1}: {stage.title}</p>
<p className="text-lg font-rubik text-primary-600 mt-6">{stage.description}</p>
</div>
</div>
))
}
</div>
</section>
</section>
</Layout>
)
}
export default Index
export async function getStaticProps(params: any) {
const file = fs.readFileSync('public/static/content/laboratorio.md', 'utf-8');
const {content, data}: any = matter(file);
const props = {
props: {
...data,
content,
}
}
return props
}
<file_sep>/src/lib/api.ts
import fs from 'fs';
import path, { join } from 'path';
import matter from 'gray-matter';
import remark from 'remark';
import html from 'remark-html';
import { getAuthor } from './author-api';
const postsDirectory = join(process.cwd(), 'static/content/_posts');
export const getPostSlugs = () => {
return fs.readdirSync(postsDirectory)
}
export const getPost = (slug: string) => {
const realSlug = slug.replace(/\.md$/, ''); /* slug.replace(/\.md$/, ''); */
const fullPath = join(postsDirectory, `${realSlug}.md`);
const file = fs.readFileSync(fullPath, 'utf-8');
const {content, data}: any = matter(file);
const author = getAuthor(data.author);
return {
...data,
content,
author:{
...author
}
}
}
export const getAllPosts = () => {
return getPostSlugs().map((post)=>{
return {
slug:post
}
});
}
export default async function markdownToHtml(markdown) {
const result = await remark().use(html).process(markdown)
return result.toString()
}
<file_sep>/public/static/content/index.md
---
title: <NAME>
description: <NAME> es una empresa 100% mexicana comprometida con el
significado de su nombre a saber, con la “vida”. Nuestra finalidad es brindar una
experiencia de calidad a nuestros clientes y socios de negocios mediante un servicio
profesional en Biología Molecular.
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_8.jpeg
stages:
- title: Laboratorio
permaLink: "/laboratorio"
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_9.jpeg
description: Somos un laboratorio especializado en biología molecular , interesados
en la salud de nuestros pacientes y su bienestar. Con un servicio de calidad y
enfocado a nuestros clientes como personas y no como un número más.
- title: Construcción
permaLink: "/"
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_10.jpeg
description: Somos una empresa interdisciplinaria dedicada al diseño, construcción
y mejoramiento de instalaciones de salud. En especial, laboratorios de Biología
Molecular. Siempre en busca de ventajas comerciales para nuestros clientes, con
la mejor relación costo beneficio, y la optimización de tiempos de implementación.
- title: Distribución
permaLink: "/"
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/lab_3.jpeg
description: Somos una empresa de vanguardia, en busca de las mejores tecnologías
y productos para nuestros clientes. Nuestras alianzas comerciales, y tlrelacion
directa con fabricantes nos permiten tener las mejores ofertas dentro del mercado
de insumos para laboratorio. Ya sea en equipos, reactivos o consumibles buscamos
la satisfacción total de nuestros clientes y el impulso a sus proyectos.
seo:
title: Nemiliz
description: Nemiliz Diagnostics es una empresa que brinda una experiencia de calidad
a nuestros clientes con un servicio profesional en Biología Molecular
image: https://nemiliz.s3-us-west-2.amazonaws.com/images/logo azul.png
keywords:
- Biología molecular
---
<file_sep>/src/components/shared/Navbar.tsx
import { useRouter } from 'next/router';
import React, {useState, useEffect} from 'react';
import Link from 'next/link'
const Navbar = () => {
const router = useRouter()
let className = 'border-primary-500 border-b-4';
return (
<section className="flex w-full justify-between pt-8 pb-5 mb-5 px-10 sticky bg-white top-0 z-9999 shadow">
<Link href="/">
<div className="flex outline-none cursor-pointer">
<img className="h-17 scale-125 transform" src="/nemiliz.png" alt="" />
<div className="xs:hidden md:flex flex-col ml-4 font-bold text-xl font-duru text-primary-600">
<p>Nemiliz</p>
<p>Diagnostics</p>
</div>
</div>
</Link>
<ul className="flex">
<Link href="/">
<p className={`text-lg mx-3 ${router.pathname === '/' ? className : null} cursor-pointer`}>Inicio</p>
</Link>
<Link href="/laboratorio">
<p className={`text-lg mx-3 ${router.pathname === '/laboratorio' ? className : null} cursor-pointer`}>Laboratorio</p>
</Link>
{/* <Link href="/proyectos">
<p className={`text-lg mx-3 ${router.pathname === '/proyectos' ? className : null}`}>Proyectos</p>
</Link> */}
</ul>
</section>
)
}
export default Navbar;
|
bc9f68d1a6907e397e95eed73ad295466c0b70cd
|
[
"Markdown",
"TypeScript",
"YAML",
"TSX"
] | 20 |
Markdown
|
wicho1001/blog
|
751bdf9abdd79c4c1dffd832b3b170742cd318e0
|
cec8f8ee1a5a972536dab8c343c6d982e9eb2814
|
refs/heads/master
|
<file_sep>/* Timer group-hardware timer example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "esp_types.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/periph_ctrl.h"
#include "driver/timer.h"
#include "driver/gpio.h"
#define GPIO_DATA 18
#define GPIO_CLOCK 19
#define GPIO_LATCH 21
#define GPIO_OUTPUT_PIN_SEL ((1ULL<<GPIO_DATA) | (1ULL<<GPIO_CLOCK) | (1ULL<<GPIO_LATCH) )
#define DATA_H gpio_set_level(GPIO_DATA, 1);
#define DATA_L gpio_set_level(GPIO_DATA, 0);
#define CLOCK_H gpio_set_level(GPIO_CLOCK, 1);
#define CLOCK_L gpio_set_level(GPIO_CLOCK, 0);
#define LATCH_H gpio_set_level(GPIO_LATCH, 1);
#define LATCH_L gpio_set_level(GPIO_LATCH, 0);
#define TIMER_DIVIDER 16 // Hardware timer clock divider
#define TIMER_SCALE (TIMER_BASE_CLK / TIMER_DIVIDER) // convert counter value to seconds
#define REFRESH_RATE (0.0005) // sample test interval for the second timer
#define TIMER_INTERVAL0_SEC (3.4179) // sample test interval for the first timer
#define LED_MATRIX_COLOR_NONE 0x0
#define LED_MATRIX_COLOR_RED 0x1
#define LED_MATRIX_COLOR_GREEN 0x2
#define LED_MATRIX_COLOR_ORANGE 0x3
extern const uint8_t flash_font_5x7[];
extern const uint8_t flash_font_hd44780[];
volatile uint32_t displayBuffer[200];
/*
* Timer group0 ISR handler
*
* Note:
* We don't call the timer API here because they are not declared with IRAM_ATTR.
* If we're okay with the timer irq not being serviced while SPI flash cache is disabled,
* we can allocate this interrupt without the ESP_INTR_FLAG_IRAM flag and use the normal API.
*/
void IRAM_ATTR refresh_isr(void *para)
{
int timer_idx = (int) para;
/* Retrieve the interrupt status and the counter value
from the timer that reported the interrupt */
uint32_t intr_status = TIMERG0.int_st_timers.val;
TIMERG0.hw_timer[timer_idx].update = 1;
uint64_t timer_counter_value =
((uint64_t) TIMERG0.hw_timer[timer_idx].cnt_high) << 32
| TIMERG0.hw_timer[timer_idx].cnt_low;
// UNSER SHIT
uint_fast8_t mask = 0;
static uint_fast8_t row = 0;
row++;
// Latch last line from shift register
LATCH_H;
LATCH_L;
mask = 1<<(row-1);
for (uint8_t i = 0; i < 200; i++){
DATA_L;
// Set high with a rising edge, don't setting low may be faster
if (displayBuffer[i] & mask){
DATA_H;
}
// Shift the register
CLOCK_L;
CLOCK_H;
}
DATA_L;
if (row >= 7){
row = 0;
}
// END UNSER SHIT
/* Clear the interrupt
and update the alarm time for the timer with without reload */
if ((intr_status & BIT(timer_idx)) && timer_idx == TIMER_0) {
TIMERG0.int_clr_timers.t0 = 1;
timer_counter_value += (uint64_t) (TIMER_INTERVAL0_SEC * TIMER_SCALE);
TIMERG0.hw_timer[timer_idx].alarm_high = (uint32_t) (timer_counter_value >> 32);
TIMERG0.hw_timer[timer_idx].alarm_low = (uint32_t) timer_counter_value;
} else if ((intr_status & BIT(timer_idx)) && timer_idx == TIMER_1) {
TIMERG0.int_clr_timers.t1 = 1;
}
/* After the alarm has been triggered
we need enable it again, so it is triggered the next time */
TIMERG0.hw_timer[timer_idx].config.alarm_en = TIMER_ALARM_EN;
}
/*
* Initialize selected timer of the timer group 0
*
* timer_idx - the timer number to initialize
* auto_reload - should the timer auto reload on alarm?
* timer_interval_sec - the interval of alarm to set
*/
static void refresh_timer_init(int timer_idx,
double timer_interval_sec)
{
/* Select and initialize basic parameters of the timer */
timer_config_t config;
config.divider = TIMER_DIVIDER;
config.counter_dir = TIMER_COUNT_UP;
config.counter_en = TIMER_PAUSE;
config.alarm_en = TIMER_ALARM_EN;
config.intr_type = TIMER_INTR_LEVEL;
config.auto_reload = 1;
timer_init(TIMER_GROUP_0, timer_idx, &config);
/* Timer's counter will initially start from value below.
Also, if auto_reload is set, this value will be automatically reload on alarm */
timer_set_counter_value(TIMER_GROUP_0, timer_idx, 0x00000000ULL);
/* Configure the alarm value and the interrupt on alarm. */
timer_set_alarm_value(TIMER_GROUP_0, timer_idx, timer_interval_sec * TIMER_SCALE);
timer_enable_intr(TIMER_GROUP_0, timer_idx);
timer_isr_register(TIMER_GROUP_0, timer_idx, refresh_isr,
(void *) timer_idx, ESP_INTR_FLAG_IRAM, NULL);
timer_start(TIMER_GROUP_0, timer_idx);
}
void glcd_draw_string(const char *s, uint16_t x, uint16_t y, uint8_t color)
{
uint8_t c=0;
uint8_t i=0;
uint8_t temp=0;
uint8_t width=0;
uint8_t h = 0;
uint8_t w = 0;
uint8_t d = 0;
c=*s;
i=x;
while (c != '\0')
{
for (w = 0; w < 6; w++)
{
temp = flash_font_5x7[(c*6)+w];
if(color == 1)
{
displayBuffer[(i+w)*2] = 0;
displayBuffer[(i+w)*2+1] = temp;
}
else if(color == 2)
{
displayBuffer[(i+w)*2] = temp;
displayBuffer[(i+w)*2+1] = temp;
}
else
{
displayBuffer[(i+w)*2] = temp;
displayBuffer[(i+w)*2+1] = 0;
}
}
i+=6;
c=*++s;
}
}
void gpio_init(){
gpio_config_t io_conf;
//disable interrupt
io_conf.intr_type = GPIO_PIN_INTR_DISABLE;
//set as output mode
io_conf.mode = GPIO_MODE_OUTPUT;
//bit mask of the pins that you want to set,e.g.GPIO18/19
io_conf.pin_bit_mask = GPIO_OUTPUT_PIN_SEL;
//disable pull-down mode
io_conf.pull_down_en = 0;
//disable pull-up mode
io_conf.pull_up_en = 0;
//configure GPIO with the given settings
gpio_config(&io_conf);
}
void display_init(){
CLOCK_H;
DATA_L;
LATCH_L;
for(uint_fast8_t i = 0; i < 200; i++){ //200
displayBuffer[i] = 0;
DATA_L;
CLOCK_L;
//_NOP();
//_NOP();
CLOCK_H;
}
for(uint_fast8_t i = 0; i < 7; i++){
displayBuffer[199-i] = (1<<i);
//displayBuffer[i] = (1<<i);
}
}
static void timer_example_evt_task(void *arg)
{
// Block for 500ms.
const TickType_t xDelay = 480 / portTICK_PERIOD_MS;
uint32_t animationPosition = 0;
const uint32_t animationLength = 4;
char animation[4] = "-/|\\";
char animText[2];
animText[1] = "\0";
while (1) {
animText[0] = animation[animationPosition];
animationPosition++;
if (animationPosition >= animationLength){
animationPosition = 0;
}
glcd_draw_string(animText, 95 - 15, 0, LED_MATRIX_COLOR_GREEN);
vTaskDelay(xDelay);
}
}
/*
* In this example, we will test hardware timer0 and timer1 of timer group0.
*/
void app_main()
{
gpio_init();
display_init();
glcd_draw_string("vspace rocks!",0,0,LED_MATRIX_COLOR_ORANGE);
refresh_timer_init(TIMER_1, REFRESH_RATE);
xTaskCreate(timer_example_evt_task, "timer_evt_task", 2048, NULL, 5, NULL);
}
<file_sep>#include <stdint.h>
const uint8_t flash_font_5x7[] = {
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 0
0x7E,0x81,0x95,0xB1,0xB1,0x95, // Zeichen= [] ASCII Code= 1
0x7E,0xFF,0xEB,0xCF,0xCF,0xEB, // Zeichen= [] ASCII Code= 2
0x0E,0x1F,0x3E,0x1F,0x0E,0x00, // Zeichen= [] ASCII Code= 3
0x08,0x1C,0x3E,0x7F,0x3E,0x1C, // Zeichen= [] ASCII Code= 4
0x38,0x3A,0x9F,0xFF,0x9F,0x3A, // Zeichen= [] ASCII Code= 5
0x18,0x3C,0xBE,0xFF,0xBE,0x3C, // Zeichen= [] ASCII Code= 6
0x00,0x00,0x18,0x3C,0x3C,0x18, // Zeichen= [] ASCII Code= 7
0xFF,0xFF,0xE7,0xC3,0xC3,0xE7, // Zeichen= [] ASCII Code= 8
0x00,0x3C,0x66,0x42,0x42,0x66, // Zeichen= [] ASCII Code= 9
0xFF,0xC3,0x99,0xBD,0xBD,0x99, // Zeichen= [] ASCII Code= 10
0x70,0xF8,0x88,0x88,0xFD,0x7F, // Zeichen= [] ASCII Code= 11
0x00,0x4E,0x5F,0xF1,0xF1,0x5F, // Zeichen= [] ASCII Code= 12
0xC0,0xE0,0xFF,0x7F,0x05,0x05, // Zeichen= [] ASCII Code= 13
0xC0,0xFF,0x7F,0x05,0x05,0x65, // Zeichen= [] ASCII Code= 14
0x5A,0x5A,0x3C,0xE7,0xE7,0x3C, // Zeichen= [] ASCII Code= 15
0x7F,0x3E,0x3E,0x1C,0x1C,0x08, // Zeichen= [] ASCII Code= 16
0x08,0x08,0x1C,0x1C,0x3E,0x3E, // Zeichen= [] ASCII Code= 17
0x00,0x24,0x66,0xFF,0xFF,0x66, // Zeichen= [] ASCII Code= 18
0x00,0x5F,0x5F,0x00,0x00,0x5F, // Zeichen= [] ASCII Code= 19
0x06,0x0F,0x09,0x7F,0x7F,0x01, // Zeichen= [] ASCII Code= 20
0x40,0x9A,0xBF,0xA5,0xA5,0xFD, // Zeichen= [] ASCII Code= 21
0x00,0x70,0x70,0x70,0x70,0x70, // Zeichen= [] ASCII Code= 22
0x80,0x94,0xB6,0xFF,0xFF,0xB6, // Zeichen= [] ASCII Code= 23
0x00,0x04,0x06,0x7F,0x7F,0x06, // Zeichen= [] ASCII Code= 24
0x00,0x10,0x30,0x7F,0x7F,0x30, // Zeichen= [] ASCII Code= 25
0x08,0x08,0x08,0x2A,0x3E,0x1C, // Zeichen= [] ASCII Code= 26
0x08,0x1C,0x3E,0x2A,0x08,0x08, // Zeichen= [] ASCII Code= 27
0x3C,0x3C,0x20,0x20,0x20,0x20, // Zeichen= [] ASCII Code= 28
0x08,0x1C,0x3E,0x08,0x08,0x3E, // Zeichen= [] ASCII Code= 29
0x30,0x38,0x3C,0x3E,0x3E,0x3C, // Zeichen= [] ASCII Code= 30
0x06,0x0E,0x1E,0x3E,0x3E,0x1E, // Zeichen= [] ASCII Code= 31
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 32
0x00,0x00,0x5F,0x00,0x00,0x00, // Zeichen= ! ASCII Code= 33
0x00,0x07,0x00,0x07,0x00,0x00, // Zeichen= " ASCII Code= 34
0x14,0x7F,0x14,0x7F,0x14,0x00, // Zeichen= # ASCII Code= 35
0x24,0x2A,0x7F,0x2A,0x12,0x00, // Zeichen= $ ASCII Code= 36
0x63,0x13,0x08,0x64,0x63,0x00, // Zeichen= % ASCII Code= 37
0x30,0x4E,0x59,0x26,0x50,0x00, // Zeichen= & ASCII Code= 38
0x00,0x04,0x02,0x01,0x00,0x00, // Zeichen= ' ASCII Code= 39
0x1C,0x22,0x41,0x00,0x00,0x00, // Zeichen= ( ASCII Code= 40
0x00,0x00,0x41,0x22,0x1C,0x00, // Zeichen= ) ASCII Code= 41
0x2A,0x1C,0x7F,0x1C,0x2A,0x00, // Zeichen= * ASCII Code= 42
0x08,0x08,0x3E,0x08,0x08,0x00, // Zeichen= + ASCII Code= 43
0x00,0x00,0x40,0x30,0x00,0x00, // Zeichen= , ASCII Code= 44
0x08,0x08,0x08,0x08,0x08,0x00, // Zeichen= - ASCII Code= 45
0x00,0x60,0x60,0x00,0x00,0x00, // Zeichen= . ASCII Code= 46
0x60,0x10,0x08,0x04,0x03,0x00, // Zeichen= / ASCII Code= 47
0x3E,0x51,0x49,0x45,0x3E,0x00, // Zeichen= 0 ASCII Code= 48
0x44,0x42,0x7F,0x40,0x40,0x00, // Zeichen= 1 ASCII Code= 49
0x62,0x51,0x51,0x49,0x46,0x00, // Zeichen= 2 ASCII Code= 50
0x22,0x41,0x49,0x49,0x36,0x00, // Zeichen= 3 ASCII Code= 51
0x18,0x14,0x12,0x7F,0x10,0x00, // Zeichen= 4 ASCII Code= 52
0x27,0x45,0x45,0x45,0x39,0x00, // Zeichen= 5 ASCII Code= 53
0x3C,0x4A,0x49,0x49,0x31,0x00, // Zeichen= 6 ASCII Code= 54
0x01,0x71,0x09,0x05,0x03,0x00, // Zeichen= 7 ASCII Code= 55
0x36,0x49,0x49,0x49,0x36,0x00, // Zeichen= 8 ASCII Code= 56
0x46,0x49,0x49,0x29,0x1E,0x00, // Zeichen= 9 ASCII Code= 57
0x00,0x00,0x00,0x12,0x00,0x00, // Zeichen= : ASCII Code= 58
0x00,0x00,0x40,0x32,0x00,0x00, // Zeichen= ; ASCII Code= 59
0x08,0x14,0x22,0x41,0x41,0x00, // Zeichen= < ASCII Code= 60
0x14,0x14,0x14,0x14,0x14,0x00, // Zeichen= = ASCII Code= 61
0x41,0x41,0x22,0x14,0x08,0x00, // Zeichen= > ASCII Code= 62
0x02,0x01,0x51,0x09,0x06,0x00, // Zeichen= ? ASCII Code= 63
0x3E,0x41,0x5D,0x55,0x5E,0x00, // Zeichen= @ ASCII Code= 64
0x7E,0x09,0x09,0x09,0x7E,0x00, // Zeichen= A ASCII Code= 65 ff war 7e
0x41,0x7F,0x49,0x49,0x36,0x00, // Zeichen= B ASCII Code= 66
0x3E,0x41,0x41,0x41,0x22,0x00, // Zeichen= C ASCII Code= 67
0x41,0x7F,0x41,0x41,0x3E,0x00, // Zeichen= D ASCII Code= 68
0x7F,0x49,0x49,0x49,0x41,0x00, // Zeichen= E ASCII Code= 69
0x7F,0x09,0x09,0x09,0x01,0x00, // Zeichen= F ASCII Code= 70
0x3E,0x41,0x41,0x49,0x3A,0x00, // Zeichen= G ASCII Code= 71
0x7F,0x08,0x08,0x08,0x7F,0x00, // Zeichen= H ASCII Code= 72
0x00,0x00,0x41,0x7F,0x41,0x00, // Zeichen= I ASCII Code= 73
0x20,0x40,0x41,0x3F,0x01,0x00, // Zeichen= J ASCII Code= 74
0x7F,0x08,0x14,0x22,0x41,0x00, // Zeichen= K ASCII Code= 75
0x7F,0x40,0x40,0x40,0x40,0x00, // Zeichen= L ASCII Code= 76
0x7F,0x02,0x0C,0x02,0x7F,0x00, // Zeichen= M ASCII Code= 77
0x7F,0x04,0x08,0x10,0x7F,0x00, // Zeichen= N ASCII Code= 78
0x3E,0x41,0x41,0x41,0x3E,0x00, // Zeichen= O ASCII Code= 79
0x7F,0x09,0x09,0x09,0x06,0x00, // Zeichen= P ASCII Code= 80
0x3E,0x41,0x51,0x21,0x5E,0x00, // Zeichen= Q ASCII Code= 81
0x7F,0x09,0x19,0x29,0x46,0x00, // Zeichen= R ASCII Code= 82
0x26,0x49,0x49,0x49,0x32,0x00, // Zeichen= S ASCII Code= 83
0x01,0x01,0x7F,0x01,0x01,0x00, // Zeichen= T ASCII Code= 84
0x3F,0x40,0x40,0x40,0x3F,0x00, // Zeichen= U ASCII Code= 85
0x1F,0x20,0x40,0x20,0x1F,0x00, // Zeichen= V ASCII Code= 86
0x3F,0x40,0x30,0x40,0x3F,0x00, // Zeichen= W ASCII Code= 87
0x63,0x14,0x08,0x14,0x63,0x00, // Zeichen= X ASCII Code= 88
0x07,0x08,0x78,0x08,0x07,0x00, // Zeichen= Y ASCII Code= 89
0x61,0x51,0x49,0x45,0x43,0x00, // Zeichen= Z ASCII Code= 90
0x00,0x00,0x7F,0x41,0x41,0x00, // Zeichen= [ ASCII Code= 91
0x03,0x04,0x08,0x10,0x60,0x00, // Zeichen= \ ASCII Code= 92
0x00,0x00,0x41,0x41,0x7F,0x00, // Zeichen= ] ASCII Code= 93
0x0C,0x02,0x01,0x02,0x0C,0x00, // Zeichen= ^ ASCII Code= 94
0x40,0x40,0x40,0x40,0x40,0x00, // Zeichen= _ ASCII Code= 95
0x00,0x01,0x02,0x04,0x00,0x00, // Zeichen= ` ASCII Code= 96
0x20,0x54,0x54,0x54,0x78,0x00, // Zeichen= a ASCII Code= 97
0x7F,0x28,0x44,0x44,0x38,0x00, // Zeichen= b ASCII Code= 98
0x38,0x44,0x44,0x44,0x28,0x00, // Zeichen= c ASCII Code= 99
0x38,0x44,0x44,0x28,0x7F,0x00, // Zeichen= d ASCII Code= 100
0x38,0x54,0x54,0x54,0x58,0x00, // Zeichen= e ASCII Code= 101
0x08,0x08,0x7E,0x09,0x0A,0x00, // Zeichen= f ASCII Code= 102
0x08,0x54,0x54,0x48,0x3C,0x00, // Zeichen= g ASCII Code= 103
0x7F,0x08,0x04,0x04,0x78,0x00, // Zeichen= h ASCII Code= 104
0x00,0x44,0x7D,0x40,0x00,0x00, // Zeichen= i ASCII Code= 105
0x20,0x40,0x44,0x3D,0x00,0x00, // Zeichen= j ASCII Code= 106
0x7F,0x20,0x10,0x28,0x44,0x00, // Zeichen= k ASCII Code= 107
0x00,0x01,0x7F,0x40,0x00,0x00, // Zeichen= l ASCII Code= 108
0x7C,0x04,0x78,0x04,0x78,0x00, // Zeichen= m ASCII Code= 109
0x7C,0x08,0x04,0x04,0x78,0x00, // Zeichen= n ASCII Code= 110
0x38,0x44,0x44,0x44,0x38,0x00, // Zeichen= o ASCII Code= 111
0x7C,0x18,0x24,0x24,0x18,0x00, // Zeichen= p ASCII Code= 112
0x18,0x24,0x24,0x18,0x7C,0x00, // Zeichen= q ASCII Code= 113
0x7C,0x08,0x04,0x04,0x08,0x00, // Zeichen= r ASCII Code= 114
0x48,0x54,0x54,0x54,0x24,0x00, // Zeichen= s ASCII Code= 115
0x04,0x04,0x3F,0x44,0x24,0x00, // Zeichen= t ASCII Code= 116
0x3C,0x40,0x40,0x3C,0x40,0x00, // Zeichen= u ASCII Code= 117
0x1C,0x20,0x40,0x20,0x1C,0x00, // Zeichen= v ASCII Code= 118
0x3C,0x40,0x3C,0x40,0x3C,0x00, // Zeichen= w ASCII Code= 119
0x44,0x28,0x10,0x28,0x44,0x00, // Zeichen= x ASCII Code= 120
0x0C,0x50,0x50,0x50,0x3C,0x00, // Zeichen= y ASCII Code= 121
0x44,0x64,0x54,0x4C,0x44,0x00, // Zeichen= z ASCII Code= 122
0x08,0x08,0x36,0x41,0x41,0x00, // Zeichen= ASCII Code= 123
0x00,0x00,0x7F,0x00,0x00,0x00, // Zeichen= | ASCII Code= 124
0x41,0x41,0x36,0x08,0x08,0x00, // Zeichen= ASCII Code= 125
0x02,0x01,0x02,0x02,0x01,0x00, // Zeichen= ~ ASCII Code= 126
0x70,0x48,0x44,0x48,0x70,0x00, // Zeichen= ASCII Code= 127
0x1E,0xBF,0xA1,0xA1,0xE1,0x73, // Zeichen= ASCII Code= 128
0x3A,0x40,0x40,0x3A,0x40,0x00, // Zeichen= ASCII Code= 129
0x38,0x7C,0x54,0x56,0x57,0x5D, // Zeichen= ASCII Code= 130
0x22,0x75,0x55,0x55,0x3D,0x79, // Zeichen= ASCII Code= 131
0x21,0x54,0x54,0x54,0x79,0x00, // Zeichen= ASCII Code= 132
0x20,0x74,0x55,0x57,0x3E,0x78, // Zeichen=
ASCII Code= 133
0x20,0x74,0x57,0x57,0x3C,0x78, // Zeichen= ASCII Code= 134
0x18,0x3C,0xA4,0xA4,0xE4,0x64, // Zeichen= ASCII Code= 135
0x3A,0x7D,0x55,0x55,0x55,0x5D, // Zeichen= ASCII Code= 136
0x39,0x7D,0x54,0x54,0x54,0x5D, // Zeichen= ASCII Code= 137
0x38,0x7C,0x55,0x57,0x56,0x5C, // Zeichen= ASCII Code= 138
0x00,0x01,0x45,0x7C,0x7C,0x41, // Zeichen= ASCII Code= 139
0x02,0x01,0x45,0x7D,0x7D,0x41, // Zeichen= ASCII Code= 140
0x00,0x00,0x49,0x7B,0x7A,0x40, // Zeichen= ASCII Code= 141
0x7D,0x12,0x12,0x12,0x7D,0x00, // Zeichen= ASCII Code= 142
0x78,0x7E,0x17,0x15,0x17,0x7E, // Zeichen= ASCII Code= 143
0x7C,0x7C,0x56,0x57,0x55,0x44, // Zeichen= ASCII Code= 144
0x20,0x74,0x54,0x7C,0x7C,0x54, // Zeichen= ASCII Code= 145
0x7C,0x7E,0x0B,0x09,0x7F,0x7F, // Zeichen= ASCII Code= 146
0x3A,0x7D,0x45,0x45,0x45,0x7D, // Zeichen= ASCII Code= 147
0x39,0x44,0x44,0x44,0x39,0x00, // Zeichen= ASCII Code= 148
0x38,0x7C,0x45,0x47,0x46,0x7C, // Zeichen= ASCII Code= 149
0x3A,0x79,0x41,0x41,0x39,0x7A, // Zeichen= ASCII Code= 150
0x3C,0x7D,0x43,0x42,0x3C,0x7C, // Zeichen= ASCII Code= 151
0x9D,0xBD,0xA0,0xA0,0xA0,0xFD, // Zeichen= ASCII Code= 152
0x3D,0x42,0x42,0x42,0x3D,0x00, // Zeichen= ASCII Code= 153
0x3D,0x40,0x40,0x40,0x3D,0x00, // Zeichen= ASCII Code= 154
0x18,0x3C,0x24,0xE7,0xE7,0x24, // Zeichen= ASCII Code= 155
0x48,0x7E,0x7F,0x49,0x43,0x66, // Zeichen= ASCII Code= 156
0x00,0x2B,0x2F,0xFC,0xFC,0x2F, // Zeichen= ASCII Code= 157
0xFF,0xFF,0x09,0x09,0x2F,0xF6, // Zeichen= ASCII Code= 158
0x20,0x60,0x48,0x7E,0x3F,0x09, // Zeichen= ASCII Code= 159
0x20,0x74,0x56,0x57,0x3D,0x78, // Zeichen= ASCII Code= 160
0x00,0x00,0x48,0x7A,0x7B,0x41, // Zeichen= ¡ ASCII Code= 161
0x38,0x7C,0x44,0x46,0x47,0x7D, // Zeichen= ¢ ASCII Code= 162
0x3C,0x7C,0x42,0x43,0x3D,0x7C, // Zeichen= £ ASCII Code= 163
0x0A,0x7B,0x71,0x0B,0x0A,0x7B, // Zeichen= ¤ ASCII Code= 164
0x7A,0x7B,0x19,0x33,0x62,0x7B, // Zeichen= ¥ ASCII Code= 165
0x00,0x26,0x2F,0x29,0x2F,0x2F, // Zeichen= ¦ ASCII Code= 166
0x00,0x26,0x2F,0x29,0x2F,0x26, // Zeichen= § ASCII Code= 167
0x00,0x20,0x70,0x5D,0x4D,0x40, // Zeichen= ¨ ASCII Code= 168
0x38,0x38,0x08,0x08,0x08,0x08, // Zeichen= © ASCII Code= 169
0x08,0x08,0x08,0x08,0x08,0x38, // Zeichen= ª ASCII Code= 170
0x42,0x6F,0x3F,0x18,0xCC,0xEE, // Zeichen= « ASCII Code= 171
0x42,0x6F,0x3F,0x58,0x6C,0xD6, // Zeichen= ¬ ASCII Code= 172
0x00,0x00,0x30,0x7D,0x7D,0x30, // Zeichen= ASCII Code= 173
0x08,0x1C,0x36,0x22,0x08,0x1C, // Zeichen= ® ASCII Code= 174
0x22,0x36,0x1C,0x08,0x22,0x36, // Zeichen= ¯ ASCII Code= 175
0xAA,0x00,0x55,0x00,0xAA,0x00, // Zeichen= ° ASCII Code= 176
0xAA,0x55,0xAA,0x55,0xAA,0x55, // Zeichen= ± ASCII Code= 177
0xAA,0xFF,0x55,0xFF,0xAA,0xFF, // Zeichen= ² ASCII Code= 178
0x00,0x00,0x00,0xFF,0xFF,0x00, // Zeichen= ³ ASCII Code= 179
0x10,0x10,0x10,0xFF,0xFF,0x00, // Zeichen= ´ ASCII Code= 180
0x14,0x14,0x14,0xFF,0xFF,0x00, // Zeichen= µ ASCII Code= 181
0x10,0x10,0xFF,0xFF,0x00,0xFF, // Zeichen= ¶ ASCII Code= 182
0x10,0x10,0xF0,0xF0,0x10,0xF0, // Zeichen= · ASCII Code= 183
0x14,0x14,0x14,0xFC,0xFC,0x00, // Zeichen= ¸ ASCII Code= 184
0x14,0x14,0xF7,0xF7,0x00,0xFF, // Zeichen= ¹ ASCII Code= 185
0x00,0x00,0xFF,0xFF,0x00,0xFF, // Zeichen= º ASCII Code= 186
0x14,0x14,0xF4,0xF4,0x04,0xFC, // Zeichen= » ASCII Code= 187
0x14,0x14,0x17,0x17,0x10,0x1F, // Zeichen= ¼ ASCII Code= 188
0x10,0x10,0x1F,0x1F,0x10,0x1F, // Zeichen= ½ ASCII Code= 189
0x14,0x14,0x14,0x1F,0x1F,0x00, // Zeichen= ¾ ASCII Code= 190
0x10,0x10,0x10,0xF0,0xF0,0x00, // Zeichen= ¿ ASCII Code= 191
0x00,0x00,0x00,0x1F,0x1F,0x10, // Zeichen= À ASCII Code= 192
0x10,0x10,0x10,0x1F,0x1F,0x10, // Zeichen= Á ASCII Code= 193
0x10,0x10,0x10,0xF0,0xF0,0x10, // Zeichen= Â ASCII Code= 194
0x00,0x00,0x00,0xFF,0xFF,0x10, // Zeichen= Ã ASCII Code= 195
0x10,0x10,0x10,0x10,0x10,0x10, // Zeichen= Ä ASCII Code= 196
0x10,0x10,0x10,0xFF,0xFF,0x10, // Zeichen= Å ASCII Code= 197
0x00,0x00,0x00,0xFF,0xFF,0x14, // Zeichen= Æ ASCII Code= 198
0x00,0x00,0xFF,0xFF,0x00,0xFF, // Zeichen= Ç ASCII Code= 199
0x00,0x00,0x1F,0x1F,0x10,0x17, // Zeichen= È ASCII Code= 200
0x00,0x00,0xFC,0xFC,0x04,0xF4, // Zeichen= É ASCII Code= 201
0x14,0x14,0x17,0x17,0x10,0x17, // Zeichen= Ê ASCII Code= 202
0x14,0x14,0xF4,0xF4,0x04,0xF4, // Zeichen= Ë ASCII Code= 203
0x00,0x00,0xFF,0xFF,0x00,0xF7, // Zeichen= Ì ASCII Code= 204
0x14,0x14,0x14,0x14,0x14,0x14, // Zeichen= Í ASCII Code= 205
0x14,0x14,0xF7,0xF7,0x00,0xF7, // Zeichen= Î ASCII Code= 206
0x14,0x14,0x14,0x17,0x17,0x14, // Zeichen= Ï ASCII Code= 207
0x10,0x10,0x1F,0x1F,0x10,0x1F, // Zeichen= Ð ASCII Code= 208
0x14,0x14,0x14,0xF4,0xF4,0x14, // Zeichen= Ñ ASCII Code= 209
0x10,0x10,0xF0,0xF0,0x10,0xF0, // Zeichen= Ò ASCII Code= 210
0x00,0x00,0x1F,0x1F,0x10,0x1F, // Zeichen= Ó ASCII Code= 211
0x00,0x00,0x00,0x1F,0x1F,0x14, // Zeichen= Ô ASCII Code= 212
0x00,0x00,0x00,0xFC,0xFC,0x14, // Zeichen= Õ ASCII Code= 213
0x00,0x00,0xF0,0xF0,0x10,0xF0, // Zeichen= Ö ASCII Code= 214
0x10,0x10,0xFF,0xFF,0x10,0xFF, // Zeichen= × ASCII Code= 215
0x14,0x14,0x14,0xFF,0xFF,0x14, // Zeichen= Ø ASCII Code= 216
0x10,0x10,0x10,0x1F,0x1F,0x00, // Zeichen= Ù ASCII Code= 217
0x00,0x00,0x00,0xF0,0xF0,0x10, // Zeichen= Ú ASCII Code= 218
0x7F,0x7F,0x7F,0x7F,0x7F,0x00, // Zeichen= Û ASCII Code= 219
0x7C,0x7C,0x7C,0x7C,0x7C,0x00, // Zeichen= Ü ASCII Code= 220
0x1F,0x1F,0x1F,0x1F,0x1F,0x00, // Zeichen= Ý ASCII Code= 221
0x1F,0x0F,0x07,0x03,0x01,0x00, // Zeichen= Þ ASCII Code= 222
0x01,0x03,0x07,0x0F,0x1F,0x00, // Zeichen= ß ASCII Code= 223
0x7C,0x78,0x70,0x60,0x40,0x00, // Zeichen= à ASCII Code= 224
0x7E,0x01,0x49,0x56,0x20,0x00, // Zeichen= á ASCII Code= 225
0x40,0x60,0x70,0x78,0x7C,0x00, // Zeichen= â ASCII Code= 226
0x04,0x7C,0x7C,0x04,0x7C,0x7C, // Zeichen= ã ASCII Code= 227
0x63,0x77,0x5D,0x49,0x41,0x63, // Zeichen= ä ASCII Code= 228
0x38,0x7C,0x44,0x7C,0x3C,0x04, // Zeichen= å ASCII Code= 229
0x80,0xFC,0x7C,0x40,0x40,0x7C, // Zeichen= æ ASCII Code= 230
0x04,0x06,0x02,0x7E,0x7C,0x06, // Zeichen= ç ASCII Code= 231
0x00,0x99,0xBD,0xE7,0xE7,0xBD, // Zeichen= è ASCII Code= 232
0x1C,0x3E,0x6B,0x49,0x6B,0x3E, // Zeichen= é ASCII Code= 233
0x4C,0x7E,0x73,0x01,0x73,0x7E, // Zeichen= ê ASCII Code= 234
0x00,0x30,0x78,0x4A,0x4F,0x7D, // Zeichen= ë ASCII Code= 235
0x18,0x3C,0x24,0x3C,0x3C,0x24, // Zeichen= ì ASCII Code= 236
0x98,0xFC,0x64,0x3C,0x3E,0x27, // Zeichen= í ASCII Code= 237
0x14,0x3E,0x55,0x55,0x55,0x41, // Zeichen= î ASCII Code= 238
0x7C,0x7E,0x02,0x02,0x02,0x7E, // Zeichen= ï ASCII Code= 239
0x2A,0x2A,0x2A,0x2A,0x2A,0x2A, // Zeichen= ð ASCII Code= 240
0x00,0x44,0x44,0x5F,0x5F,0x44, // Zeichen= ñ ASCII Code= 241
0x00,0x40,0x51,0x5B,0x4E,0x44, // Zeichen= ò ASCII Code= 242
0x00,0x40,0x44,0x4E,0x5B,0x51, // Zeichen= ó ASCII Code= 243
0x00,0x00,0x00,0xFE,0xFF,0x01, // Zeichen= ô ASCII Code= 244
0x60,0xE0,0x80,0xFF,0x7F,0x00, // Zeichen= õ ASCII Code= 245
0x00,0x08,0x08,0x2A,0x2A,0x08, // Zeichen= ö ASCII Code= 246
0x24,0x36,0x12,0x36,0x24,0x36, // Zeichen= ÷ ASCII Code= 247
0x00,0x02,0x05,0x05,0x02,0x00, // Zeichen= ø ASCII Code= 248
0x00,0x00,0x00,0x18,0x18,0x00, // Zeichen= ù ASCII Code= 249
0x00,0x00,0x00,0x08,0x08,0x00, // Zeichen= ú ASCII Code= 250
0x10,0x30,0x70,0xC0,0xFF,0xFF, // Zeichen= û ASCII Code= 251
0x00,0x01,0x1F,0x1E,0x01,0x1F, // Zeichen= ü ASCII Code= 252
0x00,0x11,0x19,0x1D,0x17,0x12, // Zeichen= ý ASCII Code= 253
0x00,0x00,0x3C,0x3C,0x3C,0x3C, // Zeichen= þ ASCII Code= 254
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ÿ ASCII Code= 255
};
const uint8_t flash_font_hd44780[] = {
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 0
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 1
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 2
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 3
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 4
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 5
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 6
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 7
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 8
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 9
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 10
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 11
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 12
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 13
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 14
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 15
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 16
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 17
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 18
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 19
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 20
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 21
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 22
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 23
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 24
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 25
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 26
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 27
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 28
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 29
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 30
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= [] ASCII Code= 31
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 32
0x00,0x00,0x5F,0x00,0x00,0x00, // Zeichen= ! ASCII Code= 33
0x00,0x07,0x00,0x07,0x00,0x00, // Zeichen= " ASCII Code= 34
0x14,0x7F,0x14,0x7F,0x14,0x00, // Zeichen= # ASCII Code= 35
0x24,0x2A,0x7F,0x2A,0x12,0x00, // Zeichen= $ ASCII Code= 36
0x23,0x13,0x08,0x64,0x62,0x00, // Zeichen= % ASCII Code= 37
0x36,0x49,0x55,0x22,0x50,0x00, // Zeichen= & ASCII Code= 38
0x00,0x05,0x03,0x00,0x00,0x00, // Zeichen= ' ASCII Code= 39
0x00,0x1C,0x22,0x41,0x00,0x00, // Zeichen= ( ASCII Code= 40
0x00,0x41,0x22,0x1C,0x00,0x00, // Zeichen= ) ASCII Code= 41
0x14,0x08,0x3E,0x08,0x14,0x00, // Zeichen= * ASCII Code= 42
0x08,0x08,0x3E,0x08,0x08,0x00, // Zeichen= + ASCII Code= 43
0x00,0x50,0x30,0x00,0x00,0x00, // Zeichen= , ASCII Code= 44
0x08,0x08,0x08,0x08,0x08,0x00, // Zeichen= - ASCII Code= 45
0x00,0x60,0x60,0x00,0x00,0x00, // Zeichen= . ASCII Code= 46
0x20,0x10,0x08,0x04,0x02,0x00, // Zeichen= / ASCII Code= 47
0x3E,0x51,0x49,0x45,0x3E,0x00, // Zeichen= 0 ASCII Code= 48
0x00,0x42,0x7F,0x40,0x00,0x00, // Zeichen= 1 ASCII Code= 49
0x42,0x61,0x51,0x49,0x46,0x00, // Zeichen= 2 ASCII Code= 50
0x21,0x41,0x45,0x4B,0x31,0x00, // Zeichen= 3 ASCII Code= 51
0x18,0x14,0x12,0x7F,0x10,0x00, // Zeichen= 4 ASCII Code= 52
0x27,0x45,0x45,0x45,0x39,0x00, // Zeichen= 5 ASCII Code= 53
0x3C,0x4A,0x49,0x49,0x30,0x00, // Zeichen= 6 ASCII Code= 54
0x01,0x71,0x09,0x05,0x03,0x00, // Zeichen= 7 ASCII Code= 55
0x36,0x49,0x49,0x49,0x36,0x00, // Zeichen= 8 ASCII Code= 56
0x06,0x49,0x49,0x29,0x1E,0x00, // Zeichen= 9 ASCII Code= 57
0x00,0x36,0x36,0x00,0x00,0x00, // Zeichen= : ASCII Code= 58
0x00,0x56,0x36,0x00,0x00,0x00, // Zeichen= ; ASCII Code= 59
0x08,0x14,0x22,0x41,0x00,0x00, // Zeichen= < ASCII Code= 60
0x14,0x14,0x14,0x14,0x14,0x00, // Zeichen= = ASCII Code= 61
0x00,0x41,0x22,0x14,0x08,0x00, // Zeichen= > ASCII Code= 62
0x02,0x01,0x51,0x09,0x06,0x00, // Zeichen= ? ASCII Code= 63
0x32,0x49,0x79,0x41,0x3E,0x00, // Zeichen= @ ASCII Code= 64
0x7E,0x09,0x09,0x09,0x7E,0x00, // Zeichen= A ASCII Code= 65
0x7F,0x49,0x49,0x49,0x36,0x00, // Zeichen= B ASCII Code= 66
0x3E,0x41,0x41,0x41,0x22,0x00, // Zeichen= C ASCII Code= 67
0x7F,0x41,0x41,0x41,0x3E,0x00, // Zeichen= D ASCII Code= 68
0x7F,0x49,0x49,0x49,0x41,0x00, // Zeichen= E ASCII Code= 69
0x7F,0x09,0x09,0x09,0x01,0x00, // Zeichen= F ASCII Code= 70
0x3E,0x41,0x49,0x49,0x7A,0x00, // Zeichen= G ASCII Code= 71
0x7F,0x08,0x08,0x08,0x7F,0x00, // Zeichen= H ASCII Code= 72
0x00,0x00,0x41,0x7F,0x41,0x00, // Zeichen= I ASCII Code= 73
0x20,0x40,0x41,0x3F,0x01,0x00, // Zeichen= J ASCII Code= 74
0x7F,0x08,0x14,0x22,0x41,0x00, // Zeichen= K ASCII Code= 75
0x7F,0x40,0x40,0x40,0x40,0x00, // Zeichen= L ASCII Code= 76
0x7F,0x02,0x0C,0x02,0x7F,0x00, // Zeichen= M ASCII Code= 77
0x7F,0x04,0x08,0x10,0x7F,0x00, // Zeichen= N ASCII Code= 78
0x3E,0x41,0x41,0x41,0x3E,0x00, // Zeichen= O ASCII Code= 79
0x7F,0x09,0x09,0x09,0x06,0x00, // Zeichen= P ASCII Code= 80
0x3E,0x41,0x51,0x21,0x5E,0x00, // Zeichen= Q ASCII Code= 81
0x7F,0x09,0x19,0x29,0x46,0x00, // Zeichen= R ASCII Code= 82
0x46,0x49,0x49,0x49,0x31,0x00, // Zeichen= S ASCII Code= 83
0x01,0x01,0x7F,0x01,0x01,0x00, // Zeichen= T ASCII Code= 84
0x3F,0x40,0x40,0x40,0x3F,0x00, // Zeichen= U ASCII Code= 85
0x1F,0x20,0x40,0x20,0x1F,0x00, // Zeichen= V ASCII Code= 86
0x3F,0x40,0x30,0x40,0x3F,0x00, // Zeichen= W ASCII Code= 87
0x63,0x14,0x08,0x14,0x63,0x00, // Zeichen= X ASCII Code= 88
0x07,0x08,0x70,0x08,0x07,0x00, // Zeichen= Y ASCII Code= 89
0x61,0x51,0x49,0x45,0x43,0x00, // Zeichen= Z ASCII Code= 90
0x7F,0x41,0x41,0x00,0x00,0x00, // Zeichen= [ ASCII Code= 91
0x15,0x16,0x7C,0x16,0x15,0x00, // Zeichen= ASCII Code= 92
0x00,0x41,0x41,0x7F,0x00,0x00, // Zeichen= ] ASCII Code= 93
0x04,0x02,0x01,0x02,0x04,0x00, // Zeichen= ^ ASCII Code= 94
0x40,0x40,0x40,0x40,0x40,0x00, // Zeichen= _ ASCII Code= 95
0x00,0x01,0x02,0x04,0x00,0x00, // Zeichen= ` ASCII Code= 96
0x20,0x54,0x54,0x54,0x78,0x00, // Zeichen= a ASCII Code= 97
0x7F,0x48,0x44,0x44,0x38,0x00, // Zeichen= b ASCII Code= 98
0x38,0x44,0x44,0x44,0x20,0x00, // Zeichen= c ASCII Code= 99
0x38,0x44,0x44,0x48,0x7F,0x00, // Zeichen= d ASCII Code= 100
0x38,0x54,0x54,0x54,0x18,0x00, // Zeichen= e ASCII Code= 101
0x08,0x7E,0x09,0x01,0x02,0x00, // Zeichen= f ASCII Code= 102
0x08,0x54,0x54,0x54,0x3C,0x00, // Zeichen= g ASCII Code= 103
0x7F,0x08,0x04,0x04,0x78,0x00, // Zeichen= h ASCII Code= 104
0x00,0x44,0x7D,0x40,0x00,0x00, // Zeichen= i ASCII Code= 105
0x20,0x40,0x44,0x3D,0x00,0x00, // Zeichen= j ASCII Code= 106
0x7F,0x10,0x28,0x44,0x00,0x00, // Zeichen= k ASCII Code= 107
0x00,0x41,0x7F,0x40,0x00,0x00, // Zeichen= l ASCII Code= 108
0x7C,0x04,0x18,0x04,0x78,0x00, // Zeichen= m ASCII Code= 109
0x7C,0x08,0x04,0x04,0x78,0x00, // Zeichen= n ASCII Code= 110
0x38,0x44,0x44,0x44,0x38,0x00, // Zeichen= o ASCII Code= 111
0x7C,0x14,0x14,0x14,0x08,0x00, // Zeichen= p ASCII Code= 112
0x08,0x14,0x14,0x18,0x7C,0x00, // Zeichen= q ASCII Code= 113
0x7C,0x08,0x04,0x04,0x08,0x00, // Zeichen= r ASCII Code= 114
0x48,0x54,0x54,0x54,0x20,0x00, // Zeichen= s ASCII Code= 115
0x04,0x3F,0x44,0x40,0x20,0x00, // Zeichen= t ASCII Code= 116
0x3C,0x40,0x40,0x20,0x7C,0x00, // Zeichen= u ASCII Code= 117
0x1C,0x20,0x40,0x20,0x1C,0x00, // Zeichen= v ASCII Code= 118
0x3C,0x40,0x38,0x40,0x3C,0x00, // Zeichen= w ASCII Code= 119
0x44,0x28,0x10,0x28,0x44,0x00, // Zeichen= x ASCII Code= 120
0x0C,0x50,0x50,0x50,0x3C,0x00, // Zeichen= y ASCII Code= 121
0x44,0x64,0x54,0x4C,0x44,0x00, // Zeichen= z ASCII Code= 122
0x00,0x08,0x36,0x41,0x00,0x00, // Zeichen= { ASCII Code= 123
0x00,0x00,0x7F,0x00,0x00,0x00, // Zeichen= | ASCII Code= 124
0x00,0x41,0x36,0x08,0x00,0x00, // Zeichen= } ASCII Code= 125
0x08,0x08,0x2A,0x1C,0x08,0x00, // Zeichen= ~ ASCII Code= 126
0x08,0x1C,0x2A,0x08,0x08,0x00, // Zeichen= ASCII Code= 127
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 128
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 129
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 130
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 131
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 132
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen=
ASCII Code= 133
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 134
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 135
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 136
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 137
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 138
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 139
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 140
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 141
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 142
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 143
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 144
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 145
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 146
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 147
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 148
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 149
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 150
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 151
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 152
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 153
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 154
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 155
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 156
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 157
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 158
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 159
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= ASCII Code= 160
0x70,0x50,0x70,0x00,0x00,0x00, // Zeichen= ¡ ASCII Code= 161
0x00,0x00,0x0F,0x01,0x01,0x00, // Zeichen= ¢ ASCII Code= 162
0x40,0x40,0x78,0x00,0x00,0x00, // Zeichen= £ ASCII Code= 163
0x10,0x20,0x40,0x00,0x00,0x00, // Zeichen= ¤ ASCII Code= 164
0x00,0x18,0x18,0x00,0x00,0x00, // Zeichen= ¥ ASCII Code= 165
0x0A,0x0A,0x4A,0x2A,0x1E,0x00, // Zeichen= ¦ ASCII Code= 166
0x04,0x44,0x34,0x14,0x0C,0x00, // Zeichen= § ASCII Code= 167
0x20,0x10,0x78,0x04,0x00,0x00, // Zeichen= ¨ ASCII Code= 168
0x18,0x08,0x4C,0x48,0x38,0x00, // Zeichen= © ASCII Code= 169
0x44,0x44,0x7C,0x44,0x44,0x00, // Zeichen= ª ASCII Code= 170
0x48,0x28,0x18,0x7C,0x08,0x00, // Zeichen= « ASCII Code= 171
0x08,0x7C,0x08,0x28,0x18,0x00, // Zeichen= ¬ ASCII Code= 172
0x40,0x48,0x48,0x78,0x40,0x00, // Zeichen= ASCII Code= 173
0x54,0x54,0x54,0x7C,0x00,0x00, // Zeichen= ® ASCII Code= 174
0x18,0x00,0x58,0x40,0x38,0x00, // Zeichen= ¯ ASCII Code= 175
0x08,0x08,0x08,0x08,0x08,0x00, // Zeichen= ° ASCII Code= 176
0x01,0x41,0x3D,0x09,0x07,0x00, // Zeichen= ± ASCII Code= 177
0x10,0x08,0x7C,0x02,0x01,0x00, // Zeichen= ² ASCII Code= 178
0x0E,0x02,0x43,0x22,0x1E,0x00, // Zeichen= ³ ASCII Code= 179
0x42,0x42,0x7E,0x42,0x42,0x00, // Zeichen= ´ ASCII Code= 180
0x22,0x12,0x0A,0x7F,0x02,0x00, // Zeichen= µ ASCII Code= 181
0x42,0x3F,0x02,0x42,0x3E,0x00, // Zeichen= ¶ ASCII Code= 182
0x0A,0x0A,0x7F,0x0A,0x0A,0x00, // Zeichen= · ASCII Code= 183
0x08,0x46,0x42,0x22,0x1E,0x00, // Zeichen= ¸ ASCII Code= 184
0x04,0x03,0x42,0x3E,0x02,0x00, // Zeichen= ¹ ASCII Code= 185
0x42,0x42,0x42,0x42,0x7E,0x00, // Zeichen= º ASCII Code= 186
0x02,0x4F,0x22,0x1F,0x02,0x00, // Zeichen= » ASCII Code= 187
0x4A,0x4A,0x40,0x20,0x1C,0x00, // Zeichen= ¼ ASCII Code= 188
0x42,0x22,0x12,0x2A,0x46,0x00, // Zeichen= ½ ASCII Code= 189
0x02,0x3F,0x42,0x4A,0x46,0x00, // Zeichen= ¾ ASCII Code= 190
0x06,0x48,0x40,0x20,0x1E,0x00, // Zeichen= ¿ ASCII Code= 191
0x08,0x46,0x4A,0x32,0x1E,0x00, // Zeichen= À ASCII Code= 192
0x0A,0x4A,0x3E,0x09,0x08,0x00, // Zeichen= Á ASCII Code= 193
0x0E,0x00,0x4E,0x20,0x1E,0x00, // Zeichen= Â ASCII Code= 194
0x04,0x45,0x3D,0x05,0x04,0x00, // Zeichen= Ã ASCII Code= 195
0x00,0x7F,0x08,0x10,0x00,0x00, // Zeichen= Ä ASCII Code= 196
0x44,0x24,0x1F,0x04,0x04,0x00, // Zeichen= Å ASCII Code= 197
0x40,0x42,0x42,0x42,0x40,0x00, // Zeichen= Æ ASCII Code= 198
0x42,0x2A,0x12,0x2A,0x06,0x00, // Zeichen= Ç ASCII Code= 199
0x22,0x12,0x7B,0x16,0x22,0x00, // Zeichen= È ASCII Code= 200
0x00,0x40,0x20,0x1F,0x00,0x00, // Zeichen= É ASCII Code= 201
0x78,0x00,0x02,0x04,0x78,0x00, // Zeichen= Ê ASCII Code= 202
0x3F,0x44,0x44,0x44,0x44,0x00, // Zeichen= Ë ASCII Code= 203
0x02,0x42,0x42,0x22,0x1E,0x00, // Zeichen= Ì ASCII Code= 204
0x04,0x02,0x04,0x08,0x30,0x00, // Zeichen= Í ASCII Code= 205
0x32,0x02,0x7F,0x02,0x32,0x00, // Zeichen= Î ASCII Code= 206
0x02,0x12,0x22,0x52,0x0E,0x00, // Zeichen= Ï ASCII Code= 207
0x00,0x2A,0x2A,0x2A,0x40,0x00, // Zeichen= Ð ASCII Code= 208
0x38,0x24,0x22,0x20,0x70,0x00, // Zeichen= Ñ ASCII Code= 209
0x40,0x28,0x10,0x28,0x06,0x00, // Zeichen= Ò ASCII Code= 210
0x0A,0x3E,0x4A,0x4A,0x4A,0x00, // Zeichen= Ó ASCII Code= 211
0x04,0x7F,0x04,0x14,0x0C,0x00, // Zeichen= Ô ASCII Code= 212
0x40,0x42,0x42,0x7E,0x40,0x00, // Zeichen= Õ ASCII Code= 213
0x4A,0x4A,0x4A,0x4A,0x7E,0x00, // Zeichen= Ö ASCII Code= 214
0x04,0x05,0x45,0x25,0x1C,0x00, // Zeichen= × ASCII Code= 215
0x0F,0x40,0x20,0x1F,0x00,0x00, // Zeichen= Ø ASCII Code= 216
0x7C,0x00,0x7E,0x40,0x30,0x00, // Zeichen= Ù ASCII Code= 217
0x7E,0x40,0x20,0x10,0x08,0x00, // Zeichen= Ú ASCII Code= 218
0x7E,0x42,0x42,0x42,0x7E,0x00, // Zeichen= Û ASCII Code= 219
0x0E,0x02,0x42,0x22,0x1E,0x00, // Zeichen= Ü ASCII Code= 220
0x42,0x42,0x40,0x20,0x18,0x00, // Zeichen= Ý ASCII Code= 221
0x02,0x04,0x01,0x02,0x00,0x00, // Zeichen= Þ ASCII Code= 222
0x07,0x05,0x07,0x00,0x00,0x00, // Zeichen= ß ASCII Code= 223
0x38,0x44,0x48,0x30,0x4C,0x00, // Zeichen= à ASCII Code= 224
0x20,0x55,0x54,0x55,0x78,0x00, // Zeichen= á ASCII Code= 225
0xF8,0x54,0x54,0x54,0x28,0x00, // Zeichen= â ASCII Code= 226
0x28,0x54,0x54,0x44,0x20,0x00, // Zeichen= ã ASCII Code= 227
0xFC,0x40,0x40,0x20,0x7C,0x00, // Zeichen= ä ASCII Code= 228
0x38,0x44,0x4C,0x54,0x24,0x00, // Zeichen= å ASCII Code= 229
0xF0,0x48,0x44,0x44,0x38,0x00, // Zeichen= æ ASCII Code= 230
0x38,0x44,0x44,0x44,0xFC,0x00, // Zeichen= ç ASCII Code= 231
0x20,0x40,0x3C,0x04,0x04,0x00, // Zeichen= è ASCII Code= 232
0x04,0x04,0x00,0x0E,0x00,0x00, // Zeichen= é ASCII Code= 233
0x00,0x00,0x04,0xFD,0x00,0x00, // Zeichen= ê ASCII Code= 234
0x0A,0x04,0x0A,0x00,0x00,0x00, // Zeichen= ë ASCII Code= 235
0x18,0x24,0x7E,0x24,0x10,0x00, // Zeichen= ì ASCII Code= 236
0x14,0x7F,0x54,0x40,0x40,0x00, // Zeichen= í ASCII Code= 237
0x7C,0x09,0x05,0x05,0x78,0x00, // Zeichen= î ASCII Code= 238
0x38,0x45,0x44,0x45,0x38,0x00, // Zeichen= ï ASCII Code= 239
0xFC,0x48,0x44,0x44,0x38,0x00, // Zeichen= ð ASCII Code= 240
0x38,0x44,0x44,0x48,0xFC,0x00, // Zeichen= ñ ASCII Code= 241
0x3C,0x4A,0x4A,0x4A,0x3C,0x00, // Zeichen= ò ASCII Code= 242
0x30,0x28,0x10,0x28,0x18,0x00, // Zeichen= ó ASCII Code= 243
0x58,0x64,0x04,0x64,0x58,0x00, // Zeichen= ô ASCII Code= 244
0x7C,0x81,0x80,0x41,0xFC,0x00, // Zeichen= õ ASCII Code= 245
0x63,0x55,0x49,0x41,0x41,0x00, // Zeichen= ö ASCII Code= 246
0x44,0x3C,0x04,0x7C,0x44,0x00, // Zeichen= ÷ ASCII Code= 247
0x45,0x29,0x11,0x29,0x45,0x00, // Zeichen= ø ASCII Code= 248
0x3C,0x40,0x40,0x40,0xFC,0x00, // Zeichen= ù ASCII Code= 249
0x14,0x14,0x7C,0x14,0x12,0x00, // Zeichen= ú ASCII Code= 250
0x44,0x3C,0x14,0x14,0x74,0x00, // Zeichen= û ASCII Code= 251
0x7C,0x14,0x1C,0x14,0x7C,0x00, // Zeichen= ü ASCII Code= 252
0x08,0x08,0x2A,0x08,0x08,0x00, // Zeichen= ý ASCII Code= 253
0x00,0x00,0x00,0x00,0x00,0x00, // Zeichen= þ ASCII Code= 254
0xFF,0xFF,0xFF,0xFF,0xFF,0x00, // Zeichen= ÿ ASCII Code= 255
};
<file_sep># SpaceMessageSign
ESP32 firmware based on ESP-IDF (FreeRTOS) for drivin a reverse engineered dot-display matrix board. Hardware is documented in our
[Wiki](https://wiki.vspace.one/doku.php?id=projekte:dotdisplay).
|
938dd42b89ab4f133e112ea9b434b76563be9edf
|
[
"Markdown",
"C"
] | 3 |
Markdown
|
vspaceone/SpaceMessageSign
|
0d05a9c4d4762737c01431efc54cd49429531bf3
|
27edc33c79f6762efc3285f4a6be329cdcbe8139
|
refs/heads/master
|
<repo_name>trungvu1706/pet-project-<file_sep>/README.md
This is a pet project i'm using HTML and CSS to build a website based on a real website i liked
HERE is link to my website : https://pet-project-trungvu.web.app/
|
c51ef9daf784aff9b6c33e303b6aa01b6333e788
|
[
"Markdown"
] | 1 |
Markdown
|
trungvu1706/pet-project-
|
718b64dce9ee1880684d326ff53b6e4176760510
|
23f962ef98b7cb133816d16983d749120b2d0eb8
|
refs/heads/master
|
<file_sep># EAJD-2015
|
edc4d42e90389ab2dfaff66935ed94443884d543
|
[
"Markdown"
] | 1 |
Markdown
|
samarasilva/EAJD-2015
|
e29fcbf04b90fb195c7153a2126cdbebfb21b6ec
|
f5fe35048a3cf9a266ad76cc403b4148f4739ede
|
refs/heads/master
|
<repo_name>talee/faceless<file_sep>/test/faceless.js
// jshint node: true, mocha: true
'use strict';
var assert = require('assert');
var fs = require('fs');
var dom5 = require('dom5');
var p = dom5.predicates;
suite('Faceless', function() {
var Faceless = require('../src/faceless');
var target = fs.realpathSync('test/test.xhtml');
test('read files', function(done) {
Faceless.getDoc(target).then(function (doc) {
assert(doc, 'Doc should exist.');
done();
});
});
// Integration tests
var faceless = new (require('../src/faceless'))({});
test('use tag and behavior rewriters', function(done) {
faceless.process(target, function(){}).then(function (output) {
var doc = dom5.parse(output);
var input = dom5.query(doc, p.hasTagName('input'));
assert(input, 'Tag rewriters should be applied');
assert(dom5.getAttribute(input, 'value').indexOf('{{') === 0,
'Behavior rewriters should be applied');
done();
}).catch(done);
});
});
<file_sep>/test/tags/input.js
// jshint node: true, mocha: true
'use strict';
var assert = require('assert');
var dom5 = require('dom5');
var p = dom5.predicates;
var u = require('../test-util');
var ROOT = process.cwd() + '/';
suite('Inputs', function() {
var InputTextRewriter = require(ROOT + 'src/tags/input-text');
test('rewrite h:input to input', function() {
var inputText = u.getInputNode(u.HTML.H.Input, p.hasTagName('h:inputtext'));
var inputTextRewriter = new InputTextRewriter();
assert(inputText, 'h:inputText should exist in document');
var input = inputTextRewriter.rewrite(inputText);
assert.equal('input', input.nodeName);
assert.equal('text', dom5.getAttribute(input, 'type'));
});
});
<file_sep>/src/tags/tags.js
// jshint node: true
'use strict';
var p = require('dom5').predicates;
var tags = {
'h:inputtext': require('./input-text')
};
var matchers = [];
for (var tag in tags) {
matchers.push(tags[tag].matches);
}
tags.matches = p.OR.apply(matchers);
module.exports = tags;
<file_sep>/src/faceless.js
// jshint node: true
'use strict';
var fs = require('fs');
var behaviors = require('./behaviors/behaviors');
var tags = require('./tags/tags');
var dom5 = require('dom5');
var Promise = global.Promise || require('es6-promise').Promise;
function Faceless(opts) {
this.opts = opts;
}
Faceless.getDoc = function (target) {
return new Promise(function (resolve, reject) {
fs.readFile(target, {encoding: 'utf-8'}, function(err, contents) {
if (err) {
reject(err);
}
var doc = dom5.parse(contents);
resolve(doc);
});
});
};
function rewrite(node) {
if (!dom5.isElement(node)) {
return node;
}
node.attrs.forEach(function(attr) {
var Behavior = behaviors[attr.name];
if (!Behavior) {
return;
}
new Behavior().rewrite(node);
});
var Rewriter = tags[node.tagName.toLowerCase()];
if (!Rewriter) {
// No handler found
return node;
}
return new Rewriter().rewrite(node);
}
Faceless.prototype = {
process: function(target, cb) {
return Faceless.getDoc(target)
.then(this._process)
.then(function(doc) {
var results = dom5.serialize(doc);
cb(null, results);
return results;
}).catch(cb);
},
_process: function(doc) {
dom5.nodeWalkAll(doc, rewrite);
return doc;
}
};
module.exports = Faceless;
<file_sep>/bin/faceless
#!/usr/bin/env node
// jshint node: true
'use strict';
var nopt = require('nopt');
var Faceless = require('../src/faceless');
var args = nopt();
var target = args.argv.remain[0];
var faceless = new Faceless(args);
faceless.process(target, function (err, result) {
if (err) {
console.error(err);
process.exit(1);
}
console.log(result);
});
<file_sep>/src/behaviors/behaviors.js
// jshint node: true
'use strict';
// attribute name : constructor
module.exports = {
value: require('./value-holder')
};
<file_sep>/README.md
# faceless
[](https://travis-ci.org/talee/faceless)
[](https://david-dm.org/talee/faceless)
JSF to Web Components converter. An experiment.
## Develop
npm run test:watch
<file_sep>/test/behaviors/behaviors.js
// jshint node: true, mocha: true
'use strict';
var assert = require('assert');
var dom5 = require('dom5');
var p = dom5.predicates;
var u = require('../test-util');
var ROOT = process.cwd() + '/';
suite('Behaviors', function() {
console.log();
var ValueHolder = require(ROOT + 'src/behaviors/value-holder');
test('rewrite value as value holder', function() {
var inputText = u.getInputNode(u.HTML.H.Input, p.hasTagName('h:inputtext'));
var valueHolder = new ValueHolder();
var input = valueHolder.rewrite(inputText);
assert.equal('{{bean.val}}', dom5.getAttribute(input, 'value'));
});
});
<file_sep>/src/tags/input-text.js
// jshint node: true
'use strict';
var dom5 = require('dom5');
function InputTextRewriter() {
}
InputTextRewriter.prototype = {
/**
* @param {Node} inputText A h:inputText node.
* @param {Node}
*/
rewrite: function(inputText) {
if (!InputTextRewriter.matches(inputText)) {
return inputText;
}
var input = dom5.constructors.element('input');
inputText.attrs.forEach(function(attr) {
input.attrs.push({
name: attr.name,
value: attr.value
});
});
input.attrs.push({
name: 'type',
value: 'text'
});
dom5.replace(inputText, input);
return input;
}
};
InputTextRewriter.matches = function(inputText) {
return inputText.tagName == 'h:inputtext';
};
module.exports = InputTextRewriter;
<file_sep>/test/test-util.js
// jshint node: true
'use strict';
var parser = new (require('parse5').Parser)();
var dom5 = require('dom5');
module.exports = {
HTML: {
H: {
Input: '<h:inputText value="#{bean.val}"></h:inputText>'
}
},
getInputNode: function(str, predicate) {
var doc = parser.parse(str);
return dom5.query(doc, predicate);
}
};
<file_sep>/src/behaviors/value-holder.js
// jshint node: true
'use strict';
require('../utils/utils');
var dom5 = require('dom5');
function ValueHolder() {
}
ValueHolder.prototype = {
START_KEY: '#{',
END_KEY: '}',
REPLACE_START_KEY: '{{',
REPLACE_END_KEY: '}}',
// TODO: Move out to EL expression rewriter?
/**
* @param {Node} node A DOM Node
* @return {Node}
*/
rewrite: function(node) {
var valueAttr = node.attrs[dom5.getAttributeIndex(node, 'value')];
if (!valueAttr) {
return node;
}
valueAttr.value = valueAttr.value.replace(this.START_KEY,
this.REPLACE_START_KEY)
.replace(this.END_KEY, this.REPLACE_END_KEY);
return node;
}
};
module.exports = ValueHolder;
|
3a4a0676626434df45106cc9c3e72efaaa001f8d
|
[
"Markdown",
"JavaScript"
] | 11 |
Markdown
|
talee/faceless
|
5bc41907d98701a6cb92e667e17f4ff14e2c1302
|
133b6cec6bfb6c5898163392e12ff2d3fe870d2c
|
refs/heads/master
|
<repo_name>LukeHackett12/simple-golang-webserver<file_sep>/webserver.go
package main
import (
"bufio"
"database/sql"
"html/template"
"log"
"net/http"
"os"
"strconv"
"strings"
_ "github.com/go-sql-driver/mysql"
)
//var templates *template.Template
type postBin struct {
Posters []article
}
type article struct {
ID int
Title string
PostText string
Date string
ImageURL string
Tags []string
}
var db *sql.DB
func main() {
dbString := readConfig("server.confi")
var err error
//var articleMux = http.NewServeMux()
db, err = sql.Open("mysql", dbString)
if err != nil {
log.Fatal("dbConnection failed : ", err)
}
//defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal("dbConnection failed : ", err)
}
http.Handle("/", http.FileServer(http.Dir("./src")))
http.HandleFunc("/articles/", articleHandler)
http.HandleFunc("/index.html", homePage)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func articleHandler(w http.ResponseWriter, r *http.Request) {
requestURI := strings.SplitAfter(r.RequestURI, "/")
articleID, err := strconv.Atoi(requestURI[len(requestURI)-1])
template, err := template.ParseFiles("./src/articles/article.html")
article := getArticle(articleID)
err = template.Execute(w, article)
if err != nil {
//go fileNotFound(err, w, r)
log.Fatal("Fatal parsing error : ", err)
}
}
func homePage(w http.ResponseWriter, r *http.Request) {
var allp = frontPagePosts(db)
//var posts = postBin{testPost}
templates, err := template.ParseFiles("./src/index.html")
if err != nil {
log.Fatal("Parsing error : ", err)
}
homePage := templates.Lookup("index.html")
homePage.Execute(w, allp)
}
func frontPagePosts(db *sql.DB) postBin {
returnPost, err := db.Query("SELECT * FROM blog.blog_posts LIMIT 5")
if err != nil {
log.Fatal("DB statement failed : ", err)
}
var dbResults []article
defer returnPost.Close()
for returnPost.Next() {
var bp article
returnPost.Scan(&bp.ID, &bp.Title, &bp.PostText, &bp.Date)
bp.PostText = bp.PostText[0:40]
dbResults = append(dbResults, bp)
}
pb := postBin{
dbResults,
}
return pb
}
func getArticle(id int) article {
var ar = article{}
s, err := db.Prepare("SELECT * from blog.blog_posts WHERE idblog_posts = ?")
if err != nil {
log.Fatal("Statement prep failed : ", err)
}
returnArticle := s.QueryRow(id)
returnArticle.Scan(&ar.ID, &ar.Title, &ar.PostText, &ar.Date)
return ar
}
func readConfig(s string) string {
config, err := os.Open(s)
if err != nil {
log.Fatal("File open failure : ", err)
}
defer config.Close()
scanner := bufio.NewScanner(config)
scanner.Scan()
return scanner.Text()
}
/*func check(err error) {
if err != nil {
if _, noLog := os.Stat("log.txt"); os.IsNotExist(noLog) {
newLog, err := os.Create("log.txt")
if err != nil {
log.Fatal(err)
}
newLog.Close()
}
errorLog, err := os.Open("log.txt")
if err != nil {
log.Fatal(err)
}
defer errorLog.Close()
log.SetOutput(errorLog)
log.Printf("An error has occured : ", err)
}
}*/
<file_sep>/README.md
# simple-golang-webserver
An extremely simple and novice attempt at a golang blog-esc static web server and website, free to be re-used.
Feel free to fork and improve, this is a slow and arduious exploration of Golang for me and is going to be a tangled mess forver.
|
89d4c8b43738fe2ce46dbd3119380e47bd043422
|
[
"Markdown",
"Go"
] | 2 |
Markdown
|
LukeHackett12/simple-golang-webserver
|
894d496dac29d0e9668344b1bf057a91de6b907f
|
57c90465a8e2bfc931c60eed6f22585fa810caf7
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Scr_PlayerOilSystem : MonoBehaviour {
public Image oilMeter;
public float maxOil;
public float oilDrain;
private float currentOil;
private float oilRefill;
// Use this for initialization
void Start () {
currentOil = maxOil;
InvokeRepeating("DrainOil", 1, 2);
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("OilRefill") && currentOil != maxOil)
{
oilRefill = 25.0f;
RefillOil(oilRefill);
}
}
void DrainOil()
{
currentOil -= oilDrain;
if (currentOil <= 0)
{
//TODO: Shutdown spotlight
TriggerLoss();
}
}
void RefillOil(float oilRefill)
{
currentOil += oilRefill;
if (currentOil > maxOil)
{
currentOil = maxOil;
}
float calcOil = currentOil / maxOil; //Calculate % of maxOil for UI
SetOil(calcOil);
}
void SetOil(float myOil)
{
oilMeter.fillAmount = myOil;
}
void TriggerLoss()
{
//TODO: Change to loss scene
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Scr_PlayerHealthSystem : MonoBehaviour {
public Image healthBar;
public float maxHealth;
private float currentHealth = 0f;
private float damage = 0f;
private float healthRegen = 15.0f;
// Use this for initialization
void Start () {
currentHealth = maxHealth;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Hazard"))
{
damage = 15f;
TakeDamage(damage);
}
if (other.gameObject.CompareTag("Shark"))
{
damage = 20f;
TakeDamage(damage);
}
if (other.gameObject.CompareTag("HealthPack") && currentHealth != maxHealth)
{
other.gameObject.SetActive(false);
RegenHealth(healthRegen);
}
}
void TakeDamage(float damage)
{
currentHealth -= damage;
float calcHealth = currentHealth / maxHealth; //Calculate % of maxHealth for UI
SetHealth(calcHealth);
if (currentHealth <= 0)
{
//TODO: Play death animation
TriggerLoss();
}
}
void RegenHealth(float regenAmount)
{
currentHealth += regenAmount;
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
float calcHealth = currentHealth / maxHealth; //Calculate % of maxHealth for UI
SetHealth(calcHealth);
}
void SetHealth(float myHealth)
{
healthBar.fillAmount = myHealth;
}
void TriggerLoss()
{
//TODO: Change to loss scene
}
}
|
0db8958f3e981437ee8cf264d792c58ae758fc9d
|
[
"C#"
] | 2 |
C#
|
TeddyChavezA/Umibozu
|
74824e9257cc38c056d0855de4dcc69008266ecb
|
217ffea7c2e2dd03b0ef257ff31924c3a19ffe87
|
refs/heads/master
|
<repo_name>dkshkdk123/project4<file_sep>/test4/WebContent/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="java.sql.*" %>
<%@ page import ="java.lang.*, java.net.*, java.util.*, java.text.*" %>
<%@ page import ="test4.DBcon" %>
<link rel="stylesheet" href="./css/header.css" />
<link rel="stylesheet" href="./css/footer.css" />
<%@ include file = "header.jsp" %>
<style>
.content{clear: both; width: 100%; height: 830px; background: yellow;}
.page{clear: both;width: 2000px; margin: 0 auto;}
.tit{padding: 20px; font-size:20px; font-weight:bold; text-align:center;}
.text{font-size:16px; font-weight:bold; line-height:50px;}
.lst2{font-size:14px; font-weight:bold;}
</style>
</head>
<body>
<%@ include file = "nav.jsp" %>
<main class="content">
<section class="page">
<h1 class="tit">쇼핑몰 회원관리 프로그램</h1>
<div class="page_help">
<p class="text">쇼핑몰 회원정보와 회원매출정보 데이터베이스를 구축하고 회원관리 프로그램을 작성하는 프로그램이다.</p>
<p class="text">프로그램 작성순서</p>
<ol class="lst2">
<li>회원정보 테이블을 작성한다.</li>
<li>매출정보 테이블을 생성한다.</li>
<li>회원정보,매출정보 테이블을 제시된 문제지의 참조데이터를 추가 생성한다.</li>
<li>회원정보 입력 화면 프로그램을 작성한다.</li>
<li>회원정보 조회 프로그램을 작성한다.</li>
<li>회원매출정보 조회 프로그램을 작성한다.</li>
</ol>
</div>
</section>
</main>
<%@ include file = "footer.jsp" %><file_sep>/README.md
# 1. 메인화면
<div>
<img src = "./img/메인화면.PNG" width="1000px" height="600px">
</div>
## 설명
### 첫 메인화면 index.jsp 화면이다. header,nav,content,footer로 구성되어 있으며 nav에 메뉴바에 ul>li>a로 구성되어 있어 클릭하면 다른 페이지로 이동한다.
----------------------------------------------------------------------------------------------------------------------------------------------
# 2. 회원등록화면
<div>
<img src = "./img/회원등록화면.PNG" width="1000px" height="600px">
</div>
## 설명
### memberIns.jsp 회원 등록화면이다. 회원번호와 가입날짜는 자동으로 생성되게 작성하였고 memberInsPro.jsp 화면에서 insert into 테이블 이름 values(들어갈값);
### 을 사용하여 회원등록이 되게 작성하였다. 만약 값이 들어가있지 않으면 값이 입력되지 않았다는 alert 문이 나오게 작성하였다.
----------------------------------------------------------------------------------------------------------------------------------------------
# 3.회원목록조회
<div>
<img src = "./img/회원목록조회화면.PNG" width="1000px" height="600px">
</div>
## 설명
### memberList.jsp 회원목록조회 화면이다. 여기서 회원번호를 클릭하면 회원정보수정 페이지로 이동하게 작성하였다.
----------------------------------------------------------------------------------------------------------------------------------------------
# 4. 회원정보수정
<div>
<img src = "./img/회원정보수정.PNG" width="1000px" height="600px">
</div>
## 설명
### memberEdit.jsp 화면이다. 회원정보 수정을 할수 있는 페이지다 값을 입력하지 않으면 입력하지 않았다는 alert 문이 나오고 값을 입력하고 수정버튼을 누르면
### 회원 수정이 완료되었다는 alert문이 나오며 memberList.jsp 회원목록조회 페이지로 이동하게 된다.
----------------------------------------------------------------------------------------------------------------------------------------------
# 5. 회원매출조회
<div>
<img src = "./img/회원매출조회.PNG" width="1000px" height="600px">
</div>
## 설명
### memberSearch.jsp 회원매출조회 화면이다. table member_tbl_02, money_tbl_02 두개 테이블을 조인하여 회원번호,회원성명,고객등급,매출에 대한 값을 출력하였다.
----------------------------------------------------------------------------------------------------------------------------------------------
<file_sep>/test4/WebContent/memberEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="java.sql.*" %>
<%@ page import ="java.lang.*, java.net.*, java.util.*, java.text.*" %>
<%@ page import ="test4.DBcon" %>
<link rel="stylesheet" href="./css/header.css" />
<link rel="stylesheet" href="./css/footer.css" />
<%@ include file = "header.jsp" %>
<style>
.content{width: 100%; height: 830px; background: yellow;}
.page{clear: both; width: 1280px; margin: 0 auto;}
.tit{font-size:24px; font-weight:bold; text-align:center; padding: 20px;}
table{width: 960px; margin: 25px auto;}
.tb td{padding: 10px; text-align:center;}
.tb2{text-align:left;}
input{height: 40px; width: 200px;}
button{width: 150px; height: 50px; margin: 25px auto;text-align:center;}
</style>
</head>
<body>
<%@ include file = "nav.jsp" %>
<main class="content">
<section class="page">
<h1 class="tit">홈쇼핑 회원 정보 수정</h1>
<div class="page_help">
<form action="memberEditPro.jsp" id="register" name="register" method="post">
<table border="1" class="tb">
<tbody>
<%
request.setCharacterEncoding("utf-8");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs;
String custno = request.getParameter("custno");
String custname, phone, address, joindate, grade, city;
try{
conn = DBcon.getConnection();
String sql = "select * from member_tbl_02 where custno=? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, custno);
rs = pstmt.executeQuery();
while(rs.next()){
custname = rs.getString("custname");
phone = rs.getString("phone");
address = rs.getString("address");
joindate = rs.getString("joindate");
grade = rs.getString("grade");
city = rs.getString("city");
joindate = joindate.substring(0, 10);
%>
<tr>
<td><label for="custno">회원번호</label></td>
<td><input type="text" id="custno" name="custno" value="<%=custno %>"/></td>
</tr>
<tr>
<td><label for="custname">회원성명</label></td>
<td><input type="text" id="custname" name="custname" value="<%=custname %>"/></td>
</tr>
<tr>
<td><label for="phone">회원전화</label></td>
<td><input type="text" id="phone" name="phone" value="<%=phone %>"/></td>
</tr>
<tr>
<td><label for="address">회원주소</label></td>
<td><input type="text" id="address" name="address" value="<%=address %>"/></td>
</tr>
<tr>
<td><label for="joindate">가입일자</label></td>
<td><input type="text" id="joindate" name="joindate" value="<%=joindate %>"/></td>
</tr>
<tr>
<td><label for="grade">고객등급[A:VIP,B:일반,C:직원]</label></td>
<td><input type="text" id="grade" name="grade" value="<%=grade %>"/></td>
</tr>
<tr>
<td><label for="city">도시코드</label></td>
<td><input type="text" id="city" name="city" value="<%=city %>"/></td>
</tr>
<tr>
<td colspan="2">
<button type="button" id="submit_btn" name="submit_btn">수정</button>
<button type="button" id="search_btn" name="search_btn">조회</button>
</td>
</tr>
<%
}
%>
</tbody>
</table>
</form>
<script>
var form = document.register;
var submit_btn = document.getElementById("submit_btn");
var search_btn = document.getElementById("search_btn");
var custno = form.custno;
var custname = form.custname;
var phone = form.phone;
var address = form.address;
var grade = form.grade;
var city = form.city;
submit_btn.addEventListener("click",function(){
if(custno.value==""){
alert("회원번호가 입력되지 않았습니다.");
custno.focus();
return;
}
if(custname.value==""){
alert("회원성명이 입력되지 않았습니다.");
custname.focus();
return;
}
if(phone.value==""){
alert("전화번호가 입력되지 않았습니다.");
phone.focus();
return;
}
if(address.value==""){
alert("주소가 입력되지 않았습니다.");
address.focus();
return;
}
if(grade.value==""){
alert("등급이 입력되지 않았습니다.");
grade.focus();
return;
}
if(city.value==""){
alert("도시코드가 입력되지 않았습니다.");
city.focus();
return;
}
if(custno.value!="" && custname.value!="" && phone.value!="" && address.value!="" && grade.value!="" && city.value!=""){
form.submit();
}
});
search_btn.addEventListener("click",function(){
location.href="memberList.jsp";
});
</script>
</div>
</section>
</main>
<%
}catch(Exception e){
System.out.println("join error:"+e);
}finally{
try{
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception e){
System.out.println("DBcon error:"+e);
}
}
%>
<%@ include file = "footer.jsp" %>
|
f520bc20aebbde3064ad99a711e77c632e61fa8b
|
[
"Markdown",
"Java Server Pages"
] | 3 |
Markdown
|
dkshkdk123/project4
|
3ab461e10ef2a59952a30d04eca82cfb0a4d51e5
|
d58f57501b4b2fd964e1bba2a89ac683fdb79689
|
refs/heads/master
|
<repo_name>CapsuleCat/CommandsMeteorPackage<file_sep>/README.md
# Commands for Meteor
[](https://travis-ci.org/CapsuleCat/MeteorCommands) [](/LICENSE)
Dispatch reusable commands synchronously or asynchronously.
## Installation
```sh
meteor add capsulecat:commands
```
## The Command Pattern
The command pattern is a great way to encapsulate actions into an object. When working with Meteor (or almost any programming framework), you will find that you will want to do the same action over and over, but with some minor changes in the request or response. The Command Pattern is a nice way of encapsulating all the data and logic necessary for an action.
## Documentation
All commands should have a handle function:
```js
class MyCommand {
constructor(arg1, arg2) {}
handle() {}
}
```
You can dispatch any command syncronously or asyncronously:
```js
var result = dispatch(MyCommand, arg1, arg2);
var callback = function (result) {}
dispatchAsync(MyCommand, arg1, arg2, callback);
```
## Example Code
```js
class EmailNotificationCommand {
constructor(email) {
this.email = email;
},
handle() {
// Do something with this.email
console.log(this.email);
}
}
dispatchAsync(EmailNotificationCommand, '<EMAIL>');
```
## Running Tests
Tests use Jasmine. You can run tests completely from the command line using:
```sh
VELOCITY_TEST_PACKAGES=1 meteor test-packages --driver-package velocity:html-reporter --velocity ./
```
|
74ce8ca0f32eb14e48c393340da3f243b4e17b81
|
[
"Markdown"
] | 1 |
Markdown
|
CapsuleCat/CommandsMeteorPackage
|
3169d008ef8672fd72cc3656597646b6667758ba
|
12bb5012a859d90583806eda8979d23dad66d9e0
|
refs/heads/master
|
<file_sep>
library(glmnet)
predixcan <- function(x1, y, x2, z) {
Ti <- ncol(y)
p <- ncol(x1)
pvalue <- numeric(Ti)
for (k in 1:Ti) {
fit.elasnet.cv <- cv.glmnet(x1, y[,k], type.measure="mse", alpha=0.5, family="gaussian")
elasnet_M <- predict(fit.elasnet.cv, s=fit.elasnet.cv$lambda.min, newx=x2)
hat <- coefficients(summary(lm(z~elasnet_M)))
pvalue[k] <- ifelse(var(elasnet_M) < 1E-6, 1, hat[2,4])
}
pvalue
}
# transform Normal x to SNPs.
x2snp = function (X)
{
n <- nrow(X)
p <- ncol(X)
maf <- runif(p, 0.05, 0.5)
AAprob = maf^2;
Aaprob = 2 * maf * (1-maf);
quanti = cbind(1-Aaprob-AAprob, 1- AAprob) ## attention
snp = matrix(0, n, p);
for (j in 1:p){
cutoff = qnorm(quanti[j,]);
snp[X[,j] < cutoff[1], j] = 0;
snp[X[,j] >= cutoff[1] & X[,j] < cutoff[2],j] = 1; ## attention
snp[X[,j] >= cutoff[2], j] = 2;
}
snp
}
# check some equations for block matrix
AR = function(rho, p) {
outer(1:p, 1:p, FUN = function(x, y) rho^(abs(x - y)))
}
# adaptive weighting based on marginal regression.
# SNP matrix, GE matrix of all tissues.
adw <- function(x, y){
w <- matrix(0, nrow = ncol(x), ncol = ncol(y))
for (i in 1:ncol(x))
{
for (j in 1:ncol(y))
{
w[i, j] <- coefficients(lm(y[,j]~x[,i]))[2]
}
}
w
}
###################
####################
# multiple predixcan (individual data).
MulTiXcan <- function(x1, y, x2, z, cond = 30)
{
n <- nrow(x2)
Ti <- ncol(y)
yhat2 <- matrix(0, nrow = n, ncol = Ti)
for (ti in 1:Ti) {
cvfit = cv.glmnet(x1, y[, ti], alpha = 0.5)
beta_hat = coef(cvfit, s = "lambda.min")
yhat2[, ti] = x2%*%beta_hat[-1] + beta_hat[1]
}
# remove zero columns.
yhat2_var <- apply(yhat2, 2, var)
if (all(yhat2_var == 0)) {
alpha <- 0
pval <- 1
} else if (sum(yhat2_var != 0) == 1) {
twas <- summary(lm(z ~ yhat2))
alpha <- twas$coefficients[2,1]
pval <- twas$coefficients[2,4]
} else {
yhat2 <- yhat2[, yhat2_var != 0]
yhat2_pca <- summary(prcomp(yhat2, center = TRUE, scale. = TRUE))
ind_top <- which(yhat2_pca$importance[2, 1]/yhat2_pca$importance[2, ] < cond)
pc_top <- yhat2_pca$x[, ind_top]
twas <- summary(lm(z ~ pc_top))
alpha <- twas$coefficients[-1]
pval <- pf(twas$fstatistic[1],twas$fstatistic[2],twas$fstatistic[3],lower.tail=FALSE)
}
list(alpha = alpha,
pval = unname(pval))
}
# prepare binary ped files for GEMMA/Plink.
# imput:
# x --- simulated design matrix, enties are
# counts of minor alleles.
# y --- mulvariate outcomes
# stringname --- prefix for filenames
# plink_exe --- location of plink.exe
# output:
# write files fro analysis in Gemma/Plink.
ad2bed = function(x, y, stringname, plink_exe="/home/sysadmin/Software/plink/plink")
{
n <- nrow(x)
p <- ncol(x)
snp <- ad2mm(x) # its body is in vb_aux.cpp.
tped <- cbind(rep(1, p),
paste0("snp", 1:p),
rep(0, p),
rep(0, p),
snp
)
write.table(tped, quote = FALSE,
row.names = FALSE, col.names = FALSE,
paste0(stringname, ".tped"))
tfam = data.frame(paste0("ID", 1:n),
paste0("ID", 1:n),
paste0("PD", 1:n),
paste0("MD", 1:n),
rep(1, n),
rep(-9,n))
write.table(tfam, quote = FALSE,
row.names = FALSE, col.names = FALSE,
paste0(stringname, ".tfam"))
cmd = paste0(plink_exe, " --tfile ", stringname, " --noweb --make-bed --out ", stringname)
system(cmd)
# fill y in ".fam" files
famfile <- read.table(paste0(stringname, ".fam"),
stringsAsFactors=FALSE, header=FALSE)
famfile$V6 <- NULL
famfileK <- cbind(famfile, y)
write.table(famfileK, quote = FALSE,
row.names = FALSE, col.names = FALSE,
paste0(stringname, ".fam"))
}
<file_sep>#ifndef mammot_part_hpp
#define mammot_part_hpp
#include <RcppArmadillo.h>
//#include <Rcpp.h>
//#include <omp.h>
using namespace Rcpp;
using namespace arma;
using namespace std;
arma::mat ADW(arma::mat& x, arma::mat& y);
void PXem_part(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const arma::vec& constrFactor, const bool& PX, int& Iteration, const int& maxIter);
void PXem_ss_part(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const arma::vec& constrFactor, const bool& PX, int& Iteration, const int& maxIter);
List mammot_PXem_part(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter);
List mammotSS_PXem_part(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter);
List mammot_part_test(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter);
List mammotSS_part_test(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter);
void lmm_pxem_ptr2(const arma::vec& y, const arma::mat& W, const arma::mat& X, const int& maxIter,
double& sigma2y, double& sigma2beta, arma::vec& beta0, double& loglik_max,
int& iteration, arma::mat& Sigb, arma::vec& mub);
List lmm_pxem(const arma::vec y, const arma::mat w, const arma::mat x, const int maxIter);
#endif /* mammot_part_hpp */
<file_sep>setwd("/home/xingjies/mammot/simulation/mammotPartVScommCOR")
source("/home/xingjies/R/ggplot_theme_publication.R")
nz_ti <- c(1, 2)[2]
Ti = 3
method <- c("MAMMO", "CoMM", "PrediXcan", "TWAS")
h_z <- 0.01
ymax <- 1#ifelse(rhoX < 0.8, 0.5, 0.75)
gg_fdr <- NULL
gg_pow <- NULL
for(i in 1:5) {
for (j in 1:3) {
for (k in 1:3) {
h_c <- c(0.025, 0.05, 0.1, 0.2, 0.4)[i]
rhoW = c(0.2, 0.5, 0.8)[j]
rhoX <- c(0.2, 0.5, 0.8)[k]
path <- paste0("part_hc", h_c*10, "_rhoX", rhoX*10, "_rhoW", rhoW*10, "nz_ti", nz_ti, "_batch-*")
batch <- list.files(pattern=path)
pvalue_mammot <- NULL
pvalue_mammotpart <- NULL
pvalue_comm <- NULL
pvalue_predixcan <- NULL
pvalue_TWAS <- NULL
for (l in batch) {
res <- readRDS(l)
pvalue_mammot <- rbind(pvalue_mammot, res$pvalue_mammot)
pvalue_mammotpart <- rbind(pvalue_mammotpart, res$pvalue_mammotpart)
pvalue_comm <- rbind(pvalue_comm, res$pvalue_comm)
pvalue_predixcan <- rbind(pvalue_predixcan, res$pvalue_predixcan)
pvalue_TWAS <- rbind(pvalue_TWAS, res$pvalue_TWAS)
}
Rep <- nrow(pvalue_TWAS)
cutoff <- 0.05
power <- c(#sum(pvalue_mammotpart[pvalue_mammot < cutoff/Rep, (1:nz_ti)] < 0.05/Ti)/Rep,
mean(pvalue_mammotpart[, (1:nz_ti)] < 0.05/Ti),
mean(pvalue_comm[, (1:nz_ti)] < 0.05/Ti),
mean(pvalue_predixcan[, (1:nz_ti)] < 0.05/Ti),
mean(pvalue_TWAS[, (1:nz_ti)] < 0.05/Ti)
)
fpr <- c(#sum(pvalue_mammotpart[pvalue_mammot < cutoff/Rep, -(1:nz_ti)] < 0.05/Ti)/Rep,
mean(pvalue_mammotpart[, -(1:nz_ti)] < 0.05/Ti),
mean(pvalue_comm[, -(1:nz_ti)] < 0.05/Ti),
mean(pvalue_predixcan[, -(1:nz_ti)] < 0.05/Ti),
mean(pvalue_TWAS[, -(1:nz_ti)] < 0.05/Ti))
gg_pow <- rbind(gg_pow, data.frame(method, power, h_c, rhoX, rhoW))
gg_fdr <- rbind(gg_fdr, data.frame(method, fpr, h_c, rhoX, rhoW))
}
}
}
gg_fdr$method <- ordered(gg_fdr$method, levels = c("MAMMO", "CoMM", "PrediXcan", "TWAS"))
gg_fdr$h_c <- factor(gg_fdr$h_c)
#gg_fdr$nz_ti <- factor(gg_fdr$nz_ti)
#gg_fdr$s <- factor(gg_fdr$s)
gg_pow$method <- ordered(gg_pow$method, levels = c("MAMMO", "CoMM", "PrediXcan", "TWAS"))
gg_pow$h_c <- factor(gg_pow$h_c)
#gg_pow$nz_ti <- factor(gg_pow$nz_ti)
#gg_pow$s <- factor(gg_pow$s)
library(ggplot2)
outfile = paste0("../fpr_PartTestCOR_nzTis", nz_ti, ".png")
pl_fdr <- ggplot(gg_fdr, aes(x = h_c, y = fpr, fill = method)) + labs(x = expression(h[c]^2), y="FPR") +
geom_bar(stat="identity", position=position_dodge())+
coord_cartesian(ylim=c(0, ymax)) +
#facet_grid(s~nz_ti, labeller = label_both, scales = "free_y") +
facet_grid(rhoW~rhoX, labeller = label_bquote(rows = rho[W]: .(rhoW), cols= rho[X]: .(rhoX))) +
scale_fill_manual(values=c("#FDBF6F", "#cccccc", "#969696", "#525252"),##FDBF6F
labels=c("TisCoMM", "CoMM", "PrediXcan", "TWAS")) + theme_Publication(base_size=28, border_col=NA)
ggsave(outfile, plot=pl_fdr, width = 360, height = 360, units = "mm", dpi=300, type = "cairo")
outfile = paste0("../pow_PartTestCOR_nzTis", nz_ti, ".png")
pl_pow <- ggplot(gg_pow, aes(x = h_c, y = power, fill = method)) + labs(x = expression(h[c]^2), y="Power") +
geom_bar(stat="identity", position=position_dodge())+
coord_cartesian(ylim=c(0, 1)) +
#facet_grid(s~nz_ti, labeller = label_both, scales = "free_y") +
facet_grid(rhoW~rhoX, labeller = label_bquote(rows = rho[W]: .(rhoW), cols= rho[X]: .(rhoX))) +
scale_fill_manual(values=c("#FDBF6F", "#cccccc", "#969696", "#525252"),
labels=c("TisCoMM", "CoMM", "PrediXcan", "TWAS")) +theme_Publication(base_size=28, border_col=NA)
ggsave(outfile, plot=pl_pow, width = 360, height = 360, units = "mm", dpi=300, type = "cairo")
<file_sep># include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// convert a Additive and dominance components
// back to minor and major alleles
// fixed convert habit: minor is 1, major is 2
// [[Rcpp::export()]]
mat ad2mm(mat x) {
int n = x.n_rows;
int p = x.n_cols;
mat snp(p, 2*n, fill::zeros);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < p; j++)
{
if (x(i, j) == 0) {
snp(j, 2*i) = 2;
snp(j, 2*i+1) = 2;
} else if (x(i, j) == 1) {
snp(j, 2*i) = 1;
snp(j, 2*i+1) = 2;
} else {
snp(j, 2*i) = 1;
snp(j, 2*i+1) = 1;
}
}
}
return snp;
}
// [[Rcpp::export()]]
mat vec2mat(vec V, uword n, uword p) {
mat M(n, p, fill::zeros);
for (int j=0; j < p ; j++)
M.col(j) = V.subvec(j*n, (j+1)*n-1);
return M;
}
//convert a matrix of local fdr to a matrix of Global FDR
// [[Rcpp::export()]]
mat fdr2Fdr(mat fdr){
vec pool = vectorise(fdr);
uword M = pool.size();
uvec indices = sort_index(pool);
vec sort_pool = pool(indices);
vec Pool = cumsum(sort_pool) / linspace<vec>(1, M, M);
Pool.elem(find(Pool > 1)).ones();
Pool(indices) = Pool;
return vec2mat(Pool, fdr.n_rows, fdr.n_cols);
}
//convert a vector of local fdr to a vector of Global FDR
// [[Rcpp::export()]]
vec fdr2FDR(vec fdr){
uword M = fdr.size();
uvec indices = sort_index(fdr);
vec sort_fdr = fdr(indices);
vec FDR = cumsum(sort_fdr) / linspace<vec>(1, M, M);
FDR.elem(find(FDR > 1)).ones();
FDR(indices) = FDR;
return FDR;
}
// [[Rcpp::export()]]
double calAUC(vec label, vec pred){
double auc = 0;
double m = mean(label);
vec label2 = label;
label2(find(label >= m)).fill(1);
label2(find(label < m)).fill(0);
label = label2;
uword N = pred.size();
uword N_pos = sum(label);
uvec idx = sort_index(pred,"descend");
vec above = linspace<vec>(1, N, N) - cumsum(label(idx));
auc = (1 - sum(above % label(idx)) / (N_pos * (N-N_pos)));
auc = auc > 0.5?auc:(1-auc);
return auc;
}<file_sep>---
title: "TisCoMM User Manual"
author: |
| <NAME>
| <EMAIL>
date: "`r Sys.Date()`"
output: rmarkdown::pdf_document
urlcolor: blue
toc: true
vignette: >
%\VignetteIndexEntry{Vignette Title}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Introduction
**TisCoMM** package provides a unified probabilistic model for TWAS, leveraging the co-regulation of genetic variations across different tissues explicitly. **TisCoMM** not only performs hypothesis testing to prioritize gene-trait associations,
but also detects the tissue-specific role of candidate target genes in complex traits. To make use of widely available GWAS summary statistics, TisCoMM is extended to use summary-level data, namely, TisCoMM-S$^2$ .
## Models
TisCoMM tests for gene-trait associations one gene at a time. Assume $\mathcal{D}_1=\{\mathbf Y_g, \mathbf X_{1g}\}$ denote the reference transcriptome data set of gene $g$ for $n_1$ samples over $T$ tissues, e.g. $\mathbf Y_g\in \mathbb{R}^{n_1\times T}$ is the expression matrix for this gene over $T$ tissues, $\mathbf X_{1g}\in \mathbb{R}^{n_1\times M_g}$ is the genotype matrix for cis-SNPs within this gene. Denote the GWAS data $\mathcal{D}_2=\{\mathbf z, \mathbf X_{2g}\}$, where $\mathbf z$ is an $n_2\times 1$ vector of phenotypic values, $\mathbf X_{2g}$ is the genotype matrix for $M_g$ cis-SNPs.
To simplify notation we will omit the subscript $g$ in all the expression that has dependence on gene $g$. Our model is
$$
\begin{aligned}
\mathbf Y &= \mathbf X_{1}\mathbf B+\mathbf E, \\
\mathbf z &= \mathbf X_{2}\mathbf B\mathbf \alpha + \mathbf e_z,
\end{aligned}
$$
where $\mathbf \alpha\in\mathbb R^T$, $\mathbf E\sim\mathcal{MN}(0, \mathbf I_{m}, \mathbf V_e)$, and $\mathbf e_z\sim\mathcal{N}(0,\sigma^2\mathbf I_n)$. Note that we assume $\mathcal{D}_1$ and $\mathcal{D}_2$ are centered and thus intercepts can be omitted.
## Statistical Inference in TisCoMM
Problem:
1. Parameter Estimation: $\mathbf V_e, \sigma_b^2, \sigma^2, \mathbf\alpha$;
2. (testing gene-trait association) do joint testing: $\mathbf \alpha = 0$ to detect significant candidate genes;
3. (testing tissue-specific effects) for significant genes only, do tissue-specific tesing: $\alpha_{t} = 0$, $t = 1, \dots T$.
Methods:
- the EM algorithm with parameter expansion (Liu et al. 1998, Biometrika)
- the log-likelihood ratio test (LRT)
- multiple testing ($p$-values $\leq 5\times 10^{-6}$ for joint test)
## Installation
To install the development version of **TisCoMM**, it's easiest to use the 'devtools' package. Note that **TisCoMM** depends on the 'Rcpp' package, which also requires appropriate setting of Rtools and Xcode for Windows and Mac OS/X, respectively.
```{r, fig.show='hold', eval=FALSE}
library(devtools)
install_github("XingjieShi/TisCoMM")
```
# Real Data Analysis with GWAS Individual Data
## 1. Preparing eQTL data
The eQTL data consists of matched genotype data and gene expression data in multiple target tissues.
### Genotype data ($\mathbf X_1$)
Genotype data of the eQTL samples in the PLINK binary format (.\textbf{bed}), and must be accompanied by .\textbf{bim} and .\textbf{fam} files with the same prefix. For example:
\begin{itemize}
\item GTEx.bed,
\item GTEx.bim,
\item GTEx.fam.
\end{itemize}
### Gene expression across multiple tissues ($\mathbf Y_1$)
\begin{itemize}
\item Please note that gene expression in each tissue should be previously normalized for covariates which may confound the eQTL associations. We can achieve this by regressing the phenotypes (gene expressions) on the covariates and use the residuals as new phenotypes. After peforming this procedures for all the tissues, they can be specified as input of TisCoMM.
\item Each tissue file should be a \textbf{tab-delimited} text file and include following information for each gene:
\begin{itemize}
\item Start location
\item End location
\item Gene type
\item Hugo name
\item Ensembl ID
\item Chromosome number
\item normalized expression levels cross samples
\end{itemize}
If some gene annotation is not included in the original gene expression file, one will have to extract these information by performing gene ID mapping with other annotation files. GENCODE (\href{https://www.gencodegenes.org/human/}{https://www.gencodegenes.org/human/}) provides comprehensive gene annotation files.
\item \textit{TisCoMM} will use the headers in the expression files to extract information. It is required to have specific columns in all the formatted expression file. See Table \ref{tab:ge} for a demonstration. Note that the first six column names should be exactly the same as those in Table \ref{tab:ge}. Expression levels across individuals should be appended after the first six columns.
\begin{table}[ht]
\centering
\caption{The first three rows and eight columns in an example gene expression file (rows for genes, and columns after the first six columns for samples).}
\label{tab:ge}
\begin{tabular}{ccccccccc}
\hline
lower & up & genetype1 & genetype2 & TargetID & Chr & ID1 & ID2 & $\cdots$ \\
\hline
59783540 & 59843484 & lincRNA & PART1 & ENSG00000152931.6 & 5 & 0.51 & 0.71 & $\cdots$ \\
48128225 & 48148330 & protein\_coding & UPP1 & ENSG00000183696.9 & 7 & 1.41 & -0.01 & $\cdots$ \\
57846106 & 57853063 & protein\_coding & INHBE & ENSG00000139269.2 & 12 & 0.58 & -1.02 & $\cdots$ \\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots& \vdots & \vdots \\
\hline
\end{tabular}
\end{table}
After this step, we will have the eQTL gene expression files:
\begin{itemize}
\item Skin\_Sun\_Exposed\_Lower\_leg\_gene\_expression.txt
\item Whole\_Blood\_gene\_expression.txt
\end{itemize}
\end{itemize}
## 2. Preparing GWAS data
TisCoMM can handle two different types of GWAS input dataset, the individual level data and summary statistics. There are some difference between these two types of input, here we discuss them separately.
### Formatting GWAS individual data
The GWAS individual data files consist of genotype ($\mathbf X_2$) and phenotype data $\mathbf z$ for all GWAS samples. They should be in the PLINK binary format. For example:
\begin{itemize}
\item NFBC1966.bed,
\item NFBC1966.bim,
\item NFBC1966.fam.
\end{itemize}
You could optionally add the covariate file, which contains all confounding covariates used to adjust population stratification in the GWAS data. The covariate file should be formatted in a similar manner to the plink phenotype file, which should also be a \textbf{tab-delimited} file.
## 3. Testing gene-trait associations with GWAS individual data
```{r, fig.show='hold', eval=FALSE}
# eQTL genotype file
file1 <- "GTEx_qc"
# GWAS individual level data
file2 <- "NFBC1966_qc"
# eQTL gene expression files
file3 <- c("Skin_Sun_Exposed_Lower_leg_gene_expression.txt",
"Whole_Blood_gene_expression.txt")
# eQTL covariates file. Since normalized GE is provided, we do not need this file.
file4 <- ""
# GWAS covariates file
file5 <- ""
wihchPheno <- 1
bw <- 5e5
coreNum <- 24
fit <-mammot_paral(file1, file2, file3, file4, file5,
wihchPheno, bw, coreNum)
```
There are other three arguments.
- whichPheno specifies which phenotype in the phenotype file (GTEX\_qc.fam) is used for association tests.
- bw defines the cisSNPs within a gene: either up to bw proximal to the start of gene, or up to bw distal to the end of the gene.
- corNum sets the number of threads the program will use.
## 4. Testing tissue-specific effects with GWAS individual data
```{r, fig.show='hold', eval=FALSE}
# eQTL genotype file
file1 <- "GTEx_qc"
# GWAS individual level data
file2 <- "NFBC1966_qc"
# eQTL gene expression files
file3 <- c("Skin_Sun_Exposed_Lower_leg_gene_expression.txt",
"Whole_Blood_gene_expression.txt")
# eQTL covariates file. If normalized GE is provided, we do not need this file.
file4 <- ""
# GWAS covariates file
file5 <- ""
# genes (TargetID) on which we want to perform tissue-specific test.
targetList <- c("ENSG00000196666.3"
"ENSG00000213619.5"
"ENSG00000149187.13")
wihchPheno <- 1
bw <- 5e5
coreNum <- 24
fit <-mammot_part_paral(file1, file2, file3, file4, file5,
targetList, wihchPheno, bw, coreNum)
```
Compared with the input for gene-trait association test, there is a new arguments "targetList". It is a character vecter containing genes' names. Note that it should be the same identifiers as "targetID" in the eQTL data. In general, You can perform the tissue-specific test on any genes. Usually, we would like to focus on genes which are significantly associated with the trait.
# Real Data Analysis with GWAS Summary Statisitc Data
## 1. Preparing eQTL data
This step is the same as analysis with GWAS individual data.
## 2. Formatting GWAS summary statisitc data
### Reference panel ($\mathbf X_r$)
Reference panel in the PLINK binary format (.\textbf{bed}, .\textbf{bim}, .\textbf{fam}).
For example,
\begin{itemize}
\item 1000G.bed,
\item 1000G.bim,
\item 1000G.fam.
\end{itemize}
### GWAS summary statistic data
GWAS summary statistic data is required to have specific columns. See Table \ref{tab:gwasSS} for a demonstration. Note that all the column names should be exactly the same as those in Table \ref{tab:gwasSS}.If GWAS summary statistic in the original downloaded file do not come with all the information \textit{TisCoMM} needs, one will have to compute them manually. For example, if odds ratio is included, then beta can be computed as $\log(\text{Odds Ratio})$. Assume our interested trait is the late-onset Alzheimer's disease (LOAD), and we download the summary statistic file from \href{http://web.pasteur-lille.fr/en/recherche/u744/igap/igap_download.php}{http://web.pasteur-lille.fr/en/recherche/u744/igap/igap\_download.php}. After this step, the summary statistic is formatted correctly in following file:
\begin{itemize}
\item LOAD.txt
\end{itemize}
\begin{table}[ht]
\centering
\caption{An example for the GWAS summary statistics.}
\label{tab:gwasSS}
\begin{tabular}{ccccccc}
\hline
SNP & chr & BP & A1 & A2 & beta & se \\
\hline
rs3094315 & 1 & 752566 & G & A & -0.0122 & 0.0294 \\
rs3128117 & 1 & 944564 & C & T & -0.0208 & 0.0278 \\
rs1891906 & 1 & 950243 & C & A & -0.0264 & 0.0260 \\
rs2710888 & 1 & 959842 & T & C & -0.0439 & 0.0297 \\
rs4970393 & 1 & 962606 & G & A & -0.0252 & 0.0233 \\
rs7526076 & 1 & 998395 & A & G & -0.0512 & 0.0229 \\
\vdots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots \\
\hline
\end{tabular}
\end{table}
## 3. Testing gene-trait associations with GWAS sumary statistics
```{r, fig.show='hold', eval=FALSE}
# eQTL genotype file
file1 <- "GTEx_qc"
# GWAS summary statistic file
file2 <- "LOAD.txt"
# reference panel file
file3 <- "1000G"
# eQTL gene expression files
file4 <- c("Skin_Sun_Exposed_Lower_leg_gene_expression.txt",
"Whole_Blood_gene_expression.txt")
# eQTL covariates file. Since normalized GE is provided, we do not need this file.
file5 <- ""
lam <- 0.95
bw <- 5e5
coreNum <- 24
fit <- mammotSS_paral(file1, file2, file3, file4, file5,
lam, bw, coreNum)
```
There are other three arguments.
- lam is the shrinkage intensify for the reference panel.
- bw defines the cisSNPs within a gene: either up to bw proximal to the start of gene, or up to bw distal to the end of the gene.
- corNum sets the number of threads the program will use.
## 4. Testing tissue-specific effects with GWAS individual data
```{r, fig.show='hold', eval=FALSE}
# eQTL genotype file
file1 <- "GTEx_qc"
# GWAS summary statistic file
file2 <- "LOAD.txt"
# reference panel file
file3 <- "1000G"
# eQTL gene expression files
file4 <- c("Skin_Sun_Exposed_Lower_leg_gene_expression.txt",
"Whole_Blood_gene_expression.txt")
# eQTL covariates file. Since normalized GE is provided, we do not need this file.
file5 <- ""
# genes (TargetID) on which we want to perform tissue-specific test.
targetList <- c("ENSG00000196666.3"
"ENSG00000213619.5"
"ENSG00000149187.13")
lam <- 0.95
bw <- 5e5
coreNum <- 24
fit <- mammotSS_part_paral(file1, file2, file3, file4, file5,
targetList, lam, bw, coreNum)
```
Compared with the input for gene-trait association test, there is a new arguments "targetList". It is a character vecter containing genes' names. Note that it should be the same identifiers as "targetID" in the eQTL data. In general, You can perform the tissue-specific test on any genes. Usually, we would like to focus on genes which are significantly associated with the trait.
# Replicate simulation results in Shi et al. (2020)
All the simulation results can be reproduced by using the code at [simulation](https://github.com/XingjieShi/TisCoMM/tree/master/simulation). Before running simulation to reproduce the results, please familiarize yourself with **TisCoMM** using 'TisCoMM User Manual'.
1. Simulation results for multi-tissue joint can be reproduced by following steps:
- ExampleOne.R: This function can be run in a HPC cluster (with minor revisions, it could be run on a PC), it will output files, named pvalue_hz0.1_hc0.25_rhoX5_s5_batch-6.txt, which contain inference results of each replicate, for all multi-tissue TWAS methods: TisCoMM, TisCoMM-S$^2$, MultiXcan, S-MultiXcan and UTMOST.
- ExampleOnePlot.R: This function produces simulation figures of joint test in Shi et al. (2019).
2. Simulation results for tissue-specific test can be reproduced by following steps:
- PartCoMMCOR.R: This function can be run in a HPC cluster (with minor revisions, it could be run on a PC), it will output files, named part_hc4_rhoX8_rhoW8nz_ti2_batch-2.rds, which contain inference results of each replicate, for all single-tissue TWAS methods: CoMM, PrediXcan, and TWAS.
- SummaryCOR.R: This function produces simulation figures of tissue-specific test in Shi et al. (2019).
## Reference
[Shi et al (2020). A tissue-specific collaborative mixed model for jointly analyzing multiple tissues in transcriptome-wide association studies](https://www.biorxiv.org/content/10.1101/789396v3.full)
<file_sep>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <Rcpp.h>
#include <omp.h>
#include <stdio.h>
#include <bitset>
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <armadillo_bits/config.hpp>
#include "plinkfun.hpp"
#include "readExprFile.hpp"
using namespace std;
using namespace Rcpp;
using namespace arma;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(BH, bigmemory)]]
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
Rcpp::List getColNum_Header(std::string filename, char delimiter){
//cout << "Count columns in the file: ";
std::ifstream myfile (filename.c_str());
std::string line, temp;
if (myfile.is_open()){
getline(myfile, line);
}
stringstream ss(line); // Turn the string into a stream.
string tok;
CharacterVector header;
while(getline(ss, tok, delimiter)) {
header.push_back(tok);
}
//cout << "line 1" << line;
std::istringstream iss(line);
int columns = 0;
do{
std::string sub;
iss >> sub;
if (sub.length())
++columns;
}
while(iss);
//cout << columns << endl;
List output = List::create(//Rcpp::Named("NumGene") = NumGene,
Rcpp::Named("columns") = columns,
Rcpp::Named("header") = header);
return output;
}
CharacterVector charv_subset2(CharacterVector x, uvec idx){
CharacterVector v(idx.n_elem);
for (unsigned int i = 0; i < idx.n_elem; i++){
v(i) = x(idx(i));
}
return v;
}
// format of covariate file is "FID IID, covar1, covar2, covar3 ..."
Rcpp::List getCovarFile(std::string filename, char delimiter, int ncols, int nrows){
std::ifstream myfile (filename.c_str());
mat covar(nrows, ncols-2);
std::string line;
CharacterVector IID(nrows), FID(nrows);
//clock_t t1 = clock();
int nrow_ind = 0;
vector <string> tmp;
if (myfile.is_open()){
while (nrow_ind < nrows ){
getline(myfile, line);
boost::split(tmp, line, boost::is_any_of(" \t *"));
IID(nrow_ind) = tmp[1];
FID(nrow_ind) = tmp[0];
// cout << ncols-ncols_omit << ";" << nrow_ind << endl;
for (int j = 0; j < ncols - 2; j++){
if (tmp[j + 2].compare("NA") == 0){
covar(nrow_ind, j) = log(-10);
}
else {
covar(nrow_ind, j) = atof(tmp[j + 2].c_str());
}
}
nrow_ind++;
}
}
List output = List::create(Rcpp::Named("IID") = IID,
Rcpp::Named("FID") = FID,
Rcpp::Named("covar") = covar);
return output;
}
// [[Rcpp::export]]
Rcpp::List dataLoader(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3,
std::string stringname4, std::string stringname5, int whCol){
//match SNPs in file 1 and file 2 GWAS (common SNPs in x1 and x2 in columns)
// plink file 1: stringname1; plink file 2: stringname2; expression file: stringname3
// covariates file for file 1: stringname4; covariates file for file 2: stringname5
// NOTE:
// 1. overlapped individuals in expression files should be a subset of plink file1,
// and also should be a subset of covariate file1.
// 2. individuals in (row order of ) covariate file2 should be exactly the same as
// those in the fam file of GWAS (plink file 2).
// whCol: which pheno is used (1 stands for first pheno (6th column of fam file and so on )
cout << "## Start matching SNPs in plink files (1, 2). " << endl;
List tmp = match_SNPs(stringname1, stringname2);
uvec idxinFile1 = tmp["idxinFile1"];
uvec idxinFile2 = tmp["idxinFile2"];
vec ind = tmp["indicator"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
uvec A1_1_r = tmp["A1_1_r"], A1_2_r = tmp["A1_2_r"], A2_1_r = tmp["A2_1_r"], A2_2_r = tmp["A2_2_r"];
// load IID in file 1 (fam file 1)
cout << "## Start loading fam files (1, 2). " << endl;
string famfile1 = stringname1;
famfile1 += ".fam";
int N1 = getLineNum(famfile1);
IntegerVector tmp1(N1);
CharacterVector FID_1(N1), IID_1(N1);
NumericVector tmp2(N1);
ReadPlinkFamFile(famfile1, FID_1, IID_1, tmp1, tmp2, N1);
// load pheno in file 2 (fam file 2)
string famfile2 = stringname2;
famfile2 += ".fam";
int N2 = getLineNum(famfile2);
IntegerVector sex_2(N2);
NumericVector pheno_2(N2);
CharacterVector FID_2(N2), IID_2(N2);
// ReadPlinkFamFile(famfile2, FID_2, IID_2, sex_2, pheno_2, N2);
ReadPlinkFamFile2(famfile2, FID_2, IID_2, pheno_2, N2, whCol);
vec y = as<vec>(pheno_2);
// read multiple expression files.
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// get intersections of sample IDs, gene IDs for all expression files and
// TWAS files (plink file 1).
cout << "## Start loading multiple expression files. " << endl;
CharacterVector indiv_inter = IID_1;
char delimiter = '\t'; // for all the expression files.
int t = 0, T = stringname3.size();
List IID_expr(T);
ivec Nindiv = ones<ivec>(T);
ivec Ngene = ones<ivec>(T);
for (t = 0; t < T; t++) { // overlapped individuals.
List tmp_e = getColNum_Header(stringname3[t], delimiter);
Nindiv(t) = tmp_e["columns"];
Ngene(t) = getLineNum(stringname3[t]) - 1; // header is first line;
CharacterVector header = tmp_e["header"];
uvec idxtmp = linspace<uvec>(6, Nindiv(t)-1, Nindiv(t) - 6);
CharacterVector IID_expr_tmp = charv_subset2(header, idxtmp);
IID_expr[t] = IID_expr_tmp;
indiv_inter = intersect(indiv_inter, header);
}
//cout << " indiv_inter: " << indiv_inter.size() << endl;
// read expression files and
List expr_tmp(T);
vec lower, upper, chr_expr;
CharacterVector genetype1, genetype2;
CharacterVector gene_inter;
for (t = 0; t < T; t++) {
List expr_t = getExprFile2(stringname3[t], delimiter, Nindiv(t), Ngene(t) + 1, 6);
expr_tmp[t] = expr_t;
// find overlapped genes.
CharacterVector targetID = expr_t["targetID"];
if (t == 0) gene_inter = targetID;
else gene_inter = intersect(gene_inter, targetID);
// save information of overlapped genes.
if (t == (T-1)) {
IntegerVector ind_gene = match(gene_inter, targetID) - 1;
uvec index_gene = as<uvec>(ind_gene);
CharacterVector genetype1_t = expr_t["genetype1"];
CharacterVector genetype2_t = expr_t["genetype2"];
vec chr_expr_t = expr_t["chr_expr"];
vec lower_t = expr_t["lower"];
vec upper_t = expr_t["upper"];
genetype1 = genetype1_t[ind_gene];
genetype2 = genetype2_t[ind_gene];
chr_expr = chr_expr_t(index_gene);
lower = lower_t(index_gene);
upper = upper_t(index_gene);
}
}
// draw overlapped samples and genes acorss all expression files.
cube expr_used(gene_inter.size(), indiv_inter.size(), T, fill::zeros);
for (t =0; t < T; t++) {
List expr_t = expr_tmp[t];
CharacterVector IID_expr_tmp = IID_expr[t];
IntegerVector ind_indiv = match(indiv_inter, IID_expr_tmp) - 1;
uvec index_indiv = as<uvec>(ind_indiv);
CharacterVector targetID = expr_t["targetID"];
IntegerVector ind_gene = match(gene_inter, targetID) - 1;
uvec index_gene = as<uvec>(ind_gene);
mat expr_all = expr_t["expr"];
expr_used.slice(t) = expr_all(index_gene, index_indiv);
}
// read two plink files.
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
clock_t t1 = clock();
cout << "## Start loading genotype files 1, " ;
//read file 1 (plink bim bed fam files)
string bimfile1 = stringname1;
bimfile1 += ".bim";
long int P1 = getLineNum(bimfile1);
cout << N1 << "-by-" << P1;
arma::Mat<unsigned> X1(N1,P1);
//cout << " break 1: " << N1 << "X" << P1 << endl;
readPlink(stringname1, N1, P1, X1.memptr());
// subset overlapped samples and SNPs.
IntegerVector indiv_idx_in1 = match(indiv_inter, IID_1) -1;
X1 = X1.cols(idxinFile1 - 1);
X1 = X1.rows(as<uvec>(indiv_idx_in1));
// replace NA with 0 dosage
X1.replace(3, 0);
cout << ", Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
t1 = clock();
cout << "## Start loading genotype files 2, ";
//read file 2 (plink bim bed fam files)
//cout << endl;
string bimfile2 = stringname2;
bimfile2 += ".bim";
//cout << "break 1... " << endl;
long int P2 = getLineNum(bimfile2);
cout << N2 << "-by-" << P2;
arma::Mat<unsigned> X2(N2,P2);
//cout << "break 3..." << endl;
readPlink(stringname2, N2, P2, X2.memptr());
// subset overlapped SNPs
X2 = X2.cols(idxinFile2 -1);
// replace NA with 0 dosage
X2.replace(3, 0);
// if needed, change the reference allele in file 2
uvec idxtmp = linspace<uvec>(1, idxinFile1.size(), idxinFile1.size());
uvec idx = find(ind == -1);
uvec idxc = idxtmp.elem(idx);
X2.cols(idxc-1) = 2 - X2.cols(idxc-1);
cout << ", Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
cout << "## Start loading covariates files ... " << endl;
// load covariates file w1
mat covar1;
//cout << "break ..." << covar2.n_rows << ";" << covar2.n_cols << ";" << N1 << ";" << !stringname4.empty() << endl;
CharacterVector IID_w1;
if (!stringname4.empty()){
int Nincovar1 = getLineNum(stringname4);
tmp = getColNum_Header(stringname4, delimiter);
int Ncovar = tmp["columns"];
tmp = getCovarFile(stringname4, delimiter, Ncovar, Nincovar1);
mat covartmp = tmp["covar"];
IID_w1 = tmp["IID"];
mat w1one = ones<mat>(X1.n_rows, 1);
IntegerVector indiv_idx_covar1 = match(indiv_inter, IID_w1) - 1;
covar1 = join_rows(w1one, covartmp.rows(as<uvec>(indiv_idx_covar1)));
}
else {
covar1 = ones<mat>(X1.n_rows, 1);
}
// load covariates file w2
mat covar2;
if (!stringname5.empty()){
tmp = getColNum_Header(stringname5, delimiter);
int Ncovar = tmp["columns"];
tmp = getCovarFile(stringname5, delimiter, Ncovar, N2);
mat covartmp = tmp["covar"];
mat w2one = ones<mat>(N2, 1);
//cout << endl << "break ..." << covartmp.n_rows << ";" << covartmp.n_cols << ";" << N2 << endl;
covar2 = join_rows(w2one, covartmp);
}
else {
covar2 = ones<mat>(N2, 1);
}
cout << "## End loading files ... " << endl;
List output = List::create(
Rcpp::Named("covar1") = covar1,
Rcpp::Named("X1") = X1,
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("chr_4use_r") = chr_4use_r,
Rcpp::Named("bp_4use_r") = bp_4use_r,
Rcpp::Named("lower") = lower,
Rcpp::Named("upper") = upper,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("targetID") = gene_inter,
Rcpp::Named("chr_expr") = chr_expr,
Rcpp::Named("indiv_inter") = indiv_inter,
Rcpp::Named("expr_used") = expr_used,
Rcpp::Named("covar2") = covar2,
Rcpp::Named("X2") = X2,
Rcpp::Named("y") = y);
return output;
}
// [[Rcpp::export]]
Rcpp::List dataLoaderSS(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3,
std::string stringname4, std::string stringnameSS){
//match SNPs in file 1 and file 2 GWAS (common SNPs in x1 and x2 in columns)
// plink file 1: stringname1; plink file 2: stringname2; expression file: stringname3
// covariates file for file 1: stringname4; covariates file for file 2: stringname5
// NOTE:
// 1. overlapped individuals in expression files should be a subset of plink file1,
// and also should be a subset of covariate file1.
// 2. individuals in (row order of ) covariate file2 should be exactly the same as
// those in the fam file of GWAS (plink file 2).
// whCol: which pheno is used (1 stands for first pheno (6th column of fam file and so on )
cout << "## Start matching SNPs in plink files (1, 2). " << endl;
List tmp = match_SNPs_SS(stringname1, stringname2, stringnameSS);
uvec idxinFile1 = tmp["idxinFile1"];
uvec idxinFile2 = tmp["idxinFile2"];
uvec idxinFileSS = tmp["idxinFileSS"];
vec ind = tmp["indicator"];
vec indSS = tmp["indicatorSS"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
uvec A1_1_r = tmp["A1_1_r"], A1_2_r = tmp["A1_2_r"], A2_1_r = tmp["A2_1_r"], A2_2_r = tmp["A2_2_r"];
// load IID in file 1 (fam file 1)
cout << "## Start loading fam files (1, 2). " << endl;
string famfile1 = stringname1;
famfile1 += ".fam";
int N1 = getLineNum(famfile1);
IntegerVector tmp1(N1);
CharacterVector FID_1(N1), IID_1(N1);
NumericVector tmp2(N1);
ReadPlinkFamFile(famfile1, FID_1, IID_1, tmp1, tmp2, N1);
// read multiple expression files.
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// get intersections of sample IDs, gene IDs for all expression files and
// TWAS files (plink file 1).
cout << "## Start loading multiple expression files. " << endl;
CharacterVector indiv_inter = IID_1;
char delimiter = '\t'; // for all the expression files.
int t = 0, T = stringname3.size();
List IID_expr(T);
ivec Nindiv = ones<ivec>(T);
ivec Ngene = ones<ivec>(T);
for (t = 0; t < T; t++) { // overlapped individuals.
List tmp_e = getColNum_Header(stringname3[t], delimiter);
Nindiv(t) = tmp_e["columns"];
Ngene(t) = getLineNum(stringname3[t]) - 1; // header is first line;
CharacterVector header = tmp_e["header"];
uvec idxtmp = linspace<uvec>(6, Nindiv(t)-1, Nindiv(t) - 6);
CharacterVector IID_expr_tmp = charv_subset2(header, idxtmp);
IID_expr[t] = IID_expr_tmp;
indiv_inter = intersect(indiv_inter, header);
}
//cout << " indiv_inter: " << indiv_inter.size() << endl;
// read expression files and
List expr_tmp(T);
vec lower, upper, chr_expr;
CharacterVector genetype1, genetype2;
CharacterVector gene_inter;
for (t = 0; t < T; t++) {
List expr_t = getExprFile2(stringname3[t], delimiter, Nindiv(t), Ngene(t) + 1, 6);
expr_tmp[t] = expr_t;
// find overlapped genes.
CharacterVector targetID = expr_t["targetID"];
if (t == 0) gene_inter = targetID;
else gene_inter = intersect(gene_inter, targetID);
// save information of overlapped genes.
if (t == (T-1)) {
IntegerVector ind_gene = match(gene_inter, targetID) - 1;
uvec index_gene = as<uvec>(ind_gene);
CharacterVector genetype1_t = expr_t["genetype1"];
CharacterVector genetype2_t = expr_t["genetype2"];
vec chr_expr_t = expr_t["chr_expr"];
vec lower_t = expr_t["lower"];
vec upper_t = expr_t["upper"];
genetype1 = genetype1_t[ind_gene];
genetype2 = genetype2_t[ind_gene];
chr_expr = chr_expr_t(index_gene);
lower = lower_t(index_gene);
upper = upper_t(index_gene);
}
}
cout << "just completed" << endl;
// draw overlapped samples and genes acorss all expression files.
cube expr_used(gene_inter.size(), indiv_inter.size(), T, fill::zeros);
for (t =0; t < T; t++) {
List expr_t = expr_tmp[t];
CharacterVector IID_expr_tmp = IID_expr[t];
IntegerVector ind_indiv = match(indiv_inter, IID_expr_tmp) - 1;
uvec index_indiv = as<uvec>(ind_indiv);
CharacterVector targetID = expr_t["targetID"];
IntegerVector ind_gene = match(gene_inter, targetID) - 1;
uvec index_gene = as<uvec>(ind_gene);
mat expr_all = expr_t["expr"];
expr_used.slice(t) = expr_all(index_gene, index_indiv);
}
// read two plink files.
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
clock_t t1 = clock();
cout << "## Start loading genotype files 1, " ;
//read file 1 (plink bim bed fam files)
string bimfile1 = stringname1;
bimfile1 += ".bim";
long int P1 = getLineNum(bimfile1);
cout << N1 << "-by-" << P1;
arma::Mat<unsigned> X1(N1,P1);
//cout << " break 1: " << N1 << "X" << P1 << endl;
readPlink(stringname1, N1, P1, X1.memptr());
// subset overlapped samples and SNPs.
IntegerVector indiv_idx_in1 = match(indiv_inter, IID_1) -1;
X1 = X1.cols(idxinFile1 - 1);
X1 = X1.rows(as<uvec>(indiv_idx_in1));
// replace NA with 0 dosage
X1.replace(3, 0);
cout << ", Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
t1 = clock();
cout << "## Start loading genotype files of reference panel " << endl;
// load pheno in file 2 (fam file 2)
string famfile2 = stringname2;
famfile2 += ".fam";
int N2 = getLineNum(famfile2);
//cout << endl;
string bimfile2 = stringname2;
bimfile2 += ".bim";
//cout << "break 1... " << endl;
long int P2 = getLineNum(bimfile2);
cout << N2 << "-by-" << P2;
arma::Mat<unsigned> X2(N2,P2);
//cout << "break 3..." << endl;
readPlink(stringname2, N2, P2, X2.memptr());
// subset overlapped SNPs
X2 = X2.cols(idxinFile2 -1);
// replace NA with 0 dosage
X2.replace(3, 0);
// if needed, change the reference allele in file 2
uvec idxtmp = linspace<uvec>(1, idxinFile1.size(), idxinFile1.size());
uvec idx = find(ind == -1);
uvec idxc = idxtmp.elem(idx);
X2.cols(idxc-1) = 2 - X2.cols(idxc-1);
cout << ", Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
cout << "## Start loading covariates files ... " << endl;
// load covariates file w1
mat covar1;
//cout << "break ..." << covar2.n_rows << ";" << covar2.n_cols << ";" << N1 << ";" << !stringname4.empty() << endl;
CharacterVector IID_w1;
if (!stringname4.empty()){
int Nincovar1 = getLineNum(stringname4);
tmp = getColNum_Header(stringname4, delimiter);
int Ncovar = tmp["columns"];
tmp = getCovarFile(stringname4, delimiter, Ncovar, Nincovar1);
mat covartmp = tmp["covar"];
IID_w1 = tmp["IID"];
mat w1one = ones<mat>(X1.n_rows, 1);
IntegerVector indiv_idx_covar1 = match(indiv_inter, IID_w1) - 1;
covar1 = join_rows(w1one, covartmp.rows(as<uvec>(indiv_idx_covar1)));
}
else {
covar1 = ones<mat>(X1.n_rows, 1);
}
// load Summary Statisitc files.
int P3 = getLineNum(stringnameSS);
List GWAS = read_GWAS(stringnameSS, P3);
mat GWAS_sum = GWAS["GWAS_sum"];
GWAS_sum = GWAS_sum.rows(idxinFileSS - 1);
// if needed, the signs of marginal coefficients in Summary Statistics file are changed.
GWAS_sum.cols(zeros<uvec>(1)) = GWAS_sum.cols(zeros<uvec>(1)) % indSS;
cout << "## End loading files ... " << endl;
List output = List::create(
Rcpp::Named("covar1") = covar1,
Rcpp::Named("X1") = X1,
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("chr_4use_r") = chr_4use_r,
Rcpp::Named("bp_4use_r") = bp_4use_r,
Rcpp::Named("lower") = lower,
Rcpp::Named("upper") = upper,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("targetID") = gene_inter,
Rcpp::Named("chr_expr") = chr_expr,
Rcpp::Named("indiv_inter") = indiv_inter,
Rcpp::Named("expr_used") = expr_used,
Rcpp::Named("Xpanel") = X2,
Rcpp::Named("GWAS_SS") = GWAS_sum);
return output;
}<file_sep>//
// plinkfun.cpp
// PlinkRead
//
// Created by DaiMingwei on 16/10/6.
// Copyright © 2016年 daviddai. All rights reserved.
//
#include <RcppArmadillo.h>
//#include <Rcpp.h>
#include "plinkfun.hpp"
#include <stdio.h>
#include <math.h>
#include <bitset>
#include <boost/algorithm/string.hpp>
#define MAX_LEN 20
int getLineNum(string filename){
FILE *pf = fopen(filename.c_str(), "r"); // 打开文件
int max_length = 30000;
char buf[max_length];
int lineCnt = 0;
if (!pf) // 判断是否打开成功
return -1;
while (fgets(buf, max_length, pf)) // fgets循环读取,直到文件最后,才会返回NULL
lineCnt++; // 累计行数
fclose(pf);
return lineCnt;
}
void getFourGentype(unsigned* geno, std::bitset<8> bits){
int idx = 0;
for (int j=0; j < 8; j = j + 2) {
if(bits[j] && bits[j+1]){
geno[idx] = 0;
}else if(!bits[j] && !bits[j+1]){
geno[idx] = 2;
}else if(!bits[j] && bits[j+1]){
geno[idx] = 1;
}else if(bits[j] && !bits[j+1]){
geno[idx] = 3;
}
idx++;
}
}
void readPlink(string stringname, long int N, long int P, unsigned* X){
// string stringname = dir + dataname;
FILE *fp;
unsigned char buff[3];
string bedfile = stringname +".bed";
fp = fopen(bedfile.c_str(), "rb");
if (!fp) return;
fread(buff, sizeof(char), 3, fp);
std::bitset<8> magic1(buff[0]);
std::bitset<8> magic2(buff[1]);
std::bitset<8> mode0(buff[2]);
if(magic1.to_ulong() != 108 || magic2.to_ulong() != 27){
// cout <<"Error Identifier of plink binary file" << endl;
}
unsigned long mode = mode0.to_ulong();
if(mode == 0){
printf ("individual-Major Order:improper type of plink file");
exit (EXIT_FAILURE);
}
// cout << "SNP-Major Order" << endl;
// }else if(mode == 0){
// cout << "individual-Major Order" << endl;
// }
// X = new int[N*P];
//cout << N << "x" << P << endl;
//cout << sizeof(*X) << endl;
long n = 0;
long long charNum = ceil(N*1.0/4)*10000;
long long leftGenoNum = ceil(N*1.0/4)*P;
long nblock = ceil(N*1.0/4);
long nSNP = 0;
//cout << "nblock: " << nblock << endl;
//cout << "leftGenoNum: " << leftGenoNum << endl;
while (!feof(fp)) {
if(leftGenoNum <= 0)
break;
if(leftGenoNum <= charNum){
charNum = leftGenoNum;
}
char* genotype = new char[charNum];
fread(genotype, sizeof(char), charNum, fp);
unsigned* geno = new unsigned[4];
long nSNPc = long(charNum / nblock); //number of SNPs of this iteration
//cout << n << "-th line: ";
//cout << "nSNPc: "<< nSNPc << endl;
// cout << sizeof(int) << endl;
long long idx = 0;
for (long i=0; i < nSNPc; i++) {
/*if ( n >= 4 ){
cout << i << "-th snp" << endl;
if (i == 0){
//cout << "break 1 ... " << nSNP << ";" << N << ";" << leftGenoNum << ";" << idx << endl;
}
}*/
for(long j=0; j < nblock - 1; j++){
long long indx = (long long)(nSNP) * (long long)(N) + (long long)(j*4);
// if ( n == 3 && i == 9999 && j == nblock - 2){
/*if ( n == 3 && j == nblock - 2 && i > 5000 ){
// long long indxt = nSNP * N + j*4;
// cout << "break 2 ... " << endl;
cout << "break 1 ... "<< n << "-th line, " << i << "-th snp: " << N <<";" << j << ";" <<
indx << ";" << leftGenoNum << ";" << idx << endl;
}*/
std::bitset<8> bits(genotype[idx]);
getFourGentype(geno,bits);
memcpy(X + indx, geno, 4*sizeof(unsigned));
idx++;
leftGenoNum -= 1;
}
//if ( n == 4 && i == 0 ){
// cout << "break 4 ... " << endl;
//}
// cout << "break 1 ... " << endl;
long left = N - (nblock - 1)*4;
std::bitset<8> bits(genotype[idx]);
getFourGentype(geno,bits);
long long indx2 = (long long)(nSNP) * (long long)(N) + (long long)(nblock - 1)*4;
long long indx3 = left*sizeof(unsigned);
/*if ( n == 3 && i > 5000 ){
cout << "break 2 ... " << n << "-th line, " << i << "-th snp: " << nSNP << ";" <<
N << ";" << nblock << ";" << indx2 << ";" << indx3 << endl;
}*/
memcpy(X + indx2, geno, indx3);
idx++;
leftGenoNum -= 1;
nSNP ++;
}
delete[] geno;
delete[] genotype;
n++;
// cout <<n << " processing"<<endl;
}
}
void ReadPlinkBimFile(std::string stringname, IntegerVector A1, IntegerVector A2, CharacterVector rsname,
IntegerVector chr, IntegerVector bp, NumericVector morgan, int P){
FILE *stream;
/*CharacterVector rsname(P);
IntegerVector A1(P), A2(P);*/
int ch, b;
double mor;
char s[MAX_LEN + 1], efa, nefa;
stream = fopen(stringname.c_str(), "r");
clock_t t1 = clock();
//int i = 0;
/* Put in various data. */
for ( int i = 0; i < P; i++){
if (i % 500000 == 0 && i != 0){
cout << i << "-th SNP" << ",";
cout << "Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
}
fscanf(stream, "%i %s %lf %i %c %c", &ch, &s[0], &mor, &b, &efa, &nefa);
chr(i) = ch;
rsname(i) = s;
morgan(i) = mor;
bp(i) = b;
A1(i) = (int)efa;
A2(i) = (int)nefa;
}
}
CharacterVector charv_subset(CharacterVector x, uvec idx){
CharacterVector v(idx.n_elem);
for (unsigned int i = 0; i < idx.n_elem; i++){
v(i) = x(idx(i));
}
return v;
}
void ReadPlinkFamFile(std::string stringname, CharacterVector FID, CharacterVector IID, IntegerVector sex,
NumericVector pheno, int N)
{
FILE *stream;
int gender;
double phn;
char fid[MAX_LEN + 1], iid[MAX_LEN + 1], tmp1[MAX_LEN + 1], tmp2[MAX_LEN + 1];
stream = fopen(stringname.c_str(), "r");
for (int i = 0; i < N; i++){
fscanf(stream, "%s %s %s %s %i %lf", &fid, &iid, &tmp1, &tmp2, &gender, &phn);
FID(i) = fid;
IID(i) = iid;
sex(i) = gender;
pheno(i) = phn;
}
}
void ReadPlinkFamFile2(std::string stringname, CharacterVector FID, CharacterVector IID,
NumericVector pheno, int nrows, int whCol){
std::ifstream myfile(stringname.c_str());
std::string line;
clock_t t1 = clock();
int nrow_ind = 0;
vector <string> tmp;
if (myfile.is_open()){
while (nrow_ind < nrows){
if (nrow_ind % 5000 == 0 && nrow_ind != 0){
cout << nrow_ind << "-th individual " << ",";
cout << "Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
}
getline(myfile, line);
boost::split(tmp, line, boost::is_any_of(" \t *"));
FID(nrow_ind) = tmp[0];
IID(nrow_ind) = tmp[1];
// sex(nrow_ind) = atoi(tmp[4].c_str());
pheno(nrow_ind) = atof(tmp[4 + whCol].c_str());
//cout << "value: " << tmp[0] << ";" << tmp[1] << ";" << tmp[2] << ";" << tmp[3] << ";" << tmp[4]
// << ";" << tmp[5] << ";" << tmp[6] << endl;
nrow_ind++;
}
}
}
List match_SNPs(std::string stringname1, std::string stringname2){
// stringname1: prefix for plink file 1; start working on plink file 1 (1000 G with expression data)
string bimfile1 = stringname1;
bimfile1 += ".bim";
//cout << "break 1: " << bimfile1 << endl;
int P1 = getLineNum(bimfile1);
cout << "## Number of SNPs (plink file 1):" << P1 << endl;
IntegerVector A1_1(P1), A2_1(P1);
CharacterVector rsname_1(P1);
IntegerVector chr_1(P1), bp_1(P1);
NumericVector morgan_1(P1);
ReadPlinkBimFile(bimfile1, A1_1, A2_1, rsname_1, chr_1, bp_1, morgan_1, P1);
// cout << rsname_1(0) << ";" << A1_1(0) << ";" << A2_1(0) << endl;
// stringname2: prefix for plink file 2; start working on plink file 2 (GWAS data with trait)
string bimfile2 = stringname2;
bimfile2 += ".bim";
int P2 = getLineNum(bimfile2);
cout << "## Number of SNPs (plink file 2):" << P2 << endl;
IntegerVector A1_2(P2), A2_2(P2);
CharacterVector rsname_2(P2);
IntegerVector chr_2(P2), bp_2(P2);
NumericVector morgan_2(P2);
ReadPlinkBimFile(bimfile2, A1_2, A2_2, rsname_2, chr_2, bp_2, morgan_2, P2);
// cout << rsname_2(0) << ";" << chr_2(0) << ";" << bp_2(0) << ";" << A1_2(0) << ";" << A2_2(0) << endl;
// mathcing panel SNPs in file 1 and file 2 with correction for direction of ref allele
// rsname in both files in the order of the first file.
CharacterVector rs_inter = intersect(rsname_1, rsname_2);
IntegerVector idxin = match(rsname_1, rs_inter); //index for SNPs in file 1
CharacterVector rsname_4use = rsname_1[Rcpp::is_na(idxin) == false];
IntegerVector chr_4use = chr_1[Rcpp::is_na(idxin) == false];
IntegerVector bp_4use = bp_1[Rcpp::is_na(idxin) == false];
// match snps (rsname_4use; rsname_2: file 2)
IntegerVector idxin2 = match(rsname_4use, rsname_2); //index for SNPs in file 2
// match snps (rsname_4use; rsname_1: file 1)
IntegerVector idxin1 = match(rsname_4use, rsname_1); //index for SNPs in file 1
/*IntegerVector chr_4use_tmp = chr_2[idxin2];
IntegerVector bp_4use_tmp = bp_2[idxin2];
vec idxtmp = as<vec>(chr_4use) - as<vec>(chr_4use_tmp);
cout << "check the quality: " << sum(idxtmp) << endl;
cout << "Size of matched SNPs: " << rsname_4use.size() << endl;*/
// convert ascii letter to uvec and work on overlapped SNPs
uvec idx = as<uvec>(idxin1) -1;
uvec tmp1 = as<uvec>(A1_1);
uvec A1_1_ = tmp1.elem(idx);
tmp1 = as<uvec>(A2_1);
uvec A2_1_ = tmp1.elem(idx);
idx = as<uvec>(idxin2) -1;
uvec tmp2 = as<uvec>(A1_2);
uvec A1_2_ = tmp2.elem(idx);
tmp2 = as<uvec>(A2_2);
uvec A2_2_ = tmp2.elem(idx);
//ascii: (A:65; C:67; G:71; T:84) (a:97;c:99,g:103;t:116)
/*//replace lower letter to upper letter in A1_1_ and A2_1_;
idx = find(A1_1_ > 85);
A1_1_.elem(idx) = A1_1_.elem(idx) - 32;
idx = find(A2_1_ > 85);
A2_1_.elem(idx) = A2_1_.elem(idx) - 32;
idx = find(A1_2_ > 85);
A1_2_.elem(idx) = A1_2_.elem(idx) - 32;
idx = find(A2_2_ > 85);
A2_2_.elem(idx) = A2_2_.elem(idx) - 32;*/
//compare A1_1_ A1_2_, A2_1_ A2_2_
//A1_1_: replace T with A,replace G with C
idx = find(A1_1_ == 84);
uvec idxrepl1(idx.n_elem);
idxrepl1.fill(65);
A1_1_.elem(idx) = idxrepl1;
idx = find(A1_1_ == 71);
uvec idxrepl2(idx.n_elem);
idxrepl2.fill(67);
A1_1_.elem(idx) = idxrepl2;
//A1_2_: replace T with A,replace G with C
idx = find(A1_2_ == 84);
uvec idxrepl3(idx.n_elem);
idxrepl3.fill(65);
A1_2_.elem(idx) = idxrepl3;
idx = find(A1_2_ == 71);
uvec idxrepl4(idx.n_elem);
idxrepl4.fill(67);
A1_2_.elem(idx) = idxrepl4;
//A2_1_: replace T with A,replace G with C
idx = find(A2_1_ == 84);
uvec idxrepl5(idx.n_elem);
idxrepl5.fill(65);
A2_1_.elem(idx) = idxrepl5;
idx = find(A2_1_ == 71);
uvec idxrepl6(idx.n_elem);
idxrepl6.fill(67);
A2_1_.elem(idx) = idxrepl6;
//A2_2_: replace T with A,replace G with C
idx = find(A2_2_ == 84);
uvec idxrepl7(idx.n_elem);
idxrepl7.fill(65);
A2_2_.elem(idx) = idxrepl7;
idx = find(A2_2_ == 71);
uvec idxrepl8(idx.n_elem);
idxrepl8.fill(67);
A2_2_.elem(idx) = idxrepl8;
// remove index;
idx = find((A1_1_ + A2_1_) == (A1_2_ + A2_2_));
uvec tmp3 = as<uvec>(idxin2);
uvec idxin22 = tmp3.elem(idx);
tmp3 = as<uvec>(idxin1);
uvec idxin11 = tmp3.elem(idx);
uvec A1_1_r = A1_1_.elem(idx), A2_1_r = A2_1_.elem(idx);
uvec A1_2_r = A1_2_.elem(idx), A2_2_r = A2_2_.elem(idx);
uvec chr_tmp = as<uvec>(chr_4use);
uvec chr_4use_r = chr_tmp.elem(idx);
uvec bp_tmp = as<uvec>(bp_4use);
uvec bp_4use_r = bp_tmp.elem(idx);
CharacterVector rsname_4use_r = charv_subset(rsname_4use, idx);
vec ind(A1_1_r.n_elem);
idx = find(A1_1_r == A1_2_r);
ind.ones();
ind = -ind;
ind.elem(idx).ones();
cout << "Number of matched SNPs (plink file 1 and 2):" << ind.size() << endl;
//cout << "direction (compare with trait_1000Q_match.R): " << sum(ind) << endl; //compare sum(ind) in R: Height_1000Q_match.R
//cout << "Size of matched SNPs (remove ambiguous SNPs): " << A1_1_r.n_elem << endl;
List output = List::create(Rcpp::Named("chr_4use_r") = chr_4use_r,
Rcpp::Named("A1_1_r") = A1_1_r,
Rcpp::Named("A1_2_r") = A1_2_r,
Rcpp::Named("A2_1_r") = A2_1_r,
Rcpp::Named("A2_2_r") = A2_2_r,
Rcpp::Named("bp_4use_r") = bp_4use_r,
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("indicator") = ind,
Rcpp::Named("idxinFile1") = idxin11,
Rcpp::Named("idxinFile2") = idxin22);
return output;
}
// [[Rcpp::export]]
List read_GWAS(std::string filename, int P){
std::ifstream ifs(filename.c_str());
std::string line;
vector<string> fields;
CharacterVector snp(P - 1);
IntegerVector A1(P - 1);
IntegerVector A2(P - 1);
uvec chr = zeros<uvec>(P - 1);
uvec BP = zeros<uvec>(P - 1);
mat GWAS_sum = zeros(P - 1, 2); // transpcriptome summary data
int i = 0;
string str;
while (std::getline(ifs, line)) // read one line from ifs
{
std::istringstream iss(line); // access line as a stream
boost::split(fields, line, boost::is_any_of(" \t *"));
if (i > 0){
snp[i-1] = fields[0];
chr[i-1] = atof(fields[1].c_str());
BP[i-1] = atof(fields[2].c_str());
str = fields[3];
char* chr1 = strdup(str.c_str());
A1[i-1] = (int)(*chr1);
str = fields[4];
char* chr2 = strdup(str.c_str());
A2[i-1] = (int)(*chr2);
GWAS_sum(i-1, 0) = atof(fields[5].c_str());
GWAS_sum(i-1, 1) = atof(fields[6].c_str());
}
i++;
}
ifs.close();
List output = List::create(
Rcpp::Named("GWAS_snps") = snp,
Rcpp::Named("GWAS_chr") = chr,
Rcpp::Named("BP") = BP,
Rcpp::Named("A1") = A1,
Rcpp::Named("A2") = A2,
Rcpp::Named("GWAS_sum") = GWAS_sum);
return output;
}
List match_SNPs_SS(std::string stringname1, std::string stringnamePanal, std::string stringnameSS){
// stringname1: prefix for plink file 1; start working on plink file 1 (1000 G with expression data)
string bimfile1 = stringname1;
bimfile1 += ".bim";
//cout << "break 1: " << bimfile1 << endl;
int P1 = getLineNum(bimfile1);
cout << "## Number of SNPs (plink file 1):" << P1 << endl;
IntegerVector A1_1(P1), A2_1(P1);
CharacterVector rsname_1(P1);
IntegerVector chr_1(P1), bp_1(P1);
NumericVector morgan_1(P1);
ReadPlinkBimFile(bimfile1, A1_1, A2_1, rsname_1, chr_1, bp_1, morgan_1, P1);
// cout << rsname_1(0) << ";" << A1_1(0) << ";" << A2_1(0) << endl;
// stringnamePanal: prefix for plink file 2; start working on plink file 2 (Genotype of reference panel)
string bimfile2 = stringnamePanal;
bimfile2 += ".bim";
int P2 = getLineNum(bimfile2);
cout << "## Number of SNPs (plink file 2):" << P2 << endl;
IntegerVector A1_2(P2), A2_2(P2);
CharacterVector rsname_2(P2);
IntegerVector chr_2(P2), bp_2(P2);
NumericVector morgan_2(P2);
ReadPlinkBimFile(bimfile2, A1_2, A2_2, rsname_2, chr_2, bp_2, morgan_2, P2);
// cout << rsname_2(0) << ";" << chr_2(0) << ";" << bp_2(0) << ";" << A1_2(0) << ";" << A2_2(0) << endl;
int P3 = getLineNum(stringnameSS);
List GWAS = read_GWAS(stringnameSS, P3);
IntegerVector A1_3 = GWAS["A1"];
CharacterVector rsname_3 = GWAS["GWAS_snps"];
// mathcing SNPs in file 1, file2 and file 3 with correction for direction of ref allele
// rsname in both files in the order of the first file.
CharacterVector rs_inter = intersect(rsname_1, rsname_2);
rs_inter = intersect(rs_inter, rsname_3);
IntegerVector idxin = match(rsname_1, rs_inter); //index for SNPs in file 1
CharacterVector rsname_4use = rsname_1[Rcpp::is_na(idxin) == false];
IntegerVector chr_4use = chr_1[Rcpp::is_na(idxin) == false];
IntegerVector bp_4use = bp_1[Rcpp::is_na(idxin) == false];
// match snps (rsname_4use; rsname_1: file 1)
IntegerVector idxin1 = match(rsname_4use, rsname_1); //index for SNPs in file 1
// match snps (rsname_4use; rsname_2: file 2)
IntegerVector idxin2 = match(rsname_4use, rsname_2); //index for SNPs in file 2
// match snps (rsname_4use; rsname_3: file 3)
IntegerVector idxin3 = match(rsname_4use, rsname_3); //index for SNPs in file 3
/*IntegerVector chr_4use_tmp = chr_2[idxin2];
IntegerVector bp_4use_tmp = bp_2[idxin2];
vec idxtmp = as<vec>(chr_4use) - as<vec>(chr_4use_tmp);
cout << "check the quality: " << sum(idxtmp) << endl;
cout << "Size of matched SNPs: " << rsname_4use.size() << endl;*/
// convert ascii letter to uvec and work on overlapped SNPs
uvec idx = as<uvec>(idxin1) -1;
uvec tmp1 = as<uvec>(A1_1);
uvec A1_1_ = tmp1.elem(idx);
tmp1 = as<uvec>(A2_1);
uvec A2_1_ = tmp1.elem(idx);
idx = as<uvec>(idxin2) -1;
uvec tmp2 = as<uvec>(A1_2);
uvec A1_2_ = tmp2.elem(idx);
tmp2 = as<uvec>(A2_2);
uvec A2_2_ = tmp2.elem(idx);
idx = as<uvec>(idxin3) -1;
uvec tmpSS = as<uvec>(A1_3);
uvec A1_3_ = tmpSS.elem(idx);
//ascii: (A:65; C:67; G:71; T:84) (a:97;c:99,g:103;t:116)
/*//replace lower letter to upper letter in A1_1_ and A2_1_;
idx = find(A1_1_ > 85);
A1_1_.elem(idx) = A1_1_.elem(idx) - 32;
idx = find(A2_1_ > 85);
A2_1_.elem(idx) = A2_1_.elem(idx) - 32;
idx = find(A1_2_ > 85);
A1_2_.elem(idx) = A1_2_.elem(idx) - 32;
idx = find(A2_2_ > 85);
A2_2_.elem(idx) = A2_2_.elem(idx) - 32;*/
//compare A1_1_ A1_2_, A2_1_ A2_2_
//A1_1_: replace T with A,replace G with C
idx = find(A1_1_ == 84);
uvec idxrepl1(idx.n_elem);
idxrepl1.fill(65);
A1_1_.elem(idx) = idxrepl1;
idx = find(A1_1_ == 71);
uvec idxrepl2(idx.n_elem);
idxrepl2.fill(67);
A1_1_.elem(idx) = idxrepl2;
//A1_2_: replace T with A,replace G with C
idx = find(A1_2_ == 84);
uvec idxrepl3(idx.n_elem);
idxrepl3.fill(65);
A1_2_.elem(idx) = idxrepl3;
idx = find(A1_2_ == 71);
uvec idxrepl4(idx.n_elem);
idxrepl4.fill(67);
A1_2_.elem(idx) = idxrepl4;
//A2_1_: replace T with A,replace G with C
idx = find(A2_1_ == 84);
uvec idxrepl5(idx.n_elem);
idxrepl5.fill(65);
A2_1_.elem(idx) = idxrepl5;
idx = find(A2_1_ == 71);
uvec idxrepl6(idx.n_elem);
idxrepl6.fill(67);
A2_1_.elem(idx) = idxrepl6;
//A2_2_: replace T with A,replace G with C
idx = find(A2_2_ == 84);
uvec idxrepl7(idx.n_elem);
idxrepl7.fill(65);
A2_2_.elem(idx) = idxrepl7;
idx = find(A2_2_ == 71);
uvec idxrepl8(idx.n_elem);
idxrepl8.fill(67);
A2_2_.elem(idx) = idxrepl8;
//A1_3_: replace T with A,replace G with C
idx = find(A1_3_ == 84);
uvec idxrepl9(idx.n_elem);
idxrepl9.fill(65);
A1_3_.elem(idx) = idxrepl9;
idx = find(A1_3_ == 71);
uvec idxrepl10(idx.n_elem);
idxrepl10.fill(67);
A1_3_.elem(idx) = idxrepl10;
// keep SNPs with matched A1 and A2 in file 1 and file 2 (panel file);
idx = find((A1_1_ + A2_1_) == (A1_2_ + A2_2_));
uvec tmp3 = as<uvec>(idxin2);
uvec idxin22 = tmp3.elem(idx);
tmp3 = as<uvec>(idxin1);
uvec idxin11 = tmp3.elem(idx);
tmp3 = as<uvec>(idxin3);
uvec idxin33 = tmp3.elem(idx);
uvec A1_1_r = A1_1_.elem(idx), A2_1_r = A2_1_.elem(idx);
uvec A1_2_r = A1_2_.elem(idx), A2_2_r = A2_2_.elem(idx);
uvec A1_3_r = A1_3_.elem(idx);
uvec chr_tmp = as<uvec>(chr_4use);
uvec chr_4use_r = chr_tmp.elem(idx);
uvec bp_tmp = as<uvec>(bp_4use);
uvec bp_4use_r = bp_tmp.elem(idx);
CharacterVector rsname_4use_r = charv_subset(rsname_4use, idx);
// an indicator imply whether the reference allele in Panal file need to be changed.
vec ind(A1_1_r.n_elem);
idx = find(A1_1_r == A1_2_r);
ind.ones();
ind = -ind;
ind.elem(idx).ones();
// an indicator imply whether the reference allele (marginal coefficients) in Summary Statistics file need to be changed.
vec indSS(A1_1_r.n_elem);
idx = find(A1_1_r == A1_3_r);
indSS.ones();
indSS = -indSS;
indSS.elem(idx).ones();
cout << "Number of matched SNPs (plink file 1 and 2):" << ind.size() << endl;
//cout << "direction (compare with trait_1000Q_match.R): " << sum(ind) << endl; //compare sum(ind) in R: Height_1000Q_match.R
//cout << "Size of matched SNPs (remove ambiguous SNPs): " << A1_1_r.n_elem << endl;
List output = List::create(Rcpp::Named("chr_4use_r") = chr_4use_r,
Rcpp::Named("A1_1_r") = A1_1_r,
Rcpp::Named("A1_2_r") = A1_2_r,
Rcpp::Named("A2_1_r") = A2_1_r,
Rcpp::Named("A2_2_r") = A2_2_r,
Rcpp::Named("bp_4use_r") = bp_4use_r,
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("indicator") = ind,
Rcpp::Named("indicatorSS") = indSS,
Rcpp::Named("idxinFile1") = idxin11,
Rcpp::Named("idxinFile2") = idxin22,
Rcpp::Named("idxinFileSS") = idxin33);
return output;
}
<file_sep>//
// plinkfun.hpp
// PlinkRead
//
// Created by DaiMingwei on 16/10/6.
// Copyright © 2016年 daviddai. All rights reserved.
//
#ifndef plinkfun_hpp
#define plinkfun_hpp
#include <RcppArmadillo.h>
//#include <Rcpp.h>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <bitset>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace Rcpp;
using namespace arma;
void getFourGentype(unsigned* geno, std::bitset<8> bits);
void readPlink(string stringname, long int N, long int P, unsigned* X);
int getLineNum(string filename);
void ReadPlinkBimFile(string stringname, IntegerVector A1, IntegerVector A2, CharacterVector rsname,
IntegerVector chr, IntegerVector bp, NumericVector morgan, int P);
void ReadPlinkFamFile(std::string stringname, CharacterVector FID, CharacterVector IID, IntegerVector sex,
NumericVector pheno, int N);
//CharacterVector charv_subset(CharacterVector x, uvec idx);
List match_SNPs(string stringname1, string stringname2);
List match_SNPs_SS(string stringname1, string stringnamePanal, string stringnameSS);
List read_GWAS(std::string filename, int P);
void ReadPlinkFamFile2(std::string stringname, CharacterVector FID, CharacterVector IID,
NumericVector pheno, int nrows, int whCol);
#endif /* plinkfun_hpp */
<file_sep>#include <RcppArmadillo.h>
#include <stdio.h>
#include <bitset>
#include <math.h>
#include <string>
#include <vector>
#include "data_loader.hpp"
#include "paral.hpp"
using namespace std;
using namespace Rcpp;
using namespace arma;
// There are four functions here:
// the first two functions conduct MAMMOT based on individual eQTL data and GWAS individual genotypes.
// 1. mammot
// 2. mammot_paral
// the above functions have exactly the same input and output, except that mammot_paral has an extra
// argument "coreNum", which specify the number of cores you may want to use.
//
// the last two functions conduct MAMMOT based on individual eQTL data and GWAS summary statisitcs based
// on margianl linear regression analysis:
// 3. mammotSS
// 4. mammotSS_paral
// Note that we assume the resulting coefficients are not standardized,
// which is the default settings in plink, (output of "--assoc" or "--linear"),
//' @title
//' CoMM
//' @description
//' CoMM to dissecting genetic contributions to complex traits by leveraging regulatory information.
//'
//' @param stringname1 prefix for eQTL genotype file with plink format (bim, bed).
//' @param stringname2 prefix for GWAS genotype and phenotype file with plink format (bim, bed, fam).
//' @param stringname3 gene expression file with full name.
//' @param stringname4 covariates file for eQTL data.
//' @param stringname5 covariates file for GWAS data, e.g. top 10 PCs.
//' @param whCol specify which phenotype is used in fam. For example, when whCol = 2, the seven-th column of fam file will be used as phenotype.
//' @param bw the number of downstream and upstream SNPs that are considered as cis-SNP within a gene.
//'
//' @return List of model parameters
//'
//' @examples
//' ##Working with no summary statistics, no covariates and options
//' file1 = "1000G.EUR.QC.1";
//' file2 = "NFBC_filter_mph10";
//' file3 = "Geuvadis_gene_expression_qn.txt";
//' file4 = "";
//' file5 = "pc5_NFBC_filter_mph10.txt";
//' whichPheno = 1;
//' bw = 500000;
//'
//' fm = CoMM_testing_run(file1,file2,file3, file4,file5, whichPheno, bw);
//'
//' @details
//' \code{CoMM} fits the CoMM model. It requires to provide plink binary eQTL genotype file (bim, bed)
//' the GWAS plink binary file (bim, bed, fam), gene expression file for eQTL.
//' @export
// [[Rcpp::export]]
Rcpp::List mammot(std::string stringname1, std::string stringname2,
std::vector<std::string> stringname3, std::string stringname4,
std::string stringname5, int whCol, int bw){
//int normalize_option = 1, int pred_option = 0){
//, char* A21, char* A22){
// normalize_option: 1. normalize each separately, 2. normalize both plink files together
// match SNPs in file 1 and file 2 GWAS (common SNPs in x1 and x2 in columns)
// plink file 1: stringname1; plink file 2: stringname2; expression file: stringname3
// covariates file for file 1: stringname4; covariates file for file 2: stringname5
// pred_option :0 (no calculation for prediction) 1 (calcuation for prediction)
List tmp = dataLoader(stringname1, stringname2, stringname3, stringname4, stringname5, whCol);
Mat<unsigned> X1 = tmp["X1"], X2 = tmp["X2"];
vec z = tmp["y"];
mat w1 = tmp["covar1"], w2 = tmp["covar2"];
cube expr = tmp["expr_used"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
CharacterVector genetype1 = tmp["genetype1"], genetype2 = tmp["genetype2"],
targetID = tmp["targetID"];
vec lower = tmp["lower"], upper = tmp["upper"], chr_expr = tmp["chr_expr"];
uword Ngene = lower.size();
//Ngene = 30;
int T = stringname3.size();
umat snp_info = zeros<umat>(chr_4use_r.n_elem, 2);
snp_info.col(0) = chr_4use_r;
snp_info.col(1) = bp_4use_r;
mat expr_info = zeros<mat>(lower.n_elem, 3);
expr_info.col(0) = chr_expr;
expr_info.col(1) = lower;
expr_info.col(2) = upper;
uvec idx;
mat out_param = datum::nan * ones<mat>(Ngene, 4);
mat Alpha(Ngene, T); Alpha.fill(datum::nan);
uvec idx_all = zeros<uvec>(0);
// pre-compute matrix for intercepts.
mat Prj1 = w1 * inv_sympd(w1.t() * w1) * w1.t();
mat Prj2 = w2 * inv_sympd(w2.t() * w2) * w2.t();
z = z - Prj2 * z;
// conduct testing
List fmHa;
uword g = 0;
for (g = 0; g < Ngene; g++){
idx = find(conv_to<vec>::from(bp_4use_r) < upper(g) + bw && conv_to<vec>::from(bp_4use_r) > lower(g) - bw
&& conv_to<vec>::from(chr_4use_r) == chr_expr(g));
out_param(g, 3) = idx.n_elem;
if ( g % 100 == 0 && g != 0){
cout << g << "-th Gene starts working ..." << endl ;
//cout << "Elapsed time is " << (clock() - t1)*1.0 / CLOCKS_PER_SEC << " sec" << endl;
}
//if (g == 262) break;
if (idx.is_empty() == false){
if (idx.n_elem > 1){
idx_all = join_cols(idx_all, idx);
mat X1tmp = conv_to<mat>::from((&X1) ->cols(idx));
mat X2tmp = conv_to<mat>::from((&X2) ->cols(idx));
mat y = expr.subcube(span(g), span::all, span::all);
if (y.n_rows == 1) y = y.t();
y = y - Prj1 * y;
rowvec meanX1tmp = mean(X1tmp, 0);
rowvec sdX1tmp = stddev(X1tmp, 0, 0); // see manual
X1tmp = (X1tmp - repmat(meanX1tmp, X1tmp.n_rows, 1))/ repmat(sdX1tmp, X1tmp.n_rows, 1) / sqrt(X1tmp.n_cols);
rowvec meanX2tmp = mean(X2tmp, 0);
rowvec sdX2tmp = stddev(X2tmp, 0, 0); // see manual
X2tmp = (X2tmp - repmat(meanX2tmp, X2tmp.n_rows, 1))/ repmat(sdX2tmp, X2tmp.n_rows, 1) / sqrt(X2tmp.n_cols);
rowvec X1row = X1tmp.row(0);
X1tmp = X1tmp.cols(find_finite(X1row));
X2tmp = X2tmp.cols(find_finite(X1row));
mat w = ones<mat>(X1tmp.n_cols, 1);
if (T != 1) {
w = cor(X1tmp, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(X1tmp, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
}
// fit model under Ha and H0
fmHa = mammot_PXem(X1tmp, y, X2tmp, z, w, false, false, 2000);
List fmHo = mammot_PXem(X1tmp, y, X2tmp, z, w, true, false, 2000);
vec alphatmp = fmHa["alpha"];
vec loglikHa = fmHa["loglik"], loglikHo = fmHo["loglik"];
mat Ve = fmHa["Ve"];
double sigmab = fmHa["sigmab"];
mat Ve0 = fmHo["Ve"];
double sigmaz = fmHa["sigmaz"];
out_param(g, 0) = sigmaz;
out_param(g, 1) = 2 * (max(loglikHa) - max(loglikHo));
out_param(g, 2) = sigmab;
Alpha.row(g) = alphatmp.t();
}
}
}
List out = List::create(
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("snp_info_4use_r") = snp_info,
Rcpp::Named("targetID") = targetID,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("expr_info") = expr_info,
Rcpp::Named("out_param") = out_param,
Rcpp::Named("Alpha") = Alpha);
return out;
}
// [[Rcpp::export]]
Rcpp::List mammot_paral(std::string stringname1, std::string stringname2,
std::vector<std::string> stringname3, std::string stringname4,
std::string stringname5, int whCol, int bw, int coreNum){
List tmp = dataLoader(stringname1, stringname2, stringname3, stringname4, stringname5, whCol);
Mat<unsigned> X1 = tmp["X1"], X2 = tmp["X2"];
vec z = tmp["y"];
mat w1 = tmp["covar1"], w2 = tmp["covar2"];
cube expr = tmp["expr_used"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
CharacterVector genetype1 = tmp["genetype1"], genetype2 = tmp["genetype2"],
targetID = tmp["targetID"];
vec lower = tmp["lower"], upper = tmp["upper"], chr_expr = tmp["chr_expr"];
uword Ngene = lower.size();
//Ngene = 30;
int T = stringname3.size();
mat snp_info = zeros<mat>(chr_4use_r.n_elem, 2);
snp_info.col(0) = conv_to<vec>::from(bp_4use_r);
snp_info.col(1) = conv_to<vec>::from(chr_4use_r);
mat expr_info = zeros<mat>(lower.n_elem, 3);
expr_info.col(0) = chr_expr;
expr_info.col(1) = lower;
expr_info.col(2) = upper;
// pre-compute matrix for intercepts.
mat Prj2 = w2 * inv_sympd(w2.t() * w2) * w2.t();
z = z - Prj2 * z;
mat prj1 = w1 * inv_sympd(w1.t() * w1) * w1.t();
mat out_param = datum::nan * ones<mat>(4, Ngene);
mat Alpha = datum::nan * ones<mat>(T, Ngene);
//set parallele structure object
parGene parObj(X1, X2, expr, z, prj1, out_param, Alpha, expr_info, snp_info, Ngene, bw);
//set parallel computation
const int n_thread = coreNum;
std::vector<std::thread> threads(n_thread);
for(int i_thread = 0; i_thread < n_thread; i_thread++){
threads[i_thread] = std::thread(&parGene::update_by_thread, &parObj, i_thread);
}
for(int i = 0; i < n_thread; i++){
threads[i].join();
}
List out = List::create(
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("snp_info_4use_r") = snp_info,
Rcpp::Named("targetID") = targetID,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("expr_info") = expr_info,
Rcpp::Named("out_param") = trans(parObj.out_param),
Rcpp::Named("Alpha") = trans(parObj.Alpha));
return out;
}
//' @title
//' mammot
//' @description
//'
//'
//' @param stringname1 prefix for eQTL genotype file with plink format (bim, bed).
//' @param stringname2 prefix for reference panal GWAS genotype file with plink format (bim, bed, fam).
//' @param stringname3 gene expression file with full name.
//' @param stringname4 covariates file for eQTL data.
//' @param stringname5 GWAS summary statisitcs, which has specific form.
//' @param whCol specify which phenotype is used in fam. For example, when whCol = 2, the seven-th column of fam file will be used as phenotype.
//' @param bw the number of downstream and upstream SNPs that are considered as cis-SNP within a gene.
//'
//' @return List of model parameters
//'
//' @examples
//' ##Working with no summary statistics, no covariates and options
//' file1 = "1000G.EUR.QC.1";
//' file2 = "NFBC_filter_mph10";
//' file3 = "Geuvadis_gene_expression_qn.txt";
//' file4 = "";
//' file5 = "pc5_NFBC_filter_mph10.txt";
//' whichPheno = 1;
//' bw = 500000;
//'
//' fm = mammotSS_testing_run(file1,file2,file3, file4,file5, whichPheno, bw);
//'
//' @details
//' \code{mammotSS_testing_run} fits the mammot model. It requires to provide plink binary eQTL genotype file (bim, bed)
//' the GWAS summary statisitcs file (txt), gene expression file for eQTL.
//' @export
// [[Rcpp::export]]
Rcpp::List mammotSS(std::string stringname1, std::string stringname2,
std::vector<std::string> stringname3, std::string stringname4,
std::string stringname5, double lam, int bw){
List tmp = dataLoaderSS(stringname1, stringname2, stringname3, stringname4, stringname5);
Mat<unsigned> X1 = tmp["X1"], Xpanel = tmp["Xpanel"];
mat GWAS_SS = tmp["GWAS_SS"];
mat w1 = tmp["covar1"];
cube expr = tmp["expr_used"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
CharacterVector genetype1 = tmp["genetype1"], genetype2 = tmp["genetype2"],
targetID = tmp["targetID"];
vec lower = tmp["lower"], upper = tmp["upper"], chr_expr = tmp["chr_expr"];
uword Ngene = lower.size();
//Ngene = 30;
int T = stringname3.size();
umat snp_info = zeros<umat>(chr_4use_r.n_elem, 2);
snp_info.col(0) = chr_4use_r;
snp_info.col(1) = bp_4use_r;
mat expr_info = zeros<mat>(lower.n_elem, 3);
expr_info.col(0) = chr_expr;
expr_info.col(1) = lower;
expr_info.col(2) = upper;
uvec idx;
mat out_param = datum::nan * ones<mat>(Ngene, 4);
mat Alpha(Ngene, T); Alpha.fill(datum::nan);
uvec idx_all = zeros<uvec>(0);
// pre-compute matrix for intercepts.
mat Prj1 = w1 * inv_sympd(w1.t() * w1) * w1.t();
// conduct testing
List fmHa;
uword g = 0;
for (g = 0; g < Ngene; g++){
idx = find(conv_to<vec>::from(bp_4use_r) < upper(g) + bw && conv_to<vec>::from(bp_4use_r) > lower(g) - bw
&& conv_to<vec>::from(chr_4use_r) == chr_expr(g));
out_param(g, 3) = idx.n_elem;
if ( g % 100 == 0 && g != 0){
cout << g << "-th Gene starts working ..." << endl ;
}
if (idx.is_empty() == false){
if (idx.n_elem > 1){
idx_all = join_cols(idx_all, idx);
mat X1tmp = conv_to<mat>::from((&X1) ->cols(idx));
mat Xpaneltmp = conv_to<mat>::from((&Xpanel) ->cols(idx));
mat GWAS_SStmp = GWAS_SS.rows(idx);
// deal with One tissue files.
mat y = expr.subcube(span(g), span::all, span::all);
if (y.n_rows == 1) y = y.t();
y = y - Prj1 * y;
rowvec meanX1tmp = mean(X1tmp, 0);
rowvec sdX1tmp = stddev(X1tmp, 0, 0); // see manual
X1tmp = X1tmp - repmat(meanX1tmp, X1tmp.n_rows, 1); // just centering
rowvec meanXpaneltmp = mean(Xpaneltmp, 0);
Xpaneltmp = Xpaneltmp - repmat(meanXpaneltmp, Xpaneltmp.n_rows, 1); // just centering
rowvec X1row = 1/sdX1tmp;
X1tmp = X1tmp.cols(find_finite(X1row));
Xpaneltmp = Xpaneltmp.cols(find_finite(X1row));
GWAS_SStmp = GWAS_SStmp.rows(find_finite(X1row));
// prepared summary statistics.
int p = Xpaneltmp.n_cols;
vec hatmu = GWAS_SStmp.cols(zeros<uvec>(1));
vec hats = GWAS_SStmp.cols(ones<uvec>(1));
mat R1 = cor(Xpaneltmp);
// positive definite sparse correlation matrix
mat R = lam * R1 + (1 - lam) * eye(p, p);
mat S = diagmat(hats);
mat SR = S * R;
mat V = SR * S;
mat L = chol(V);
mat Ltinv = inv(L.t());
mat gam_L = Ltinv * hatmu;
mat U = Ltinv * SR * diagmat(1.0/hats);
mat w = ones<mat>(X1tmp.n_cols, 1);
if (T != 1) {
w = cor(X1tmp, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(X1tmp, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
}
// fit model under Ha and H0
fmHa = mammot_PXem_ss(X1tmp, y, U, gam_L, w, false, true, 2000);
List fmHo = mammot_PXem_ss(X1tmp, y, U, gam_L, w, true, true, 2000);
//cout <<"break 2 ..." <<endl;
vec alphatmp = fmHa["alpha"];
vec loglikHa = fmHa["loglik"], loglikHo = fmHo["loglik"];
mat Ve = fmHa["Ve"];
double sigmab = fmHa["sigmab"];
mat Ve0 = fmHo["Ve"];
double sigmaz = fmHa["sigmaz"];
out_param(g, 0) = sigmaz;
out_param(g, 1) = 2 * (max(loglikHa) - max(loglikHo));
out_param(g, 2) = sigmab;
Alpha.row(g) = alphatmp.t();
}
}
}
List out = List::create(
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("snp_info_4use_r") = snp_info,
Rcpp::Named("targetID") = targetID,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("expr_info") = expr_info,
Rcpp::Named("out_param") = out_param,
Rcpp::Named("Alpha") = Alpha);
return out;
}
// [[Rcpp::export]]
Rcpp::List mammotSS_paral(std::string stringname1, std::string stringname2,
std::vector<std::string> stringname3, std::string stringname4,
std::string stringname5, double lam, int bw, int coreNum){
List tmp = dataLoaderSS(stringname1, stringname2, stringname3, stringname4, stringname5);
Mat<unsigned> X1 = tmp["X1"], Xpanel = tmp["Xpanel"];
mat GWAS_SS = tmp["GWAS_SS"];
mat w1 = tmp["covar1"];
cube expr = tmp["expr_used"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
CharacterVector genetype1 = tmp["genetype1"], genetype2 = tmp["genetype2"],
targetID = tmp["targetID"];
vec lower = tmp["lower"], upper = tmp["upper"], chr_expr = tmp["chr_expr"];
uword Ngene = lower.size();
//Ngene = 30;
int T = stringname3.size();
mat snp_info = zeros<mat>(chr_4use_r.n_elem, 2);
snp_info.col(0) = conv_to<vec>::from(bp_4use_r);
snp_info.col(1) = conv_to<vec>::from(chr_4use_r);
mat expr_info = zeros<mat>(lower.n_elem, 3);
expr_info.col(0) = chr_expr;
expr_info.col(1) = lower;
expr_info.col(2) = upper;
// pre-compute matrix for intercepts.
mat prj1 = w1 * inv_sympd(w1.t() * w1) * w1.t();
mat out_param = datum::nan * ones<mat>(4, Ngene);
mat Alpha = datum::nan * ones<mat>(T, Ngene);
//set paralel structure object
parGeneSS parObjSS(X1, Xpanel, expr, GWAS_SS, prj1, out_param, Alpha, expr_info, snp_info, Ngene, lam, bw);
//set paralel computation
const int n_thread = coreNum;
std::vector<std::thread> threads(n_thread);
for(int i_thread = 0; i_thread < n_thread; i_thread++){
threads[i_thread] = std::thread(&parGeneSS::update_by_thread, &parObjSS, i_thread);
}
for(int i = 0; i < n_thread; i++){
threads[i].join();
}
List out = List::create(
Rcpp::Named("rsname_4use_r") = rsname_4use_r,
Rcpp::Named("snp_info_4use_r") = snp_info,
Rcpp::Named("targetID") = targetID,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("expr_info") = expr_info,
Rcpp::Named("out_param") = trans(parObjSS.out_param),
Rcpp::Named("Alpha") = trans(parObjSS.Alpha));
return out;
}
// [[Rcpp::export]]
Rcpp::List mammot_part_paral(std::string stringname1, std::string stringname2,
std::vector<std::string> stringname3, std::string stringname4,
std::string stringname5, CharacterVector targetList, int whCol, int bw, int coreNum){
int T = stringname3.size();
List tmp = dataLoader(stringname1, stringname2, stringname3, stringname4, stringname5, whCol);
Mat<unsigned> X1 = tmp["X1"], X2 = tmp["X2"];
vec z = tmp["y"];
mat w1 = tmp["covar1"], w2 = tmp["covar2"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
cube expr = tmp["expr_used"];
CharacterVector genetype1 = tmp["genetype1"], genetype2 = tmp["genetype2"], targetID = tmp["targetID"];
vec lower = tmp["lower"], upper = tmp["upper"], chr_expr = tmp["chr_expr"];
uword Ngene = targetList.size();
IntegerVector idx = match(targetList, targetID) - 1;
uvec index_gene = as<uvec>(idx);
cube expr_idx(Ngene, expr.n_cols, T);
for (int j = 0; j < Ngene; j++)
{
expr_idx.subcube(span(j), span::all, span::all) = expr.subcube(span(index_gene(j)), span::all, span::all);
}
//expr = expr(span(index_gene), span::all, span::all);
genetype1 = genetype1[idx], genetype2 = genetype2[idx], targetID = targetID[idx];
lower = lower(index_gene), upper = upper(index_gene), chr_expr = chr_expr(index_gene);
//Ngene = 2;
mat snp_info = zeros<mat>(chr_4use_r.n_elem, 2);
snp_info.col(0) = conv_to<vec>::from(bp_4use_r);
snp_info.col(1) = conv_to<vec>::from(chr_4use_r);
mat expr_info = zeros<mat>(lower.n_elem, 3);
expr_info.col(0) = chr_expr;
expr_info.col(1) = lower;
expr_info.col(2) = upper;
// pre-compute matrix for intercepts.
mat Prj2 = w2 * inv_sympd(w2.t() * w2) * w2.t();
z = z - Prj2 * z;
mat prj1 = w1 * inv_sympd(w1.t() * w1) * w1.t();
mat out_param = datum::nan * ones<mat>(4, Ngene);
mat Alpha = datum::nan * ones<mat>(T, Ngene);
mat chisq = datum::nan * ones<mat>(T, Ngene);
mat h_y2 = datum::nan * ones<mat>(T, Ngene);
//set paralel structure object
parGene_part parObj_part(X1, X2, expr_idx, z, prj1, out_param, Alpha, chisq, h_y2, expr_info, snp_info, Ngene, bw);
//set paralel computation
const int n_thread = coreNum;
std::vector<std::thread> threads(n_thread);
for(int i_thread = 0; i_thread < n_thread; i_thread++){
threads[i_thread] = std::thread(&parGene_part::update_by_thread, &parObj_part, i_thread);
}
for(int i = 0; i < n_thread; i++){
threads[i].join();
}
List out = List::create(
Rcpp::Named("idx") = idx,
Rcpp::Named("targetID") = targetID,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("expr_info") = expr_info,
//Rcpp::Named("out_param") = trans(parObj_part.out_param),
//Rcpp::Named("Alpha") = trans(parObj_part.Alpha),
Rcpp::Named("chisq") = trans(parObj_part.chisq),
Rcpp::Named("h_y2") = trans(parObj_part.h_y2));
return out;
}
// [[Rcpp::export]]
Rcpp::List mammotSS_part_paral(std::string stringname1, std::string stringname2,
std::vector<std::string> stringname3, std::string stringname4,
std::string stringname5, CharacterVector targetList, double lam, int bw, int coreNum){
List tmp = dataLoaderSS(stringname1, stringname2, stringname3, stringname4, stringname5);
int T = stringname3.size();
Mat<unsigned> X1 = tmp["X1"], Xpanel = tmp["Xpanel"];
mat GWAS_SS = tmp["GWAS_SS"];
mat w1 = tmp["covar1"];
CharacterVector rsname_4use_r = tmp["rsname_4use_r"];
uvec bp_4use_r = tmp["bp_4use_r"];
uvec chr_4use_r = tmp["chr_4use_r"];
cube expr = tmp["expr_used"];
CharacterVector genetype1 = tmp["genetype1"], genetype2 = tmp["genetype2"], targetID = tmp["targetID"];
vec lower = tmp["lower"], upper = tmp["upper"], chr_expr = tmp["chr_expr"];
uword Ngene = targetList.size();
IntegerVector idx = match(targetList, targetID) - 1;
uvec index_gene = as<uvec>(idx);
cube expr_idx(Ngene, expr.n_cols, T);
for (int j = 0; j < Ngene; j++)
{
expr_idx.subcube(span(j), span::all, span::all) = expr.subcube(span(index_gene(j)), span::all, span::all);
}
//expr = expr(span(index_gene), span::all, span::all);
genetype1 = genetype1[idx], genetype2 = genetype2[idx], targetID = targetID[idx];
lower = lower(index_gene), upper = upper(index_gene), chr_expr = chr_expr(index_gene);
//Ngene = 30;
mat snp_info = zeros<mat>(chr_4use_r.n_elem, 2);
snp_info.col(0) = conv_to<vec>::from(bp_4use_r);
snp_info.col(1) = conv_to<vec>::from(chr_4use_r);
mat expr_info = zeros<mat>(lower.n_elem, 3);
expr_info.col(0) = chr_expr;
expr_info.col(1) = lower;
expr_info.col(2) = upper;
// pre-compute matrix for intercepts.
mat prj1 = w1 * inv_sympd(w1.t() * w1) * w1.t();
mat out_param = datum::nan * ones<mat>(4, Ngene);
mat Alpha = datum::nan * ones<mat>(T, Ngene);
mat chisq = datum::nan * ones<mat>(T, Ngene);
mat h_y2 = datum::nan * ones<mat>(T, Ngene);
//set paralel structure object
parGeneSS_part parObjSS_part(X1, Xpanel, expr_idx, GWAS_SS, prj1, out_param, Alpha, chisq, h_y2, expr_info, snp_info, Ngene, lam, bw);
//set paralel computation
const int n_thread = coreNum;
std::vector<std::thread> threads(n_thread);
for(int i_thread = 0; i_thread < n_thread; i_thread++){
threads[i_thread] = std::thread(&parGeneSS_part::update_by_thread, &parObjSS_part, i_thread);
}
for(int i = 0; i < n_thread; i++){
threads[i].join();
}
List out = List::create(
Rcpp::Named("idx") = idx,
Rcpp::Named("targetID") = targetID,
Rcpp::Named("genetype1") = genetype1,
Rcpp::Named("genetype2") = genetype2,
Rcpp::Named("expr_info") = expr_info,
//Rcpp::Named("out_param") = trans(parObjSS_part.out_param),
//Rcpp::Named("Alpha") = trans(parObjSS_part.Alpha),
Rcpp::Named("chisq") = trans(parObjSS_part.chisq),
Rcpp::Named("h_y2") = trans(parObjSS_part.h_y2));
return out;
}
<file_sep>
source("evalType1Err.R")
assig = function(n_args){
# example:
# n_args = c(2, 3, 4)
cargs <- vector("list", length(n_args))
for(i in 1:length(n_args)) cargs[[i]] = 1:n_args[i]
t(expand.grid(cargs))
}
n_args = c(2, 5, 3, 3, 5)
jobs = assig(n_args)
main <- function(number0){
number <- as.numeric(number0)
h_z <- c(0, 0.01)[jobs[1, number]]
h_c <- c(0.025, 0.05, 0.1, 0.2, 0.4)[jobs[2, number]]
s = c(0.1, 0.5, 0.9)[jobs[3, number]]
rhoX = c(0.2, 0.5, 0.8)[jobs[4, number]]
batch <- (1:10)[jobs[5, number]]
rhoE = 0.5
Ti = 10
Rep = 10
set.seed(20132014*batch)
case = c(h_z = h_z, h_c = h_c, s = s, rhoX = rhoX, batch = batch)
print(case)
evalType1Err(h_z, h_c, s, rhoX, rhoE, Ti, batch, Rep)
}
args <- commandArgs(TRUE)
main(args[1])
<file_sep>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <Rcpp.h>
#include <omp.h>
using namespace Rcpp;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
arma::mat ADW(const arma::mat& x, const arma::mat& y) {
mat w = cor(x, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(x, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
return w;
}
void PXem_part(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const arma::vec& constrFactor, const bool& PX, int& Iteration, const int& maxIter)
{
int m = y.n_rows, T = y.n_cols, p = x1.n_cols, n = z.n_elem;
mat I_p = eye<mat>(p, p);
// Parameter Expansion
double lam = 1.0;
// precomputation
mat x1tx1 = x1.t() * x1;
mat x2tx2 = x2.t() * x2;
mat ytx1 = y.t() * x1;
mat x2tz = x2.t() * z;
mat Sigma_i = I_p;
mat yhat = x1 * B_hat;
mat residual_y = y - yhat;
mat ztilde = x2 * B_hat;
vec residual_z = z - ztilde * alpha;
//mat wv_i = w * v_i;
mat v_iwt = solve(Ve, w.t());
mat wv_i = v_iwt.t();
mat wv_iwt = wv_i * w.t();
mat wa = w * alpha;
mat Lv = Ve;
mat Ls = I_p;
LogLik(0) = -INFINITY;
int iter;
uvec idx = find(constrFactor == 0);
//--------------------------------------------------------------------------------
// EM algrithm
//--------------------------------------------------------------------------------
for (iter = 1; iter < maxIter; iter ++ ) {
// E-step
Sigma_i = lam *lam * (x1tx1 % wv_iwt) + x2tx2 % (wa * wa.t())/sigmaz + I_p/sigmab;
Sigma = solve(Sigma_i, I_p);
mat x1tx1S = x1tx1 % Sigma;
mu = Sigma * (lam * diagvec(wv_i * ytx1) + diagmat(x2tz) * wa /sigmaz);
B_hat = diagmat(mu) * w;
//cout << "diagmat(mu) = " << mu << endl;
// M-step
// residual
yhat = lam * x1 * B_hat;
residual_y = y - yhat;
ztilde = x2 * B_hat;
residual_z = z - ztilde * alpha;
// v
Ve = residual_y.t()*residual_y/m + lam*lam/m * w.t() * x1tx1S * w;
//wv_i = w * v_i;
v_iwt = solve(Ve, w.t());
wv_i = v_iwt.t();
wv_iwt = wv_i * w.t();
// sigmab
sigmab = (sum(mu % mu) + trace(Sigma))/p;
// sigmaz
mat sigmaz_2 = w.t() * (x2tx2 % Sigma) * w;
sigmaz = sum(residual_z % residual_z)/n + trace(sigmaz_2 * alpha * alpha.t())/n;
// alpha
mat w_j = w.cols(idx);
mat alpha_d_1 = w_j.t() * (x2tx2 % (mu * mu.t())) * w_j;
mat alpha_d_2 = w_j.t() * (x2tx2 % Sigma) * w_j;
mat B_hat_j = B_hat.cols(idx);
vec alpha_j = solve(alpha_d_1 + alpha_d_2, B_hat_j.t()) * x2tz;
alpha(idx) = alpha_j;
//cout << alpha << endl;
vec residual_z_new = z - ztilde * alpha;
double n_sigmaz_new = sum(residual_z_new % residual_z_new) + trace(sigmaz_2 * alpha * alpha.t());
wa = w * alpha;
// Gamma
if (PX) {
double lam2 = sum(mu.t() * (x1tx1 % wv_iwt) * mu) + trace(wv_i.t() * x1tx1S * w);
lam = sum(mu % diagvec(wv_i * ytx1))/lam2;
}
// current log-likelihood
Lv = chol(Ve, "lower");
Ls = chol(Sigma, "lower");
LogLik(iter) = -(m*T + n) * 0.5 * log(2*datum::pi) - m * sum(log(Lv.diag())) - m*T/2 -
n * 0.5 * log(sigmaz) - n_sigmaz_new/2/sigmaz -
p * 0.5 * log(sigmab) +
sum(log(Ls.diag()));
if ( LogLik(iter) - LogLik(iter - 1) < -1e-8 ){
perror("The likelihood failed to increase!");
break;
}
if (abs(LogLik(iter) - LogLik(iter - 1)) < 1e-5 || rcond(Sigma_i) < 1e-6) {
break;
}
}
if (iter == maxIter) {
Iteration = iter - 1;
} else {
Iteration = iter;
}
// Reduce-step
sigmab = sigmab * lam * lam;
alpha = alpha/lam;
}
// PXem for summary statisitcs
void PXem_ss_part(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const arma::vec& constrFactor, const bool& PX, int& Iteration, const int& maxIter)
{
int m = y.n_rows, T = y.n_cols, p = x1.n_cols, n = z.n_elem;
mat I_p = eye<mat>(p, p);
// Parameter Expansion
double lam = 1.0;
// precomputation
mat x1tx1 = x1.t() * x1;
mat x2tx2 = x2.t() * x2;
mat ytx1 = y.t() * x1;
mat x2tz = x2.t() * z;
mat Sigma_i = I_p;
mat yhat = x1 * B_hat;
mat residual_y = y - yhat;
mat ztilde = x2 * B_hat;
vec residual_z = z - ztilde * alpha;
//mat wv_i = w * v_i;
mat v_iwt = solve(Ve, w.t());
mat wv_i = v_iwt.t();
mat wv_iwt = wv_i * w.t();
mat wa = w * alpha;
mat Lv = Ve;
mat Ls = I_p;
LogLik(0) = -INFINITY;
int iter;
uvec idx = find(constrFactor == 0);
//--------------------------------------------------------------------------------
// EM algrithm
//--------------------------------------------------------------------------------
for (iter = 1; iter < maxIter; iter ++ ) {
// E-step
Sigma_i = lam *lam * (x1tx1 % wv_iwt) + x2tx2 % (wa * wa.t())/sigmaz + I_p/sigmab;
Sigma = solve(Sigma_i, I_p);
mat x1tx1S = x1tx1 % Sigma;
mu = Sigma * (lam * diagvec(wv_i * ytx1) + diagmat(x2tz) * wa /sigmaz);
B_hat = diagmat(mu) * w;
//cout << "diagmat(mu) = " << mu << endl;
// M-step
// residual
yhat = lam * x1 * B_hat;
residual_y = y - yhat;
ztilde = x2 * B_hat;
residual_z = z - ztilde * alpha;
// v
Ve = residual_y.t()*residual_y/m + lam*lam/m * w.t() * x1tx1S * w;
//wv_i = w * v_i;
v_iwt = solve(Ve, w.t());
wv_i = v_iwt.t();
wv_iwt = wv_i * w.t();
// sigmab
sigmab = (sum(mu % mu) + trace(Sigma))/p;
// sigmaz
mat sigmaz_2 = w.t() * (x2tx2 % Sigma) * w;
//sigmaz = sum(residual_z % residual_z)/n + trace(sigmaz_2 * alpha * alpha.t())/n;
sigmaz = 1;
// alpha
mat w_j = w.cols(idx);
mat alpha_d_1 = w_j.t() * (x2tx2 % (mu * mu.t())) * w_j;
mat alpha_d_2 = w_j.t() * (x2tx2 % Sigma) * w_j;
mat B_hat_j = B_hat.cols(idx);
vec alpha_j = solve(alpha_d_1 + alpha_d_2, B_hat_j.t()) * x2tz;
alpha(idx) = alpha_j;
//cout << alpha << endl;
vec residual_z_new = z - ztilde * alpha;
double n_sigmaz_new = sum(residual_z_new % residual_z_new) + trace(sigmaz_2 * alpha * alpha.t());
wa = w * alpha;
// Gamma
if (PX) {
double lam2 = sum(mu.t() * (x1tx1 % wv_iwt) * mu) + trace(wv_i.t() * x1tx1S * w);
lam = sum(mu % diagvec(wv_i * ytx1))/lam2;
}
// current log-likelihood
Lv = chol(Ve, "lower");
Ls = chol(Sigma, "lower");
LogLik(iter) = -(m*T + n) * 0.5 * log(2*datum::pi) - m * sum(log(Lv.diag())) - m*T/2 -
n * 0.5 * log(sigmaz) - n_sigmaz_new/2/sigmaz -
p * 0.5 * log(sigmab) +
sum(log(Ls.diag()));
if ( LogLik(iter) - LogLik(iter - 1) < -1e-8 ){
perror("The likelihood failed to increase!");
break;
}
if (abs(LogLik(iter) - LogLik(iter - 1)) < 1e-5 || rcond(Sigma_i) < 1e-6) {
break;
}
}
if (iter == maxIter) {
Iteration = iter - 1;
} else {
Iteration = iter;
}
// Reduce-step
sigmab = sigmab * lam * lam;
alpha = alpha/lam;
}
// [[Rcpp::export]]
List mammot_part_test(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter) {
if (y.n_rows != x1.n_rows || x1.n_cols != x2.n_cols || z.n_elem != x2.n_rows) {
perror("Dimensions of inpute (x1, y, x2, z) are not matched.");
}
int T = y.n_cols, p = x1.n_cols;
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1;
double sigmaz = var(z);
vec alpha = zeros<vec>(T);
vec LogLik0 = zeros<vec>(maxIter);
vec LogLik1 = zeros<vec>(maxIter);
int Iteration0 = 1, Iteration1 = 1;
mat B_hat = zeros<mat>(x1.n_cols, y.n_cols);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
PXem_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik0, constrFactor, PX, Iteration0, maxIter);
vec alpha0 = alpha;
vec Noconstr = zeros<vec>(T);
PXem_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik1, Noconstr, PX, Iteration1, maxIter);
vec alpha1 = alpha;
List output = List::create(
Rcpp::Named("alpha0") = alpha0,
Rcpp::Named("alpha1") = alpha1,
Rcpp::Named("chisq") = 2 * (LogLik1(Iteration1) - LogLik0(Iteration0)));
return output;
}
// [[Rcpp::export]]
List mammotSS_part_test(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter) {
if (y.n_rows != x1.n_rows || x1.n_cols != x2.n_cols || z.n_elem != x2.n_rows) {
perror("Dimensions of inpute (x1, y, x2, z) are not matched.");
}
int T = y.n_cols, p = x1.n_cols;
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1;
double sigmaz = 1;
vec alpha = zeros<vec>(T);
vec LogLik0 = zeros<vec>(maxIter);
vec LogLik1 = zeros<vec>(maxIter);
int Iteration0 = 1, Iteration1 = 1;
mat B_hat = zeros<mat>(x1.n_cols, y.n_cols);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
PXem_ss_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik0, constrFactor, PX, Iteration0, maxIter);
vec alpha0 = alpha;
vec Noconstr = zeros<vec>(T);
PXem_ss_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik1, Noconstr, PX, Iteration1, maxIter);
vec alpha1 = alpha;
List output = List::create(
Rcpp::Named("alpha0") = alpha0,
Rcpp::Named("alpha1") = alpha1,
Rcpp::Named("mu") = mu,
Rcpp::Named("Sigma") = Sigma,
Rcpp::Named("B_hat") = B_hat,
Rcpp::Named("Ve") = Ve,
Rcpp::Named("chisq") = 2 * (LogLik1(Iteration1) - LogLik0(Iteration0)));
return output;
}
// [[Rcpp::export]]
List mammot_PXem_part(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter) {
if (y.n_rows != x1.n_rows || x1.n_cols != x2.n_cols || z.n_elem != x2.n_rows) {
perror("Dimensions of inpute (x1, y, x2, z) are not matched.");
}
int T = y.n_cols, p = x1.n_cols;
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1;
double sigmaz = var(z);
vec alpha = zeros<vec>(T);
vec LogLik = zeros<vec>(maxIter);
int Iteration = 1;
mat B_hat = zeros<mat>(x1.n_cols, y.n_cols);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
PXem_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik, constrFactor, PX, Iteration, maxIter);
vec loglik;
loglik = LogLik.subvec(1, Iteration);
List output = List::create(
Rcpp::Named("x1") = x1,
Rcpp::Named("y") = y,
Rcpp::Named("x2") = x2,
Rcpp::Named("z") = z,
Rcpp::Named("W") = w,
Rcpp::Named("mu") = mu,
Rcpp::Named("Sigma") = Sigma,
Rcpp::Named("B_hat") = B_hat,
Rcpp::Named("sigmab") = sigmab,
Rcpp::Named("Ve") = Ve,
Rcpp::Named("alpha") = alpha,
Rcpp::Named("sigmaz") = sigmaz,
Rcpp::Named("loglik") = loglik);
return output;
}
// [[Rcpp::export]]
List mammotSS_part_est(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::mat B_hat, arma::vec mu, arma::mat Sigma, double sigmab, arma::mat Ve, arma::vec alpha,
arma::vec constrFactor, bool PX, int maxIter) {
double sigmaz = 1;
vec LogLik0 = zeros<vec>(maxIter);
int Iteration0 = 1;
PXem_ss_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik0, constrFactor, PX, Iteration0, maxIter);
List output = List::create(
Rcpp::Named("alpha") = alpha,
Rcpp::Named("loglik") = LogLik0(Iteration0));
return output;
}
// [[Rcpp::export]]
List mammotSS_PXem_part(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
arma::vec constrFactor, bool PX, int maxIter) {
if (y.n_rows != x1.n_rows || x1.n_cols != x2.n_cols || z.n_elem != x2.n_rows) {
perror("Dimensions of inpute (x1, y, x2, z) are not matched.");
}
int T = y.n_cols, p = x1.n_cols;
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1;
double sigmaz = 1;
vec alpha = zeros<vec>(T);
vec LogLik = zeros<vec>(maxIter);
int Iteration = 1;
mat B_hat = zeros<mat>(x1.n_cols, y.n_cols);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
PXem_ss_part(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik, constrFactor, PX, Iteration, maxIter);
vec loglik;
loglik = LogLik.subvec(1, Iteration);
List output = List::create(
Rcpp::Named("x1") = x1,
Rcpp::Named("y") = y,
Rcpp::Named("x2") = x2,
Rcpp::Named("z") = z,
Rcpp::Named("W") = w,
Rcpp::Named("mu") = mu,
Rcpp::Named("Sigma") = Sigma,
Rcpp::Named("B_hat") = B_hat,
Rcpp::Named("sigmab") = sigmab,
Rcpp::Named("Ve") = Ve,
Rcpp::Named("alpha") = alpha,
Rcpp::Named("sigmaz") = sigmaz,
Rcpp::Named("loglik") = loglik);
return output;
}
// a simple linear mixed model, PXEM algorithm.
void lmm_pxem_ptr2(const arma::vec& y, const arma::mat& W, const arma::mat& X, const int& maxIter,
double& sigma2y, double& sigma2beta, arma::vec& beta0, double& loglik_max,
int& iteration, arma::mat& Sigb, arma::vec& mub){
int n = y.n_elem, p = X.n_cols;
if (y.n_elem != X.n_rows || X.n_rows != W.n_rows){
perror("The dimensions in outcome and covariates (X and W) are not matched");
}
if (beta0.n_elem != W.n_cols){
perror("The dimensions in covariates are not matched in W and beta0");
}
if (p != mub.n_elem){
perror("The dimensions in covariates are not matched in mub");
}
if (p != Sigb.n_cols){
perror("The dimensions in covariates are not matched in Sigb");
}
mat XtX = X.t()*X, WtW = W.t()*W, WtX = W.t()*X;
vec Xty = X.t()*y, Wty = W.t()*y;
vec SWy;
mat SWX;
if(W.n_cols==1){
SWy = mean(y);
SWX = mean(X,0);
} else{
SWy = solve(WtW, Wty);
SWX = solve(WtW, WtX);
}
double gam, gam2; // parameter expansion
vec eVal;
mat eVec;
eig_sym(eVal, eVec, XtX);
// initialize
sigma2y = var(y);
sigma2beta = sigma2y/p;
beta0 = SWy - SWX * mub;
vec loglik(maxIter);
loglik(0) = -datum::inf;
vec D;
vec Xmu;
vec y_bar = y - W * beta0;
double y_Xmu2, E;
iteration = maxIter-1;
for (int iter = 1; iter < maxIter; iter ++ ) {
// E-step
D = 1 / sigma2beta + eVal / sigma2y;
mub = 1/sigma2y * eVec * (eVec.t() * (X.t() * y_bar) / D);
Xmu = X * mub;
y_Xmu2 = sum(pow(y_bar-Xmu,2));
// Evaluate loglik
E = y_Xmu2/(2*sigma2y) + accu(pow(mub,2))/(2*sigma2beta);
loglik(iter) = - p*log(sigma2beta)/2 - n*log(sigma2y)/2 - E - sum(log(D))/2 - n/2*log(2*datum::pi);
if ( loglik(iter) - loglik(iter - 1) < 0 ){
perror("The likelihood failed to increase!");
}
if (abs(loglik(iter) - loglik(iter - 1)) < 1e-10) {
iteration = iter;
break;
}
// M-step
gam = sum(y_bar % Xmu) / (accu(pow(Xmu,2)) + sum(eVal/D));
gam2 = pow(gam , 2);
beta0 = SWy - (SWX * mub) * gam;
y_bar = y - W * beta0;;
sigma2y = sum(pow(y_bar-Xmu*gam,2))/n + gam2 * sum(eVal/D)/n;
sigma2beta = accu(pow(mub,2))/p + sum(1/D)/p;
// Reduction step
sigma2beta = gam2 * sigma2beta;
// gam = 1;
// gam2 = pow(gam , 2);
}
vec loglik_out;
loglik_out = loglik.subvec(0, iteration);
loglik_max = loglik(iteration);
}
// [[Rcpp::export]]
Rcpp::List lmm_pxem(const arma::vec y, const arma::mat w, const arma::mat x, const int maxIter){
double sigma2y = var(y)/2, sigma2beta = var(y)/2, loglik;
vec beta0 =zeros<vec>(w.n_cols);
int iter;
mat Sigb = zeros<mat>(x.n_cols,x.n_cols);
vec mub = zeros<vec>(x.n_cols);
lmm_pxem_ptr2(y, w, x, maxIter,sigma2y,sigma2beta,beta0,loglik,iter,Sigb,mub);
List output = List::create(Rcpp::Named("sigma2y") = sigma2y,
Rcpp::Named("sigma2beta") = sigma2beta,
Rcpp::Named("beta0") = beta0,
Rcpp::Named("loglik") = loglik,
Rcpp::Named("iteration") = iter,
Rcpp::Named("Sigb") = Sigb,
Rcpp::Named("mub") = mub);
return output;
}
<file_sep>// Created by <NAME>, 24/06/2019.
// Copyright © 2019 <NAME>. All rights reserved.
// NOTE: the standardization methods of X1 for mammot and mammotSS are different.
//
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include "paral.hpp"
using namespace std;
using namespace arma;
void parGene::loop_by_gene(int i){
uvec idx = find(snp_info.col(0) < expr_info(i,2) + bw && snp_info.col(0) > expr_info(i,1) - bw
&& snp_info.col(1) == expr_info(i,0));
vec out_param_par = vec(out_param.colptr(i), 4, false);
out_param_par(3) = idx.n_elem;
if (idx.n_elem > 1){
//cout << "Error: no matching SNPs for " << i << "-th gene ... " << endl;
//} else {
mat y = expr.subcube(span(i), span::all, span::all);
if (y.n_rows == 1) y = y.t();
y = y - Prjy * y;
int T = y.n_cols;
vec Alpha_par = vec(Alpha.colptr(i), T, false);
mat X1tmp = conv_to<mat>::from(X1.cols(idx));
mat X2tmp = conv_to<mat>::from(X2.cols(idx));
rowvec meanX1tmp = mean(X1tmp, 0);
rowvec sdX1tmp = stddev(X1tmp, 0, 0); // see manual
rowvec meanX2tmp = mean(X2tmp, 0);
rowvec sdX2tmp = stddev(X2tmp, 0, 0); // see manual
X1tmp = (X1tmp - repmat(meanX1tmp, X1tmp.n_rows, 1)) / repmat(sdX1tmp, X1tmp.n_rows, 1)/ sqrt(X1tmp.n_cols);
X2tmp = (X2tmp - repmat(meanX2tmp, X2tmp.n_rows, 1))/ repmat(sdX2tmp, X2tmp.n_rows, 1) / sqrt(X2tmp.n_cols);
rowvec X1row = X1tmp.row(0);
uvec idx3 = find_finite(X1row);
X1tmp = X1tmp.cols(idx3);
X2tmp = X2tmp.cols(idx3);
if (idx3.n_elem == 0){
cout << "Error: the number of SNPs are 0 for " << i << "-th gene ... " << endl;
}
int p = X1tmp.n_cols, maxIter = 2000;
//H0: constr = true; produce initial values for Ha, and also hertitability estimate in EQTL.
int IterationH0 = 1;
vec LogLikH0 = zeros<vec>(maxIter);
mat w = ones<mat>(X1tmp.n_cols, 1);
if (T != 1) {
w = cor(X1tmp, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(X1tmp, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
}
mat B_hat = zeros<mat>(p, T);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1.0;
double sigmaz = var(z);
vec alpha = zeros<vec>(T);
PXem(X1tmp, y, X2tmp, z, w, B_hat, mu, Sigma, sigmab, Ve, alpha, sigmaz, LogLikH0, true, true, IterationH0, maxIter);
//H1: constr = false;
int IterationH1 = 1;
vec LogLikH1 = zeros<vec>(maxIter);
PXem(X1tmp, y, X2tmp, z, w, B_hat, mu, Sigma, sigmab, Ve, alpha, sigmaz, LogLikH1, false, true, IterationH1, maxIter);
Alpha_par = alpha;
out_param_par(0) = sigmaz;
out_param_par(1) = 2 * (LogLikH1(IterationH1) - LogLikH0(IterationH0));
out_param_par(2) = sigmab;
}
if ( i % 100 == 0 && i != 0) {
cout << i + 1 << "-th Gene starts working ..." << endl;
}
}
std::mutex _mtx2;
int parGene::next(){
std::lock_guard<std::mutex> lockGuard(_mtx2);
if(current_idx >= (int)Ngene){
return -1;
}
current_idx++;
return current_idx-1;
}
void parGene::update_by_thread(int thread_id){
while(true){
int idx = next();
if(idx == -1){
break;
}
// cout << idx << endl;
loop_by_gene(idx);
}
}
void parGeneSS::loop_by_gene(int i){
uvec idx = find(snp_info.col(0) < expr_info(i,2) + bw && snp_info.col(0) > expr_info(i,1) - bw
&& snp_info.col(1) == expr_info(i,0));
vec out_param_par = vec(out_param.colptr(i), 4, false);
out_param_par(3) = idx.n_elem;
if (idx.n_elem > 1){
//cout << "Error: no matching SNPs for " << i << "-th gene ... " << endl;
//} else {
mat y = expr.subcube(span(i), span::all, span::all);
//mat y = expr_active;
if (y.n_rows == 1) y = y.t();
y = y - Prjy * y;
int T = y.n_cols;
vec Alpha_par = vec(Alpha.colptr(i), T, false);
mat X1tmp = conv_to<mat>::from(X1.cols(idx));
mat Xpaneltmp = conv_to<mat>::from(Xpanel.cols(idx));
mat GWAS_SStmp = GWAS_SS.rows(idx);
rowvec meanX1tmp = mean(X1tmp, 0);
rowvec sdX1tmp = stddev(X1tmp, 0, 0); // see manual
rowvec meanXpaneltmp = mean(Xpaneltmp, 0);
//rowvec sdXpaneltmp = stddev(Xpaneltmp, 0, 0); // see manual
// centering
X1tmp = X1tmp - repmat(meanX1tmp, X1tmp.n_rows, 1);
Xpaneltmp = Xpaneltmp - repmat(meanXpaneltmp, Xpaneltmp.n_rows, 1);
rowvec X1row = 1/sdX1tmp;
uvec idx3 = find_finite(X1row);
X1tmp = X1tmp.cols(idx3);
Xpaneltmp = Xpaneltmp.cols(idx3);
GWAS_SStmp = GWAS_SStmp.rows(idx3);
if (idx3.n_elem == 0){
cout << "Error: the number of SNPs are 0 for " << i << "-th gene ... " << endl;
}
// prepared summary statistics.
int p = Xpaneltmp.n_cols;
vec hatmu = GWAS_SStmp.cols(zeros<uvec>(1));
vec hats = GWAS_SStmp.cols(ones<uvec>(1));
mat R1 = cor(Xpaneltmp);
// positive definite sparse correlation matrix
mat R = lam * R1 + (1 - lam) * eye(p, p);
mat S = diagmat(hats);
mat SR = S * R;
mat V = SR * S;
mat L = chol(V);
mat Ltinv = inv(L.t());
mat gam_L = Ltinv * hatmu;
mat U = Ltinv * SR * diagmat(1.0/hats);
//H0: constr = true; produce initial values for Ha, and also heritability estimate in EQTL.
int IterationH0 = 1, maxIter = 2000;
vec LogLikH0 = zeros<vec>(maxIter);
mat w = ones<mat>(X1tmp.n_cols, 1);
if (T != 1) {
w = cor(X1tmp, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(X1tmp, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
}
mat B_hat = zeros<mat>(p, T);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1.0;
double sigmaz = 1.0;
vec alpha = zeros<vec>(T);
PXem_ss(X1tmp, y, U, gam_L, w, B_hat, mu, Sigma, sigmab, Ve, alpha, sigmaz, LogLikH0, true, true, IterationH0, 2000);
//h_y2_par = 1.0/(1.0+Ve.diag()/Sigma.diag());
//H1: constr = true;
int IterationH1 = 1;
vec LogLikH1 = zeros<vec>(maxIter);
PXem_ss(X1tmp, y, U, gam_L, w, B_hat, mu, Sigma, sigmab, Ve, alpha, sigmaz, LogLikH1, false, true, IterationH1, 2000);
Alpha_par = alpha;
out_param_par(0) = sigmaz;
out_param_par(1) = 2 * (LogLikH1(IterationH1) - LogLikH0(IterationH0));
out_param_par(2) = sigmab;
}
if ( i % 100 == 0 && i != 0) {
cout << i + 1 << "-th Gene starts working ..." << endl;
}
}
//std::mutex _mtx3;
int parGeneSS::next(){
std::lock_guard<std::mutex> lockGuard(_mtx2);
if(current_idx >= (int)Ngene){
return -1;
}
current_idx++;
return current_idx-1;
}
void parGeneSS::update_by_thread(int thread_id){
while(true){
int idx = next();
if(idx == -1){
break;
}
// cout << idx << endl;
loop_by_gene(idx);
}
}
void parGene_part::loop_by_gene(int i){
uvec idx = find(snp_info.col(0) < expr_info(i,2) + bw && snp_info.col(0) > expr_info(i,1) - bw
&& snp_info.col(1) == expr_info(i,0));
vec out_param_par = vec(out_param.colptr(i), 4, false);
out_param_par(3) = idx.n_elem;
if (idx.n_elem > 1){
//cout << "Error: no matching SNPs for " << i << "-th gene ... " << endl;
//} else {
mat y = expr.subcube(span(i), span::all, span::all);
//mat y = expr_active;
if (y.n_rows == 1) y = y.t();
y = y - Prjy * y;
int T = y.n_cols;
vec Alpha_par = vec(Alpha.colptr(i), T, false);
vec chisq_par = vec(chisq.colptr(i), T, false);
vec h_y2_par = vec(h_y2.colptr(i), T, false);
mat X1tmp = conv_to<mat>::from(X1.cols(idx));
mat X2tmp = conv_to<mat>::from(X2.cols(idx));
rowvec meanX1tmp = mean(X1tmp, 0);
rowvec sdX1tmp = stddev(X1tmp, 0, 0); // see manual
rowvec meanX2tmp = mean(X2tmp, 0);
rowvec sdX2tmp = stddev(X2tmp, 0, 0); // see manual
X1tmp = (X1tmp - repmat(meanX1tmp, X1tmp.n_rows, 1)) / repmat(sdX1tmp, X1tmp.n_rows, 1)/ sqrt(X1tmp.n_cols);
X2tmp = (X2tmp - repmat(meanX2tmp, X2tmp.n_rows, 1))/ repmat(sdX2tmp, X2tmp.n_rows, 1) / sqrt(X2tmp.n_cols);
rowvec X1row = X1tmp.row(0);
uvec idx3 = find_finite(X1row);
X1tmp = X1tmp.cols(idx3);
X2tmp = X2tmp.cols(idx3);
if (idx3.n_elem == 0){
cout << "Error: the number of SNPs are 0 for " << i << "-th gene ... " << endl;
}
int p = X1tmp.n_cols, maxIter = 2000;
mat w = ones<mat>(X1tmp.n_cols, 1);
if (T != 1) {
w = cor(X1tmp, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(X1tmp, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
}
//1. H0_t: part test
//2. H1, using output of H0_t as initial values (more robust);
for (int t = 0; t < T; t++)
{
vec mu0_t = zeros<vec>(p);
mat B_hat0_t = zeros<mat>(p, T), Sigma0_t = eye<mat>(p, p);
mat Ve0_t = eye<mat>(T, T);
Ve0_t.diag() = vectorise(var(y));
double sigmab0_t = 1.0, sigmaz = 1.0;
vec constrFactor = zeros<vec>(T);
constrFactor(t) = 1;
int IterationH0_t = 1, IterationH1 = 1;
vec LogLikH0_t = zeros<vec>(maxIter), LogLikH1 = zeros<vec>(maxIter);
vec alpha0_t = zeros<vec>(T);
PXem_part(X1tmp, y, X2tmp, z, w,
B_hat0_t, mu0_t, Sigma0_t, sigmab0_t, Ve0_t, alpha0_t,
sigmaz, LogLikH0_t, constrFactor, true, IterationH0_t, maxIter);
constrFactor = zeros<vec>(T);
PXem_part(X1tmp, y, X2tmp, z, w,
B_hat0_t, mu0_t, Sigma0_t, sigmab0_t, Ve0_t, alpha0_t,
sigmaz, LogLikH1, constrFactor, true, IterationH1, maxIter);
chisq_par(t) = 2 * (LogLikH1(IterationH1) - LogLikH0_t(IterationH0_t));
//estimate heritability.
vec covar = ones<vec>(X1tmp.n_rows);
List lmm = lmm_pxem(y.col(t), covar, X1tmp, maxIter);
double sigma2y = lmm["sigma2y"], sigma2beta= lmm["sigma2beta"];
h_y2_par(t) = 1 / (1 + sigma2y/sigma2beta );
}
}
if ( i % 10 == 0 && i != 0) {
cout << i + 1 << "-th Gene starts working ..." << endl;
}
}
int parGene_part::next(){
std::lock_guard<std::mutex> lockGuard(_mtx2);
if(current_idx >= (int)Ngene){
return -1;
}
current_idx++;
return current_idx-1;
}
void parGene_part::update_by_thread(int thread_id){
while(true){
int idx = next();
if(idx == -1){
break;
}
// cout << idx << endl;
loop_by_gene(idx);
}
}
void parGeneSS_part::loop_by_gene(int i){
uvec idx = find(snp_info.col(0) < expr_info(i,2) + bw && snp_info.col(0) > expr_info(i,1) - bw
&& snp_info.col(1) == expr_info(i,0));
vec out_param_par = vec(out_param.colptr(i), 4, false);
out_param_par(3) = idx.n_elem;
if (idx.n_elem > 1){
//cout << "Error: no matching SNPs for " << i << "-th gene ... " << endl;
//} else {
mat y = expr.subcube(span(i), span::all, span::all);
//mat y = expr_active;
if (y.n_rows == 1) y = y.t();
y = y - Prjy * y;
int T = y.n_cols;
vec chisq_par = vec(chisq.colptr(i), T, false);
vec Alpha_par = vec(Alpha.colptr(i), T, false);
vec h_y2_par = vec(h_y2.colptr(i), T, false);
mat X1tmp = conv_to<mat>::from(X1.cols(idx));
mat Xpaneltmp = conv_to<mat>::from(Xpanel.cols(idx));
mat GWAS_SStmp = GWAS_SS.rows(idx);
rowvec meanX1tmp = mean(X1tmp, 0);
rowvec sdX1tmp = stddev(X1tmp, 0, 0); // see manual
rowvec meanXpaneltmp = mean(Xpaneltmp, 0);
//rowvec sdXpaneltmp = stddev(Xpaneltmp, 0, 0); // see manual
// centering
X1tmp = X1tmp - repmat(meanX1tmp, X1tmp.n_rows, 1);
Xpaneltmp = Xpaneltmp - repmat(meanXpaneltmp, Xpaneltmp.n_rows, 1);
mat X1_norm = X1tmp / repmat(sdX1tmp, X1tmp.n_rows, 1)/ sqrt(X1tmp.n_cols);//for heritability estimation.
rowvec X1row = 1/sdX1tmp;
uvec idx3 = find_finite(X1row);
X1tmp = X1tmp.cols(idx3);
X1_norm = X1_norm.cols(idx3);
Xpaneltmp = Xpaneltmp.cols(idx3);
GWAS_SStmp = GWAS_SStmp.rows(idx3);
if (idx3.n_elem == 0){
cout << "Error: the number of SNPs are 0 for " << i << "-th gene ... " << endl;
}
// prepared summary statistics.
int p = Xpaneltmp.n_cols, maxIter = 2000;
vec hatmu = GWAS_SStmp.cols(zeros<uvec>(1));
vec hats = GWAS_SStmp.cols(ones<uvec>(1));
mat R1 = cor(Xpaneltmp);
// positive definite sparse correlation matrix
mat R = lam * R1 + (1 - lam) * eye(p, p);
mat S = diagmat(hats);
mat SR = S * R;
mat V = SR * S;
mat L = chol(V);
mat Ltinv = inv(L.t());
mat gam_L = Ltinv * hatmu;
mat U = Ltinv * SR * diagmat(1.0/hats);
mat w = ones<mat>(X1tmp.n_cols, 1);
if (T != 1) {
w = cor(X1tmp, y);
rowvec sdy = stddev(y, 0, 0); // see manual
colvec sdx = vectorise(stddev(X1tmp, 0, 0));
w.each_row() %= sdy;
w.each_col() /= sdx;
}
//1. H0_t: part test
//2. H1, using output of H0_t as initial values (more robust);
for (int t = 0; t < T; t++)
{
vec mu0_t = zeros<vec>(p);
mat B_hat0_t = zeros<mat>(p, T), Sigma0_t = eye<mat>(p, p);
mat Ve0_t = eye<mat>(T, T);
Ve0_t.diag() = vectorise(var(y));
double sigmab0_t = 1.0, sigmaz = 1.0;;
vec constrFactor = zeros<vec>(T);
constrFactor(t) = 1;
int IterationH0_t = 1, IterationH1 = 1;
vec LogLikH0_t = zeros<vec>(maxIter), LogLikH1 = zeros<vec>(maxIter);
vec alpha0_t = zeros<vec>(T);
PXem_ss_part(X1tmp, y, U, gam_L, w,
B_hat0_t, mu0_t, Sigma0_t, sigmab0_t, Ve0_t, alpha0_t,
sigmaz, LogLikH0_t, constrFactor, true, IterationH0_t, maxIter);
constrFactor = zeros<vec>(T);
PXem_ss_part(X1tmp, y, U, gam_L, w,
B_hat0_t, mu0_t, Sigma0_t, sigmab0_t, Ve0_t, alpha0_t,
sigmaz, LogLikH1, constrFactor, true, IterationH1, maxIter);
chisq_par(t) = 2 * (LogLikH1(IterationH1) - LogLikH0_t(IterationH0_t));
//estimate heritability.
vec covar = ones<vec>(X1tmp.n_rows);
List lmm = lmm_pxem(y.col(t), covar, X1_norm, maxIter);
double sigma2y = lmm["sigma2y"], sigma2beta= lmm["sigma2beta"];
h_y2_par(t) = 1 / (1 + sigma2y/sigma2beta );
}
}
if ( i % 100 == 0 && i != 0) {
cout << i + 1 << "-th Gene starts working ..." << endl;
}
}
int parGeneSS_part::next(){
std::lock_guard<std::mutex> lockGuard(_mtx2);
if(current_idx >= (int)Ngene){
return -1;
}
current_idx++;
return current_idx-1;
}
void parGeneSS_part::update_by_thread(int thread_id){
while(true){
int idx = next();
if(idx == -1){
break;
}
// cout << idx << endl;
loop_by_gene(idx);
}
}
<file_sep>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <Rcpp.h>
#include <omp.h>
using namespace Rcpp;
using namespace arma;
using namespace std;
void PXem_ss(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const bool& constr, const bool& PX, int& Iteration, const int& maxIter)
{
int m = y.n_rows, T = y.n_cols, p = x1.n_cols, n = z.n_elem;
mat I_p = eye<mat>(p, p);
// Parameter Expansion
double lam = 1.0;
// precomputation
mat x1tx1 = x1.t() * x1;
mat x2tx2 = x2.t() * x2;
mat ytx1 = y.t() * x1;
mat x2tz = x2.t() * z;
mat Sigma_i = I_p;
mat yhat = x1 * B_hat;
mat residual_y = y - yhat;
mat ztilde = x2 * B_hat;
vec residual_z = z - ztilde * alpha;
mat v_iwt = solve(Ve, w.t());
mat wv_i = v_iwt.t();
mat wv_iwt = wv_i * w.t();
mat wa = w * alpha;
mat Lv = Ve;
mat Ls = I_p;
LogLik(0) = -INFINITY;
int iter;
//--------------------------------------------------------------------------------
// EM algrithm
//--------------------------------------------------------------------------------
for (iter = 1; iter < maxIter; iter ++ ) {
// E-step
Sigma_i = lam *lam * (x1tx1 % wv_iwt) + x2tx2 % (wa * wa.t())/sigmaz + I_p/sigmab;
Sigma = inv_sympd(Sigma_i);
mat x1tx1S = x1tx1 % Sigma;
mu = Sigma * (lam * diagvec(wv_i * ytx1) + diagmat(x2tz) * wa /sigmaz);
B_hat = diagmat(mu) * w;
// M-step
// residual
yhat = lam * x1 * B_hat;
residual_y = y - yhat;
ztilde = x2 * B_hat;
residual_z = z - ztilde * alpha;
// v
Ve = residual_y.t()*residual_y/m + lam*lam/m * w.t() * x1tx1S * w;
v_iwt = solve(Ve, w.t());
wv_i = v_iwt.t();
wv_iwt = wv_i * w.t();
// sigmab
sigmab = (sum(mu % mu) + trace(Sigma))/p;
// sigmaz
mat alpha_d_2 = w.t() * (x2tx2 % Sigma) * w;
//sigmaz = sum(residual_z % residual_z)/n + trace(alpha_d_2 * alpha * alpha.t())/n;
sigmaz = 1.0;
// alpha
mat alpha_d_1 = w.t() * (x2tx2 % (mu * mu.t())) * w;
if (!constr) alpha = solve(alpha_d_1 + alpha_d_2, B_hat.t()) * x2tz;
vec residual_z_new = z - ztilde * alpha;
double n_sigmaz_new = sum(residual_z_new % residual_z_new) + trace(alpha_d_2 * alpha * alpha.t());
wa = w * alpha;
// Gamma
if (PX) {
double lam2 = sum(mu.t() * (x1tx1 % wv_iwt) * mu) + trace(wv_i.t() * x1tx1S * w);
lam = sum(mu % diagvec(wv_i * ytx1))/lam2;
}
// current log-likelihood
Lv = chol(Ve, "lower");
Ls = chol(Sigma, "lower");
LogLik(iter) = -(m*T + n) * 0.5 * log(2*datum::pi) - m * sum(log(Lv.diag())) - m*T/2 -
n * 0.5 * log(sigmaz) - n_sigmaz_new/2/sigmaz -
p * 0.5 * log(sigmab) +
sum(log(Ls.diag()));
if ( LogLik(iter) - LogLik(iter - 1) < -1e-8 ){
perror("The likelihood failed to increase!");
}
if (abs(LogLik(iter) - LogLik(iter - 1)) < 1e-5 || rcond(Sigma_i) < 1e-7) {
break;
}
}
if (iter == maxIter) {
Iteration = iter - 1;
} else {
Iteration = iter;
}
// Reduce-step
sigmab = sigmab * lam * lam;
alpha = alpha/lam;
}
// [[Rcpp::export]]
List mammot_PXem_ss(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
bool constr, bool PX, int maxIter) {
if (y.n_rows != x1.n_rows || x1.n_cols != x2.n_cols || z.n_elem != x2.n_rows) {
perror("Dimensions of inpute (x1, y, x2, z) are not matched.");
}
int T = y.n_cols, p = x1.n_cols;
mat Ve = eye<mat>(T, T);
Ve.diag() = vectorise(var(y));
double sigmab = 1;
double sigmaz = 1.0;
vec alpha = zeros<vec>(T);
vec LogLik = zeros<vec>(maxIter);
int Iteration;
mat B_hat = zeros<mat>(x1.n_cols, y.n_cols);
vec mu = zeros<vec>(p);
mat Sigma = eye<mat>(p, p);
PXem_ss(x1, y, x2, z, w, B_hat, mu, Sigma,
sigmab, Ve, alpha, sigmaz,
LogLik, constr, PX, Iteration, maxIter);
vec loglik;
loglik = LogLik.subvec(1, Iteration);
List output = List::create(
Rcpp::Named("x1") = x1,
Rcpp::Named("y") = y,
Rcpp::Named("x2") = x2,
Rcpp::Named("z") = z,
Rcpp::Named("W") = w,
Rcpp::Named("mu") = mu,
Rcpp::Named("Sigma") = Sigma,
Rcpp::Named("B_hat") = B_hat,
Rcpp::Named("sigmab") = sigmab,
Rcpp::Named("Ve") = Ve,
Rcpp::Named("alpha") = alpha,
Rcpp::Named("sigmaz") = sigmaz,
Rcpp::Named("loglik") = loglik);
return output;
}<file_sep>
library(glmnet)
library(foreach)
dyn.load("optim.so")
### optimization part ###
grad_prep <- function(X, Y){
## pre-calculate some metrics for gradient
## args
## X: a list of covariate matrices corresponding to each response
## Y: a list of response vectors
## value
## XY: a list of matrices X^TY for each response
ll = length(Y)
P = ncol(X[[1]])
XY = matrix(0,P,ll)
for(i in 1:ll){
XY[,i] = t(X[[i]])%*%Y[[i]]/nrow(X[[i]])
}
XY
}
cv_helper <- function(N, fold){
## helper function for generating cross-validation sets
## args
## N: number of sample size
## fold: number of folds
## values
## perm: a permutation of 1 to N
## idx: matrix of fold by 2 with first col being starting index and second col being ending index
valid_num = floor(N/fold)
#set.seed(123)
perm = sample(1:N, size = N)
idx1 = seq(1,N,valid_num)
idx2 = c(idx1[-1]-1,N)
list(perm=perm, idx=cbind(idx1,idx2))
}
minmax_lambda <- function(lst){
## get the minimum and maximum of lambda searched in cross-validation of an elastic net model
## args
## lst: an object returned by glmnet
## value
## min_lam: smallest lambda searched in glmnet cross-validation
## max_lam: largest lambda searched in glmnet cross-validation
max_lam = max(unlist(lapply(lst, function(x){max(x$lambda)})))
min_lam = min(unlist(lapply(lst, function(x){min(x$lambda)})))
c(min_lam, max_lam)
}
elastic_net_mse <- function(lst, X_tune, Y_tune, X_test, Y_test){
## evaluate the performance of elastic net on each response
## args
## lst: a list of glmnet object (fitted elastic net model for each response)
## X_tune: a list of covariate matrices corresponding for each response (for tuning lambda)
## Y_tune: a list of response vectors (for tuning lambda)
## X_test: a list of covariate matrices corresponding for each response (for testing performance)
## Y_test: a list of response vectors (for testing performance)
## value
## lam: best performing lambda (on (X_tune,Y_tune)) for each response
## mse: list of matrices with each element being a matrix of predicted vs observed response
## est: estimated effect sizes for each response (B matrix)
P = length(lst)
M = ncol(X_tune[[1]])
lam_V = rep(0, P)
test_res = list()
test_beta = matrix(0, M, P)
for(t in 1:P){
ncv = length(lst[[t]]$lambda)
tmp_mse = rep(0, ncv)
for(k in 1:ncv){
tmp_mse[k] = mean((Y_tune[[t]] - X_tune[[t]]%*%lst[[t]]$glmnet.fit$beta[,k])^2)
}
ss = which.min(tmp_mse)
test_beta[,t] = lst[[t]]$glmnet.fit$beta[,ss]
lam_V[t] = lst[[t]]$lambda[ss]
predicted = X_test[[t]]%*%lst[[t]]$glmnet.fit$beta[,ss]
test_res[[t]] = cbind(Y_test[[t]], predicted)
}
list(lam = lam_V, mse = test_res, est = test_beta)
}
multi_mse <- function(theta_est, X_test, Y_test){
answer = list()
P = ncol(theta_est)
for(t in 1:P){
predicted = X_test[[t]]%*%theta_est[,t]
answer[[t]] = cbind(Y_test[[t]], predicted)
}
answer
}
avg_perm <- function(mse_lst){
fd = length(mse_lst)
P = length(mse_lst[[1]])
rsq = mse = adj_mse = matrix(0, fd, P)
for(f in 1:fd){
for(t in 1:P){
rsq[f,t] = (cor(mse_lst[[f]][[t]])[1,2])^2
mse[f,t] = mean((mse_lst[[f]][[t]][,1]-mse_lst[[f]][[t]][,2])^2)
adj_mse[f,t] = mse[f,t]/var(mse_lst[[f]][[t]][,1])
}
}
cbind(apply(rsq, 2, mean), apply(mse, 2, mean), apply(adj_mse, 2, mean))
#list(rsq = apply(rsq, 2, mean), mse = apply(mse, 2, mean), adj_mse = apply(adj_mse, 2, mean))
}
pred_test <- function(Y){
if(sum(Y[,2]==0)==nrow(Y)|var(Y[,2])==0){
return(2)
}else{
summary(lm(Y[,1]~Y[,2]))$coefficients[2,4]
}
}
glasso <- function(X, Y, X1, Y1, XX, XY, Xnorm, lambda1, lambda2, theta, stepsize = 1e-4, maxiter = 50, eps = 1e-3){
bgt = Sys.time()
M = nrow(XY)
P = length(X)
NN = unlist(lapply(X, nrow))
old_objV1 = rep(0,P)
for(t in 1:P){
old_objV1[t] = 1/2*mean((Y[[t]]-X[[t]]%*%theta[,t])^2)
}
#cat("Training error: ", old_objV1, '\n')
old_objV2 = rep(0,P)
for(t in 1:P){
old_objV2[t] = 1/2*mean((Y1[[t]]-X1[[t]]%*%theta[,t])^2)
}
#cat("Testing error: ", old_objV2, '\n')
beta_j_lasso = rep(0, P)
tmp_XYj = 0
if(!is.loaded("wrapper")){
dyn.load("optim.so")
}
for(i in 1:maxiter){
bgt = Sys.time()
res = .Call("wrapper", XX, XY, theta, M, P, beta_j_lasso, lambda1, lambda2, Xnorm)
edt = Sys.time()
#print(edt-bgt)
new_objV1 = new_objV2 = rep(0,P)
for(t in 1:P){
new_objV1[t] = 1/2*mean((Y[[t]]-X[[t]]%*%theta[,t])^2)
}
#cat("Training error: ", new_objV1, '\n')
for(t in 1:P){
new_objV2[t] = 1/2*mean((Y1[[t]]-X1[[t]]%*%theta[,t])^2)
}
#cat("Testing error: ", new_objV2, '\n')
if(mean(new_objV2) > mean(old_objV2)|mean(new_objV1) > mean(old_objV1)){
break
}else{
old_objV2 = new_objV2
}
if(max(abs(new_objV1-old_objV1)) < eps){
break
}else{
old_objV1 = new_objV1
}
}
#edt = Sys.time()
#print(edt-bgt)
list(est = theta, avg_tune_err = mean(new_objV2), tune_err=new_objV2)
}
glasso_no_early_stopping <- function(X, Y, XX, XY, Xnorm, lambda1, lambda2, theta, stepsize = 1e-4, maxiter = 50, eps = 1e-3){
M = nrow(XY)
P = length(X)
NN = unlist(lapply(X, nrow))
old_objV1 = rep(0,P)
for(t in 1:P){
old_objV1[t] = 1/2*mean((Y[[t]]-X[[t]]%*%theta[,t])^2)
}
#cat("Training error: ", mean(old_objV1), '\n')
beta_j_lasso = rep(0, P)
tmp_XYj = 0
if(!is.loaded("wrapper")){
dyn.load("optim.so")
}
for(i in 1:maxiter){
res = .Call("wrapper", XX, XY, theta, M, P, beta_j_lasso, lambda1, lambda2, Xnorm)
new_objV1 = rep(0,P)
for(t in 1:P){
new_objV1[t] = 1/2*mean((Y[[t]]-X[[t]]%*%theta[,t])^2)
}
#cat("Training error: ", mean(new_objV1), '\n')
if(max(abs(new_objV1-old_objV1)) < eps|mean(new_objV1) > mean(old_objV1)){
break
}else{
old_objV1 = new_objV1
}
}
list(est = theta, avg_train_err = mean(new_objV1), train_err = new_objV1)
}
# given y, x
multiEstB <- function(x, y, fold = 5) {
bgt = Sys.time()
N <- nrow(x)
P = ncol(y)
ntune <- 50
## expr files ##
Y = list()
for(t in 1:P){
Y[[t]] = data.frame(V1 = 1:N, V2 = y[, t])
}
ssize = unlist(lapply(Y, nrow))
T_num = length(Y)
## genotype files ##
dose = data.frame(1:N, x)
for(j in 2:ncol(dose)){ ## if no 'dose' column
# for(j in 3:ncol(dose)){
dose[,j] = dose[,j] - mean(dose[,j])
}
## covariance matrix ##
tmp = as.matrix(dose[,-1])
XX = t(tmp)%*%as.matrix(tmp)/N
Xnorm = diag(XX)
remove(tmp); remove(XX)
#sub_id = matrix(unlist(strsplit(dose[,1], "->")), ncol=2, byrow=T)[,1]
sub_id = dose[,1]
M = ncol(dose) - 1
sub_id_map = list()
for(t in 1:T_num){
tmp = rep(0, nrow(Y[[t]]))
for(j in 1:length(tmp)){
tmp[j] = which(sub_id==Y[[t]][j,1])
}
sub_id_map[[t]] = tmp
}
cv_config = cv_helper(N, fold)
cv_perm = cv_config$perm
cv_idx = cv_config$idx
single_res_test = list()
single_lam = matrix(0,fold,P)
single_theta_est = list()
multi_res_test = list()
multi_lam = matrix(0,fold,2)
multi_theta_est = list()
multi_res_test2 = list()
multi_lam2 = array(0, dim=c(fold, P, 2))
multi_theta_est2 = list()
res_tune = list()
rec_lamv = matrix(0, fold, ntune)
for(f in 1:fold){
test_index = cv_perm[cv_idx[f,1]:cv_idx[f,2]]
test_id = sub_id[test_index]
tuning_index = cv_perm[cv_idx[f%%fold+1,1]:cv_idx[f%%fold+1,2]]
tuning_id = sub_id[tuning_index]
X_test = list()
Y_test = list()
X_tune = list()
Y_tune = list()
X_train = list()
Y_train = list()
for(t in 1:T_num){
X_train_tmp = sub_id_map[[t]][!(sub_id_map[[t]]%in%c(test_index,tuning_index))]
Y_train_tmp = !(sub_id_map[[t]]%in%c(test_index,tuning_index))
X_tuning_tmp = sub_id_map[[t]][(sub_id_map[[t]]%in%tuning_index)]
Y_tuning_tmp = (sub_id_map[[t]]%in%tuning_index)
X_test_tmp = sub_id_map[[t]][(sub_id_map[[t]]%in%test_index)]
Y_test_tmp = (sub_id_map[[t]]%in%test_index)
X_train[[t]] = apply(as.matrix(dose[X_train_tmp,-c(1)]),2,as.numeric)
Y_train[[t]] = Y[[t]][Y_train_tmp, 2]
X_tune[[t]] = apply(as.matrix(dose[X_tuning_tmp,-c(1)]),2,as.numeric)
Y_tune[[t]] = Y[[t]][Y_tuning_tmp, 2]
X_test[[t]] = apply(as.matrix(dose[X_test_tmp,-c(1)]),2,as.numeric)
Y_test[[t]] = Y[[t]][Y_test_tmp, 2]
}
## model training ##
## train elastic net and used average lambda as tuning parameters ##
single_initial_est = matrix(0, ncol(X_train[[1]]), T_num)
single_summary = list()
for(t in 1:T_num){
tt = cv.glmnet(X_train[[t]], Y_train[[t]], alpha = 0.5, nfolds = 5)
single_summary[[t]] = tt
single_initial_est[,t] = tt$glmnet.fit$beta[,which.min(tt$cvm)]
}
## performance of Elastic net on tuning and testing data with various tuning parameters
els_output = elastic_net_mse(single_summary, X_tune, Y_tune, X_test, Y_test)
single_res_test[[f]] = els_output$mse
single_lam[f,] = els_output$lam
single_theta_est[[f]] = els_output$est
remove(els_output)
## use elastic net ests row norm as weights ##
lam_range = minmax_lambda(single_summary)
sig_norm = apply(single_initial_est, 1, function(x){sqrt(sum(x^2))})
sig_norm[sig_norm==0] = rep(min(sig_norm[sig_norm>0]), sum(sig_norm==0))/2
sig_norm = sig_norm/sum(sig_norm)
weights2 = 1/sig_norm; weights2 = weights2/sum(weights2);
tis_norm = apply(single_initial_est, 2, function(x){sum(abs(x))})
tis_norm[tis_norm==0] = rep(min(tis_norm[tis_norm>0]), sum(tis_norm==0))/2
tis_norm = tis_norm/sum(tis_norm)
weights1 = 1/tis_norm; weights1 = weights1/sum(weights1);
lam_V = seq(lam_range[1], lam_range[2], length.out = ntune)
#lam_V = seq(lam_range[1], lam_range[2], length.out = ntune)
initial_numeric = as.numeric(single_initial_est)
remove(single_summary); remove(single_initial_est);
## preparation
XY = grad_prep(X_train, Y_train)
XX_train = lapply(X_train, function(x){t(x)%*%x/nrow(x)})
spsz = unlist(lapply(X_train,nrow))
#res_tune = rep(0, ntune)
res_tune[[f]] = array(-1, dim=c(ntune, ntune, P))
#best.lam = 0
rec_lamv[f,] = lam_V
for(lam1 in 1:ntune){
for(lam2 in 1:ntune){
single_est = matrix(initial_numeric, M, P)
ans = glasso(X=X_train, Y=Y_train, X1=X_tune, Y1=Y_tune, XX=XX_train, XY=XY,
Xnorm=Xnorm, lambda1=lam_V[lam1]/spsz, lambda2=lam_V[lam2], theta=single_est)
if(sum(ans$est!=0)>0){
res_tune[[f]][lam1,lam2, ] = ans$tune_err
#cat("lambda1=",lam_V[lam1], "; lambda2=", lam_V[lam2], "; avg tune err=", ans$avg_tune_err, '\n')
remove(single_est); remove(ans);
}else{
remove(single_est); remove(ans);
break
}
}
}
avg_tune_res = apply(res_tune[[f]], c(1,2), mean)
best.lam = which(avg_tune_res == min(avg_tune_res[avg_tune_res>=0]), arr.ind = TRUE)[1,]
single_est = matrix(initial_numeric, M, P)
ans = glasso(X=X_train, Y=Y_train, X1=X_tune, Y1=Y_tune, XX=XX_train, XY=XY,
Xnorm=Xnorm, lambda1=lam_V[best.lam[1]]/spsz, lambda2=lam_V[best.lam[2]], theta=single_est)
multi_res_test[[f]] = multi_mse(ans$est, X_test, Y_test)
multi_lam[f,] = lam_V[best.lam]
multi_theta_est[[f]] = ans$est
remove(single_est); remove(ans);
}
## generate an estimate with whole data ###############################################################################
#######################################################################################################################
X_all = list()
Y_all = list()
for(t in 1:T_num){
X_all_tmp = sub_id_map[[t]]
X_all[[t]] = apply(as.matrix(dose[X_all_tmp,-c(1)]),2,as.numeric)
Y_all[[t]] = Y[[t]][,2]
}
# initial values
single_initial_est = matrix(0, ncol(X_train[[1]]), T_num)
for(t in 1:T_num){
tt = cv.glmnet(X_all[[t]], Y_all[[t]], alpha = 0.5, nfolds = 5)
single_initial_est[,t] = tt$glmnet.fit$beta[,which.min(tt$cvm)]
}
sig_norm = apply(single_initial_est, 1, function(x){sqrt(sum(x^2))})
sig_norm[sig_norm==0] = rep(min(sig_norm[sig_norm>0]), sum(sig_norm==0))/2
sig_norm = sig_norm/sum(sig_norm)
weights2 = 1/sig_norm; weights2 = weights2/sum(weights2);
tis_norm = apply(single_initial_est, 2, function(x){sum(abs(x))})
tis_norm[tis_norm==0] = rep(min(tis_norm[tis_norm>0]), sum(tis_norm==0))/2
tis_norm = tis_norm/sum(tis_norm)
weights1 = 1/tis_norm; weights1 = weights1/sum(weights1);
spsz = unlist(lapply(X_all,nrow))
initial_numeric = as.numeric(single_initial_est)
#remove(single_initial_est)
XY = grad_prep(X_all, Y_all)
XX_all = lapply(X_all, function(x){t(x)%*%x/nrow(x)})
tmp_res = rep(0, fold)
for(f in 1:fold){
ans = glasso_no_early_stopping(X=X_all, Y=Y_all, XX=XX_all, XY=XY, Xnorm=Xnorm,
lambda1=multi_lam[f,1]/spsz, lambda2=multi_lam[f,2], theta=matrix(initial_numeric,M,P))
tmp_res[f] = ans$avg_train_err
}
final.lam = multi_lam[which.min(tmp_res),]
ans = glasso_no_early_stopping(X=X_all, Y=Y_all, XX=XX_all, XY=XY, Xnorm=Xnorm,
lambda1=final.lam[1]/spsz, lambda2=final.lam[2], theta=matrix(initial_numeric,M,P))
edt = Sys.time()
print(edt-bgt)
ans$est
}
# B_hat <- multiEstB(x1, y)
# par(mfrow = c(1, 2))
# image(B)
# image(B_hat)/2
# dev.off()
# norm(B-B_hat, "2")
<file_sep>
source("PartType1ErrCOR.R")
assig = function(n_args){
# example:
# n_args = c(2, 3, 4)
cargs <- vector("list", length(n_args))
for(i in 1:length(n_args)) cargs[[i]] = 1:n_args[i]
t(expand.grid(cargs))
}
n_args = c(3, 5, 3, 2, 2)
jobs = assig(n_args)
h_z <- 0.01
main <- function(number0){
number <- as.numeric(number0)
a0 <- 1
rhoX <- c(0.2, 0.5, 0.8)[jobs[1, number]]
h_c <- c(0.025, 0.05, 0.1, 0.2, 0.4)[jobs[2, number]]
s = c(0.1, 0.5, 0.9)[1]
rhoW = c(0.2, 0.5, 0.8)[jobs[3, number]]
Ti <- 3
nz_ti = c(1, 2, 3)[jobs[4, number]]
batch <- (1:10)[jobs[5, number]]
rhoE = 0.5
Rep = 500
set.seed(20102014*batch)
case = c(rhoX = rhoX, rhoW = rhoW, h_c = h_c, s = s, nz_ti = nz_ti, batch = batch)
print(case)
PartType1Err(h_z, h_c, s, rhoX, rhoE, rhoW, nz_ti, Ti, a0, batch, Rep)
}
args <- commandArgs(TRUE)
main(args[1])
<file_sep>source("/home/xingjies/mammot/qqplot5.R")
source("/home/xingjies/R/ggplot_theme_publication.R")
############################################################################################################
############################################################################################################
################################################ QQ plot (type 1 error) ####################################
############################################################################################################
############################################################################################################
for(k in 1:5){
case <- 1
plot_list <- vector("list", 9)
for (j in 1:3) {
for (i in 1:3) {
h_z <- c(0, 0.01)[1]
h_c <- c(0.025, 0.05, 0.1, 0.2, 0.4)[k]
rhoX = c(0.2, 0.5, 0.8)[i]
s = c(0.1, 0.5, 0.9)[j]
batch <- list.files(pattern = paste0("pvalue_hz", h_z*10, "_hc", h_c*10, "_rhoX", rhoX*10, "_s", s*10, "_batch-*"))
pvalue <- NULL
for (l in batch) {
pvalue <- rbind(pvalue, read.table(l, header=F))
}
pvalue[is.na(pvalue)] <- 1
pv <- list(MAMMOT = pvalue[, 1],
MAMMOT_S = pvalue[, 2],
MultiXcan = pvalue[, 3],
MultiXcan_S = pvalue[, 4],
UTMOST = pvalue[, 5])
plot_list[[case]] <- qqunif.plot(pv, xlab="Expected: -log10(p-value)", ylab = "Observed: -log10(p-value)",
mytitle = bquote((s~","~rho[X])==(.(s)~","~.(rhoX))))
case <- case + 1
}
}
library(gridExtra) # also loads grid
outfile = paste0("../example1_qqplot_", "h_c_", k,".png")
png(filename = outfile, width = 480, height = 480, units = "mm", res=200, type = "cairo")
grid.arrange(grobs=plot_list, nrow = 3)
#grid_arrange_shared_legend(grobs=plot_list, nrow = 3, position='bottom')
dev.off()
}
############################################################################################################
############################################################################################################
#################################################### power plot ############################################
############################################################################################################
############################################################################################################
method <- c("MAMMO", "S-MAMMO", "MultiXcan", "S-MultiXcan", "UTMOST")
h_z <- c(0, 0.01)[2]
ymax <- ifelse(h_z==0, 0.2, 1)
gg_df <- NULL
for(i in 1:5) {
for (j in 1:3) {
for (k in 1:3) {
h_c <- c(0.025, 0.05, 0.1, 0.2, 0.4)[i]
rhoX = c(0.2, 0.5, 0.8)[j]
s = c(0.1, 0.5, 0.9)[k]
batch <- list.files(pattern = paste0("pvalue_hz", h_z*10, "_hc", h_c*10, "_rhoX", rhoX*10, "_s", s*10, "_batch-*"))
pvalue <- NULL
for (l in batch) {
pvalue <- rbind(pvalue, read.table(l, header=F))
}
pvalue[is.na(pvalue)] <- 1
power <- apply(pvalue < 0.05, 2, mean, na.rm=T)
gg_df <- rbind(gg_df, data.frame(method, power, h_c, rhoX, s))
}
}
}
gg_df$method <- ordered(gg_df$method, levels = c("MAMMO", "S-MAMMO", "MultiXcan", "S-MultiXcan", "UTMOST"))
gg_df$h_c <- factor(gg_df$h_c)
library(ggplot2)
outfile = paste0("../power_hz", h_z*100, ".png")
pl <- ggplot(data=gg_df, aes(x = h_c, y = power, fill = method)) + labs(x = expression(h[c]^2), y="Power") +
geom_bar(stat="identity", position=position_dodge())+
coord_cartesian(ylim=c(0, ymax)) +
facet_grid(s~rhoX, labeller = label_bquote(rows = s: .(s), cols= rho[X]: .(rhoX))) +
scale_fill_manual(values=c("#FDBF6F", "#FF7F00", "#A6CEE3", "#1F78B4","#6A3D9A"),
labels=c("TisCoMM", expression(TisCoMM-S^2), "MultiXcan", "S-MultiXcan", "UTMOST")) +
#scale_colour_manual(labels=c("TisCoMM", "S-MAMMO", "MultiXcan", "S-MultiXcan", "UTMOST")) +
theme_Publication(base_size=30, border_col=NA)
ggsave(outfile, plot=pl, width = 360, height = 360, units = "mm", dpi=300, type = "cairo")
<file_sep>#ifndef PXem_ss_hpp
#define PXem_ss_hpp
#include <RcppArmadillo.h>
//#include <Rcpp.h>
//#include <omp.h>
#include <math.h>
using namespace Rcpp;
using namespace arma;
using namespace std;
void PXem_ss(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const bool& constr, const bool& PX, int& Iteration, const int& maxIter);
List mammot_PXem_ss(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
bool constr, bool PX, int maxIter);
#endif /* PXem_ss_hpp */<file_sep># TisCoMM
TisCoMM leverages the co-regulation of genetic variations across different tissues explicitly via a unified probabilistic model. TisCoMM not only performs hypothesis testing to prioritize gene-trait associations black, but also detects the tissue-specific role of candidate target genes in complex traits. To make use of widely available GWAS summary statistics, we extend TisCoMM to use summary-level data, namely, TisCoMM-S$^2$.
**TisCoMM** R package implements the TisCoMM method described in [Shi 2020](https://www.biorxiv.org/content/10.1101/789396v1). Get started with the [User Manual](https://github.com/XingjieShi/TisCoMM/blob/master/vignettes/TisCoMM.pdf).
## Installation
To install the development version of **TisCoMM**, it's easiest to use the 'devtools' package. Note that **TisCoMM** depends on the 'Rcpp' package, which also requires appropriate setting of Rtools and Xcode for Windows and Mac OS/X, respectively.
```{r, fig.show='hold', eval=FALSE}
library(devtools)
install_github("XingjieShi/TisCoMM")
```
## Usage
```{r, fig.show='hold', eval=FALSE}
library(TisCoMM)
?TisCoMM
```
## Replicate simulation results in Shi et al. (2019)
All the simulation results can be reproduced by using the code in folder [simulation](https://github.com/XingjieShi/TisCoMM/tree/master/simulation). Before running simulation to reproduce the results, please familiarize yourself with **TisCoMM** using 'TisCoMM' vignette.
1. Simulation results for multi-tissue joint test can be reproduced by following steps:
- ExampleOne.R: This function can be run in a HPC cluster (with minor revisions, it could be run on a PC), it will output files, named pvalue_hz0.1_hc0.25_rhoX5_s5_batch-6.txt, which contain inference results of each replicate, for all multi-tissue TWAS methods: TisCoMM, TisCoMM-S$^2$, MultiXcan, S-MultiXcan and UTMOST.
- ExampleOnePlot.R: This function produces simulation figures of joint test in Shi et al. (2019).
2. Simulation results for tissue-specific test can be reproduced by following steps:
- PartCoMMCOR.R: This function can be run in a HPC cluster (with minor revisions, it could be run on a PC), it will output files, named part_hc4_rhoX8_rhoW8nz_ti2_batch-2.rds, which contain inference results of each replicate, for all single-tissue TWAS methods: CoMM, PrediXcan, and TWAS.
- SummaryCOR.R: This function produces simulation figures of tissue-specific test in Shi et al. (2019).
## Reference
[A tissue-specific collaborative mixed model for jointly analyzing multiple tissues in transcriptome-wide association studies](https://www.biorxiv.org/content/10.1101/789396v1)
<file_sep>#ifndef data_loader_hpp
#define data_loader_hpp
#include <RcppArmadillo.h>
//#include <Rcpp.h>
//#include <omp.h>
#include <stdio.h>
#include <bitset>
#include <math.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "plinkfun.hpp"
//#include "lmm_covar_pxem.hpp"
//#include "mammot_covar_vbPXem.hpp"
#include "readExprFile.hpp"
using namespace std;
using namespace Rcpp;
using namespace arma;
Rcpp::List getColNum_Header(std::string filename, char delimiter);
Rcpp::List dataLoader(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3,
std::string stringname4, std::string stringname5, int whCol);
Rcpp::List dataLoaderSS(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3,
std::string stringname4, std::string stringnameSS);
#endif /* data_loader_hpp */
<file_sep># Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: <PASSWORD>
mammot_PXem <- function(x1, y, x2, z, w, constr, PX, maxIter) {
.Call(`_TisCoMM_mammot_PXem`, x1, y, x2, z, w, constr, PX, maxIter)
}
ADW <- function(x, y) {
.Call(`_TisCoMM_ADW`, x, y)
}
mammot_part_test <- function(x1, y, x2, z, w, constrFactor, PX, maxIter) {
.Call(`_TisCoMM_mammot_part_test`, x1, y, x2, z, w, constrFactor, PX, maxIter)
}
mammotSS_part_test <- function(x1, y, x2, z, w, constrFactor, PX, maxIter) {
.Call(`_TisCoMM_mammotSS_part_test`, x1, y, x2, z, w, constrFactor, PX, maxIter)
}
mammot_PXem_part <- function(x1, y, x2, z, w, constrFactor, PX, maxIter) {
.Call(`_TisCoMM_mammot_PXem_part`, x1, y, x2, z, w, constrFactor, PX, maxIter)
}
mammotSS_part_est <- function(x1, y, x2, z, w, B_hat, mu, Sigma, sigmab, Ve, alpha, constrFactor, PX, maxIter) {
.Call(`_TisCoMM_mammotSS_part_est`, x1, y, x2, z, w, B_hat, mu, Sigma, sigmab, Ve, alpha, constrFactor, PX, maxIter)
}
mammotSS_PXem_part <- function(x1, y, x2, z, w, constrFactor, PX, maxIter) {
.Call(`_TisCoMM_mammotSS_PXem_part`, x1, y, x2, z, w, constrFactor, PX, maxIter)
}
lmm_pxem <- function(y, w, x, maxIter) {
.Call(`_TisCoMM_lmm_pxem`, y, w, x, maxIter)
}
mammot_PXem_ss <- function(x1, y, x2, z, w, constr, PX, maxIter) {
.Call(`_TisCoMM_mammot_PXem_ss`, x1, y, x2, z, w, constr, PX, maxIter)
}
#' @title
#' mammot
#' @description
#'
#'
#' @param stringname1 prefix for eQTL genotype file with plink format (bim, bed).
#' @param stringname2 prefix for reference panal GWAS genotype file with plink format (bim, bed, fam).
#' @param stringname3 gene expression file with full name.
#' @param stringname4 covariates file for eQTL data.
#' @param stringname5 GWAS summary statisitcs, which has specific form.
#' @param whCol specify which phenotype is used in fam. For example, when whCol = 2, the seven-th column of fam file will be used as phenotype.
#' @param bw the number of downstream and upstream SNPs that are considered as cis-SNP within a gene.
#'
#' @return List of model parameters
#'
#' @examples
#' ##Working with no summary statistics, no covariates and options
#' file1 = "1000G.EUR.QC.1";
#' file2 = "NFBC_filter_mph10";
#' file3 = "Geuvadis_gene_expression_qn.txt";
#' file4 = "";
#' file5 = "pc5_NFBC_filter_mph10.txt";
#' whichPheno = 1;
#' bw = 500000;
#'
#' fm = mammotSS_testing_run(file1,file2,file3, file4,file5, whichPheno, bw);
#'
#' @details
#' \code{mammotSS_testing_run} fits the mammot model. It requires to provide plink binary eQTL genotype file (bim, bed)
#' the GWAS summary statisitcs file (txt), gene expression file for eQTL.
#' @export
NULL
#' @title
#' CoMM
#' @description
#' CoMM to dissecting genetic contributions to complex traits by leveraging regulatory information.
#'
#' @param stringname1 prefix for eQTL genotype file with plink format (bim, bed).
#' @param stringname2 prefix for GWAS genotype and phenotype file with plink format (bim, bed, fam).
#' @param stringname3 gene expression file with full name.
#' @param stringname4 covariates file for eQTL data.
#' @param stringname5 covariates file for GWAS data, e.g. top 10 PCs.
#' @param whCol specify which phenotype is used in fam. For example, when whCol = 2, the seven-th column of fam file will be used as phenotype.
#' @param bw the number of downstream and upstream SNPs that are considered as cis-SNP within a gene.
#'
#' @return List of model parameters
#'
#' @examples
#' ##Working with no summary statistics, no covariates and options
#' file1 = "1000G.EUR.QC.1";
#' file2 = "NFBC_filter_mph10";
#' file3 = "Geuvadis_gene_expression_qn.txt";
#' file4 = "";
#' file5 = "pc5_NFBC_filter_mph10.txt";
#' whichPheno = 1;
#' bw = 500000;
#'
#' fm = CoMM_testing_run(file1,file2,file3, file4,file5, whichPheno, bw);
#'
#' @details
#' \code{CoMM} fits the CoMM model. It requires to provide plink binary eQTL genotype file (bim, bed)
#' the GWAS plink binary file (bim, bed, fam), gene expression file for eQTL.
#' @export
mammot <- function(stringname1, stringname2, stringname3, stringname4, stringname5, whCol, bw) {
.Call(`_TisCoMM_mammot`, stringname1, stringname2, stringname3, stringname4, stringname5, whCol, bw)
}
mammot_paral <- function(stringname1, stringname2, stringname3, stringname4, stringname5, whCol, bw, coreNum) {
.Call(`_TisCoMM_mammot_paral`, stringname1, stringname2, stringname3, stringname4, stringname5, whCol, bw, coreNum)
}
mammotSS <- function(stringname1, stringname2, stringname3, stringname4, stringname5, lam, bw) {
.Call(`_TisCoMM_mammotSS`, stringname1, stringname2, stringname3, stringname4, stringname5, lam, bw)
}
mammotSS_paral <- function(stringname1, stringname2, stringname3, stringname4, stringname5, lam, bw, coreNum) {
.Call(`_TisCoMM_mammotSS_paral`, stringname1, stringname2, stringname3, stringname4, stringname5, lam, bw, coreNum)
}
mammot_part_paral <- function(stringname1, stringname2, stringname3, stringname4, stringname5, targetList, whCol, bw, coreNum) {
.Call(`_TisCoMM_mammot_part_paral`, stringname1, stringname2, stringname3, stringname4, stringname5, targetList, whCol, bw, coreNum)
}
mammotSS_part_paral <- function(stringname1, stringname2, stringname3, stringname4, stringname5, targetList, lam, bw, coreNum) {
.Call(`_TisCoMM_mammotSS_part_paral`, stringname1, stringname2, stringname3, stringname4, stringname5, targetList, lam, bw, coreNum)
}
getColNum_Header <- function(filename, delimiter) {
.Call(`_TisCoMM_getColNum_Header`, filename, delimiter)
}
dataLoader <- function(stringname1, stringname2, stringname3, stringname4, stringname5, whCol) {
.Call(`_TisCoMM_dataLoader`, stringname1, stringname2, stringname3, stringname4, stringname5, whCol)
}
dataLoaderSS <- function(stringname1, stringname2, stringname3, stringname4, stringnameSS) {
.Call(`_TisCoMM_dataLoaderSS`, stringname1, stringname2, stringname3, stringname4, stringnameSS)
}
read_GWAS <- function(filename, P) {
.Call(`_TisCoMM_read_GWAS`, filename, P)
}
<file_sep># simulation 2
# Type I effor rate evluation under NULL models
library(mvtnorm)
library(glmnet)
library(Rcpp)
library(CoMM)
library(TisCoMM)
sourceCpp("vb_aux.cpp")
source("functions.r")
source("multiEstB.R")
#ourceCpp("PXem_part.cpp")
#sourceCpp("PXem.cpp")
PartType1Err <- function(h_z, h_c, s, rhoX, rhoE, rhoW, nz_ti, Ti, a0, batch, Rep)
{
PX <- T
tic <- Sys.time()
pvalue_comm <- matrix(0, ncol=Ti, nrow=Rep)
pvalue_mammotpart <- matrix(0, ncol=Ti, nrow=Rep)
pvalue_predixcan <- matrix(0, ncol=Ti, nrow=Rep)
pvalue_TWAS <- matrix(0, ncol=Ti, nrow=Rep)
alpha_mammotpart <- matrix(0, ncol=Ti, nrow=Rep)
alpha_comm <- matrix(0, ncol=Ti, nrow=Rep)
# mammot, mammot_ss, multixcan, multixcan_ss, utmost.
for(i in 1:Rep) {
m <- 400
n <- 5000
p <- 400
# genotypes in eQTL
x1 <- x2snp(rmvnorm(m, mean=rep(0, p), sigma = AR(rhoX, p)))
x1_snp <- x1
x1mean <- matrix(rep(colMeans(x1), m), ncol=p, byrow = T)
x1sd <- matrix(rep(apply(x1, 2, sd), m), ncol=p, byrow = T)
x1 <- (x1 - x1mean)/x1sd/sqrt(m)
# genotypes in GWAS
x2 <- x2snp(rmvnorm(n, mean=rep(0, p), sigma = AR(rhoX, p)))
x2_snp <- x2
x2mean <- matrix(rep(colMeans(x2), n), ncol=p, byrow = T)
x2sd <- matrix(rep(apply(x2, 2, sd), n), ncol=p, byrow = T)
x2 <- (x2 - x2mean)/x2sd/sqrt(n)
# eQTL coefficient matrix, across Ti tissues.
b <- rnorm(p)
W <- matrix(0, nrow = p, ncol=Ti)
idx <- sample(p, s*p, replace=FALSE)
W[idx, ] <- rmvnorm(s*p, mean=rep(0, Ti), sigma = AR(rhoW, Ti))
B <- diag(b) %*% W
lp <- x1 %*% B
# error matrix in eQTL.
if (Ti != 1){
sd.lp = diag(sqrt(diag(var(lp)) * (1/h_c - 1)))
Ve = sd.lp %*% AR(rhoE, Ti) %*% sd.lp
E <- rmvnorm(m, mean = rep(0, Ti), sigma = Ve)
} else {
sd.lp = sqrt(diag(var(lp)* (1/h_c - 1)))
E <- rnorm(m, sd = sd.lp)
}
y <- lp + E
if (h_z == 0) z <- rnorm(n, 0, sqrt(3)) else {
a <- rep(0, Ti)
#a <- runif(Ti, -1, 1)
a[1:nz_ti] <- a0
lp_z <- x2 %*% B %*% a
sig2 <- c(var(lp_z)) * ((1-h_z)/h_z)
z <- lp_z + rnorm(n, 0, sqrt(sig2))
}
maxIter = 3000
y <- resid(lm(y~rep(1, m)))
z <- resid(lm(z~rep(1, n)))
# mammot (individual data)
# adaptive weight for mammot and mammot_ss.
w <- matrix(1, nrow=p, ncol=1)
if(Ti != 1) w = ADW(x1, y)
for (ti in 1:Ti) {
constrFactor <- numeric(Ti)
constrFactor[ti] <- 1
fit <- mammot_part_test(x1, y, x2, z, w, constrFactor, TRUE, maxIter=2000)
pvalue_mammotpart[i, ti] <- pchisq(fit$chisq, 1, lower.tail=F)
}
# comm
w1 = matrix(rep(1, m), ncol=1)
w2 = matrix(rep(1, n), ncol=1)
for (ti in 1:Ti) {
fmHa = CoMM_covar_pxem(y[, ti], z, x1, x2, w1, w2, constr = 0)
fmH0 = CoMM_covar_pxem(y[, ti], z, x1, x2, w1, w2, constr = 1)
loglikHa = max(fmHa$loglik, na.rm=T)
loglikH0 = max(fmH0$loglik, na.rm=T)
tstat = 2 * (loglikHa - loglikH0)
pvalue_comm[i, ti] <- pchisq(tstat, 1, lower.tail=F)
alpha_comm[i, ti] <- fmHa$alpha
}
# prediXcan
for (ti in 1:Ti) {
fit_elasnet <- cv.glmnet(x1, y[, ti], type.measure="mse", alpha=0.5, family="gaussian")
elasnet_M <- predict(fit_elasnet, s=fit_elasnet$lambda.min, newx=x2)
if (var(elasnet_M) == 0) {
pvalue_predixcan[i, ti] <- 1
} else {
bet_lm <- coefficients(summary(lm(z~elasnet_M)))
pvalue_predixcan[i, ti] <- bet_lm[2,4]
}
}
# TWAS
for (ti in 1:Ti) {
setwd(paste0("./","twasTemp"))
path <- paste0("part_hc", h_c*10, "_rhoX", rhoX*10, "_rhoW", rhoW*10, "nz_ti", nz_ti, "_batch-", batch)
base <- paste(path, ti, i, sep="_")
dir.create(base)
setwd(base)
ad2bed(x1_snp, y[, ti], stringname = base, plink_exe="/mnt/home/xuliu/Xingjie/plink/plink")
system("rm -rf *.tfam");
system("rm -rf *.tped");
system(paste0("/mnt/home/xuliu/Xingjie/gemma/bin/gemma -bfile ", base, " -bslmm 1 -w 5000 -s 5000 -o BSLMM"))
param = read.table("./output/BSLMM.param.txt", header = T)
setwd("..")
system(paste0("rm -r ", base))
beta_hat_TWAS = param[,5] + param[,6]*param[,7]
impute_M <- x2 %*% (beta_hat_TWAS*apply(x1_snp, 2, sd)) # scale back
if (var(impute_M) == 0) {
pvalue_TWAS[i, ti] <- 1
} else {
bet_lm <- coefficients(summary(lm(z~impute_M)))
pvalue_TWAS[i, ti] <- bet_lm[2,4]
}
setwd("..")
}
}
toc <- Sys.time()
print(toc - tic)
saveRDS(list(pvalue_mammotpart = pvalue_mammotpart,
pvalue_comm = pvalue_comm,
pvalue_predixcan = pvalue_predixcan,
pvalue_TWAS = pvalue_TWAS),
paste0(path, ".rds")
)
}
<file_sep># simulation I
# Type I effor rate evluation under NULL models
library(mvtnorm)
library(GBJ)
library(Rcpp)
library(TisCoMM)
source("functions.r")
source("multiEstB.R")
#sourceCpp("PXem_ss.cpp")
#sourceCpp("PXem.cpp")
evalType1Err <- function(h_z, h_c, s, rhoX, rhoE, Ti, batch, Rep = 1000)
{
PX <- T
tic <- Sys.time()
pvalue <- matrix(0, ncol=5, nrow=Rep)
# mammot, mammot_ss, multixcan, multixcan_ss, utmost.
for(i in 1:Rep) {
m = 400
n = 5000
p = 300
# genotypes in eQTL
x1 <- x2snp(rmvnorm(m, mean=rep(0, p), sigma = AR(rhoX, p)))
x1mean <- matrix(rep(colMeans(x1), m), ncol=p, byrow = T)
x1 <- (x1 - x1mean)
# genotypes in GWAS
x2 <- x2snp(rmvnorm(n, mean=rep(0, p), sigma = AR(rhoX, p)))
x2mean <- matrix(rep(colMeans(x2), n), ncol=p, byrow = T)
x2 <- (x2 - x2mean)
# eQTL coefficient matrix, across Ti tissues.
b <- rnorm(p)
W <- matrix(0, nrow = p, ncol=Ti)
for (j in 1:Ti)
W[sample(p, s*p, replace=FALSE),j] <- 1
B <- diag(b) %*% W
lp <- x1 %*% B
# error matrix in eQTL.
if (Ti != 1){
sd.lp = diag(sqrt(diag(var(lp)) * (1/h_c - 1)))
Ve = sd.lp %*% AR(rhoE, Ti) %*% sd.lp
E <- rmvnorm(m, mean = rep(0, Ti), sigma = Ve)
} else {
sd.lp = sqrt(diag(var(lp)* (1/h_c - 1)))
E <- rnorm(m, sd = sd.lp)
}
y <- lp + E
if (h_z == 0) z <- rnorm(n, 0, sqrt(3)) else {
a <- runif(Ti, -1, 1)
lp_z <- x2 %*% B %*% a
#h_z <- .01
sig2 <- c(var(lp_z)) * ((1-h_z)/h_z)
z <- lp_z + rnorm(n, 0, sqrt(sig2))
}
maxIter = 3000
# mammot (individual data)
# adaptive weight for mammot and mammot_ss.
w <- matrix(1, nrow=p, ncol=1)
if(Ti != 1) w = adw(x1, y)
fit_PX <- mammot_PXem(x1, y, x2, z, w, FALSE, PX, maxIter=maxIter)
fit_PX_0 <- mammot_PXem(x1, y, x2, z, w, TRUE, PX, maxIter=maxIter)
chisq <- 2*(max(fit_PX$loglik) - max(fit_PX_0$loglik))
pvalue[i, 1] <- pchisq(chisq, Ti, lower.tail=F)
# reference panal
n_p <- 400
x3 <- rmvnorm(n_p, mean=rep(0, p), sigma = AR(rhoX, p))
x3mean <- matrix(rep(colMeans(x3), n_p), ncol=p, byrow = T)
#x3sd <- matrix(rep(apply(x3, 2, sd), n_p), ncol=p, byrow = T)
x3 <- (x3 - x3mean)#/x3sd/sqrt(n_p)
lam = 0.95
sumx3 = apply(x3*x3, 2, sum)
RR = matrix(0, p, p);
for (i1 in 1:p){
for (j1 in 1:p){
RR[i1, j1] = t(x3[,i1])%*%x3[,j1]/sqrt(sumx3[i1]*sumx3[j1])
}
}
R = RR*lam + (1 - lam)*diag(p)
# summary statisitcs for GWAS
hatmu = matrix(0, p, 1)
hats = matrix(0, p, 1)
for (j in 1:p){
fm <- lm(z ~ 1 + x2[, j]);
hatmu[j] <- summary(fm)$coefficients[2,1]
hats[j] <- summary(fm)$coefficients[2,2];
}
# mammot_ss (GWAS summary data)
S <- diag(c(hats))
SR <- S %*% R
V <- SR %*% S
L <- chol(V)
Ltinv <- solve(t(L))
gam_L <- Ltinv %*% hatmu
U <- Ltinv %*% SR %*% solve(S)
fit_ss <- mammot_PXem_ss(x1, y, U, gam_L, w, FALSE, PX, maxIter=maxIter)
fit_ss_0 <- mammot_PXem_ss(x1, y, U, gam_L, w, TRUE, PX, maxIter=maxIter)
chisq <- 2*(max(fit_ss$loglik) - max(fit_ss_0$loglik))
pvalue[i, 2] <- pchisq(chisq, Ti, lower.tail=F)
# multiXcan (individual data)
cond <- 30
pvalue[i, 3] <- MulTiXcan(x1, y, x2, z, cond)$pval
# utmost (summary data)
B_hat = multiEstB(x1, y)
if (sum(abs(B_hat)) > 1e-6) {
B_hat <- as.matrix(B_hat[, apply(B_hat, 2, sd)!= 0])
Ge_impute <- x3 %*% B_hat
eta <- apply(Ge_impute, 2, sd)
#sig_z <- sd(z)
sig_x <- sqrt(diag(var(x3)))
Ztilde <- hatmu/hats
Lambda <- diag(sig_x) %*% sweep(B_hat, 2, eta, "/")
Lambda_sub <- Lambda[, which(eta != 0)]
test_stats <- t(Lambda_sub) %*% Ztilde
cov_Z <- t(Lambda_sub) %*% R %*% Lambda_sub
pvalue[i, 5] <- GBJ(test_stats=test_stats, cor_mat=cov_Z)$GBJ_pvalue
# multiXcan (summary data)
rhoGE <- cor(Ge_impute)
rhoGE_svd <- svd(rhoGE)
ind_top <- which(rhoGE_svd$d[1]/rhoGE_svd$d < cond)
if(length(ind_top) == 0) ind_top <- 1
u <- rhoGE_svd$u
v <- rhoGE_svd$v
us <- as.matrix(u[, ind_top])
vs <- as.matrix(v[, ind_top])
d <- rhoGE_svd$d[ind_top]
if(length(d) > 1) ds <- diag(1/d) else ds = matrix(1/d)
rhoGE_ginv <- vs %*% ds %*% t(us)
chisq <- c(t(test_stats) %*% rhoGE_ginv %*% test_stats)
pvalue[i, 4] <- pchisq(chisq, length(ind_top), lower.tail=F)
} else {
pvalue[i, 5] <- NA
pvalue[i, 4] <- NA
}
}
toc <- Sys.time()
print(toc - tic)
colnames(pvalue) <- c("mammot", "mammot_ss", "multixan", "multixcan_ss", "utmost")
write.table(pvalue, paste0("pvalue_hz", h_z*10, "_hc", h_c*10, "_rhoX", rhoX*10, "_s", s*10, "_batch-", batch, ".txt"), row.names = F, col.names = F)
}
<file_sep>
#ifndef paral_hpp
#define paral_hpp
#include <stdio.h>
#include <math.h>
#include <RcppArmadillo.h>
#include <thread>
#include <mutex>
#include "PXem.hpp"
#include "PXem_ss.hpp"
#include "PXem_part.hpp"
using namespace std;
using namespace arma;
class parGene{
public:
int current_idx=0;
// std::mutex mtx;
Mat<unsigned> X1, X2;
cube expr;
vec z;
mat Prjy;
mat out_param, Alpha, expr_info, snp_info;
uword Ngene;
int bw;
parGene(const Mat<unsigned>& X1, const Mat<unsigned>& X2, const cube& expr, const vec& z, const mat& Prjy,
mat& out_param, mat& Alpha, const mat expr_info, const mat snp_info, const uword Ngene, const int bw){
this -> X1 = X1;
this -> X2 = X2;
this -> expr = expr;
this -> z = z;
this -> Prjy = Prjy;
this -> out_param = out_param;
this -> Alpha = Alpha;
this -> expr_info = expr_info;
this -> snp_info = snp_info;
this -> Ngene = Ngene;
this -> bw = bw;
}
void loop_by_gene(int i);
void update_by_thread(int thread_id);
int next();
};
class parGeneSS{
public:
int current_idx=0;
Mat<unsigned> X1, Xpanel;
cube expr;
mat GWAS_SS, Prjy;
mat out_param, Alpha, expr_info, snp_info;
uword Ngene;
double lam;
int bw;
parGeneSS(const Mat<unsigned>& X1, const Mat<unsigned>& Xpanel, const cube& expr, const mat& GWAS_SS, const mat& Prjy,
mat& out_param, mat& Alpha, const mat expr_info, const mat snp_info, const uword Ngene, const double lam, const int bw){
this -> X1 = X1;
this -> Xpanel = Xpanel;
this -> expr = expr;
this -> GWAS_SS = GWAS_SS;
this -> Prjy = Prjy;
this -> out_param = out_param;
this -> Alpha = Alpha;
this -> expr_info = expr_info;
this -> snp_info = snp_info;
this -> Ngene = Ngene;
this -> lam = lam;
this -> bw = bw;
}
void loop_by_gene(int i);
void update_by_thread(int thread_id);
int next();
};
class parGene_part{
public:
int current_idx=0;
Mat<unsigned> X1, X2;
cube expr;
vec z;
mat Prjy;
mat out_param, Alpha, chisq, h_y2, expr_info, snp_info;
uword Ngene;
int bw;
parGene_part(const Mat<unsigned>& X1, const Mat<unsigned>& X2, const cube& expr, const vec& z, const mat& Prjy,
mat& out_param, mat& Alpha, mat& chisq, mat& h_y2, const mat expr_info, const mat snp_info, const uword Ngene, const int bw){
this -> X1 = X1;
this -> X2 = X2;
this -> expr = expr;
this -> z = z;
this -> Prjy = Prjy;
this -> out_param = out_param;
this -> Alpha = Alpha;
this -> chisq = chisq;
this -> h_y2 = h_y2;
this -> expr_info = expr_info;
this -> snp_info = snp_info;
this -> Ngene = Ngene;
this -> bw = bw;
}
void loop_by_gene(int i);
void update_by_thread(int thread_id);
int next();
};
class parGeneSS_part{
public:
int current_idx=0;
Mat<unsigned> X1, Xpanel;
cube expr;
mat GWAS_SS, Prjy;
mat out_param, Alpha, chisq, h_y2, expr_info, snp_info;
uword Ngene;
double lam;
int bw;
parGeneSS_part(const Mat<unsigned>& X1, const Mat<unsigned>& Xpanel, const cube& expr, const mat& GWAS_SS, const mat& Prjy,
mat& out_param, mat& Alpha, mat& chisq, mat& h_y2, const mat expr_info, const mat snp_info, const uword Ngene, const double lam, const int bw){
this -> X1 = X1;
this -> Xpanel = Xpanel;
this -> expr = expr;
this -> GWAS_SS = GWAS_SS;
this -> Prjy = Prjy;
this -> out_param = out_param;
this -> Alpha = Alpha;
this -> chisq = chisq;
this -> h_y2 = h_y2;
this -> expr_info = expr_info;
this -> snp_info = snp_info;
this -> Ngene = Ngene;
this -> lam = lam;
this -> bw = bw;
}
void loop_by_gene(int i);
void update_by_thread(int thread_id);
int next();
};
#endif /* paral_hpp */
<file_sep>#ifndef PXem_hpp
#define PXem_hpp
//#include <RcppArmadillo.h>
//#include <Rcpp.h>
//#include <omp.h>
//#include <math.h>
using namespace Rcpp;
using namespace arma;
using namespace std;
void PXem(const arma::mat& x1, const arma::mat& y, const arma::mat& x2, const arma::vec& z, const arma::mat& w, arma::mat& B_hat, arma::vec& mu, arma::mat& Sigma,
double& sigmab, arma::mat& Ve, arma::vec& alpha, double& sigmaz,
arma::vec& LogLik, const bool& constr, const bool& PX, int& Iteration, const int& maxIter);
List mammot_PXem(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w,
bool constr, bool PX, int maxIter);
#endif /* PXem_hpp */<file_sep>// Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 1<PASSWORD>
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
#ifdef RCPP_USE_GLOBAL_ROSTREAM
Rcpp::Rostream<true>& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
Rcpp::Rostream<false>& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
#endif
// mammot_PXem
List mammot_PXem(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, bool constr, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammot_PXem(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP constrSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< bool >::type constr(constrSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammot_PXem(x1, y, x2, z, w, constr, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// ADW
arma::mat ADW(const arma::mat& x, const arma::mat& y);
RcppExport SEXP _TisCoMM_ADW(SEXP xSEXP, SEXP ySEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::mat& >::type x(xSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type y(ySEXP);
rcpp_result_gen = Rcpp::wrap(ADW(x, y));
return rcpp_result_gen;
END_RCPP
}
// mammot_part_test
List mammot_part_test(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, arma::vec constrFactor, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammot_part_test(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP constrFactorSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< arma::vec >::type constrFactor(constrFactorSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammot_part_test(x1, y, x2, z, w, constrFactor, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// mammotSS_part_test
List mammotSS_part_test(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, arma::vec constrFactor, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammotSS_part_test(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP constrFactorSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< arma::vec >::type constrFactor(constrFactorSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammotSS_part_test(x1, y, x2, z, w, constrFactor, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// mammot_PXem_part
List mammot_PXem_part(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, arma::vec constrFactor, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammot_PXem_part(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP constrFactorSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< arma::vec >::type constrFactor(constrFactorSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammot_PXem_part(x1, y, x2, z, w, constrFactor, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// mammotSS_part_est
List mammotSS_part_est(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, arma::mat B_hat, arma::vec mu, arma::mat Sigma, double sigmab, arma::mat Ve, arma::vec alpha, arma::vec constrFactor, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammotSS_part_est(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP B_hatSEXP, SEXP muSEXP, SEXP SigmaSEXP, SEXP sigmabSEXP, SEXP VeSEXP, SEXP alphaSEXP, SEXP constrFactorSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< arma::mat >::type B_hat(B_hatSEXP);
Rcpp::traits::input_parameter< arma::vec >::type mu(muSEXP);
Rcpp::traits::input_parameter< arma::mat >::type Sigma(SigmaSEXP);
Rcpp::traits::input_parameter< double >::type sigmab(sigmabSEXP);
Rcpp::traits::input_parameter< arma::mat >::type Ve(VeSEXP);
Rcpp::traits::input_parameter< arma::vec >::type alpha(alphaSEXP);
Rcpp::traits::input_parameter< arma::vec >::type constrFactor(constrFactorSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammotSS_part_est(x1, y, x2, z, w, B_hat, mu, Sigma, sigmab, Ve, alpha, constrFactor, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// mammotSS_PXem_part
List mammotSS_PXem_part(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, arma::vec constrFactor, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammotSS_PXem_part(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP constrFactorSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< arma::vec >::type constrFactor(constrFactorSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammotSS_PXem_part(x1, y, x2, z, w, constrFactor, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// lmm_pxem
Rcpp::List lmm_pxem(const arma::vec y, const arma::mat w, const arma::mat x, const int maxIter);
RcppExport SEXP _TisCoMM_lmm_pxem(SEXP ySEXP, SEXP wSEXP, SEXP xSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::vec >::type y(ySEXP);
Rcpp::traits::input_parameter< const arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< const arma::mat >::type x(xSEXP);
Rcpp::traits::input_parameter< const int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(lmm_pxem(y, w, x, maxIter));
return rcpp_result_gen;
END_RCPP
}
// mammot_PXem_ss
List mammot_PXem_ss(arma::mat x1, arma::mat y, arma::mat x2, arma::vec z, arma::mat w, bool constr, bool PX, int maxIter);
RcppExport SEXP _TisCoMM_mammot_PXem_ss(SEXP x1SEXP, SEXP ySEXP, SEXP x2SEXP, SEXP zSEXP, SEXP wSEXP, SEXP constrSEXP, SEXP PXSEXP, SEXP maxIterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::mat >::type x1(x1SEXP);
Rcpp::traits::input_parameter< arma::mat >::type y(ySEXP);
Rcpp::traits::input_parameter< arma::mat >::type x2(x2SEXP);
Rcpp::traits::input_parameter< arma::vec >::type z(zSEXP);
Rcpp::traits::input_parameter< arma::mat >::type w(wSEXP);
Rcpp::traits::input_parameter< bool >::type constr(constrSEXP);
Rcpp::traits::input_parameter< bool >::type PX(PXSEXP);
Rcpp::traits::input_parameter< int >::type maxIter(maxIterSEXP);
rcpp_result_gen = Rcpp::wrap(mammot_PXem_ss(x1, y, x2, z, w, constr, PX, maxIter));
return rcpp_result_gen;
END_RCPP
}
// mammot
Rcpp::List mammot(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, int whCol, int bw);
RcppExport SEXP _TisCoMM_mammot(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP whColSEXP, SEXP bwSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< int >::type whCol(whColSEXP);
Rcpp::traits::input_parameter< int >::type bw(bwSEXP);
rcpp_result_gen = Rcpp::wrap(mammot(stringname1, stringname2, stringname3, stringname4, stringname5, whCol, bw));
return rcpp_result_gen;
END_RCPP
}
// mammot_paral
Rcpp::List mammot_paral(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, int whCol, int bw, int coreNum);
RcppExport SEXP _TisCoMM_mammot_paral(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP whColSEXP, SEXP bwSEXP, SEXP coreNumSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< int >::type whCol(whColSEXP);
Rcpp::traits::input_parameter< int >::type bw(bwSEXP);
Rcpp::traits::input_parameter< int >::type coreNum(coreNumSEXP);
rcpp_result_gen = Rcpp::wrap(mammot_paral(stringname1, stringname2, stringname3, stringname4, stringname5, whCol, bw, coreNum));
return rcpp_result_gen;
END_RCPP
}
// mammotSS
Rcpp::List mammotSS(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, double lam, int bw);
RcppExport SEXP _TisCoMM_mammotSS(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP lamSEXP, SEXP bwSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< double >::type lam(lamSEXP);
Rcpp::traits::input_parameter< int >::type bw(bwSEXP);
rcpp_result_gen = Rcpp::wrap(mammotSS(stringname1, stringname2, stringname3, stringname4, stringname5, lam, bw));
return rcpp_result_gen;
END_RCPP
}
// mammotSS_paral
Rcpp::List mammotSS_paral(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, double lam, int bw, int coreNum);
RcppExport SEXP _TisCoMM_mammotSS_paral(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP lamSEXP, SEXP bwSEXP, SEXP coreNumSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< double >::type lam(lamSEXP);
Rcpp::traits::input_parameter< int >::type bw(bwSEXP);
Rcpp::traits::input_parameter< int >::type coreNum(coreNumSEXP);
rcpp_result_gen = Rcpp::wrap(mammotSS_paral(stringname1, stringname2, stringname3, stringname4, stringname5, lam, bw, coreNum));
return rcpp_result_gen;
END_RCPP
}
// mammot_part_paral
Rcpp::List mammot_part_paral(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, CharacterVector targetList, int whCol, int bw, int coreNum);
RcppExport SEXP _TisCoMM_mammot_part_paral(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP targetListSEXP, SEXP whColSEXP, SEXP bwSEXP, SEXP coreNumSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< CharacterVector >::type targetList(targetListSEXP);
Rcpp::traits::input_parameter< int >::type whCol(whColSEXP);
Rcpp::traits::input_parameter< int >::type bw(bwSEXP);
Rcpp::traits::input_parameter< int >::type coreNum(coreNumSEXP);
rcpp_result_gen = Rcpp::wrap(mammot_part_paral(stringname1, stringname2, stringname3, stringname4, stringname5, targetList, whCol, bw, coreNum));
return rcpp_result_gen;
END_RCPP
}
// mammotSS_part_paral
Rcpp::List mammotSS_part_paral(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, CharacterVector targetList, double lam, int bw, int coreNum);
RcppExport SEXP _TisCoMM_mammotSS_part_paral(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP targetListSEXP, SEXP lamSEXP, SEXP bwSEXP, SEXP coreNumSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< CharacterVector >::type targetList(targetListSEXP);
Rcpp::traits::input_parameter< double >::type lam(lamSEXP);
Rcpp::traits::input_parameter< int >::type bw(bwSEXP);
Rcpp::traits::input_parameter< int >::type coreNum(coreNumSEXP);
rcpp_result_gen = Rcpp::wrap(mammotSS_part_paral(stringname1, stringname2, stringname3, stringname4, stringname5, targetList, lam, bw, coreNum));
return rcpp_result_gen;
END_RCPP
}
// getColNum_Header
Rcpp::List getColNum_Header(std::string filename, char delimiter);
RcppExport SEXP _TisCoMM_getColNum_Header(SEXP filenameSEXP, SEXP delimiterSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type filename(filenameSEXP);
Rcpp::traits::input_parameter< char >::type delimiter(delimiterSEXP);
rcpp_result_gen = Rcpp::wrap(getColNum_Header(filename, delimiter));
return rcpp_result_gen;
END_RCPP
}
// dataLoader
Rcpp::List dataLoader(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringname5, int whCol);
RcppExport SEXP _TisCoMM_dataLoader(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringname5SEXP, SEXP whColSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname5(stringname5SEXP);
Rcpp::traits::input_parameter< int >::type whCol(whColSEXP);
rcpp_result_gen = Rcpp::wrap(dataLoader(stringname1, stringname2, stringname3, stringname4, stringname5, whCol));
return rcpp_result_gen;
END_RCPP
}
// dataLoaderSS
Rcpp::List dataLoaderSS(std::string stringname1, std::string stringname2, std::vector<std::string> stringname3, std::string stringname4, std::string stringnameSS);
RcppExport SEXP _TisCoMM_dataLoaderSS(SEXP stringname1SEXP, SEXP stringname2SEXP, SEXP stringname3SEXP, SEXP stringname4SEXP, SEXP stringnameSSSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type stringname1(stringname1SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname2(stringname2SEXP);
Rcpp::traits::input_parameter< std::vector<std::string> >::type stringname3(stringname3SEXP);
Rcpp::traits::input_parameter< std::string >::type stringname4(stringname4SEXP);
Rcpp::traits::input_parameter< std::string >::type stringnameSS(stringnameSSSEXP);
rcpp_result_gen = Rcpp::wrap(dataLoaderSS(stringname1, stringname2, stringname3, stringname4, stringnameSS));
return rcpp_result_gen;
END_RCPP
}
// read_GWAS
List read_GWAS(std::string filename, int P);
RcppExport SEXP _TisCoMM_read_GWAS(SEXP filenameSEXP, SEXP PSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< std::string >::type filename(filenameSEXP);
Rcpp::traits::input_parameter< int >::type P(PSEXP);
rcpp_result_gen = Rcpp::wrap(read_GWAS(filename, P));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_TisCoMM_mammot_PXem", (DL_FUNC) &_TisCoMM_mammot_PXem, 8},
{"_TisCoMM_ADW", (DL_FUNC) &_TisCoMM_ADW, 2},
{"_TisCoMM_mammot_part_test", (DL_FUNC) &_TisCoMM_mammot_part_test, 8},
{"_TisCoMM_mammotSS_part_test", (DL_FUNC) &_TisCoMM_mammotSS_part_test, 8},
{"_TisCoMM_mammot_PXem_part", (DL_FUNC) &_TisCoMM_mammot_PXem_part, 8},
{"_TisCoMM_mammotSS_part_est", (DL_FUNC) &_TisCoMM_mammotSS_part_est, 14},
{"_TisCoMM_mammotSS_PXem_part", (DL_FUNC) &_TisCoMM_mammotSS_PXem_part, 8},
{"_TisCoMM_lmm_pxem", (DL_FUNC) &_TisCoMM_lmm_pxem, 4},
{"_TisCoMM_mammot_PXem_ss", (DL_FUNC) &_TisCoMM_mammot_PXem_ss, 8},
{"_TisCoMM_mammot", (DL_FUNC) &_TisCoMM_mammot, 7},
{"_TisCoMM_mammot_paral", (DL_FUNC) &_TisCoMM_mammot_paral, 8},
{"_TisCoMM_mammotSS", (DL_FUNC) &_TisCoMM_mammotSS, 7},
{"_TisCoMM_mammotSS_paral", (DL_FUNC) &_TisCoMM_mammotSS_paral, 8},
{"_TisCoMM_mammot_part_paral", (DL_FUNC) &_TisCoMM_mammot_part_paral, 9},
{"_TisCoMM_mammotSS_part_paral", (DL_FUNC) &_TisCoMM_mammotSS_part_paral, 9},
{"_TisCoMM_getColNum_Header", (DL_FUNC) &_TisCoMM_getColNum_Header, 2},
{"_TisCoMM_dataLoader", (DL_FUNC) &_TisCoMM_dataLoader, 6},
{"_TisCoMM_dataLoaderSS", (DL_FUNC) &_TisCoMM_dataLoaderSS, 5},
{"_TisCoMM_read_GWAS", (DL_FUNC) &_TisCoMM_read_GWAS, 2},
{NULL, NULL, 0}
};
RcppExport void R_init_TisCoMM(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
|
6acedc89827d0ef8fb04687e35b430b74da71b0c
|
[
"RMarkdown",
"Markdown",
"R",
"C++"
] | 25 |
RMarkdown
|
XingjieShi/TisCoMM
|
04edc5e9843293b1c15e9edf66fcdb6b822cdf59
|
f75cee9e6f7763aa1be3f9b940781925455659b3
|
refs/heads/master
|
<file_sep># Bootcamp_Semana2
# Week 2 using Spring based on Maven Webapp Archetype
|
fce2696eea9a0a5f39453b7d587c89e3aea72142
|
[
"Markdown"
] | 1 |
Markdown
|
MagaPache/Bootcamp_Semana2
|
53bf87d7888c8b810b497671010bbcc0d21084f9
|
85d2b9ec6c5a7d01ff6e97fbf19b4cbc72c57152
|
refs/heads/master
|
<repo_name>theo82/BootstrapCoursera<file_sep>/README.md
**LINKS**
[01_Bootstrap](http://www.theo-android.co.uk/01_Bootrap/)
[02_BootstrapWithDataElements](http://www.theo-android.co.uk/02_BootstrapWithDataElements/)
[03_BootstrapWithJquery](http://www.theo-android.co.uk/03_BootstrapWithJquery/)
[04_AddingLess](http://www.theo-android.co.uk/04_AddingLess/)
[05_UsingBower](http://www.theo-android.co.uk/05_UsingBower/)
|
2cb62480b5dd1bb2c38f3308c512f777a73fc255
|
[
"Markdown"
] | 1 |
Markdown
|
theo82/BootstrapCoursera
|
965e4d969c03a83554f6a76ca6bb522654d2a611
|
fb2cb47117cc4c19151a1a0562f4db9a9962d209
|
refs/heads/master
|
<file_sep>'use strict';
var path = require('path');
var Funnel = require('broccoli-funnel');
var mergeTrees = require('broccoli-merge-trees');
var defaults = require('lodash.defaults');
var rename = require('broccoli-stew').rename;
module.exports = {
name: 'moment',
included: function(app) {
this._super.included.apply(this, arguments);
// see: https://github.com/ember-cli/ember-cli/issues/3718
if (typeof app.import !== 'function' && app.app) {
app = app.app;
}
this.app = app;
this.importDependencies(app);
},
importDependencies: function(app) {
if (arguments.length < 1) {
throw new Error('Application instance must be passed to import');
}
var vendor = this.treePaths.vendor;
var options = this.getConfig();
if (options.includeTimezone) {
app.import(path.join(vendor, 'moment-timezone', 'tz.js'), { prepend: true });
}
if (typeof options.includeLocales === 'boolean' && options.includeLocales) {
app.import(path.join(vendor, 'moment', 'min', 'moment-with-locales.min.js'), { prepend: true });
}
else {
if (Array.isArray(options.includeLocales)) {
options.includeLocales.map(function(locale) {
app.import(path.join(vendor, 'moment', 'locales', locale + '.js'), { prepend: true })
});
}
app.import(path.join(vendor, 'moment', 'min', 'moment.min.js'), { prepend: true });
}
},
getConfig: function() {
var projectConfig = ((this.project.config(process.env.EMBER_ENV) || {}).moment || {});
var config = defaults(projectConfig, {
includeTimezone: null,
includeLocales: []
});
if (Array.isArray(config.includeLocales)) {
config.includeLocales = config.includeLocales.filter(function(locale) {
return typeof locale === 'string';
}).map(function(locale) {
return locale.replace('.js', '').trim().toLowerCase();
});
}
return config;
},
treeForVendor: function(vendorTree) {
var trees = [];
var options = this.getConfig();
if (vendorTree) {
trees.push(vendorTree);
}
var momentPath = path.join(this.project.bowerDirectory, 'moment');
trees.push(new Funnel(momentPath, {
destDir: 'moment',
include: [new RegExp(/\.js$/)],
exclude: ['tests', 'ender', 'package'].map(function(key) {
return new RegExp(key + '\.js$');
})
}));
if (Array.isArray(options.includeLocales) && options.includeLocales.length) {
trees.push(new Funnel(momentPath, {
srcDir: 'locale',
destDir: path.join('moment', 'locales'),
include: options.includeLocales.map(function(locale) {
return new RegExp(locale + '.js$');
})
}));
}
if (options.includeTimezone) {
var timezonePath = [this.project.bowerDirectory, 'moment-timezone', 'builds'];
switch(options.includeTimezone) {
case 'all':
timezonePath.push('moment-timezone-with-data.min.js');
break;
case '2010-2020':
timezonePath.push('moment-timezone-with-data-2010-2020.min.js');
break;
case 'none':
timezonePath.push('moment-timezone.min.js');
break;
default:
throw new Error("ember-moment: Please specify the moment-timezone dataset to include as either 'all', '2010-2020', or 'none'.");
break;
}
trees.push(rename(new Funnel(path.join(this.project.bowerDirectory, 'moment-timezone', 'builds'), {
files: [timezonePath[timezonePath.length - 1]]
}), function(filepath) {
return path.join('moment-timezone', 'tz.js');
}));
}
return mergeTrees(trees);
}
};
|
2f2666c5ac6e598ac2bb10527f26f65a9793fad8
|
[
"JavaScript"
] | 1 |
JavaScript
|
marcinsklodowski/ember-cli-moment-shim
|
2785e73cb03e5a61c9f847b698733dd0e5eadd3f
|
43c71eafa9c23a291a1b859b0b8a83f2954e7e63
|
refs/heads/master
|
<file_sep>config.folder=${file.reference.Esquivela-snake-config}
file.reference.Esquivela-snake-config=config
file.reference.Esquivela-snake-public_html=public_html
file.reference.Esquivela-snake-test=test
files.encoding=UTF-8
site.root.folder=${file.reference.Esquivela-snake-public_html}
test.folder=${file.reference.Esquivela-snake-test}
|
a8bcb884666753c695703b0f67e2fe1c9f32718d
|
[
"INI"
] | 1 |
INI
|
EsquivelA/SnakeAdrianE
|
c0c761b3583cebddb725a641f43cc700fc4280af
|
2cf11835c752e6823e9bf701279fdb5762663a94
|
refs/heads/master
|
<file_sep># Challenge - school-district-analysis
1. How is the district summary affected?
--
The % Passing values have all declined. % Passing Math declined (22) points from 75 to 53. % Passing Reading declined (25) points from 86 to 61. % Overall Passing declined (19) points from 65 to 46.
District Summary Module

District Summary Challenge

2. How is the school summary affected?
--
The % Passing values have all declined.
School Summary Module

School Summary Challenge

3. How does replacing the ninth graders’ math and reading scores affect Thomas High School’s performance, relative to the other schools?
--
Thomas High School went from being the second-best performing school to the fourth which may mean their ninth graders performed better than the ninth graders at other schools.
Top Schools Module

Top School Challenge

4. How does replacing the ninth-grade scores affect the following?
--
a. Math and Reading Scores by Grade
--
Only the 9th grade scores show up as nan, no other grades were affected.
Math Scores by Grade Module

Math Scores by Grade Challenge

Reading Scores by Grade Module

Reading Scores by Grade Challenge

b. Scores by School Spending
--
Average Math Score for the $585-629 spending range schools grew +0.1 percentage points and the $645-675 schools declined (-0.1) with all other school spending groups remaining the same. Average Reading Scores remained the same apart from the <$584 spending range of schools increased +0.1 percentage points. % Passing dropped overall.
Scores by School Spending Module

Scores by School Spending Challenge

c. Scores by School Size
--
The Average Math Score grew +0.1 percentage points for both Small and Medium schools. The Average Reading Score grew +0.1 for Small schools. % Passing Math, % Passing Reading, and % Overall Passing all declined.
Scores by School Size Module

Scores by School Size Challenge

d. Scores by School Type
--
Charter Average Math Score increased +0.1 percentage points and Average Reading Score remained the same. District Average Math and Reading Scores both dropped (-0.1) percentage points. % Passing dropped for both Charter and District.
Scores by School Type Module

Scores by School Type Challenge

|
bd77fdeabc2750d7478e694ed2f8065a909b43ac
|
[
"Markdown"
] | 1 |
Markdown
|
diapopa/school-district-analysis
|
52778995217151ba916d71fb3596ddee44b290ac
|
0495a0e35a4ceb474074d31c8ff553a13ae9ba3b
|
refs/heads/main
|
<repo_name>Daphne1998/Daphne1998<file_sep>/README.md
- 👋 Hi, I’m @Daphne1998
- 👀 I’m interested in the planet
- 🌱 I’m currently learning about bussiness
- 💞️ I'm looking to collaborate on projects with other colleagues.
- 📫 How to reach me ... maybe calling me? ha.
<!---
Daphne1998/Daphne1998 is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile.
You can click the Preview link to take a look at your changes.
--->
|
9bff017b6469bab0a0a53bfb1217e60cfc91291e
|
[
"Markdown"
] | 1 |
Markdown
|
Daphne1998/Daphne1998
|
a350373d234b171802326c1a50fff206e45181c9
|
a17d88cc6c16c2829ae8edef130f15a3e1879802
|
refs/heads/master
|
<file_sep>using System;
using System.ComponentModel;
using System.Reflection;
namespace GymTracker.ViewModels
{
public static class EnumExtensions
{
public static string GetEnumDescription(this Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
}
}<file_sep>namespace GymTracker
{
/// <summary>
/// Interaction logic for WorkoutItemView.xaml
/// </summary>
public partial class WorkoutItemView
{
/// <summary>
/// Creates a new Task Item User Control view.
/// </summary>
public WorkoutItemView()
{
InitializeComponent();
}
}
}
<file_sep>using System;
using GymTracker.Models;
using NUnit.Framework;
namespace GymTracker.Tests
{
[TestFixture]
public sealed class WorkoutTests
{
[Test]
public void WorkoutHasDayAsDateNow()
{
Workout workout = new Workout();
double diffInSeconds = (DateTime.Now - workout.WorkoutDay).TotalSeconds;
Assert.LessOrEqual(diffInSeconds, 5);
}
}
}<file_sep>namespace GymTracker
{
/// <summary>
/// Interaction logic for TimeDistanceItemView.xaml
/// </summary>
public partial class TimeDistanceItemView
{
public TimeDistanceItemView()
{
InitializeComponent();
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using GymTracker.Models;
namespace GymTracker.ViewModels
{
public class WorkoutItemViewModel : NotifiableViewModel
{
private readonly Workout workout;
public WorkoutItemViewModel(Workout workout)
{
this.workout = workout;
Exercises = workout.Exercises.ToList();
}
public string WorkoutTime => workout.TimeSinceWorkout.ToDaysAgo();
public IEnumerable<Exercise> Exercises { get; }
}
}<file_sep>using System.Globalization;
using GymTracker.Models;
namespace GymTracker.ViewModels
{
public class StrengthSetItemViewModel : ExerciseItemViewModel<StrengthSet>
{
public StrengthSetItemViewModel(StrengthSet exercise)
: base(exercise)
{
}
public string Reps => $"{Exercise.Reps} reps";
public string Weight => $"{Exercise.Weight.ToString(CultureInfo.InvariantCulture)} kg";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
namespace GymTracker.Models
{
public class GymContextInitializer : DropCreateDatabaseAlways<GymContext>
{
protected override void Seed(GymContext context)
{
var defaultWorkouts = new List<Workout>();
Workout workout1 = new Workout(DateTime.Now.AddDays(-1));
workout1.AddExercise(new StrengthSet(Routine.DumbellPress, 8, 50));
workout1.AddExercise(new StrengthSet(Routine.BenchPress, 12, 80));
workout1.AddExercise(new StrengthSet(Routine.Rows, 8, 60));
workout1.AddExercise(new StrengthSet(Routine.Rows, 5, 80));
workout1.AddExercise(new TimeDistanceExercise(Routine.Running, TimeSpan.FromMinutes(13), 3000));
workout1.AddExercise(new TimeDistanceExercise(Routine.Rowing, TimeSpan.FromMinutes(7), 2000));
defaultWorkouts.Add(workout1);
Workout workout2 = new Workout(DateTime.Now.AddDays(-3));
workout2.AddExercise(new StrengthSet(Routine.DumbellPress, 5, 64));
workout2.AddExercise(new StrengthSet(Routine.DumbellPress, 8, 56));
defaultWorkouts.Add(workout2);
Workout workout3 = new Workout(DateTime.Now.AddDays(-4));
workout3.AddExercise(new StrengthSet(Routine.DumbellPress, 5, 64));
workout3.AddExercise(new StrengthSet(Routine.DumbellPress, 8, 56));
workout3.AddExercise(new StrengthSet(Routine.DumbellPress, 8, 76));
workout3.AddExercise(new StrengthSet(Routine.DumbellPress, 8, 80));
defaultWorkouts.Add(workout3);
foreach (Workout workout in defaultWorkouts)
{
context.Workouts.Add(workout);
}
base.Seed(context);
}
}
}
<file_sep>namespace GymTracker
{
/// <summary>
/// Interaction logic for StrengthSetItemView.xaml
/// </summary>
public partial class StrengthSetItemView
{
public StrengthSetItemView()
{
InitializeComponent();
}
}
}<file_sep>using System;
namespace GymTracker.Models
{
public sealed class StrengthSet : Exercise
{
[Obsolete("Only needed for serialization and materialization", true)]
public StrengthSet()
{
}
public StrengthSet(Routine name, int reps, double weight) : base(name)
{
Reps = reps;
Weight = weight;
}
public int Reps { get; private set; }
public double Weight { get; private set; }
}
}<file_sep>using System;
namespace GymTracker.Models
{
public abstract class Exercise : IEntity
{
[Obsolete("Only needed for serialization and materialization", true)]
protected Exercise()
{
}
protected Exercise(Routine name)
{
Name = name;
}
public virtual Workout Workout { get; private set; }
public Routine Name { get; private set; }
public int Id { get; private set; }
}
}<file_sep>using GymTracker.Models;
using NUnit.Framework;
namespace GymTracker.Tests
{
[TestFixture]
public sealed class ExcersiceTests
{
[Test]
public void ExerciseHasName()
{
Routine routine = Routine.BenchPress;
Exercise exercise = new StrengthSet(routine, 2, 20);
Assert.AreEqual(exercise.Name, routine);
}
}
}<file_sep>using System;
namespace GymTracker.Models
{
public sealed class TimeDistanceExercise : Exercise
{
[Obsolete("Only needed for serialization and materialization", true)]
public TimeDistanceExercise()
{
}
public TimeDistanceExercise(Routine name, TimeSpan time, double meters) : base(name)
{
Time = time;
Meters = meters;
}
public TimeSpan Time { get; private set; }
public double Meters { get; private set; }
}
}<file_sep>using GymTracker.Models;
using NUnit.Framework;
namespace GymTracker.Tests
{
[TestFixture]
public class StrengthSetTests
{
[Test]
public void StrengthSetHasWeight()
{
const double weight = 50.5;
StrengthSet strenghtSet = new StrengthSet(Routine.DumbellPress, 12, weight);
Assert.AreEqual(weight, strenghtSet.Weight);
}
[Test]
public void StrengthSetHasReps()
{
const int reps = 12;
StrengthSet strengthSet = new StrengthSet(Routine.Rows, reps, 10);
Assert.AreEqual(reps, strengthSet.Reps);
}
}
}<file_sep>using System;
using System.IO;
using System.Windows;
namespace GymTracker
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "GymTracker");
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
}
AppDomain.CurrentDomain.SetData("DataDirectory", path);
}
catch (Exception exception)
{
Console.WriteLine("The process failed: {0}", exception);
Shutdown(1);
}
}
}
}<file_sep>using System.Data.Entity;
namespace GymTracker.Models
{
public class GymContext : DbContext
{
public GymContext()
{
Database.SetInitializer(new GymContextInitializer());
}
public DbSet<Workout> Workouts { get; set; }
}
}<file_sep>using GymTracker.Models;
namespace GymTracker.ViewModels
{
public sealed class TimeDistanceItemViewModel : ExerciseItemViewModel<TimeDistanceExercise>
{
public TimeDistanceItemViewModel(TimeDistanceExercise exercise) : base(exercise)
{
}
public string TimeInMinutes => $"{Exercise.Time.Minutes} Minutes";
public string DistanceInMeters => $"{Exercise.Meters} Meters";
}
}<file_sep>using System.ComponentModel;
namespace GymTracker.Models
{
public enum Routine
{
[Description("Bench Press")]
BenchPress,
[Description("Dumbell Press")]
DumbellPress,
Rows,
Running,
Rowing
}
}<file_sep># GymTracker
Project used to learn the new C# 6.0 features.
<file_sep>using System;
using GymTracker.Models;
namespace GymTracker.ViewModels
{
public abstract class ExerciseItemViewModel<TExercise> : ExerciseItemViewModel where TExercise : Exercise
{
protected readonly TExercise Exercise;
protected ExerciseItemViewModel(TExercise exercise) : base(exercise)
{
Exercise = exercise;
}
public string Name => Exercise.Name.GetEnumDescription();
}
public abstract class ExerciseItemViewModel : NotifiableViewModel
{
public Type ExerciseType { get; }
public Routine ExerciseRoutine { get; }
protected ExerciseItemViewModel(Exercise exerciseType)
{
ExerciseType = exerciseType.GetType();
ExerciseRoutine = exerciseType.Name;
}
}
}<file_sep>using System;
using System.Linq;
using GymTracker.Models;
namespace GymTracker.ViewModels
{
public class ExerciseInformationViewModel : NotifiableViewModel
{
public ExerciseInformationViewModel(Routine routine)
{
ExerciseName = routine.GetEnumDescription();
using (GymContext context = new GymContext())
{
TimeSpan lastDateTime = TimeSpan.MaxValue;
foreach (Workout workout in context.Workouts)
{
foreach (Exercise exercise in workout.Exercises.Where(exercise => exercise.Name.Equals(routine)))
{
if (lastDateTime > workout.TimeSinceWorkout)
{
lastDateTime = workout.TimeSinceWorkout;
}
}
}
LastPerformed = lastDateTime.ToDaysAgo();
}
}
public string ExerciseName { get; }
public string LastPerformed { get; }
public static string ExerciseDetails => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed velit mauris, imperdiet vel nunc in, convallis tristique elit. " +
"Nullam sed ipsum porta felis rutrum feugiat sit amet pulvinar diam. Nulla augue quam, rutrum eget magna vitae, congue pulvinar dui. " +
"Mauris enim nunc, tristique quis erat at, dictum tristique metus. Morbi et nulla eu tellus bibendum eleifend eu vitae nisi. " +
"Fusce sit amet arcu vel justo tincidunt accumsan non ut dui. Quisque vitae risus malesuada, placerat libero sed, viverra justo.";
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using GymTracker.Models;
using Microsoft.Practices.Prism.Commands;
namespace GymTracker.ViewModels
{
public class MainViewModel : NotifiableViewModel
{
private ExerciseInformationViewModel exerciseInformationViewModel;
private string searchWorkouts;
private ExerciseItemViewModel selectedExercise;
private WorkoutItemViewModel selectedWorkout;
public MainViewModel()
{
CreateWorkoutCommand = new DelegateCommand(CreateWorkout, CanCreateWorkout);
using (var context = new GymContext())
{
List<Workout> workouts = context.Workouts.ToList();
Workouts = new ObservableCollection<WorkoutItemViewModel>();
Exercises = new ObservableCollection<ExerciseItemViewModel>();
foreach (Workout workout in workouts)
{
Workouts.Add(new WorkoutItemViewModel(workout));
}
}
}
public static string Title => "Gym Tracker";
public ObservableCollection<WorkoutItemViewModel> Workouts { get; set; }
public ObservableCollection<ExerciseItemViewModel> Exercises { get; set; }
public WorkoutItemViewModel SelectedWorkout
{
get { return selectedWorkout; }
set
{
Exercises.Clear();
selectedWorkout = value;
foreach (Exercise exercise in SelectedWorkout.Exercises)
{
var strengthSet = exercise as StrengthSet;
if (strengthSet != null)
{
Exercises.Add(new StrengthSetItemViewModel(strengthSet));
}
var timeDistanceExercise = exercise as TimeDistanceExercise;
if (timeDistanceExercise != null)
{
Exercises.Add(new TimeDistanceItemViewModel(timeDistanceExercise));
}
}
OnPropertyChanged();
}
}
public string SearchWorkouts
{
get { return searchWorkouts; }
set
{
searchWorkouts = value;
OnPropertyChanged();
}
}
public DelegateCommand CreateWorkoutCommand { get; }
public ExerciseItemViewModel SelectedExercise
{
get { return selectedExercise; }
set
{
if (value != null)
{
selectedExercise = value;
ExerciseInformationViewModel = new ExerciseInformationViewModel(SelectedExercise.ExerciseRoutine);
OnPropertyChanged();
}
}
}
public ExerciseInformationViewModel ExerciseInformationViewModel
{
get { return exerciseInformationViewModel; }
set
{
exerciseInformationViewModel = value;
OnPropertyChanged();
}
}
private bool CanCreateWorkout()
{
TimeSpan latestWorkout = TimeSpan.MaxValue;
using (GymContext gymContext = new GymContext())
{
foreach (Workout workout in gymContext.Workouts)
{
if (latestWorkout > workout.TimeSinceWorkout)
{
latestWorkout = workout.TimeSinceWorkout;
}
}
}
return latestWorkout.TotalHours > 4.0;
}
private void CreateWorkout()
{
var workout = new Workout();
using (GymContext gymContext = new GymContext())
{
gymContext.Workouts.Add(workout);
gymContext.SaveChanges();
}
Workouts.Insert(0, new WorkoutItemViewModel(workout));
CreateWorkoutCommand.RaiseCanExecuteChanged();
}
}
}<file_sep>using System;
namespace GymTracker.ViewModels
{
public static class TimeSpanFormatter
{
public static string ToDaysAgo(this TimeSpan timeSpan)
{
const string singular = "Day";
const string plural = "Days";
return ToNounAgo(timeSpan.Days, singular, plural);
}
private static string ToNounAgo(int timeUnitDistance, string singularNoun, string pluralNoun)
{
NounState nounState;
switch (timeUnitDistance)
{
case 0:
// Special case.
return "Today";
case 1:
nounState = NounState.Singular;
break;
default:
nounState = NounState.Plural;
break;
}
string nounToUse = NounFinder(nounState, singularNoun, pluralNoun);
return $"{timeUnitDistance} {nounToUse} ago.";
}
private static string NounFinder(NounState nounState, string singularVersion, string pluralVersion)
{
switch (nounState)
{
case NounState.Singular:
return singularVersion;
case NounState.Plural:
return pluralVersion;
}
// If no noun state specified, return the more common plural version (worst case will say 1 days).
return pluralVersion;
}
private enum NounState
{
Singular,
Plural
}
}
}<file_sep>namespace GymTracker
{
/// <summary>
/// Interaction logic for ExerciseInformationView.xaml
/// </summary>
public partial class ExerciseInformationView
{
public ExerciseInformationView()
{
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace GymTracker.Models
{
public class Workout : IEntity
{
/// <summary>
/// Create a new workout with the day set to today.
/// </summary>
public Workout()
{
Exercises = new List<Exercise>();
}
/// <summary>
/// Set an explicit workout day.
/// </summary>
/// <param name="workoutWorkoutDay">The day of the workout.</param>
public Workout(DateTime workoutWorkoutDay) : this()
{
WorkoutDay = workoutWorkoutDay;
}
public DateTime WorkoutDay { get; private set; } = DateTime.Now;
[NotMapped]
public TimeSpan TimeSinceWorkout => DateTime.Now - WorkoutDay;
public virtual ICollection<Exercise> Exercises { get; private set; }
public int Id { get; private set; }
public void AddExercise(Exercise exercise)
{
Exercises.Add(exercise);
}
}
}
|
030fdd965f5b4bb8568f1de4e29129857d6669a9
|
[
"C#",
"Markdown"
] | 24 |
C#
|
EdAllonby/WPFGymTracker
|
f0bad5330a0211aa77f5d144281c8f7bb84dbd67
|
c53e94982c7c07fe86870f01ae8fce6870412dbe
|
refs/heads/master
|
<repo_name>RadioMan116/siemens.ret-team.ru<file_sep>/templates/main/source/components/checkbox/checkbox.scss
.checkbox {
position: relative;
display: inline-block;
padding: 0 0 0 30px;
margin: 0;
line-height: 1;
cursor: pointer;
color: #2e2e2e;
font-size: 14px;
font-weight: 400;
line-height: 1;
}
.checkbox_oferta {
font-size: 12px;
padding-top: 1px;
}
.checkbox__input {
visibility: hidden;
position: absolute;
left: 0;
top: 0;
}
.checkbox__icon {
position: absolute;
left: 0;
top: 3px;
width: 16px;
height: 16px;
border-radius: 2px;
border: 1px solid #d6d6d6;
background-color: white;
-webkit-transition: border 200ms;
transition: border 200ms;
}
.checkbox__icon:before {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%) scale(0);
transform: translate(-50%, -50%) scale(0);
-webkit-transition: -webkit-transform 200ms;
transition: -webkit-transform 200ms;
transition: transform 200ms;
transition: transform 200ms, -webkit-transform 200ms;
width: 8px;
height: 8px;
background-color: $base;
content: '';
}
.checkbox_radio .checkbox__icon {
border-radius: 50%;
}
.checkbox_radio .checkbox__icon:before {
border-radius: 50%;
}
.checkbox__input:checked~.checkbox__icon {
border: 1px solid $base;
}
.checkbox__input:checked~.checkbox__icon:before {
-webkit-transform: translate(-50%, -50%) scale(1);
transform: translate(-50%, -50%) scale(1);
}
<file_sep>/templates/main/source/components/section/seo-text/seo-text.html
<article class="about-brand">
<div class="container">
<h2 class="about-brand__title">
О бренде Siemens
</h2>
<img src="images/about-brand.png" align='right' class="pic_right loaded lazyloaded" alt="">
<p>
Конечно, самая популярная продукция компании в России — это бытовая техника Siemens. Для экспорта в нашу
страну
производятся холодильники, стиральные и посудомоечные машины, духовые шкафы, варочные панели и многое-многое
другое.
Передовые технологии и отличные дизайнерские решения делают продукцию компании востребованной и очень
популярной.
Однако не только бытовая техника получила широкое распространение в нашей стране.
<br>
<br>
Производственные площадки и офисы Siemens есть в 190 странах мира, и этот факт говорит сам за себя.
Зарекомендовав
себя как лидер в области электроники и электротехники, компания Siemens не останавливается на достигнутом и
продолжает уверенно завоевывать все новые ниши, поддерживая проекты в области науки, образования, культуры и
спорта.
<br>
<br>
В нашем интернет-магазине Siemens представлена, в первую очередь, кухонная бытовая техника. Акцент на этой
продукции
сделан неслучайно: именно с этими, казалось бы, простыми и повседневными приборами вы сможете оценить
всю радость и удобство управления «умной» техникой.
</p>
</div>
</article>
<file_sep>/templates/main/source/components/section/help/help.scss
.help {
display: flex;
flex-wrap: wrap;
margin-top: -3rem;
padding-bottom: 3rem;
&__row {
width: 100%;
// font-family: 'Gotham Pro Medium';
font-size: 16px;
font-weight: 500;
font-style: normal;
font-stretch: normal;
line-height: 1.5;
letter-spacing: normal;
text-align: left;
color: #2e2e2e;
padding: 16px 20px;
display: flex;
flex-wrap: wrap;
background-color: #ffffff;
border: solid 1px #eeeeee;
margin: 9px 0;
background: url("https://icongr.am/fontawesome/caret-down.svg?color=666666") 99% 20px/20px no-repeat;
cursor: pointer;
&-open {
background: url("https://icongr.am/fontawesome/caret-up.svg?color=666666") 99% 20px/20px no-repeat;
color: $base;
}
&:hover {
box-shadow: 0 2px 25px 0 rgba(0, 0, 0, 0.14);
}
&:first-child {
margin-top: 35px;
}
}
&__info {
// font-family: 'Gotham Pro';
font-size: 14px;
font-weight: normal;
font-style: normal;
font-stretch: normal;
line-height: 1.57;
letter-spacing: normal;
text-align: left;
color: #2e2e2e;
width: 100%;
margin-top: 15px;
display: none;
}
&.connect {
margin-top: 0;
.help {
&__row {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
font-size: 14px;
font-weight: 500;
text-align: left;
color: #333;
padding: 8px 32px 7px 40px;
width: 100%;
border: none;
border-bottom: 1px solid #e8e8e8;
margin: 0;
background-image: url("../images/arrow-black.png");
background-position: 10px;
transition: none;
font-family: Arial;
&:nth-child(odd) {
background-color: #f8f8f8;
}
&:first-child {
margin-top: 0;
margin-bottom: 0;
}
&-open {
padding-bottom: 40px;
font-weight: bold;
background-image: url("../images/arrow-green.png");
background-position-y: 10px;
.help__price {
font-weight: normal;
}
}
}
&__info {
margin-top: 0;
}
&__title {
color: #AF235F;
margin: 24px 0 16px;
font-size: 18px;
font-family: Roboto Condensed;
}
&__price {
margin-left: auto;
width: 75px;
}
}
}
@media screen and (max-width: 767px) {
&.connect {
.help {
&__row {
flex-direction: column;
&-open {
.help__price {
margin-top: 6px;
}
}
}
&__price {
margin-left: unset;
}
&__info {
// font-family: "Gotham Pro";
line-height: 22px;
}
&__title {
font-size: 16px;
}
}
}
}
}
|
5eca591c16709f4d211dd5a590fdd3fb5a474e02
|
[
"SCSS",
"HTML"
] | 3 |
SCSS
|
RadioMan116/siemens.ret-team.ru
|
541e75b861c1081d3a4598c62af005f52e42b060
|
41d87c344f27c56633c1b605992efe4cd6b9a263
|
refs/heads/master
|
<repo_name>Jose-Fernandez-Vallejo/IBAN_ENDES<file_sep>/README.md
# IBAN_ENDES
ejercicio de calculo y verificación de IBAN Español
Este es el trabajo de Entornos de desarrollo en el que debemos aplicar pruebas unitarias, refactorizacion y git.
<file_sep>/ValidarIBAN/ValidarIBAN/IBAN.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ValidarIBAN
{
public class LongitudIncorrectaException : Exception { }
public class ParametroFormatoIncorrecto : Exception { }
public class IbanNoEspanolExeption : Exception { }
public class NumerosControlIBANFormatoIncorrectoException : Exception { }
// este .cs tiene todas las clases publicas para poder hacerle las pruebas unitarias, el final deberia tener la gran mayoria en private pues no es necesario que el usuario las vea
public class IBAN
{
public static bool ValidarCC(string Cuenta)
{
return (CalcularNumeroControl(Cuenta) == Cuenta.Substring(8, 2));
}
public static string CalcularNumeroControl(string cadena)
{
int[] multiplicador = new int[] { 4, 8, 5, 10, 9, 7, 3, 6, 0, 0, 1, 2, 4, 8, 5, 10, 9, 7, 3, 6 };
string resultado = string.Empty;
int acumulador1 = 0;
int acumulador2 = 0;
if (cadena.Length != 20)
{
throw new LongitudIncorrectaException();
}
for (int i = 0; i < 10; i++)
{
try
{
acumulador1 += int.Parse(cadena[i].ToString()) * multiplicador[i];
acumulador2 += int.Parse(cadena[i + 10].ToString()) * multiplicador[i + 10];
}
catch (FormatException)
{
throw new ParametroFormatoIncorrecto();
}
}
resultado = CalculoAculmulador(acumulador1);
resultado += CalculoAculmulador(acumulador2);
return resultado;
}
public static string CalculoAculmulador(int acumulador)
{
int resultadoTmp = 11 - (acumulador % 11);
if (resultadoTmp == 10)
{
return "1";
}
else if (resultadoTmp == 11)
{
return "0";
}
else
{
return resultadoTmp.ToString();
}
}
public static string[] dividirIBAN(string cadena)
{
string[] IBAN = new string[5];
IBAN[0] = cadena.Substring(0, 5);
IBAN[1] = cadena.Substring(5, 5);
IBAN[2] = cadena.Substring(10, 5);
IBAN[3] = cadena.Substring(15, 5);
IBAN[4] = cadena.Substring(20, 6);
return IBAN;
}
public static string CalcularNumeroControlIBAN(string cadena)
{
string ES = "142800";
string IBAN = cadena + ES;
string[] IBANDividido = dividirIBAN(IBAN);
string NumeroControl = string.Empty;
for (int i = 0; i < IBANDividido.Length; i++)
{
NumeroControl += IBANDividido[i];
NumeroControl = (int.Parse(NumeroControl) % 97).ToString();
}
NumeroControl = (98 - (int.Parse(NumeroControl))).ToString();
if (NumeroControl.Length == 1)
{
NumeroControl = "0" + NumeroControl;
}
return NumeroControl;
}
public static bool ValidarIBAN(string Cadena)
{
string CC = Cadena.Substring(4, 20);
string ControlIBAN = Cadena.Substring(2, 2);
if (Cadena[0] != 'E' || Cadena[1] != 'S')
{
throw new IbanNoEspanolExeption();
}
try
{
int.Parse(Cadena.Substring(2, 2));
}
catch
{
throw new NumerosControlIBANFormatoIncorrectoException();
}
if (!ValidarCC(CC))
{
return false;
}
return ControlIBAN == CalcularNumeroControlIBAN(CC);
}
}
}
<file_sep>/ValidarIBAN/IBANTest/IBANTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using ValidarIBAN;
namespace IBANTest
{
[TestFixture]
public class IBANTest
{
[Test]
public void ElDigitoDeControlSeCalculaCorrectamente()
{
int acumulador1 = 6; //debe devolver 11 - el numero insertado (5)
int acumulador2 = 10; // debe devolver 1
int acumulador3 = 11; // debe devolver 0
Assert.AreEqual("5", IBAN.CalculoAculmulador(acumulador1));
Assert.AreEqual("1", IBAN.CalculoAculmulador(acumulador2));
Assert.AreEqual("0", IBAN.CalculoAculmulador(acumulador3));
}
[Test]
public void ElCCEsValido()
{
string CC = "20852066623456789011";
Assert.IsTrue(IBAN.ValidarCC(CC));
}
[Test]
public void ElCCNoTieneLaLongitudCorrecta()
{
try
{
string CC = "123458001234567890";
IBAN.ValidarCC(CC);
Assert.Fail("Longitud Incorrecta");
}
catch (LongitudIncorrectaException)
{
//algo
}
}
[Test]
public void ElCCTieneUnformatoIncorrecto()
{
try
{
string CC = "12345j6789001234h56h";
IBAN.ValidarCC(CC);
Assert.Fail("Formato mal");
}
catch (ParametroFormatoIncorrecto)
{
//algo
}
}
[Test]
public void ElIBANSeCalculaCorrectamente()
{
string CC = "20852066623456789011";
Assert.AreEqual("17", IBAN.CalcularNumeroControlIBAN(CC));
}
[Test]
public void AlPasarleTodoJuntoCalculaCorrectamenteTantoIBANComoCC()
{
string CC = "ES1720852066623456789011";
Assert.IsTrue(IBAN.ValidarIBAN(CC));
}
[Test]
public void DevuelveFalsoConUnNumeroDeControlInCorrectoEnELIBAN()
{
string CC = "ES1220852066623456789011";
Assert.IsFalse(IBAN.ValidarIBAN(CC));
}
[Test]
public void DevuelveFalsoConUnNumeroDeControlInCorrectoEnELCC()
{
string CC = "ES1720852066223456789011";
Assert.IsFalse(IBAN.ValidarIBAN(CC));
}
[Test]
public void ElMetodoParaDividirElIBANLoDivideCorrectamente()
{
string CC = "20852066223456789011142800";
string[] ccDividido =IBAN.dividirIBAN(CC);
Assert.AreEqual(5, ccDividido.Length);
}
[Test]
public void AlValidarIBANNoEspanolSaltaExcepcion()
{
try
{
string iban = "FR0212345678101023749586";
IBAN.ValidarIBAN(iban);
Assert.Fail("iban no español");
}
catch (IbanNoEspanolExeption)
{
//algo
}
}
[Test]
public void AlValidarIBANConFormatoIncorrectoSaltaExcepcion()
{
try
{
string iban = "ESgM12345678101023749586";
IBAN.ValidarIBAN(iban);
Assert.Fail("Formato de los numeros de control del IBAN incorrecto");
}
catch (NumerosControlIBANFormatoIncorrectoException)
{
//algo
}
}
}
}
|
abcc0a074c0b215d1893b66d104a3f3bc5692280
|
[
"C#",
"Markdown"
] | 3 |
C#
|
Jose-Fernandez-Vallejo/IBAN_ENDES
|
0b51c8cbc4847854942bfbf5cacabaa059f016d4
|
02b3f25e9b307d7428479d4455482bff95f46a59
|
refs/heads/master
|
<file_sep>CREATE TABLE Customers(
username VARCHAR (100) PRIMARY KEY NOT NULL,
passwordhash VARCHAR(MAX) NOT NULL,
passwordsalt BINARY(16) NOT NULL,
acctBalance INT NOT NULL);
CREATE TABLE Reservations(
rsvid INT PRIMARY KEY NOT NULL,
customer VARCHAR(100) NOT NULL,
totprice INT NOT NULL,
origin_city_fid INT NOT NULL,
indirect_oc_fid INT,
date INT NOT NULL,
paid BIT NOT NULL);
CREATE TABLE SeatsSold(
fid INT PRIMARY KEY NOT NULL,
seatsSold INT NOT NULL);
|
68854aa9df66087da6005abeb0605bef155af60f
|
[
"SQL"
] | 1 |
SQL
|
surapan1/FlightBookingService
|
f9284033ac4415f1188539abd977c7fb262eb46c
|
3d3990acc8ef645f5dc4a17a44f66c33699391c0
|
refs/heads/master
|
<repo_name>RyanCRickert/node-chat-app<file_sep>/server/utils/users.test.js
const expect = require("expect");
var {Users} = require("./users");
describe("Users", () => {
var users;
beforeEach(() => {
users = new Users();
users.users = [{
id: "1",
name: "Bob",
room: "example"
}, {
id: "2",
name: "Bobby",
room: "example2"
}, {
id: "3",
name: "Bobbie",
room: "example"
}]
})
it("should add new user", () => {
var users = new Users();
var user = {
id: "123",
name: "Ryan",
room: "Wow"
};
var resUser = users.addUser(user.id, user.name, user.room);
expect(users.users).toEqual([user]);
});
it("should remove a user", () => {
var remove = users.removeUser("2");
expect(remove.id).toEqual("2");
expect(users.users.length).toBe(2);
});
it("should not remove a user", () => {
var remove = users.removeUser("6");
expect(remove).toBeFalsy();
expect(users.users.length).toBe(3);
});
it("should find a user", () => {
var user = users.getUser("1");
expect(user.id).toEqual("1");
});
it("should not find a user", () => {
var user = users.getUser("5");
expect(user).toBeFalsy();
});
it("should return names for example course", () => {
var userList = users.getUserList("example");
expect(userList).toEqual(["Bob", "Bobbie"]);
});
it("should return names for example2 course", () => {
var userList = users.getUserList("example2");
expect(userList).toEqual(["Bobby"]);
});
});
|
c106d1e037509f4e9836d6538b5d17c400f05975
|
[
"JavaScript"
] | 1 |
JavaScript
|
RyanCRickert/node-chat-app
|
54105441933d37d99579b42baffc6354062e1165
|
b739367246c1c248a8f9efd906d6e276e2e2ea3a
|
refs/heads/master
|
<repo_name>steventran3/Budget-Application<file_sep>/README.md
# Budget-Application
Application to keep track of your spending
Build with vanilla javascript
https://steventran3.github.io/Budget-Application/
|
5c5e0ff6579bf8e026ff14e31949d143973b40a5
|
[
"Markdown"
] | 1 |
Markdown
|
steventran3/Budget-Application
|
f327ed5c47958d038f1aca93a0eb5670814d4072
|
d4373e2b82ba6083e1078307c5e034d5a4e597af
|
refs/heads/master
|
<file_sep>import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class DataService extends ChangeNotifier {
String topRatedUrl =
'https://api.themoviedb.org/3/movie/popular?api_key=8561ac90901236d3888023b8e21667fc&language=en-US&page=1';
String genreUrl =
'https://api.themoviedb.org/3/genre/movie/list?api_key=8561ac90901236d3888023b8e21667fc&language=en-US';
var movies = [];
var genres = [];
var genresData = [];
var topRatedMovies = [];
DataService() {
getTopRatedMovies();
}
getTopRatedMovies() async {
http.Response data = await http.get('$topRatedUrl');
var rated = json.decode(data.body);
topRatedMovies = rated['results'];
// print(topRatedMovies);
notifyListeners();
}
getGenreData() async {
http.Response id = await http.get('$genreUrl');
var gen = json.decode(id.body);
genresData = gen['genres'];
notifyListeners();
// print(genresData);
}
getChangedData(String val) async {
http.Response res = await http.get(
'https://api.themoviedb.org/3/search/movie?api_key=8561ac90901236d3888023b8e21667fc&language=en-US&page=1&query=$val');
if (res.statusCode == 200) {
var data = json.decode(res.body);
movies = data['results'];
// genres = data['results']['genre_ids'];
notifyListeners();
} else {
movies=[];
getTopRatedMovies();
print(res.statusCode);
}
}
}
<file_sep># movies
This is a Flutter Application which uses IMDB open source api for showing movies on user based input.
# Steps for building the project.
1. Get all the packages using "flutter pub get" in CLI of project directory.
2. Connect your devices to the PC.
3. Build the app using "flutter run" in CLI or use fn+F5 shortcut.<file_sep>import 'package:flutter/material.dart';
import 'package:movies/dataService.dart';
import 'movieCard.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String imageUrl = 'https://image.tmdb.org/t/p/w500/';
String genreUrl =
'https://api.themoviedb.org/3/genre/movie/list?api_key=8561ac90901236d3888023b8e21667fc&language=en-US';
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
// var width = MediaQuery.of(context).size.width;
return ChangeNotifierProvider<DataService>(
create: (context) => DataService(),
child: SafeArea(
child: Scaffold(
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(16),
child: Column(
children: <Widget>[
Consumer<DataService>(
builder: (context, dataService, child) {
return TextField(
decoration: InputDecoration(
hintText: 'Search',
hintStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w900,
),
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
style: BorderStyle.solid,
),
),
),
onChanged: (val) async {
dataService.getChangedData(val);
},
);
},
),
SizedBox(
height: height * 0.02,
),
Container(
height: height * 0.8,
child: Consumer<DataService>(
builder: (context, dataService, child) {
return ListView.builder(
itemCount: dataService.movies.length == 0
? dataService.topRatedMovies.length
: dataService.movies.length,
itemBuilder: (context, index) {
dataService.genres = [];
var genreID = dataService.movies.length == 0
? dataService.topRatedMovies[index]['genre_ids']
: dataService.movies[index]['genre_ids'];
for (var i = 0; i < genreID.length; i++)
for (var j = 0;
j < dataService.genresData.length;
j++) {
if (genreID[i] == dataService.genresData[j]['id']) {
dataService.genres
.add(dataService.genresData[j]['name']);
}
}
return dataService.movies.length != 0
? MovieCard(
imageUrl: imageUrl,
moviePicture: dataService.movies[index]
['poster_path'],
movieTitle: dataService.movies[index]['title'],
genre: dataService.genres,
rating: dataService.movies[index]
['vote_average']
.toDouble(),
)
: MovieCard(
imageUrl: imageUrl,
moviePicture: dataService.topRatedMovies[index]
['poster_path'],
movieTitle: dataService.topRatedMovies[index]
['title'],
genre: dataService.genres,
rating: dataService.topRatedMovies[index]
['vote_average']
.toDouble(),
);
},
);
}),
)
],
),
),
)),
),
);
}
}
<file_sep>import 'package:flutter/material.dart';
class MovieCard extends StatelessWidget {
const MovieCard({
Key key,
@required this.imageUrl,
@required this.moviePicture,
@required this.movieTitle,
@required this.genre,
@required this.rating,
}) : super(key: key);
final String imageUrl;
final String moviePicture;
final String movieTitle;
final List<dynamic> genre;
final double rating;
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Container(
height: height * 0.25,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned(
top: height * 0.02,
left: width * 0.08,
height: height * 0.2,
width: width * 0.8,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
child: Card(
elevation: 8.0,
),
),
),
Positioned(
left: width * 0.08,
bottom: height * 0.04,
child: Container(
height: height * 0.2,
width: width * 0.3,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
image: DecorationImage(
fit: BoxFit.fitWidth,
image: NetworkImage('$imageUrl$moviePicture'),
),
),
// child: Image.network('$imageUrl$moviePicture'),
),
),
Positioned(
top: height * 0.04,
left: width * 0.4,
child: Container(
width: width * 0.4,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
movieTitle,
textAlign: TextAlign.center,
maxLines: 2,
softWrap: true,
overflow: TextOverflow.clip,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: height * 0.01),
Wrap(
alignment: WrapAlignment.spaceEvenly,
children: <Widget>[
for (var i = 0; i < genre.length; i++)
Text(
' ${genre[i]}, ',
style: TextStyle(fontSize: 12.0),
),
],
),
SizedBox(height: height * 0.02),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$rating',
style: TextStyle(fontSize: 20, color: Colors.blue),
),
SizedBox(
width: width * 0.02,
),
Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(5, (index) {
return Icon(
index < rating.toInt() / 2
? Icons.star
: Icons.star_border,
size: 16.0,
color: Colors.orange,
);
}),
),
],
),
],
),
),
),
],
),
);
}
}
|
e3a01a017114b4abafdf8add6ae2c953ae5fd2df
|
[
"Markdown",
"Dart"
] | 4 |
Markdown
|
manikanta14038/Movies
|
a0211cdfb12585ffbc0a8417adf292c144630995
|
1ea4f0ccddf306cbd49f07afc96a699b88f5fe53
|
refs/heads/main
|
<repo_name>amtlib/knapsack<file_sep>/1.cpp
#include <iostream>
using namespace std;
int max(int a, int b) { return (a > b) ? a : b; }
int KnapsackRec(int n, int c, int weight[], int value[]) {
// Jezeli skonczyly nam sie elementy lub pojemnosc, zwracamy zero
if(n == 0 || c == 0) {
return 0;
// waga przedmiotu jest wieksza od dostepnego miejsca, wiec przechodzimy do kolejnego elementu
}else if(weight[n - 1] > c) {
return KnapsackRec(n - 1, c, weight, value);
}else {
// porownujemy wybranie elementu i jego niewybranie, wybieramy co nam daje lepszy rezultat
int tmp1 = KnapsackRec(n - 1, c, weight, value);
int tmp2 = value[n - 1] + KnapsackRec(n - 1, c - weight[n - 1], weight, value);
return max(tmp1, tmp2);
}
}
int main() {
int n = 5;
int c = 10;
int weight[] = {1, 2, 3, 2, 5};
int value[] = {5, 3, 5, 3, 2};
int values[n][c];
for(int i = 0; i < n;i++) {
for(int j = 0; j < c;j++) {
values[i][j] = -1;
}
}
cout << KnapsackRec(5, 10, weight, value) << endl;
return 0;
} <file_sep>/README.md
# Problem plecakowy
## Na czym polega?
Mamy zadaną ilość przedmiotów, wraz z ich wartościami i wagą/rozmiarem. Mamy również pojemnik (plecak), który ma określoną pojemność. Problem polega na tym, że należy podjąć decyzję, które przedmioty wybrać, by ich wartość była jak największa.
Idąc dalej, nie każdy przedmiot musi się znaleźć w pojemniku. Próbując rozwiązać ten problem licząc każdą kombinację jest ich 2^n, co już przy niewielu przedmiotach generuje bardzo dużo możliwości. Istnieje wiele podejść, które mają na celu zoptymalizowanie procesu doboru przedmiotów.
## Podejście dynamiczne
Stosując programowanie dynamiczne, mamy do wykonania następujące kroki:
1. Rekurencja
2. Zapamiętywanie wewnątrzprocesowych wyników
## Pierwszy krok - rekurencja
Liczba elementów pozostałych do rozważenia: n
Ile jeszcze zmieści się w plecaku: c
Aktualna wartośc plecaka: v
Zaczynamy sprawdzać elementy od ostatniego. Dany przedmiot może zostać umieszczony w plecaku, lub nie.
Tak:
- n = n - 1
- c = c - <waga przedmiotu>
- v = v + <wartość przedmiotu>
Nie:
- n = n -1
- c = c
- v = v
Postępujemy ze sprawdzaniem dopóki nie skończą nam się elementy do rozważenia, lub skończy się nam pojemość plecaka.
```cpp
int max(int a, int b) { return (a > b) ? a : b; }
int KnapsackRec(int n, int c, int weight[], int value[]) {
// Jezeli skonczyly nam sie elementy lub pojemnosc, zwracamy zero
if(n == 0 || c == 0) {
return 0;
// waga przedmiotu jest wieksza od dostepnego miejsca, wiec przechodzimy do kolejnego elementu
}else if(weight[n - 1] > c) {
return KnapsackRec(n - 1, c, weight, value);
}else {
// porownujemy wybranie elementu i jego niewybranie, wybieramy co nam daje lepszy rezultat
int tmp1 = KnapsackRec(n - 1, c, weight, value);
int tmp2 = value[n - 1] + KnapsackRec(n - 1, c - weight[n - 1], weight, value);
return max(tmp1, tmp2);
}
}
```
Powyższe rozwiązanie to rozwiązanie naiwne, przez co jego złożoność wynosi O(2^n). Programowanie dynamiczne polega na tym, że przechowujemy wyniki operacji, przez co nie musimy ich ponownie obliczać przy kolejnych krokach. Do tego celu skorzystamy z dwuwymiarowej tablicy, gdzie jeden wymiar będzie miał rozmiar n, a drugi c.
```cpp
int max(int a, int b) { return (a > b) ? a : b; }
int KnapsackRec(int n, int c, int weight[], int value[], int *values) {
int result;
// Jezeli mamy obliczony wynik dla danej kombinacji, po prostu go zwracamy
if(*((values+n*n) + c) != -1){
result = *((values+n*n) + c);
}
// Jezeli skonczyly nam sie elementy lub pojemnosc, zwracamy zero
if(n == 0 || c == 0) {
result = 0;
// waga przedmiotu jest wieksza od dostepnego miejsca, wiec przechodzimy do kolejnego elementu
}else if(weight[n - 1] > c) {
result = KnapsackRec(n - 1, c, weight, value, values);
}else {
// porownujemy wybranie elementu i jego niewybranie, wybieramy co nam daje lepszy rezultat
int tmp1 = KnapsackRec(n - 1, c, weight, value, values);
int tmp2 = value[n - 1] + KnapsackRec(n - 1, c - weight[n - 1], weight, value, values);
result = max(tmp1, tmp2);
}
// zapisujemy wynik operacji w odpowiedniej komorce w tablicy dwuwymiarowej
*((values+n*n) + c) = result;
return result;
}
```
Dzięki temu podejściu złożoność programu wynosi maksymalnie O(nc), co jest znacznie lepszym wynikiem niż O(2^n).
<file_sep>/2.cpp
#include <iostream>
#include <string>
using namespace std;
int max(int a, int b) { return (a > b) ? a : b; }
int KnapsackRec(int n, int c, int weight[], int value[], int *values)
{
int result;
// Jezeli mamy obliczony wynik dla danej kombinacji, po prostu go zwracamy
if (*((values + n * n) + c) != -1)
{
result = *((values + n * n) + c);
}
// Jezeli skonczyly nam sie elementy lub pojemnosc, zwracamy zero
if (n == 0 || c == 0)
{
result = 0;
}
// waga przedmiotu jest wieksza od dostepnego miejsca, wiec przechodzimy do kolejnego elementu
else if (weight[n - 1] > c)
{
result = KnapsackRec(n - 1, c, weight, value, values);
}
else
{
// porownujemy wybranie elementu i jego niewybranie, wybieramy co nam daje lepszy rezultat
int tmp1 = KnapsackRec(n - 1, c, weight, value, values);
int tmp2 = value[n - 1] + KnapsackRec(n - 1, c - weight[n - 1], weight, value, values);
result = max(tmp1, tmp2);
}
// zapisujemy wynik operacji w odpowiedniej komorce w tablicy dwuwymiarowej
*((values + n * n) + c) = result;
return result;
}
void printItemsInKnapsack(int *values, int weight[], int value[], int c, int n)
{
cout << "Wybrane przedmioty:" << endl;
int totalProfit = *((values + n * n) + c);
for (int i = n - 1; i > 0; i--)
{
if (totalProfit != *((values + i * i) + c))
{
cout << "Przedmiot o wadze " << weight[i] << " i wartosci " << value[i] << endl;
c -= weight[i];
totalProfit -= value[i];
}
}
if (totalProfit != 0)
{
cout << "Przedmiot o wadze " << weight[0] << " i wartosci " << value[0] << endl;
}
}
int main()
{
// ilosc przedmiotow, ktore bierzemy pod uwage
int n = 3;
// pojemnosc plecaka
int c = 4;
// wagi przedmiotow
int weight[] = {1, 2, 3};
// wartosc przedmiotwo
int value[] = {2, 3, 4};
// tablica przechowujaca wartosci dotychczas obliczone
int values[n][c];
// Wypelnienie tablicy pustymi wartosciami
for (int i = 0; i < n; i++)
{
for (int j = 0; j < c; j++)
{
values[i][j] = -1;
}
}
cout << KnapsackRec(n, c, weight, value, (int *)values) << endl;
// na podstawie tablicy wartosci jestesmy w stanie uzyskac poszczegolne elementy, ktore wyladowaly w plecaku
printItemsInKnapsack((int *)values, weight, value, c, n);
return 0;
}
|
7c17c54392f11f8e45b041929fa4f76ac6fa0630
|
[
"Markdown",
"C++"
] | 3 |
Markdown
|
amtlib/knapsack
|
8abb9bc9a68a88e936bf1762a15101efb2f80d2e
|
ece65173d816244f9e8a8c7211d1fedf7197acac
|
refs/heads/master
|
<repo_name>octave08/node-mqtt-tutorial<file_sep>/server/index.js
'use strict'
import express from 'express';
import mqtt from 'mqtt';
const app = express();
const client = mqtt.connect('mqtt://broker.hivemq.com', 1883);
let receivedMsg = 'No MQTT received';
function changeText(req, res) {
res.send(receivedMsg);
}
client.on('message', (topic, message) => {
console.log(message.toString());
receivedMsg = message.toString();
app.get('/', changeText);
});
client.on('connect', () => {
client.subscribe('message');
client.publish('message', "Hello MQTT");
});
app.get('/', changeText);
app.listen(8080, () => {
console.log("Express server has started on port 8080");
});
|
31cc7ed155072f6084b27001a62945eaa4a1180c
|
[
"JavaScript"
] | 1 |
JavaScript
|
octave08/node-mqtt-tutorial
|
440a2b999adb4a3331ff8639146190b03e672eb9
|
f27094c21765d4bfc53bf17605b7a4286d5ba7dc
|
refs/heads/master
|
<file_sep># expcalculator
A React sample program to do experience calculator
Please refer the below link to set up the React environment in local
https://www.raywenderlich.com/247-react-native-tutorial-building-android-apps-with-javascript
See the below one also
https://inducesmile.com/facebook-react-native/how-to-setup-react-native-for-android-app-development-in-windows/
https://www.npmjs.com/package/react-native-svg-charts
https://stackoverflow.com/questions/44149921/broadcast-reciever-not-working-when-app-is-closed
https://stackoverflow.com/questions/47425668/alarm-manager-not-working-when-app-closed
https://stackoverflow.com/questions/38995469/how-to-get-miui-security-app-auto-start-permission-programmatically
|
af6f181f9ee8774733ccbad7044acc1efee249d8
|
[
"Markdown"
] | 1 |
Markdown
|
Tamil048/ExperienceCalculator
|
ea2dd6276a465d7a59fd5b4bd6e29bacc48b2eac
|
ef0313f20b53c1c3f522d97e2f8a6258a5e4d069
|
refs/heads/master
|
<repo_name>BrinoOficial/Site<file_sep>/TED.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Br.ino - Sugestões</title>
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<body style="margin: 0;">
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<!-- ********* TEDs indicados ********* -->
<section class="ATutoriais">
<div style="position: relative; height: 2vw"></div>
<table class="TableTut">
<!-- The magical science of storytelling | <NAME> | TEDxStockholm -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxIQEBUQEBIQFRUVFRUPDxUVFQ8PFRAPFRUWFhUVFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGhAQGi0lHx0tMCstLS0tLS0tLS0tLSs3Ky0rLS0tLS0tLS0tLS8tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAKgBLAM<KEY>" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">A ciência mágica do story telling</p>
<a href="https://youtu.be/Nj-hdQMa3uA" target="_blank"><p>Assista: TED2017</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
<div style="position: relative; height: 3px"></div>
<!-- Ensine as meninas a serem corajosas, não perfeitas -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="https://pi.tedcdn.com/r/talkstar-photos.s3.amazonaws.com/uploads/82d53db4-ebad-4435-b960-b715661eb135/ReshmaSaujani_2016-embed.jpg?w=1200" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Ensine as meninas a serem corajosas, não perfeitas</p>
<a href="https://www.ted.com/talks/reshma_saujani_teach_girls_bravery_not_perfection" target="_blank"><p>Assista: TED2016</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- How hip-hop helps us understand science -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="https://pi.tedcdn.com/r/s3.amazonaws.com/talkstar-photos/uploads/3060dca6-1cb1-4fdd-b18d-23ff89568a7c/DanielleNLee_2019U-embed.jpg?op=%5E&c=1280%2C720&gravity=t&u%5Br%5D=2&u%5Bs%5D=0.5&u%5Ba%5D=0.8&u%5Bt%5D=0.03&quality=82&w=1280&h=720" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Como o hip-hop te ajuda a entender ciências</p>
<a href="https://www.ted.com/talks/danielle_n_lee_how_hip_hop_helps_us_understand_science/up-next" target="_blank"><p>Assista: TED2019</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- Este laboratório virtual vai revolucionar o ensino de ciências -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="https://pi.tedcdn.com/r/s3.amazonaws.com/talkstar-photos/uploads/fdbc019c-dc35-40a0-b301-af704f21fc1c/MichaelBodekaer_2015X-embed.jpg?op=%5E&c=1280%2C720&gravity=t&u%5Br%5D=2&u%5Bs%5D=0.5&u%5Ba%5D=0.8&u%5Bt%5D=0.03&quality=82&w=1280&h=720" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Este laboratório virtual vai revolucionar o ensino de ciências</p>
<a href="https://www.ted.com/talks/michael_bodekaer_this_virtual_lab_will_revolutionize_science_class?language=pt-br" target="_blank"><p>Assista: TEDxCERN</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- The real story of Rosa Parks — and why we need to confront myths about black history -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="Imagens/TED/DavidIkard_2018X-embed.jpg" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">A verdadeira história de Rosa Parks — e porque temo que confrontar mitos sobre a história dos negros</p>
<a href="https://www.ted.com/talks/david_ikard_the_real_story_of_rosa_parks_and_why_we_need_to_confront_myths_about_black_history" target="_blank"><p>Assista: TEDxNashville</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- Como professores podem ajudar alunos a encontrarem a voz política deles -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="https://pi.tedcdn.com/r/s3.amazonaws.com/talkstar-photos/uploads/d0dd08c9-69c6-4258-a22e-e0a73ee435bb/SydneyChaffee_2017X-embed.jpg?op=%5E&c=1280%2C720&gravity=t&u%5Br%5D=2&u%5Bs%5D=0.5&u%5Ba%5D=0.8&u%5Bt%5D=0.03&quality=82&w=1280&h=72" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Como professores podem ajudar alunos a encontrarem a voz política deles</p>
<a href="https://www.ted.com/talks/sydney_chaffee_how_teachers_can_help_kids_find_their_political_voices?language=pt-br" target="_blank"><p>Assista: TEDxBeaconStreet</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- <NAME>: o perigo de uma única história -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="Imagens/TED/ChimamandaAdichie_2009G-embed.jpg" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut"><NAME>: o perigo de uma única história</p>
<a href="https://www.ted.com/talks/chimamanda_ngozi_adichie_the_danger_of_a_single_story?language=pt-br" target="_blank"><p>Assista: TEDGlobal 2009</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- E para o meu próximo truque, um robô -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="Imagens/TED/EDYMarco.jpg" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">E para o meu próximo truque, um robô</p>
<a href="https://www.ted.com/talks/marco_tempest_and_for_my_next_trick_a_robot?language=pt-br#t-177135" target="_blank"><p>Assista: TED 2014</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- O perigo da IA é mais estranho do que se imagina -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="Imagens/TED/PerigoIA.png" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">O perigo da IA é mais estranho do que se imagina</p>
<a href="https://www.ted.com/talks/janelle_shane_the_danger_of_ai_is_weirder_than_you_think?language=pt-br#t-544593" target="_blank"><p>Assista: TED 2019</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
<table class="TableTut">
<!-- O efeito Super Mario -->
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<img src="Imagens/TED/MarkRobber.jpg" alt="TED" class="ImagemTut">
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">O efeito Super Mario</p>
<a href="https://www.youtube.com/watch?v=9vJRopau0g0 " target="_blank"><p>Assista: TEDxPenn</p></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
.ATutoriais{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/BGTutoriais.jpg");
background-attachment: fixed;
padding: 0;
}
.TitATutoriais{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
color:#efefef;
width: 40%;
font-family: Coolvetica;
}
.TableTut{
width:60%;
text-align: center;
}
.BoxLongoCinza{
background-color: #efefef;
margin-left: 20%;
width: 60%;
}
.BoxLongoVerde{
background-color: #38b54f;
margin-left: 20%;
width: 60%;
}
.FotoTut{
width:50%;
}
.ImagemTut{
width: 60%;
}
.DescricaoTutCinza{
color: #38b54f;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
}
.DescricaoTutVerde{
color: #efefef;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
width: 50%;
}
.NomeTut{
font-weight: 900;
font-size: 1.7em;
line-height: 1em;
text-align: left;
}
@media screen and (max-width: 850px) {
.ATutoriais{
background-attachment: inherit;
}
.TitATutoriais{
left: 0;
text-align: center;
font-size: 50px;
width: 100%;
}
.TableTut{
width: 95%;
}
.BoxLongoCinza{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.BoxLongoVerde{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.NomeTut{
font-weight: 700;
font-size: 1em;
line-height: .7em;
}
}
</style>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/tartaruga.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>tartaruga</title>
</head>
<meta http-equiv="refresh" content=1;url="https://blockly.games/turtle?lang=pt-br&level=1">
<body>
</body>
</html>
<file_sep>/cabecalho.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=no" />
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: optional;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: optional;
}
</style>
</head>
<body>
<header>
<a href="https://brino.cc" title="Titulo do Site"><img src="https://brino.cc/Imagens/logoNomeBranca.png" alt="Logo Branca" class="LogoTopo"></a>
<input type="checkbox" id="control-nav" />
<label for="control-nav" class="control-nav"></label>
<label for="control-nav" class="control-nav-close"></label>
<nav class="float-r">
<ul class="list-auto">
<li>
<a href="https://brino.cc/" title="Página Inicial">Home</a>
</li>
<li>
<a href="https://brino.cc/sobre" title="Conheça mais sobre o Br.ino">Sobre</a>
</li>
<!--
<li>
<a href="EJE" title="Conheça mais sobre o Br.ino">EJE</a>
</li>
<li>
<a href="SAFA" title="Conheça mais sobre o Br.ino">SAFA</a>
</li>
-->
<li>
<a href="https://brino.cc/inscricao" title="Conheça nosso curso">Cursos</a>
</li>
<li>
<a href="https://brino.cc/download" title="Faça o download do programa">Downloads</a>
</li>
<li>
<a href="https://brino.cc/tutoriais" title="Conheça tutorias gratuitos">Tutoriais</a>
</li>
<li>
<a href="https://brino.cc/dicionario" title="Veja nosso dicionário de palavras chave">Dicionário</a>
</li>
</ul>
</nav>
</header>
<style>
/* lists */
.list-full, .list-full li,
.list-auto, .list-auto li { width: 100%; float: left; display: block; position: relative; }
.list-auto, .list-auto li { width: auto; }
/* floats */
.float-l { float: left; }
.float-r { float: right; }
header {
min-height: 60px;
top: 0;
right: 0;
left: 0;
border-bottom: 1px solid #38b54f;
background: #222222;
z-index: 2;
font-family: Lato;
}
header ul {
padding: 15px 10px 0 0;
}
header li {
border-left: 1px solid #ccc;
}
header li:first-child {
border: none;
}
header li a {
display: block;
padding: 0 10px;
color: #efefef;
font-size: 16px;
line-height: 30px;
text-decoration: none;
-webkit-transition: all 300ms ease;
transition: all 300ms ease;
}
header li a:hover {
color: #38b54f;
}
input#control-nav {
visibility: hidden;
position: absolute;
left: -9999px;
opacity: 0;
}
.LogoTopo{
width: 10em;
margin-left: 10em;
}
@media screen and (max-width: 767px) {
img.LogoTopo{
margin-left: 2em;
}
}
/* content */
section {
padding: 80px 20px 50px;
font-size: 20px;
}
section:after {
content: "";
display: block;
clear: both;
}
.highlights {
position: relative;
}
.highlights input {
visibility: hidden;
position: absolute;
left: -9999px;
opacity: 0;
}
.highlights-item {
float: left;
margin: 0 0 0 2%;
width: 32%;
text-align: center;
}
.highlights-item:first-of-type {
margin-left: 0;
}
.highlights-item img {
display: block;
width: 100%;
margin: 0 0 5px;
}
.highlights-item p {
font-size: 14px;
}
.highlights-button {
display: inline-block;
padding: 10px 15px 8px;
cursor: pointer;
border-radius: 3px;
border: 1px solid #ccc;
background-color: #ececec;
-webkit-transition: background-color 300ms ease-in-out, border-color 300ms ease-in-out;
transition: background-color 300ms ease-in-out, border-color 300ms ease-in-out;
}
.highlights-button:hover {
background-color: #000;
}
.highlights-buttons {
display: none;
clear: both;
text-align: center;
}
.highlights-buttons label {
display: inline-block;
width: 15px;
height: 15px;
margin: 0 10px;
border-radius: 10px;
background-color: #ccc;
cursor: pointer;
position: relative;
overflow: hidden;
text-indent: -9999px;
-webkit-transition: background-color 300ms ease-in-out;
transition: background-color 300ms ease-in-out;
}
.highlights-buttons label:hover {
background-color: #000;
}
/* init modal */
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 10;
opacity: 0;
visibility: hidden;
-webkit-transition: all 0.5s 0.5s ease-in-out;
transition: all 0.5s 0.5s ease-in-out;
}
.modal-content {
padding: 10px;
max-width: 600px;
min-width: 360px;
max-height: 85%;
overflow: auto;
position: absolute;
top: 5%;
left: 50%;
z-index: 2;
opacity: 0;
border-radius: 3px;
background-color: #222222;
-webkit-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
transform: translate(-50%, 0);
-webkit-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
.modal-content img {
display: block;
width: 100%;
margin: 10px 0 0;
}
.modal-content p {
padding-top: 10px;
text-align: justify;
}
.modal-close {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
}
.modal-close:after {
content: "X";
float: right;
margin: 5px 5px 0 0;
width: 30px;
height: 30px;
position: relative;
z-index: 3;
text-align: center;
line-height: 30px;
cursor: pointer;
background-color: rgba(255,255,255,0.8);
border-radius: 20px;
box-shadow: 0 0 3px #000;
}
input[id*="modal_"] {
position: fixed;
left: -9999px;
top: 50%;
opacity: 0;
}
input[id*="modal_"]:checked + div.modal {
opacity: 1;
visibility: visible;
-webkit-transition-delay: 0s;
-ms-transition-delay: 0s;
transition-delay: 0s;
}
input[id*="modal_"]:checked + div.modal .modal-content {
opacity: 1;
-webkit-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
transform: translate(-50%, 0);
-webkit-transition-delay: 0.5s;
-ms-transition-delay: 0.5s;
transition-delay: 0.5s;
}
header ul.list-auto {
margin-right: 6em;
}
@media screen and (max-width: 905px) {
header nav {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: 250px;
border-left: 3px solid #38b54f;
background: #222222;
overflow-x: auto;
z-index: 2;
-webkit-transition: all 500ms ease;
transition: all 500ms ease;
-webkit-transform: translate(100%, 0);
-ms-transform: translate(100%, 0);
transform: translate(100%, 0);
}
header ul.list-auto {
padding: 0;
margin-right: 0;
}
header ul.list-auto li {
width: 100%;
border: solid #38b54f;
border-width: 0 0 1px;
}
header li a {
padding: 15px 10px;
font-family: Lato;
}
header li a:hover {
background-color: #ccc;
}
.control-nav { /* label icon */
position: absolute;
right: 20px;
top: 40px;
display: block;
width: 30px;
padding: 5px 0;
border: solid #efefef;
border-width: 3px 0;
z-index: 2;
cursor: pointer;
}
.control-nav:before {
content: "";
display: block;
height: 3px;
background: #efefef;
}
.control-nav-close {
position: fixed; /* label layer */
right: 0;
top: 0;
bottom: 0;
left: 0;
display: block;
z-index: 1;
background: rgba(0,0,0,0.4);
-webkit-transition: all 500ms ease;
transition: all 500ms ease;
-webkit-transform: translate(100%, 0);
-ms-transform: translate(100%, 0);
transform: translate(100%, 0);
}
/* checked nav */
input#control-nav {
display: block;
}
input#control-nav:focus ~ .control-nav {
border-color: #000;
box-shadow: 0px 0px 9px rgba(0,0,0,0.3);
}
input#control-nav:focus ~ .control-nav:before {
background: #000;
}
input#control-nav:checked ~ nav,
input#control-nav:checked ~ .control-nav-close {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
transform: translate(0, 0);
}
header+section {
padding-top: 80px;
}
section {
padding: 30px 15px 10px;
}
.highlights {
-webkit-transition: all 500ms ease-in-out;
transition: all 500ms ease-in-out;
}
.highlights-item {
width: 100%;
margin-left: 0;
position: absolute;
top: 0;
opacity: 0;
visibility: hidden;
-webkit-transition: all 500ms ease-in-out;
transition: all 500ms ease-in-out;
-webkit-transform: scale(0.9);
-ms-transform: scale(0.9);
transform: scale(0.9);
}
.highlights-item p {
opacity: 0;
-webkit-transition: opacity 500ms 500ms ease-in-out;
transition: opacity 500ms 500ms ease-in-out;
}
.highlights-buttons {
display: block;
padding-top: 10px;
}
/*checked*/
.highlights input:checked + div {
position: relative;
opacity: 1;
visibility: visible;
z-index: 1;
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
}
.highlights input:checked + div p {
opacity: 1;
}
.highlights input:nth-of-type(1):checked ~ .highlights-buttons label:nth-child(1),
.highlights input:nth-of-type(2):checked ~ .highlights-buttons label:nth-child(2),
.highlights input:nth-of-type(3):checked ~ .highlights-buttons label:nth-child(3) {
background-color: #000
}
.modal-content {
padding: 10px 5%;
min-width: 88%;
}
}
</style>
</body>
</html>
<file_sep>/minicurso.php
<!DOCTYPE html>
<html style="scroll-behavior: smooth;" lang=pt-br>
<!-- scroll-behavior serve para rolagem suave -->
<head>
<!-- COMECO: Rastreio google -->
<?php include_once("analyticstracking.php") ?>
<!-- FIM: Rastreio google -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Language" content="pt-br">
<!-- Google -->
<meta name="description" content="Conheça nosso curso de robótica e metodologias ativas para educadores.">
<meta name="keywords" content="curso robotica, curso arduino, curso professores,curso educadores,software,educacinal, arduino,programção,portugues,brino,br.ino,startup,robótica,tutoriais,robótica educacional"/>
<title>Br.ino - Minicurso</title>
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '711652272970556');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" alt="pixel" style="display:none"
src="https://www.facebook.com/tr?id=711652272970556&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
</head>
<body style="margin:0px; padding:0px;">
<!-- COMECO: Estilo do body -->
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
<!-- FIM: Estilo do body -->
<table style="background-image: linear-gradient(#e0e0e0,#e0e0e0); border-collapse:collapse; width: 100%;" cellpadding="0" cellspacing="0" border="0" >
<!-- COMECO: head da pagina -->
<tr>
<td background="Imagens/BG/PainelBG.png" valign="middle" style="text-align: center; background-position: center center !important; background-size: cover !important; background-attachment: fixed;">
<table width="60%" style=" margin-left: 20%; margin-right: 20%;">
<tr>
<td>
<p style="color: #efefef; font-size: 50px; padding-top: 15vh;"><b>Robótica e metodologias ativas</b></p>
</td>
</tr>
<!-- Espaco -->
<tr>
<td>
<hr style="width: 90%; height: 2px; background-image: linear-gradient(#efefef,#efefef); margin-right: auto; margin-left: auto;">
</td>
</tr>
<!-- Fim espaco -->
<tr>
<td>
<p style="color: #efefef; font-size: 35px; margin-bottom: 15vh;">Minicurso online gratuito</p>
</td>
</tr>
</table>
</td>
</tr>
<!-- FIM: head da pagina -->
<!-- COMECO: duas colunas -->
<style>
.icones{
width: 40%;
margin-left: 30%;
}
.textoIcones{
font-size: 1.5em;
color: #38b54f;
font-family:
}
</style>
<tr style=" background-image: linear-gradient(#efefef,#efefef)">
<td>
<table width="100%">
<tr>
<!-- COMECO: Primeira coluna -->
<td class="coluna">
<table width="100%" style="margin-top: 50px; margin-bottom: 50px;">
<tr>
<td width="20%">
<img src="Imagens/Icones/Calendario.png" class="icones" alt="Calendario">
</td>
<td>
<p class="textoIcones">1° aula disponível em 31 de Agosto</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/Arn.png" class="icones" alt="Arduino">
</td>
<td>
<p class="textoIcones">É possível participar mesmo sem um kit Arduino</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/Pig.png" class="icones" alt="Custo">
</td>
<td>
<p class="textoIcones">Inteiramente grátis</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/Clock_ico.png" class="icones" alt="Carga horaria">
</td>
<td>
<p class="textoIcones">Carga horária de 6 horas</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Tutoriais/HC-SR04.png" class="icones" alt="Calendario">
</td>
<td>
<p class="textoIcones">Não é necessário ter nenhum conhecimento prévio</p>
</td>
</tr>
</table>
</td>
<!-- FIM: Primeira coluna -->
<!-- COMECO: Segunda coluna -->
<td class="coluna">
<div class="boxVenda" id="Inscrever">
<!-- espaco -->
<div style="position: relative; height: 2vh"></div>
<img src="Cursos/Minicurso/CapaMinicurso.png" width="70%" style="margin-left: 15%;" alt="Capa Curso">
<h3 style="color: #efefef; text-align: center; font-size: 2em; margin-bottom: 0;">Inscrições aqui!</h3>
<table width="80%" style="margin-left: 10%;">
<tr>
<td align="center">
<!-- COMECO: Form do phpList Curso Arduino -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=8" name="subscribeform">
<div class="required"></div>
<label for="attribute1" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" >Nome: </label>
<input type="text" name="attribute1" required class="attributeinput" size="40" placeholder="Seu nome..." id="attribute1" />
<div class="required"></div>
<label for="email" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" >Email: </label>
<input type=email name=email required placeholder="Seu melhor email..." size="40" id="email" />
<input type="hidden" name="htmlemail" value="1" />
<label for="botaoDeEnvio" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" >Enviar: </label>
<input type="hidden" name="list[12]" value="signup" /><input type="hidden" name="listname[12]" value="Mini curso: Robótica e metodologias ativas"/><div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div><input type=submit name="subscribe" value="Me inscrever!" style="font-weight: bold;" onClick="return checkform();" id="submitButton">
</form>
<!-- Rastreamento Pixel Clique download -->
<script type="text/javascript">
document.getElementById('submitButton').addEventListener('click', function() {
fbq('track', 'CompleteRegistration');
}, false);
</script>
<!-- FIM Rastreamento Pixel Clique download -->
<style>
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=email], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #38b54f;
color: #efefef;
padding: 14px 20px;
margin: 8px 0;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #efefef;
color: #38b54f;
}
div.caixa {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
<!-- FIM: Form do phpList Curso Arduino -->
</td>
</tr>
</table>
</div>
</td>
<style>
/* Classe botao */
.botaoSobre{
font: normal 25px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:5px 5px 5px 5px;
/* Largura */
width:90%;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
margin-bottom: 2em;
/* Posição do botao */
position:relative;
}
/* Quando clicar nele */
.botaoSobre:active{
cursor:pointer;
position:relative;
top: 0.3vh;
}
.botaoSobre:hover{
background: #38b54f;
color:#efefef;
border-color: #efefef;
}
td.coluna{
width: 40%;
margin: 0;
}
.boxVenda{
background: #655b4a;
margin: 100px;
}
@media screen and (max-width: 850px) {
td.coluna{
width: 90%;
margin-left: 5%;
display: block;
}
div.boxVenda{
margin: 0;
}
}
</style>
<!-- FIM: Segunda coluna -->
</tr>
</table>
</td>
</tr>
<!-- FIM: duas colunas -->
<!-- COMECO: Video promocional -->
<tr width="100%" style="padding: 0; background-position: 50% 50%; background-repeat: no-repeat; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; background-image: url('Imagens/BG/Educadores.jpg'); background-attachment: fixed;" id="Video">
<td align="center">
<div class="h_iframe" align="center">
<img class="ratio estiloVideo" src="http://brino.cc/Imagens/BG/BgS1.jpg" alt="Video Brino"/>
<iframe scrolling="no" src="https://www.youtube.com/embed/C-4uhwB12nE" frameborder="0" title="Video sobre o curso" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</td>
</tr>
<style>
.h_iframe {position:relative;}
.h_iframe img.ratio {display:block;width:50%;height:50%;margin-top: 50px;margin-bottom: 50px;}
.h_iframe iframe {position:absolute;top:0;width:50%; height:100%;right: 25%;}
@media screen and (max-width: 850px) {
.h_iframe img.ratio {width:80%;height:80%;}
.h_iframe iframe {width:80%; height:100%;right: 10%;}
}
</style>
<!-- FIM: Video promocional -->
<!-- COMECO: FAQ -->
<tr style="background-image: linear-gradient(#38b54f,#38b54f); width: 100%;">
<td width="100%">
<!-- espaco -->
<div style="position: relative; height: 8vh"></div>
<h3 style="text-align: center; color: #fff; font-size: 3em;">Perguntas frequentes</h3>
<!-- espaco -->
<div style="position: relative; height: 4vh"></div>
<table width="100%">
<tr width="100%">
<td class="Coluna1FAQ">
<!-- Primeira coluna -->
<button class="collapsible"><b>Como eu faço para me inscrever?</b></button>
<div class="content">
<p>
O curso é inteiramente gratuito e as inscrições são realizadas por e-mail. Faça seu cadastro e siga os passos descritos na mensagem que você recebeu.
</p>
</div>
<button class="collapsible"><b>Recebo algum material em casa?</b></button>
<div class="content">
<p>
Não, o curso usa de simuladores e atividades 100% online. Contudo, você terá acesso a dois materiais complementares digitais. Vale lembrar que você não precisa de um kit Arduino para participar, mas quem preferir pode usar seu próprio Arduino.
</p>
</div>
<button class="collapsible"><b>Por quanto tempo terei acesso ao curso?</b></button>
<div class="content">
<p>
Esse curso permance aberto até o dia 13 de setembro de 2020.
</p>
</div>
<button class="collapsible"><b>Qual o conteúdo abordado no curso?</b></button>
<div class="content">
<p>
Este minicurso mostra os primeiros passos no mundo da robótica educacional, além de apresentar técnicas para tornar suas aulas mais ativas.
</p>
</div>
<button class="collapsible"><b>Para quem é esse curso?</b></button>
<div class="content">
<p>
O curso é voltado para educadores e entusistas da área. Ele também é super interessante para quem trabalha com crianças e jovens.
</p>
</div>
<button class="collapsible"><b>Esse curso emite certificado?</b></button>
<div class="content">
<p>
Sim, para receber seu certificado é preciso apenas completar 75% do curso até sua data de fechamento.
</p>
</div>
<!-- espaco -->
<div style="position: relative; height: 4vh"></div>
<a href="#Inscrever"><div align="center" class="botaoDownload" alt="Quero participar">Inscrição</div></a>
<!-- espaco -->
<div style="position: relative; height: 8vh"></div>
</td>
<!-- Segunda coluna -->
<td class="Coluna2FAQ">
<img src="Imagens/FAQMini.png" alt="Ornitobrino FAQ" class="ImagemFAQ">
</td>
</tr>
</table>
</td>
</tr>
<style>
.collapsible {
background-color: #efefef;
color: #38b54f;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
outline: none;
font-size: 15px;
border-style: solid;
border-color: #38b54f;
border-width: 5px;
}
.active, .collapsible:hover {
background-color: #655b4a;
}
.collapsible:after {
content: '\002B';
color: #38b54f;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
.Coluna1FAQ{
width:60%;
padding-left: 10%;
padding-right: 10%;
}
.Coluna2FAQ{
width: 40%;
vertical-align: middle;
}
.ImagemFAQ{
width: 60%;
margin-left: 20%;
}
@media screen and (max-width: 850px) {
td.Coluna1FAQ{
width:70%;
padding-left: 5%;
padding-right: 0%;
}
td.Coluna2FAQ{
width: 30%;
vertical-align: middle;
}
img.ImagemFAQ{
width: 80%;
margin-left: 10%;
}
}
</style>
<!-- Funcao para abrir e fechar os itens -->
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
<!-- FIM: FAQ -->
<style>
.botaoDownload{
font:normal 35px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #efefef;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 300px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
transition: 0.7s;
}
.botaoDownload:hover{
background: #38b54f;
color: #efefef;
}
</style>
<!-- FIM: botao inscricao -->
<!-- COMECO: depoimento -->
<tr width="100%" style="background-image: linear-gradient(#655b4a,#655b4a)">
<td>
<table width="100%">
<tr>
<td width="100%">
<p style="color: #efefef; font-size: 1.5em; text-align: center; margin-top: 8vh; margin-bottom: 3vh; font-weight: bold;">O que nossos alunos dizem</p>
</td>
</tr>
<tr>
<td width="100%">
<p style="color: #efefef; font-size: 1.3em; text-align: center; margin-top: 8vh; margin-bottom: 3vh; padding: 0 10% 0;"> "Agradeço muito pelo curso, foi excelente. Agora tenho uma visão muito melhor sobre robótica e como explorá-la utilizando diversas metodologias ativas.
Amei a parte de metodologias ativas, eu realmente não conhecia várias.
A didática e alegria de vocês no curso é sensacional. O domínio do conteúdo e os materiais extras disponíveis também foram sensacionais.
Só quero agradecer mesmo, tudo foi excelente!"</p>
</td>
</tr>
<tr>
<td width="100%">
<p style="color: #efefef; text-align: right; margin-bottom: 3vh; padding: 0 10% 0;"><NAME>ascimento, professora.</p>
</td>
</tr>
<tr>
<td width="100%">
<p style="color: #efefef; font-size: 1.3em; text-align: center; margin-top: 8vh; margin-bottom: 3vh; padding: 0 10% 0;">"Sem dúvidas foi uma das melhores experiências durante essa quarentena, todo conteúdo ministrado vai ajudar muito nessa nova jornada. Gostaria de agradecer a todos os envolvidos e avisar que já estou esperando o próximo módulo."</p>
</td>
</tr>
<tr>
<td width="100%">
<p style="color: #efefef; text-align: right; margin-bottom: 3vh; padding: 0 10% 0;">Eval<NAME></p>
</td>
</tr>
</table>
</td>
</tr>
<!-- FIM: depoimento -->
</table>
<!-- COMECO: rodapeh -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- FIM: do rodapeh -->
</body>
</html>
<file_sep>/rodape.php
<!DOCTYPE html>
<html>
<head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
</head>
<body>
<!-- A classe onde entra o BG -->
<section style="background-color: #222222; padding: 0;">
<table style="width:100%;">
<tr>
<!-- Primeira colunaRodapeh -->
<td class="colunaRodapeh">
<a href="https://brino.cc" alt="Página inicial"><img src="Imagens/logoNomeBranca.png" class="imagemLogoBrino"/></a>
</td>
<!-- Segunda colunaRodapeh -->
<td class="colunaRodapeh iconesSocial">
<!-- espaco -->
<div style="height: 1vw"></div>
<!-- comeco segunda coluna -->
<a href="https://github.com/BrinoOficial/Brino" target="_blank"><i class="fab fa-github icone"></i></a>
<a href="mailto:<EMAIL>;"><i class="far fa-envelope icone"></i></a>
<a href="tel:055(61) 9 8259-6730"><i class="fab fa-whatsapp icone" ></i></a>
<a href="https://www.instagram.com/br.ino_oficial/" target="_blank"><i class="fab fa-instagram icone"></i></a>
<a href="https://www.facebook.com/BrinoIDE/" target="_blank"><i class="fab fa-facebook-square icone"></i></a>
<a href="https://www.youtube.com/channel/UCNtwMLJg3lVNdCqko-XoODA" target="_blank"><i class="fab fa-youtube icone"></i></a>
<!-- espaco -->
<div style="height: 2vw"></div>
</td>
</tr>
</table>
<a target="_blank" href="https://goo.gl/maps/pyAcMcT9jcTiNREP9" ><p style="text-align: center; color: #EFEFEF; font-family: Lato; margin-left: 5%; margin-right: 5%;"><i class="fas fa-map-marker-alt" style="
position: relative; top: 2px; right: 6px;"></i>Brasília, DF - Asa Sul - CLS 306 Bloco C Loja 6 Andar 1</p></a>
<p style="text-align: center; color: #EFEFEF; font-family: Lato"> 2019 © Brino</p>
<!-- Espaco -->
<div style="position: relative; height: 1px"></div>
</section>
<style>
a{
text-decoration: none;
color: inherit;
}
.colunaRodapeh{
width: 50%;
text-align: left;
}
.icone{
font-size:30px;
position:relative;
margin-right: 10px;
color:#ffffff;
}
.iconesSocial{
padding-left: 20%;
}
td.segunda1{
width:50%;
text-align: center;
}
td.segunda2{
width:50%;
text-align: center;
}
.imagemLogoBrino{
width: 18%;
margin-left: 30%;
}
/* Media Queries */
@media screen and (max-width: 850px) {
td.colunaRodapeh{
width: 100%;
display: block;
align-content: center;
text-align: center;
}
.iconesSocial{
padding-left: 0%;
}
td.segunda{
display: block;
width: 100%;
text-align: center;
padding: 0;
}
td.imagemLogoBrino{
width: 50%;
}
td.colunaRodapeh{
display: block;
width: 100%;
text-align: center;
}
.imagemLogoBrino{
width: 18%;
margin: 0;
}
}
</style>
</body>
</html><file_sep>/jogos/Investigacao.php
<html class=" js">
<head>
<title> Br.ino - <NAME> </title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<!--[if IE]><script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/excanvas.min.js"></script><![endif]-->
<script type="text/javascript" src="Investigacao_arquivos/RobotLib.js"></script>
<script type="text/javascript" src="Investigacao_arquivos/RobotKeyLib.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="Investigacao_arquivos/style.css"> -->
<script language="JavaScript">
<!-- Begin
// This is version of robot3 where keys such as L R V are used to navigate
var simtime = 20 // defines how often robot simulation updated
var robot // define robot object
var active = false // is robot active?
var canvasback = "rgb(233, 234, 232)"; // default colour of background
var speeds = [0, 0] // default speeds of left and right motors
var inBoxIds = ["robleftspeed", "robrightspeed"] // names of input boxes in which speeds are entered
// function to draw environment
function checkKeySpecial() {
// keySpecial has value of a key thathas been pressed ... detect if it is special and act accordingly if so
switch (keySpecial) {
case 76 : // 'l' or 'L' mean focus on LeftSpeed Box
case 108 :
checkStr() // first tidy current string remove off characters
document.controlsys.robleftspeed.focus(); // make leftSpeed box the focus
whereFocus = 1
break
case 82 : // r or R means focus on RightSpeed Box
case 114 :
checkStr()
document.controlsys.robrightspeed.focus();
whereFocus = 2
break
case 87 : // W means toggle the revise Wire box
case 119 :
checkStr()
document.getElementById("LMBack").checked = !document.getElementById("LMBack").checked
// invert checked status of the left motor reverse checkbox
deFocus()
break
case 83 : // S means toggle stop / start simulation
case 115 :
checkStr()
setchecked()
deFocus()
break
default: checkKeyRest() // call general function which moves the robot if press IJKM etc...
}
keySpecial = 0 // have used keySpecial ... now set to 0 so dont use it again.
}
function moveTheRobot() {
// function called by timer to animate the robot
checkStrings() // check that speeds array and input texts are ok
checkKeySpecial() // next look for any keys the user has pressed
var lspeed = ( ( document.getElementById("LMBack").checked ) ? 1 : -1) * speeds[0]
// Get Left Speed by reading value from LeftSpeed box and mult by -1 if not reversed wires
var rspeed = speeds[1]
// Get Right speed by reading RightSpeed box
if (active) { // if robot has started
robot.robotDraw(false) // undraw robot in current position
robot.moveRobot(lspeed, rspeed) // move to new position, travelling at given speed
redrawEnvironment(robot.ctx) // redraw box round environment, in case partly obliterated
// which also draws the robot
}
}
function setchecked() {
// when start/stop button pressed, toggle state and update caption on button to start or stop
active = !active
document.getElementById("StopCheck").value=""+(active ? "Parar" : "Começar");
}
function setRobotTimer() {
// set up timer, and fact that moveTheRobot function is called every simtime seconds...
setInterval(function(){moveTheRobot()},simtime);
}
function load() {
// load function - called when page loaded
window.defaultStatus="RJM's Simple Robot System";
checkBrowser()
var canvas = document.getElementById("myCanvasSYS"); // get canvas
var ctx = canvas.getContext("2d");
setGrayBack()
addMouseDown (canvas) // allow mouse presses to reposition robot
document.getElementById("LMBack").checked=false // set so left speed not reversed initially
addKeySpecial() // allow user to command using keys
basicEnvironment(canvas.width, canvas.height) // define basic environment
robot = new aRobot(70, 50, 10, ctx) // define a robot
oneRobot = true // and specify robot exists
handleResize(); // so that page copes if browser resized
setRobotTimer() // enable timer for simulation
active = false // but robot not moving initially
focusOn(0) // set focus on input for left speed
}
function handleResize(evt) {
// function to cope when browser resized
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100;
doResize(newWidth)
}
window.addEventListener('resize', handleResize);
// End -->
</script>
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()">
<div class="no-js">
<!-- Fallback content here -->
<h1>Desculpe-nos, mas você precisa ativar o JavaScript do seu navegador para ter acesso a este exercício.</h1>
</div>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="js">
<table width="90%" style="margin-left: 5%; margin-right: 5%; margin-top: 2%; margin-bottom: 2%">
<tr>
<!-- Lado esquerdo -->
<td width="40%" style="vertical-align: top;" class="ColapsarColuna">
<h1>Investigação</h1>
<p>Veja o comportamento do robô variando de acordo com as velocidades inseridas em cada um dos motores.</p>
<p>A velocidade deve ser um número inteiro entre -40 e 40. Números positivos representam um movimento nas rodas no sentido horário e números negativos o sentido anti-horário.</p>
<p>Você pode clicar na arena para alterar a posição do robô.</p>
<br>
<h2>Atividades</h2>
<p>Verifique o que acontece quando são inseridos digerentes valores para o motor direito e esquerdo.</p>
<p>Faça com que o robô: Ande para frente; Ande para trás; Vire para a direita; Vire para a esquerda e Rode.</p>
</td>
<!-- Lado direito -->
<td width="60%" style="padding-left: 3%; vertical-align: top;" class="ColapsarColuna">
<table width="100%">
<tr>
<td width="100%">
<div class="robot" width="100%">
<form name="controlsys" width="100%">
<canvas id="myCanvasSYS" name="myCanvasSYS" width="766" height="300"></canvas>
<table width="100%">
<tr>
<td style="width: 50%;">
<p>Velocidades dos motores</p>
<p><input type="button" id="StopCheck" value="Começar" onclick="setchecked();"></p>
</td>
<td style="width: 50%;">
<p>Motor esquerdo <input type="text" id="robleftspeed" size="2" tabindex="1" value="0">
motor direito<input type="text" id="robrightspeed" size="2" tabindex="2" value="0"></p>
<p>Inverter motor esquerdo<input type="checkbox" id="LMBack" tabindex="3"></p>
</td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<br>
<p> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></p>
<style>
.ColapsarColuna{
display: table-cell;
}
@media only screen and (max-width: 900px){
td.ColapsarColuna{
display: block;
width: 96%;
margin-left: 2%;
margin-right: 2%;
}
}
</style>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/contador.php
<?php
if(isset($_GET['data'])){
echo "isSet";
$os=$_GET['data'];
}
$filePath = "./".$os.".txt";
/*Se o arquivo existe, leia o contador que ele possui senão inicialize com 0*/
$count = file_exists($filePath) ? file_get_contents($filePath) : 0;
// Incrementa o novo valor e subscreve com o novo número
file_put_contents($filePath, ++$count);
// Mostra o contador atual
echo "Downloads:".$count." de ".$os;
?><file_sep>/jogos/DemonstracaoUltrassonico.php
<html class=" js">
<head>
<title>Br.ino - Sensor Ultrassônico</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Language" content="pt-br">
<script type="text/javascript" src="DemonstracaoUltrassonico_arquivos/RobotLib.js"></script>
<script language="JavaScript">
<!-- Begin
var simtime = 50
var active = false
var canvasback = "rgb(233, 234, 232)" // "rgb(255, 255, 192)";
var mouseSel = -1, keySel = -1
var beams = [] // array of beams
var doingFirst = true
var pns = ["p1", "p2", "p3", "p4"]
var keySpecial
var dummyRobot
var dummyLight
function keyDeviceMove (dx, dy) {
var fac = 20
if (keySel >= 100) {
lights[keySel-100].lightDraw(false)
lights[keySel-100].lightx += dx*fac
lights[keySel-100].lighty += dy*fac
lights[keySel-100].lightDraw(true)
}
else if (keySel >= 0) {
robots[keySel].robotDraw(false)
robots[keySel].robotx += dx*fac
robots[keySel].roboty += dy*fac
robots[keySel].robotDraw(true)
}
}
function checkKeySpecial() {
// keySpecial has value of a key that has been pressed ... detect if it is special and act ,,
switch (keySpecial) {
case 83 :
case 115 : // S = start
setPulse()
break
case 84 : // T = Two Beam toggle
case 116 :
document.getElementById("twoSensors").checked = !document.getElementById("twoSensors").checked
checkTwoSensors()
break
case 82 : // M = select Robot
case 114 : keySel = 0
break
case 80 : // P = select Purple Light
case 112 : keySel = 100
break
case 67 : // V = select violet Light
case 101 : keySel = 101
break
case 66 : // B = select Blue Light
case 100 : keySel = 102
break
case 71 : // G = select Green Light
case 103 : keySel = 103
break
case 74 : // J = left // these four move the robot Left/Right/Up/Down
case 106 :
keyDeviceMove(-1, 0)
break
case 73 :
case 105 : // I=Up
keyDeviceMove(0, -1)
break
case 77 : // M = Dn
case 109 :
keyDeviceMove(0, 1)
break
case 75 : // K = Right
case 107 :
keyDeviceMove(1, 0)
break
}
keySpecial = 0 // have used keySpecial ... now set to 0 o dont do again.
}
// function to draw environment
function reportState (pndx, mess) {
// report message mess to string pn but only if pn string currently empty
var pn = pns[(doingFirst) ? pndx : pndx+2]
var swas = document.getElementById(pn).innerHTML
if ((swas.length==19)||(swas.length==20)) document.getElementById(pn).innerHTML=mess
}
function abeam(bcol, bno) { // object for a beam
this.beamno = bno // its number
this.beamx = 0 // its start position
this.beamy = 0
this.beams = 0 // size of object which started it (as affects starting point)
this.beama = 0 // angle of trabel of beam
this.timeSinceStart = -1 // time since this instance started
this.totalBeamTime = -1 // time since original beam started (sets width of beam)
this.beamcol = bcol // colour of beam
this.setBeam = setBeam
this.drawBeamPulse = drawBeamPulse
this.pulseHitTarget = pulseHitTarget
this.hitNoLight = hitNoLight
this.updateSensor = updateSensor
function setBeam(x, y, s, a, TTBTime) {
// beams starts from object at x,y of size s, angle is a
this.beamx = x + s * Math.cos(a) // actual x start position
this.beamy = y + s * Math.sin(a) // actual y start position
this.beams = s
this.beama = a
this.totalBeamTime = TTBTime // set time since beam oringinally started (0 if from robot) else if echo
this.timeSinceStart = 1 // time since actually started
}
function drawBeamPulse(show) {
// draw the pulse ... show is true if normal show, otherwise remove it
rad = 5 * this.timeSinceStart // radius of beam is set by time simnce it started
var col = (show) ? this.beamcol : canvasback // colour is background if remove else beam col
var exang = (show) ? 0 : Math.PI/64 // draw slight
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
var bw = (110-this.totalBeamTime)/10 // thickness of beam decrease over time as loses power
ctx.lineWidth = (show) ? bw+1: bw+3
ctx.strokeStyle = col
ctx.beginPath()
ctx.arc(this.beamx, this.beamy, rad, this.beama - Math.PI/8 - exang, this.beama + Math.PI/8 + exang*2)
ctx.stroke()
}
function pulseHitTarget(tnum) {
var tx = (tnum<0) ? robots[0].robotx : lights[tnum].lightx
var ty = (tnum<0) ? robots[0].roboty : lights[tnum].lighty
var ts = (tnum<0) ? robots[0].robotsz : lights[tnum].lightsz
var distbeamtolight = distance(this.beamx, this.beamy, tx, ty)
var anglebeamtolight = Math.atan2(ty-this.beamy, tx-this.beamx)
return this.timeSinceStart*5 >= distbeamtolight-ts && Math.abs(anglebeamtolight-this.beama)<Math.PI/7
}
function hitNoLight() {
// look to see if beam hits Light ... if so, start echo
var nohit = true
var ct = 0
while (ct<numLights && nohit) {
if (beams[ct+1].totalBeamTime<0 && this.pulseHitTarget(ct)) {
reportState (0, "Tempo até objeto = "+this.timeSinceStart.toString())
var retang = Math.atan2(this.beamy-lights[ct].lighty, this.beamx-lights[ct].lightx)
beams[ct+1].setBeam(lights[ct].lightx, lights[ct].lighty, lights[ct].lightsz, retang, this.totalBeamTime)
beams[ct+1].drawBeamPulse(true) // start echo
nohit = false
}
else ct++
}
return nohit
}
function updateSensor() {
if (this.timeSinceStart >= 0) {
this.drawBeamPulse(false);
this.totalBeamTime++
if (this.totalBeamTime > 100) {
if (this.beamno==0) reportState(0, "Não atingiu nenhum objeto")
reportState(1, "Retorno perdido")
this.timeSinceStart = -1
this.totalBeamTime = 0
}
else if (hitNoTarget(this.beamno)) {
this.timeSinceStart++
this.drawBeamPulse(true)
}
}
}
}
function hitNoTarget (bct) {
var ans
if (bct == 0) { // is beam from robot
ans = beams[bct].hitNoLight() // test if hit light
}
else if (beams[bct].pulseHitTarget(-1)) { // if echo hits robot
reportState(1, "Tempo até retorno = "+beams[bct].totalBeamTime.toString())
beams[bct].timeSinceStart = -1
ans = false
}
else ans = true
return ans
}
function checkRestart() {
if (document.getElementById("twoSensors").checked && doingFirst) {
var sp2 = document.getElementById("p2").innerHTML
if (sp2.length>0) {
if (beams[0].timeSinceStart > 0) beams[0].drawBeamPulse(false)
doingFirst = false
startAPulse(Math.PI/4)
}
}
}
function doTheSensor() {
for (var ct=0; ct<=numLights; ct++) beams[ct].updateSensor() //update beams
for (var ct=0; ct<numLights; ct++) lights[ct].lightDraw(true) // redraw lights
checkRestart()
robots[0].robotDraw(true) // and robot
}
function setRobotTimer() {
setInterval(function(){doTheSensor()},simtime);
}
function startAPulse (angle) {
for (var ct=1; ct<=numLights; ct++) {
beams[ct].totalBeamTime = -1
beams[ct].timeSinceStart = -1
}
beams[0].setBeam (robots[0].robotx, robots[0].roboty, robots[0].robotsz, angle, 0)
beams[0].drawBeamPulse(true)
}
function setPulse() {
var istwo = document.getElementById("twoSensors").checked
document.getElementById("p1").innerHTML="Tempo até objeto = "
document.getElementById("p2").innerHTML="Tempo até retorno = "
document.getElementById("p3").innerHTML=""
document.getElementById("p4").innerHTML=""
doingFirst = true
startAPulse ((istwo) ? -Math.PI/4 : 0)
}
function checkTwoSensors() {
if (document.getElementById("twoSensors").checked) doingFirst=false
} // bodge so dont first second sensor
function drawKeyRobot() {
dummyRobot.robotx = 170
dummyRobot.basecol = robots[0].basecol
dummyRobot.robotDraw(true)
dummyRobot.ctx.fillStyle = "black"
dummyRobot.ctx.fillText("R", dummyRobot.robotx-30, 25)
}
function drawKeyLight(ct, lstr) {
dummyLight.lightx = 270 + ct*80
dummyLight.lightcol = lights[ct].lightcol
dummyLight.lightDraw(true)
dummyLight.ctx.fillStyle = "black"
dummyLight.ctx.fillText(lstr, dummyLight.lightx-30, 25)
}
function drawKeys() {
var canvas2 = document.getElementById("myCanvasKey");
var ctx2=canvas2.getContext("2d");
ctx2.fillStyle = canvasback;
ctx2.fillRect(0, 0, canvas2.width, canvas2.height);
ctx2.fillStyle = "black"
ctx2.fillText("Tecla de seleção:", 10, 25)
drawKeyRobot()
var lkeys = "PCBG"
for (var ct = 0; ct< numLights; ct++) drawKeyLight(ct, lkeys[ct])
}
function drawEnvironment() {
var canvas = document.getElementById("myCanvasSYS");
var ctx=canvas.getContext("2d");
var cw = canvas.width / 100;
var ch = canvas.height / 100;
ctx.fillStyle = canvasback;
ctx.fillRect(0, 0, canvas.width, canvas.height);
basicEnvironment(canvas.width, canvas.height);
redrawEnvironment(ctx)
ctx.font = '14pt Calibri';
ctx.lineWidth = 2;
robots[0].robotDraw(true)
}
function getMousePos(canvas, event) {
var rect = canvas.getBoundingClientRect();
return {
x : event.pageX - rect.left - document.body.scrollLeft,
y : event.pageY - rect.top - document.body.scrollTop
};
}
function doMousedown(event) {
var canvas = document.getElementById("myCanvasSYS")
var mousepos = getMousePos(canvas, event);
var dist, sdist, ct
if (mouseSel >= 100) {
lights[mouseSel-100].lightDraw(false)
lights[mouseSel-100].lightx = mousepos.x
lights[mouseSel-100].lighty = mousepos.y
lights[mouseSel-100].lightDraw(true)
mouseSel = -1
}
else if (mouseSel >= 0) {
robots[mouseSel].robotDraw(false)
robots[mouseSel].robotx = mousepos.x
robots[mouseSel].roboty = mousepos.y
robots[mouseSel].robotDraw(true)
mouseSel = -1
}
else {
rsel = -1;
lsel = -1
sdist = 1000
for (ct = 0; ct < numRobs; ct++) {
dist = robots[ct].distFrom (mousepos.x, mousepos.y)
if (dist < sdist) {
sdist = dist
rsel = ct
}
}
for (ct = 0; ct < numLights; ct++) {
dist = lights[ct].distFrom (mousepos.x, mousepos.y)
if (dist < sdist) {
sdist = dist
lsel = ct
rsel = -1
}
}
if (rsel >= 0) {
if (sdist <= robots[rsel].robotsz * 2) mouseSel = rsel
}
else if (sdist <= lights[lsel].lightsz) mouseSel = lsel + 100
}
}
function load() {
window.defaultStatus="RJM's Simple Robot System";
document.getElementById("twoSensors").checked=false
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
document.addEventListener('keydown', function(e) { // define function for key strokes
keySpecial = e.charCode || e.keyCode // (e.keyCode)
checkKeySpecial()
}, false);
numRobs = 1
robots[0] = new aRobot(200, 150, 10, ctx, canvas.width, canvas.height)
robots[0].basecol = "rgb(0, 128, 128)"
robots[0].robNum = 0
robots[0].defineSensors([0, 0, 0])
numLights = 4
lights[0] = new aLight(450, 80, 10, ctx, 0, "purple")
lights[1] = new aLight(330, 220, 10, ctx, 1, "crimson")
lights[2] = new aLight(550, 190, 10, ctx, 2, "blue")
lights[3] = new aLight(250, 50, 5, ctx, 3, "green")
beams[0] = new abeam ("blue", 0)
beams[1] = new abeam ("green", 1)
beams[2] = new abeam ("red", 2)
beams[3] = new abeam ("orange", 3)
beams[4] = new abeam ("purple", 4)
canvas.addEventListener("mousedown", doMousedown, false); // define mouse functions
var canvas2 = document.getElementById("myCanvasKey");
var ctx2 = canvas2.getContext("2d");
ctx2.font = '14pt Calibri';
dummyRobot = new aRobot(50, 25, 10, ctx2, canvas2.width, canvas2.height)
dummyRobot.sensorTypes = [0,0,0]
dummyLight = new aLight(50, 25, 10, ctx2, 0, "black")
handleResize();
setRobotTimer()
active = true
}
function handleResize(evt) {
var canvas = document.getElementById("myCanvasSYS")
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100
canvas.setAttribute('width', newWidth);
var newHeight = (newWidth>600) ? 300 : newWidth*0.5
canvas.setAttribute('height', newHeight);
drawEnvironment();
drawKeys()
}
window.addEventListener('resize', handleResize);
// End -->
</script>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()" style="margin: 0;">
<!-- *************** Rastreador google *************** -->
<?php include_once("../analyticstracking.php") ?>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="js">
<table style="width: 100%; padding-top: 20px; padding-botton: 20px;">
<tr>
<td class="ColapsarColunaCima">
<div>
<h1 style="color: #38b54f;">Demonstração do funcionamento do sensor ultrassônico</h1>
<p>
Posicione o robô e os objetos para observar como a leitura é feita.<br>
Para movimentar um elemento basta clicar nele e em seguida no local que você deseje que ele fique.<br>
<!--Por padrão será usado um sensor apontado para a frente do robô, mas a opção para usar dois sensores também pode ser ativada.<br>-->
</p>
<h2 style="color: #38b54f;">Atalhos</h2>
<p>Para mover os itens pressione a tecla correspondente a ele e use o I, J, K ou M para mover para cima, esquerda, direita ou baixo.</p>
</div>
</td>
<td class="ColapsarColunaBaixo">
<div class="robot">
<form name="controlsys">
<canvas style="border-style: solid; border-width: medium; border-color: #38b54f;" id="myCanvasSYS" name="myCanvasSYS" width="766" height="300"></canvas>
<p></p>
<canvas id="myCanvasKey" name="myCanvasKey" width="600" height="50"></canvas>
<div class="left">
<p><input type="button" id="StopCheck" value="Acionar sensor" onclick="setPulse();"></p>
<p id="p1">Tempo até objeto = 48</p><p id="p2">Tempo até retorno = 96</p></div>
<div class="right">
<p><input type="checkbox" id="twoSensors" onchange="checkTwoSensors();" style="display: none"> <!--Dois sensores--></p>
<p id="p3"></p><p id="p4"></p>
</div>
</form>
</div>
</td>
</tr>
</table>
<span style="padding-left: 2em;"> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></span>
</div>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
.ColapsarColunaCima{
display: table-cell;
width: 40%;
padding-left: 5%;
padding-right: 5%;
vertical-align: top;
}
.ColapsarColunaBaixo{
width: 60%;
padding-right: 5%;
vertical-align: top;
}
@media only screen and (max-width: 900px){
td.ColapsarColunaCima{
display: block;
padding-left: 2%;
padding-right: 2%;
width: 96%;
}
td.ColapsarColunaBaixo{
display: block;
padding-left: 2%;
padding-right: 2%;
width: 96%;
}
}
</style>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
<div class="no-js">
<!-- Fallback content here -->
<h1>Sentimos muito, mas é preciso usar um navegador com Javascript disponível para acessar esse simulador.</h1>
</div>
</body>
</html><file_sep>/entrevista1.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0, ">
<title>Mês das Mulheres #1</title>
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<body>
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php"?>
</header>
<!-- ********* Titulo ********* -->
<section class="titulo">
<!-- espaco -->
<div style="position: relative; height:5vw"></div>
<h1 class="linhaTitUm">Entrevista<br>com<br><span style="color: #38b54f; font-family: Coolvetica;"><NAME>
</span></h1>
<!-- espaco -->
<div style="position: relative; height: 4vw"></div>
</section>
<!-- ********* Video ********* -->
<section class="video" id="video">
<!-- Espacamento antes do titulo -->
<div style="position: relative; height: 8vw"></div>
<img src="Imagens/GedeaneFinal.png" alt="Gedeane" class="imagemMulher">
<!-- espaco no fim do BG -->
<div style="height: 2vw"></div>
</section>
<!-- ********* texto sobre ********* -->
<section class="bgTexto">
<!-- espaco -->
<div style="height: 1vw"></div>
<p class="textop"> Para comemorar o mês das mulheres (pq só um dia é muito pouco) o Br.ino preparou uma série de postagens e entrevistas sobre mulheres que lutam contra os estereótipos e conquistam seu espaço na área da tecnologia.
Para começar, convidamos alguém que nos inspira muito:<br>
<b><NAME></b>
é professora na ETEC <NAME> no curso técnico em Eletrônica. Mestranda em Automação e Controle de Processos, Engenheira de Controle e Automação, Técnica em Automação industrial, todos pelo IFSP. Deu seus primeiros passos com a plataforma Arduino em 2013, e desde 2015 tem ministrado palestras, oficinas e workshops com os temas de Arduino, circuitos vestíveis, eletrônica, mulheres makers, Internet das Coisas e Movimento Maker.Já redigiu artigos para o portal Embarcados, Blog FilipeFlop e atualmente é colaboradora do site Instituto Newton C Braga.</p><br><br><br><br>
<h3 class="tituloMenor">Leia a entrevista:</h3><br><br>
<p class="textop"><b>1 - Como você começou no mundo da eletrônica? Com quantos anos?</b><br>
"O meu ingresso na área parece meio tardio, mas foi com 20 anos, quando entrei no curso técnico em Automação Industrial no IFSP Guarulhos. Eu não tinha a menor ideia do que era automação, prestei vestibulinho por sugestão de um amigo da minha mãe, que é professor. Minha vontade era prestar pra informática sempre gostei de computadores. Porém me apaixonei na primeira aula, de instalações elétricas, onde o professor mostrou como funcionava uma lâmpada."<br>
<br>
<b>2 - O que te motivou / motiva a entrar nesse mundo tecnológico?</b><br>
"Desde a infância eu tinha um sonho de trabalhar com computadores. Mas por incrível que pareça, eu queria ser secretária pra ficar mexendo em computadores (risos). Ouvia dizer que engenharia era muito difícil, nem tinha pretensão de fazer. Mas quando ia na casa de alguém que tinha um computador, eu queria simplesmente apertar algum botão pra dizer que mexi. "<br><br>
<b>3 - Acha que as mulheres estão conseguindo seu espaço nesse mercado?</b><br>
"Ainda há muito pra se explorar. Tem poucas mulheres na área de robótica/eletrônica/Automação e há necessidade de incentiva-las muito mais a permanecer nos cursos."
<br><br>
<b>4 - Hoje em dia , acha que valeu a pena investir sua educação nessa área?</b><br>
"Sem dúvidas. Eu me encontrei fazendo o que gosto. É muito legal saber como as coisas funcionam e como fazer sistemas e projetos do "zero". A integração entre hardware e software na prática é muito legal."<br><br>
<b>5 - Como lidou (caso tenha acontecido) com o preconceito de gênero no seu curso?</b><br>
"No primeiro dia de aula no curso técnico, passei por algo que sempre relato em minhas palestras. Um dos funcionários fez uma visita pelo campus, depois pediu pra que a gente se dividissem em Automação e Informática. Eu fui pro lado da automação. Quando ele olhou, falou: "nossa, mulher fazendo automação? Vão ser as primeiras a desistir".<br>
Pra quem estava caindo de para quedas em um curso que nem sabia do que se tratava foi desanimador. Porém, adoraria encontrá-lo pra dizer que além do curso Técnico em Automação, me formei como Engenheira de Controle e Automação, faço palestras, oficinas e até artigos sobre o assunto, além de cursar mestrado em Automação e Controle de Processos."<br><br>
Fique ligado pra ver mais exemplos de mulheres que manjam muito de tecnologia!!</p>
<p class='textop'>Confira também a nossa segunda entrevista com <a href="entrevista2" style="text-decoration=none;color:#38b54f;"><NAME></a>!</p>
<!-- espaco -->
<div style="height: 9vw"></div>
</section>
</body>
<style>
body{
margin:0px;
padding:0px;
}
.imagemMulher{
width: 30%;
margin-left: 35%;
}
.espaco{
width: 4%;
}
.titulo{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/Computador.jpg");
}
.tituloMenor{
color: #000;
margin-left: 20%;
}
h1.linhaTitUm{
font-size: 6em;
line-height: 0.9em;
font-weight: 400;
color: #ffffff;
position: relative;
left: 30%;
width: 70%;
font-family: Coolvetica;
}
@media screen and (max-width: 500px) {
img.imagemMulher{
width: 50%;
margin-left: 25%;
}
h1.linhaTitUm{
text-align: center;
font-size: 5em;
left: 0;
width: 100%;
}
h3.tituloMenor{
text-align: center;
margin-left: 0;
}
}
.linhaTitDois{
font-size: 80px;
color: #ffffff;
position: relative;
left: 30%;
width:20%;
}
.video{
background-color: #efefef;
}
.bgTexto{
background-color: #efefef;
}
.textoSob{
width: 100%;
}
.textop{
margin-left: 25%;
margin-right: 25%;
color: #000;
text-align: justify;
}
@media screen and (max-width: 500px) {
p.textop{
margin-left: 15%;
margin-right: 15%;
text-align: center;
}
p.submvvVal{
text-align: center;
}
p.submvv{
text-align: center;
}
h1.titVideo{
font-size: 3em;
margin-left: 0;
text-align: center;
}
}
.bgContato{
background-color: #f2f2f2;
}
@media screen and (max-width: 800px) {
p.linhaVendasUm{
font-size: 15vw;
text-align: center;
left: 0%;
right: 900px;
}
p.linhaVendasDois{
font-size: 13vw;
text-align: center;
left: 0%;
}
}
@font-face {
font-family: Coolvetica;
src: url(Coolvetica.ttf);
}
@font-face {
font-family: Lato;
src: url(Lato.ttf);
}
h1, h2, h3, h4{
font-family: Coolvetica;
font-size: 3em;
}
p, input, li, textarea, ol, spam, table, th, tr, header{
font-family: Lato;
font-size: 1em;
}
</style>
<!-- ********* rodapeh ********* -->
<footer align="left">
<?php include "rodape.php" ?>
</footer>
<!-- fim do rodapeh -->
<meta name="description" content="Conheça o software que visa a democratização da robótica e do movimento maker diminuindo as barreiras para o aprendizado!!!">
</html>
<file_sep>/brino/receber_log.php
<?php
reset($_FILES);
$first_key = key($_FILES);
$uploaddir = "logs/";
$uploadfile = $uploaddir . basename( $first_key.".log");
if(move_uploaded_file($_FILES[$first_key]['tmp_name'], $uploadfile))
{
echo "LOG enviado";
} else
{
echo "LOG não enviado";
}
?>
<file_sep>/index.php
<!doctype html>
<html lang=pt-br>
<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-KV2MXDP');</script>
<!-- End Google Tag Manager -->
<?php
if(isset($_GET["file"])){
// Get parameters
$file = $_GET["file"]; // Decode URL-encoded string
$filepath = "downloads/" . $file;
echo "<meta http-equiv=\"refresh\" content=\"0;url=https://brino.cc/baixar.php?file=".$file."\" target = \"_blank\"/>";
}
?>
<meta charset="utf-8">
<title>Br.ino - Robótica educacional</title>
<link rel="shortcut icon" href="favicon.ico" />
<meta name="google-sdownte-verification" content="v8paVM-jrk0KWi2fnT4rpKGYW_IP7bn3PSevhzq2SJQ" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Language" content="pt-br">
<!-- Google -->
<meta name="description" content="O Br.ino objetiva democratizar o ensino da robótica de forma intuitiva e acessível para jovens. ">
<meta name="keywords" content="curso robotica, curso arduino, curso professores,curso educadores,software,educacinal, arduino,programção,portugues,brino,br.ino,startup,IDE,fácil,robótica,tutoriais,grátis,robótica educacional,voluntariado,voluntario, social"/>
<!-- Marcação JSON-LD gerada pelo Assistente de marcação para dados estruturados do Google. -->
<script type="application/ld+json">
{
"@context" : "http://schema.org",
"@type" : "LocalBusiness",
"name" : "Br.ino",
"image" : "https://brino.cc/Imagens/logoNomeBranca.png",
"telephone" : "(61) 9 8259-6730",
"email" : "<EMAIL>",
"address" : {
"@type" : "PostalAddress",
"streetAddress" : "Asa Sul - CLS 306 Bloco C Loja 6 Andar 1",
"addressLocality" : "Brasília",
"addressRegion" : ", DF"
},
"url" : "https://brino.cc/"
}
</script>
<!-- *************** Fontes *************** -->
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
@font-face {
font-family: ZillaSlab;
src: url("Fontes/ZillaSlab-Medium.ttf");
font-display: swap;
}
@font-face {
font-family: FiraSans;
src: url("Fontes/FiraSans-Regular.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
font-size: 3em;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
font-size: 1em;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KV2MXDP"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<!-- *************** Chamada *************** -->
<div class="ChamadaSection">
<!-- espaco -->
<div style="position: relative; height:3vw"></div>
<section>
<p class="LinhaUmChamada">Aprenda<br><spam style="font-family: Coolvetica;color: #38b54f;">Robótica e Metodologias Ativas</spam></p>
</section>
<!-- espaco -->
<div style="position: relative; height: 6vh"></div>
<!-- Chamada de botão começar-->
<a href="inscricao" title="Curso para educadores"><div align="center" class="botaoChamada">Saber mais!</div></a>
<!-- espaco -->
<div style="position: relative; height: 8vw"></div>
</div>
<style>
.ChamadaSection{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/Educadores.jpg");
}
.LinhaUmChamada{
margin: 0;
font-size: 4.5vw;
line-height: 5vw;
font-weight: 800;
color: #ffffff;
position: relative;
text-align: center;
}
.LinhaDoisChamada{
margin: 0;
font-size: 5vw;
line-height: 5vw;
font-weight: 600;
color: #ffffff;
position: relative;
text-align: center;
}
.botaoChamada{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 200px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.botaoChamada:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.botaoChamada:hover{
background: #efefef;
color: #38b54f;
border:1px solid #38b54f;
}
@media screen and (max-width: 850px) {
.LinhaUmChamada{
font-size: 12vw;
line-height: 13vw;
}
.LinhaUmChamada{
font-size: 8vw;
line-height: 9vw;
}
.ChamadaSection{
background-attachment: inherit;
}
}
</style>
<!-- *************** Sobre o Br.ino *************** -->
<section style="background-color: #ebebeb;" id="sobre">
<!-- espacamento antes do titulo -->
<div style="position: relative; height: 5vw"></div>
<!--Ancora do "Sobre" -->
<h1 class="sobre" id="sobre"> Sobre o Br<a rel=”noreferrer” target="_blank" href="https://www.google.com.br/search?q=breakout&biw=1922&bih=947&source=lnms&tbm=isch&sa=X&ved=0ahUKEwij6-fp9fTQAhUHWCYKHX2CACgQ_AUIBigB#tbm=isch&q=atari+breakout">.</a>ino </h1>
<!-- espaco depois do titulo -->
<div style="position: relative; height: 2vw"></div>
<table>
<!-- Primeira coluna -->
<tr align="left">
<th class="thSobre">
<!-- espaco -->
<div style="position: relative; height: 3vw"></div>
<a href="sobre.php" align="center">
<video autoplay loop muted playsinline width="40%" style="margin-left: 30%;">
<source src="Imagens/FogueteAnimado.mp4" type="video/mp4">
</video>
</a>
<!-- espaco -->
<div style="position: relative; height: 3vw"></div>
</th>
<!-- Segunda coluna -->
<th class="thSobre">
<p class="textoSobre">"Br.ino é a startup que revolucionará o ensino de robótica no Brasil. Fundada por jovens universitários, a empresa concentra seus esforços no desenvolvimento de ferramentas intuitivas e acessíveis, que melhorem o processo de aprendizagem.<br>
<br><br>
Nossa missão é romper com o mito de que robótica é um setor para poucos. Trabalhamos todos os dias para que qualquer um possa conhecer mais sobre esse setor tão vasto. O mundo está repleto de boas ideias e nós, da Br.ino, vamos garantir que nenhuma se perca pelo caminho.”<br><br>
<NAME><br>
sócio diretor</p>
<!-- Botao para pagina Sobre -->
<a href="sobre" alt="Ir para a página sobre a equipe"><div align="center" class="botaoSobre">Saiba mais</div></a>
</th>
</tr>
</table>
</section>
<style>
.imagemSobre {
width: 40%;
margin-left: 35%;
}
.textoSobre{
width: 92%;
margin-right: 8%;
text-align: right;
}
/* Classe botao mais */
.botaoSobre{
font: normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:5px 5px 5px 5px;
/* Largura */
width:200px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
margin-bottom: 2em;
/* Posição do botao */
position:relative;
}
/* Quando clicar nele */
.botaoSobre:active{
cursor:pointer;
position:relative;
top: 0.3vh;
}
.botaoSobre:hover{
background: #38b54f;
color:#efefef;
}
.sobre {
position: relative;
left: 15vw;
font-size: 50px;
color:#38b54f;
width: 40%;
}
.thSobre{
width: 20%;
}
@media screen and (max-width: 850px) {
.tamImgSob{
width: 40%;
}
.sobre {
text-align: center;
left: 0;
width: 100%;
}
.imagemSobre {
width: 50%;
margin-left: 25%;
margin-right:25%;
}
th.thSobre{
width: 100%;
display: block;
}
.textoSobre{
text-align: center;
width: 65%;
margin-left: auto;
margin-right: auto;
margin-bottom: 8vw;
}
}
</style>
<!-- *************** Box Ebook *************** -->
<section style="width: 100%;" class="BoxSection">
<div style="position: relative; height: 2vw"></div>
<h2 class="BoxEbookTitulo">E-book Br.ino</h2>
<div style="position: relative; height: 2vw"></div>
<table align="center">
<tr>
<th class="CaixaVerde">
Eletrônica
</th>
<th class="CaixaCinza">
<video autoplay loop muted playsinline width="40%">
<source src="Imagens/LED.mp4" type="video/mp4">
</video>
</th>
</tr>
<tr>
<th class="CaixaCinza">
<video autoplay loop muted playsinline width="40%">
<source src="Imagens/IDEPreenchendo.mp4" type="video/mp4">
</video>
</th>
<th class="CaixaVerde">
Programação
</th>
</tr>
<tr>
<th class="CaixaVerde">
Projetos
</th>
<th class="CaixaCinza">
<video autoplay loop muted playsinline width="40%">
<source src="Imagens/Carro.mp4" type="video/mp4">
</video>
</th>
</tr>
</table>
<div style="position: relative; height: 3vw"></div>
</section>
<style>
.BoxEbookTitulo{
position: relative;
left: 15vw;
font-size: 50px;
color:#efefef;
width: 40%;
}
.CaixaCinza{
background-color: #EBEBEB;
width: 20vw;
height: 15vw;
align-items: center;
}
.CaixaVerde{
background-color: #38b54f;
width: 20vw;
height: 15vw;
color: #efefef;
font-size: 2.5vw;
font-family: Coolvetica;
}
.BoxSection{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/BGVictorEBaliza.png");
background-attachment: fixed;
padding: 0;
}
@media screen and (max-width: 850px) {
.BoxEbookTitulo{
position: relative;
left: 0;
text-align: center;
font-size: 30px;
color:#efefef;
width: 100%;
}
.CaixaCinza{
background-color: #ebebeb;
width: 45%;
height: 25vw;
}
.CaixaVerde{
background-color: #38b54f;
width: 45%;
height: 25vw;
color: #efefef;
font-size: 8vw;
font-family: Coolvetica;
}
}
</style>
<!-- *************** Download da apostila *************** -->
<section id="IdDownloadApostila" style="background-color: #efefef;">
<!-- espacamento antes do titulo -->
<div style="position: relative; height: 1vw"></div>
<table style="width: 100%;">
<tr>
<th class="thSobre" width="40%;">
<img src="Cursos/EducacaoDoFuturo/CapaNutror.png" alt="Ebook" width="80%">
</th>
<th class="thSobre">
<h3 style="color: #38b54f; margin-right: 5%; margin-left: 5%; line-height: 8vw;" class="tamanhoCel">Quer melhorar as suas aulas? Nós ajudamos</h3>
<br>
<ul class="anchorList" style="list-style-type: none; padding: 0;">
<!-- Chamada de botão download-->
<li style="width: 100%; margin: 0;"><a href="#inscricao"><div align="center" class="botaoDownload" alt="Conferir">Saber mais</div></a></li>
</ul>
</th>
</tr>
</table>
<div style="position: relative; height: 3vw"></div>
</section>
<style>
.botaoDownload{
font:normal 40px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 300px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
}
.botaoDownload:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.botaoDownload:hover{
background: #efefef;
color: #38b54f;
border:1px solid #38b54f;
}
@media screen and (max-width: 850px) {
.tamanhoCel{
font-size: 7vw;
line-height: 8vw;
}
}
</style>
<!-- *************** Contato *************** -->
<section class="ContatoSection" id="contato">
<table width="100%">
<tr>
<th class="thContato" style="align:center;">
<!-- PRIMEIRA COLUNA -->
<!-- espaco -->
<div style="position: relative; height: 3vw"></div>
<!-- Titulo -->
<h2 class="contato"> Contato </h2>
<!-- espaco -->
<div style="position: relative; height: 3vw"></div>
<!-- Comeco do formulario -->
<form action="contato.php" method="get" id="contato" name="contato" target="_self">
<div align="center">
<div class="container" style="position:relative;">
<div class="head"></div>
<label for="name" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" >Nome: </label>
<input class="inIndex" style="color:#474747;" type="name" required name="name" id="name" value="Nome" onfocus="if(this.value=='Nome') this.value='';" onblur="if(this.value=='') this.value='Nome';" />
<br />
<label for="emailContato" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" >Email: </label>
<input class="inIndex" style="color:#474747;" type="email" required name="emailContato" id="emailContato" value="E-mail" onfocus="if(this.value=='E-mail') this.value='';" onblur="if(this.value=='') this.value='E-mail';" />
<br />
<label for="message" style="border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px;" >Mensagem: </label>
<textarea style="color:#474747;" class="inIndex" type=text required name="message" id="message" onfocus="if(this.value=='Mensagem') this.value='';" onblur="if(this.value=='') this.value='Mensagem';">Mensagem</textarea>
<br />
<input type="hidden" name="recipient" id="recipient" value="<EMAIL>">
<input type="hidden" name="subject" id="subject" value="formulario">
<!-- Chamada de botão enviar-->
<div align="center"> <button id="submit" type="submit" name="submit" class="BotaoFormIndex">Enviar</button></div>
</div>
</div>
</form>
<style>
.inIndex {
width: 60%;
padding: 12px 20px;
margin: 8px 0;
margin-left: auto;
margin-right: auto;
display: inline-block;
border: 1px solid #ccc;
border-radius: 15px;
box-sizing: border-box;
font-family: Coolvetica;
font-size: 17px;
}
/* Style do botao */
.BotaoFormIndex {
width: 30%;
background-color: #38b54f;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: 0;
border-radius: 5px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
font-family: Coolvetica;
}
.BotaoFormIndex:hover {
background-color: #428209;
}
</style>
<!-- fim do formulario -->
<!-- espaco -->
<div style="position: relative; height: 10vw"></div>
<!-- declaracao caixa face
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.8";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!-- Box do face
<div align="center">
<iframe src="https://www.facebook.com/plugins/page.php? href=https%3A%2F%2Fwww.facebook.com%2FBrinoIDE&tabs&width=340&height=500&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=false&appId" width="340" style="border:none;overflow:hidden; position:relative; right: %" scrolling="no" frameborder="0" allowTransparency="true"></iframe>
<!-- Fim box face -->
<!-- espaco -
<div style="height: 5vw"></div> -->
</div>
<!-- Fim da primeira coluna -->
</th>
<th class="thContato">
<!-- COMECO DA SEGUNDA COLUNA -->
<aside class="colCon">
<!-- espaco -->
<div style="height: 13vw"></div>
<!-- comeco segunda coluna -->
<p align="center" style="color:#ffffff; font-size:20px; position:relative;"><a href="mailto:<EMAIL>;"><i class="far fa-envelope" style="font-size:50px; position:relative; right: 5%; top: 1vw; color:#ffffff;"></i><EMAIL></a></p>
<p align="center"style=" color:#ffffff; font-size:20px; position:relative;"><a href="tel:055(61) 9 9913-6506"><i class="fab fa-whatsapp" style="font-size:50px; position:relative; right: 5%; top: 1vw; color:#ffffff;"></i>(61) 9 9913-6506</a></p>
<p align="center" style="color:#ffffff; font-size:20px; position:relative;"><a href="https://www.instagram.com/br.ino_oficial/" rel=”noreferrer” target="_blank"><i class="fab fa-instagram" style="font-size:50px; position:relative; right: 5%; top: 0.7vw; color:#ffffff;"></i>br.ino_oficial</a></p>
<p align="center" style="color:#ffffff; font-size:20px; position:relative;"><a href="https://www.facebook.com/BrinoIDE/" rel=”noreferrer” target="_blank"><i class="fab fa-facebook-square" style="font-size:50px; position:relative; right: 5%; top: 0.7vw; color:#ffffff;"></i>BrinoIDE</a></p>
<p align="center" style="color:#ffffff; font-size:20px; position:relative;"><a href="brino.cc/comunidade" rel=”noreferrer” target="_blank"><i class="fab fa-telegram-plane" style="font-size:50px; position:relative; right: 5%; top: 0.7vw; color:#ffffff;"></i>Participar</a></p>
<p align="center" style="color:#ffffff; font-size:20px; position:relative;"><a href="https://www.youtube.com/channel/UCNtwMLJg3lVNdCqko-XoODA" rel=”noreferrer” target="_blank"><i class="fab fa-youtube" style="font-size:50px; position:relative; right: 5%; top: 0.7vw; color:#ffffff;"></i>Brino</a></p>
<!-- espaco -->
<div style="height: 7vw"></div>
</aside>
<!-- Fim da segunda coluna -->
</th>
</tr>
</table>
</section>
<style>
.thContato{
width="40%";
}
.ContatoSection{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/Computador.jpg");
background-attachment: fixed;
}
h2.contato{
position: relative;
left: 7vw;
font-size: 50px;
color:#efefef;
width: 40%;
}
@media screen and (max-width: 850px) {
h2.contato{
left: 0;
text-align: center;
width: 100%;
}
th.thContato{
width: 100%;
display: block;
}
.ContatoSection{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/Computador.jpg");
background-attachment: inherit;
}
}
</style>
<style>
a{
text-decoration: none;
color: inherit;
}
</style>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<!-- Download Apostila -->
<div id="DownloadApostilaModal" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF; font-size: 1.5em;">Para completar o Download complete os campos abaixo:</h2>
</div>
<!-- Form do phpList baixar apostila -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=4″ name="subscribeform" class="formPopUp">
<div class="required" style="color: #ffffff;"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" required placeholder="Seu nome..." size="40" value="" id="attribute1" class="in attributeinput"/>
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required" style="color: #ffffff;"><label for="email">Email</label></div>
<input type="email" name="email" required placeholder="Seu email..." size="40" id="email" class="in"/>
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="htmlemail" value="1" />
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/EbookBrinoFree.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[8]" value="signup" />
<input type="hidden" name="listname[8]" value="Download IDE Br.ino"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input class="BotaoForm" type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF; font-size: 1.5em;">Você está baixando o Ebook Brino!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!--CSS do formulario -->
<style>
.in {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
margin-left: auto;
margin-right: auto;
display: inline-block;
border: 1px solid #ccc;
border-radius: 15px;
box-sizing: border-box;
font-family: Coolvetica;
font-size: 17px;
}
/* Style do botao */
.BotaoForm {
width: 30%;
background-color: #38b54f;
color: #efefef;
padding: 14px 20px;
margin: 8px 0;
border: 0;
border-radius: 5px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
font-family: Coolvetica;
border:1px solid rgba(0,0,0,0);
}
.BotaoForm:hover {
background-color: #efefef;
border:1px solid #38b54f;
color: #38b54f;
}
.modalDialog {
position: fixed;
font-family: Lato;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity:1;
pointer-events: auto;
}
.modalDialog > div {
width: 60%;
position: relative;
margin: 10% auto;
margin-bottom: 0;
margin-top: 0;
padding: 5px 20px 13px 20px;
border-radius: 5px;
background-color: #38b54f;
}
.close {
color: #efefef;
line-height: 25px;
float: right;
text-decoration: none;
font-weight: bold;
}
.formPopUp{
background: rgba(0,0,0,0.5);
width: 60%;
padding: 5px 20px 13px 20px;
margin: 10% auto;
margin-bottom: 0;
margin-top: 0;
}
@media screen and (max-width: 700px) {
.modalDialog > div {
width: 90%;
}
.formPopUp{
width: 90%;
padding: 20px 0 20px 0;
}
}
</style>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/inscricao.php
<!DOCTYPE html>
<html style="scroll-behavior: smooth;" lang=pt-br>
<!-- scroll-behavior serve para rolagem suave -->
<script src="https://www.googleoptimize.com/optimize.js?id=OPT-MQQ2VZN"></script>
<head>
<!-- COMECO: Rastreio google -->
<?php include_once("analyticstracking.php") ?>
<!-- FIM: Rastreio google -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Language" content="pt-br">
<!-- Google -->
<meta name="description" content="Seja o(a) professor(a) com quem você gostaria de aprender!
O curso Educação do futuro é a formação para educadores que desejam se reinventar e utilizar tecnologia, mundo maker e metodologias ativas de aprendizagem em suas aulas. Aqui você encontra aulas contextualizadas, que utilizam as próprias metodologias ativas para ensinar sobre robótica, plataformas digitais e como integrar esses conteúdos no currículo tradicional.">
<meta name="keywords" content="curso robotica, curso arduino, curso professores,curso educadores,software,educacinal, arduino,programção,portugues,brino,br.ino,startup,robótica,tutoriais,robótica educacional"/>
<title>Br.ino - Curso Robótica e Metodologias Ativas</title>
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '711652272970556');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" alt="pixel" style="display:none"
src="https://www.facebook.com/tr?id=711652272970556&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
</head>
<body style="margin:0px; padding:0px;">
<!-- COMECO: Estilo do body -->
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
<!-- FIM: Estilo do body -->
<table style="background-image: linear-gradient(#e0e0e0,#e0e0e0); border-collapse:collapse; width: 100%;" cellpadding="0" cellspacing="0" border="0" >
<!-- COMECO: head da pagina -->
<tr>
<td background="Imagens/BG/BgVictorTecAssis.png" valign="middle" style="text-align: center; background-position: center center !important; background-size: cover !important; background-attachment: fixed;">
<table width="60%" style=" margin-left: 20%; margin-right: 20%;">
<tr>
<td>
<p style="color: #efefef; font-size: 50px; padding-top: 15vh;"><b>Educação do Futuro</b></p>
</td>
</tr>
<!-- Espaco -->
<tr>
<td>
<hr style="width: 90%; height: 2px; background-image: linear-gradient(#efefef,#efefef); margin-right: auto; margin-left: auto;">
</td>
</tr>
<!-- Fim espaco -->
<tr>
<td>
<p style="color: #efefef; font-size: 35px; margin-bottom: 15vh;">Robótica e metodologias ativas no ensino 4.0</p>
</td>
</tr>
</table>
</td>
</tr>
<!-- FIM: head da pagina -->
<!-- COMECO: duas colunas -->
<style>
.icones{
width: 40%;
margin-left: 30%;
}
.textoIcones{
font-size: 1.5em;
color: #38b54f;
font-family:
}
</style>
<tr style=" background-image: linear-gradient(#efefef,#efefef)">
<td>
<table width="100%">
<tr>
<!-- COMECO: Primeira coluna -->
<td class="coluna">
<table width="100%" style="margin-top: 50px; margin-bottom: 50px;">
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/AprendaDoZero.png" class="icones" alt="Calendario">
</td>
<td>
<p class="textoIcones">Aprenda robótica do zero e 100% online</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/NPossuirKitDeRobotica.png" class="icones" alt="Arduino">
</td>
<td>
<p class="textoIcones">Não é necessário possuir kit de robótica</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/16Metodologias.png" class="icones" alt="Custo">
</td>
<td>
<p class="textoIcones">16 metodologias ativas para aplicar</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/CargaHoraria.png" class="icones" alt="Carga horaria">
</td>
<td>
<p class="textoIcones">Carga horária de 60 horas</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/ConhecimentoPrevio.png" class="icones" alt="Calendario">
</td>
<td>
<p class="textoIcones">Não é necessário ter nenhum conhecimento prévio</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/CriacaoDeProjetosEApllicativos.png" class="icones" alt="Calendario">
</td>
<td>
<p class="textoIcones">Criação de projetos e aplicativos</p>
</td>
</tr>
<tr>
<td width="20%">
<img src="Imagens/Icones/VendasOEducador/Simuladores.png" class="icones" alt="Calendario">
</td>
<td>
<p class="textoIcones">Aprenda com simuladores e jogos</p>
</td>
</tr>
</table>
</td>
<!-- FIM: Primeira coluna -->
<!-- COMECO: Segunda coluna -->
<td class="coluna">
<div class="boxVenda" id="Inscrever">
<!-- espaco -->
<div style="position: relative; height: 2vh"></div>
<a href="https://cursos.nutror.com/curso/924a1dc5b51f3a68d0157bc407deb59be91ea2a3"><img src="Cursos/EducacaoDoFuturo/CapaNutror.png" width="70%" style="margin-left: 15%;" alt="Capa Curso"></a>
<h3 style="color: #efefef; text-align: center; font-size: 2em; margin-bottom: 0;">Garanta já a sua vaga!</h3>
<img src="Imagens/Preco.png?nocache=<?php echo time(); ?>" width="60%" style="margin-left: 20%;">
<!--<p style="color: #efefef; text-align: center; font-size: 1.5em; margin-bottom: 0;"><b>17% de desconto</b> por tempo limitado</p>-->
<!-- COMECO: Relogio -->
<!--<p id="Relogio" style="font-size: 3em; color: #efefef; text-align: center;"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Sept 13, 2020 23:59:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("Relogio").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("Relogio").innerHTML = "EXPIRED";
}
}, 1000);
</script>-->
<!-- FIM: Relogio -->
<a href="https://sun.eduzz.com/371710" target="_blank"><div align="center" class="botaoSobre" alt="Quero participar"><b>Inscreva-se já</b></div></a> <br>
</div>
</td>
<style>
/* Classe botao */
.botaoSobre{
font: normal 25px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:5px 5px 5px 5px;
/* Largura */
width:90%;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
margin-bottom: 2em;
/* Posição do botao */
position:relative;
}
/* Quando clicar nele */
.botaoSobre:active{
cursor:pointer;
position:relative;
top: 0.3vh;
}
.botaoSobre:hover{
background: #38b54f;
color:#efefef;
border-color: #efefef;
}
td.coluna{
width: 40%;
margin: 0;
}
.boxVenda{
background: #38b54f;
margin: 100px;
}
@media screen and (max-width: 850px) {
td.coluna{
width: 90%;
margin-left: 5%;
display: block;
}
div.boxVenda{
margin: 0;
}
}
</style>
<!-- FIM: Segunda coluna -->
</tr>
</table>
</td>
</tr>
<!-- FIM: duas colunas -->
<!-- COMECO: Video promocional -->
<tr width="100%" style="padding: 0; background-position: 50% 50%; background-repeat: no-repeat; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; background-image: url('Imagens/BG/Educadores.jpg'); background-attachment: fixed;">
<td align="center">
<div class="h_iframe" align="center">
<img class="ratio estiloVideo" src="http://brino.cc/Imagens/BG/BgS1.jpg" alt="Video Brino"/>
<iframe scrolling="no" src="https://www.youtube.com/embed/BDRNBHdAmXE" frameborder="0" title="Video sobre o curso" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</td>
</tr>
<style>
.h_iframe {position:relative;}
.h_iframe img.ratio {display:block;width:50%;height:50%;margin-top: 50px;margin-bottom: 50px;}
.h_iframe iframe {position:absolute;top:0;width:50%; height:100%;right: 25%;}
@media screen and (max-width: 850px) {
.h_iframe img.ratio {width:80%;height:80%;}
.h_iframe iframe {width:80%; height:100%;right: 10%;}
}
</style>
<!-- FIM: Video promocional -->
<!-- COMECO: FAQ -->
<tr style="background-image: linear-gradient(#38b54f,#38b54f); width: 100%;">
<td width="100%">
<!-- espaco -->
<div style="position: relative; height: 8vh"></div>
<h3 style="text-align: center; color: #fff; font-size: 3em;">Perguntas frequentes</h3>
<!-- espaco -->
<div style="position: relative; height: 4vh"></div>
<table width="100%">
<tr width="100%">
<td class="Coluna1FAQ">
<!-- Primeira coluna -->
<button class="collapsible"><b>Qual o conteúdo abordado no curso?</b></button>
<div class="content">
<p>
O curso aborda tanto o uso do Arduino como diversas metodologias ativas.
</p>
<ul>
<li><strong>Metodologias ativas de ensino</strong> - Como tornar o aluno protagonista de seu próprio aprendizado;</li>
<li><strong>Fabricação digital</strong> - Como o uso de impressão 3D e corte a laser podem afetar a sua didática;</li>
<li><strong>Programação</strong> - Iremos desenvolver o raciocínio lógico e a abstração, ensinando programação na prática do zero;</li>
<li><strong>Robótica</strong> - Vamos aprender a dar vida as linhas de código, trazendo efeitos para além da telinha;</li>
<li><strong>Arduino</strong> - Como utilizar esta ferramenta de baixo custo para criar projetos incriveis, desde piscar um LED até automação residencial;</li>
<li><strong>Cultura digital</strong> - Adapatado a BNCC, ensinamos como utilizar a tecnologia de forma segura e crítica;</li>
<li><strong>Plataformas</strong> - Vamos te mostrar diversas plataformas para tornar o ensino simples, lúdico e gamificado.</li>
</ul>
</div>
<button class="collapsible"><b>Não sou professor de robótica, posso fazer o curso?</b></button>
<div class="content">
<p>
Sim! O curso é voltado para educadores e entusistas. Nós vamos te ensinar a adaptar as suas aulas para o século XXI utilizando tecnologia e o que há de mais moderno no mundo da pedagogia.
</p>
</div>
<button class="collapsible"><b>O curso tem garantia de satisfação?</b></button>
<div class="content">
<p>
Sim, oferecemos a opção de devolução integral do valor em até 15 dias.
</p>
</div>
<button class="collapsible"><b>É seguro pagar com Cartão de Crédito?</b></button>
<div class="content">
<p>
Sim, todos os pagamentos são realizados através da plataforma. Os dados pessoais informados são armazenados em bancos de dados seguros, com acesso restrito.
</p>
</div>
<button class="collapsible"><b>Recebo algum material em casa?</b></button>
<div class="content">
<p>
Não, o curso usa de simuladores e atividades 100% online. Nenhum material físico é obrigatório, mas quem preferir pode usar seu próprio Arduino.
</p>
</div>
<button class="collapsible"><b>Posso parcelar a compra?</b></button>
<div class="content">
<p>
Sim, a compra pode ser parcelada em até 12 vezes sem juros no cartão de crédito.
</p>
</div>
<button class="collapsible"><b>Por quanto tempo terei acesso ao curso?</b></button>
<div class="content">
<p>
Após confirmado o pagamento é liberado o acesso que tem validade de 2 anos.
</p>
</div>
<button class="collapsible"><b>O que é o método Br.ino de ensino?</b></button>
<div class="content">
<p>
É o método que te ajuda a aplicar robótica e métodologias ativas para ensinar o seu cobteúdo de forma inovadora.
</p>
</div>
<!-- espaco -->
<div style="position: relative; height: 8vh"></div>
</td>
<!-- Segunda coluna -->
<td class="Coluna2FAQ">
<img src="Imagens/OrniFAQ.png" alt="Ornitobrino FAQ" class="ImagemFAQ">
</td>
</tr>
</table>
</td>
</tr>
<style>
.collapsible {
background-color: #efefef;
color: #38b54f;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
outline: none;
font-size: 15px;
border-style: solid;
border-color: #38b54f;
border-width: 5px;
}
.active, .collapsible:hover {
background-color: #655b4a;
}
.collapsible:after {
content: '\002B';
color: #38b54f;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
.Coluna1FAQ{
width:60%;
padding-left: 10%;
padding-right: 10%;
}
.Coluna2FAQ{
width: 40%;
vertical-align: middle;
}
.ImagemFAQ{
width: 60%;
margin-left: 20%;
}
@media screen and (max-width: 850px) {
td.Coluna1FAQ{
width:70%;
padding-left: 5%;
padding-right: 0%;
}
td.Coluna2FAQ{
width: 30%;
vertical-align: middle;
}
img.ImagemFAQ{
width: 80%;
margin-left: 10%;
}
}
</style>
<!-- Funcao para abrir e fechar os itens -->
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
<!-- FIM: FAQ -->
<!-- COMECO: infografico curso -->
<tr width="100%" style="background-image: linear-gradient(#000000,#000000); padding: 0;">
<td>
<!-- espaco -->
<div style="position: relative; height: 2vh"></div>
<h3 style="text-align: center; color: #38b54f; font-size: 3em; margin-left: 10%; margin-right: 10%">10 motivos para adquirir e fazer as suas aulas decolarem!</h3>
<img src="Cursos/EducacaoDoFuturo/Foguete10Passos.png" alt="cronograma" class="infograficoClass">
</td>
</tr>
<style>
.infograficoClass{
width: 60%;
margin-left: 20%;
}
@media screen and (max-width: 850px) {
img.infograficoClass{
width: 100%;
margin-left: 0;
}
}
</style>
<!-- FIM: infografico curso -->
<!-- COMECO: botao inscricao -->
<tr width="100%" style="background-image: linear-gradient(#000000,#000000); padding: 0;">
<td>
<h3 style="text-align: center; color: #38b54f">Ainda não tem certeza? Se não gostar do curso no prazo de 15 dias devolvemos o seu dinheiro!</h3>
<a href="#Inscrever"><div align="center" class="botaoDownload" alt="Quero participar">Inscrição</div></a>
<!-- espaco -->
<div style="position: relative; height: 8vh"></div>
</td>
</tr>
<style>
.botaoDownload{
font:normal 35px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 300px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
transition: 0.7s;
}
.botaoDownload:active{
cursor:pointer;
position:relative;
background: #efefef;
color: #efefef;
top:1px;
}
.botaoDownload:hover{
background: #efefef;
color: #38b54f;
border:1px solid #38b54f;
}
</style>
<!-- FIM: botao inscricao -->
<!-- COMECO: depoimento -->
<tr width="100%" style="background-image: linear-gradient(#38b54f,#38b54f)">
<td>
<table class="SecaoDepoimentos">
<tr>
<td width="100%">
<p style="color: #efefef; font-size: 1.5em; text-align: center; margin-top: 8vh; margin-bottom: 3vh; font-weight: bold;">O que nossos alunos dizem</p>
</td>
</tr>
<tr>
<td width="100%">
<table width="100%">
<tr>
<td width="15%">
<img src="Imagens/Depoimento2.png" width="70%" style="margin-left: 30%">
</td>
<td width="85%">
<p style="color: #efefef; font-size: 1.3em; text-align: center; margin-top: 8vh; margin-bottom: 3vh; padding-right: 10%; margin-left: 2%;">"Eu amei o curso e ainda sigo estudando. O curso tem bastante conteúdo e em uma semana eu não conseguia dar conta de alguns módulos. As lives foram extremamente enriquecedoras e os projetos também. Só tenho gratidão e quero sempre continuar com vocês."</p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="100%">
<p style="color: #efefef; text-align: right; margin-bottom: 3vh; padding: 0 10% 0;"><NAME></p>
</td>
</tr>
<tr>
<td width="100%">
<table width="100%">
<tr>
<td width="85%">
<p style="color: #efefef; font-size: 1.3em; text-align: center; margin-top: 8vh; margin-bottom: 3vh; padding-right: 2%; margin-left: 10%;">"Eu sou professor de biologia aqui no Rio Grande do Sul e vim falar um pouco da minha experiência com o curso do Br.ino, o Educação do Futuro 4.0.<br>
Esse curso é muito interessante, eu fiz ele agora (jullho/agosto2020). A gente passou por alguns tópicos de arduino, conhecimento que eu não tinha nenhum, falou também sobre metodologias ativas e no curso eles juntaram essas duas coisas, metodologias ativas e robótica na educação e isso foi muito interessante para minha construção como professor e também para outros aprendizados pra vida. Além disso eles passam por diversos aspectos como linguagem de programação, como construir circuitos eletrônicos e outras coisas super interessantes. <br>
Eu indico esse curso, esse curso foi muito bom. A equipe do Br.ino é super atenciosa, em todo momento que eu tive uma dúvida ou algum questionamento, ele prontamente me responderam. O curso só tem a agregar na formação de qualquer um, então eu indico total esse curso e parabenizo a equipe Br.ino por esse excelente curso.
"</p>
</td>
<td width="15%">
<img src="Imagens/Depoimento1.png" width="70%" style="margin-right: 30%">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="100%">
<p style="color: #efefef; text-align: right; margin-bottom: 3vh; padding: 0 10% 0;"><NAME>, professor de biologia</p>
</td>
</tr>
</table>
</td>
</tr>
<!-- FIM: depoimento -->
<style>
.SecaoDepoimentos{
width: 80%;
margin-left: 10%;
margin-right: 10%;
}
@media screen and (max-width: 850px) {
table.SecaoDepoimentos{
width: 96%;
margin-left: 2%;
margin-right: 2%;
}
}
</style>
<!-- COMECO: plataformas -->
<tr>
<td>
<!-- espaco -->
<div style="position: relative; height: 2vh"></div>
<h2 style="margin-left: 10%; margin-right: 10%; color: #38b54f;">Algumas das plataformas que você aprenderá no curso:</h2>
<!-- espaco -->
<div style="position: relative; height: 2vh"></div>
<table width="70%" style="margin-left: 15%;">
<tr>
<!-- Scratch -->
<td>
<a href="https://scratch.mit.edu/" target="_blank"><img src="Imagens/Icones/VendasOEducador/LogoScratch.png" width="70%" style="margin-left: 15%; margin-right: 15%" alt="scratch"></a>
</td>
<!-- Tinkercad -->
<td>
<a href="https://tinkercad.com" target="_blank"><img src="Imagens/Icones/VendasOEducador/LogoTinkercad.png" width="70%" style="margin-left: 15%; margin-right: 15%" alt="scratch"></a>
</td>
<!-- AppInventor -->
<td>
<a href="https://appinventor.mit.edu/" target="_blank"><img src="Imagens/Icones/VendasOEducador/LogoAppInventor.png" width="70%" style="margin-left: 15%; margin-right: 15%" alt="MIT AppInventor"></a>
</td>
<!-- Blockly-games -->
<td>
<a href="https://blockly-games.appspot.com/" target="_blank"><img src="Imagens/Icones/VendasOEducador/LogoBlockly.png" width="70%" style="margin-left: 15%; margin-right: 15%" alt="Blockly"></a>
</td>
</tr>
</table>
<!-- espaco -->
<div style="position: relative; height: 5vh"></div>
</td>
</tr>
<!-- FIM: plataformas -->
</table>
<!-- COMECO: WPP -->
<!--WPP-->
<!--Jquery-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<!--Floating WhatsApp css-->
<link rel="stylesheet" href="https://rawcdn.githack.com/rafaelbotazini/floating-whatsapp/3d18b26d5c7d430a1ab0b664f8ca6b69014aed68/floating-wpp.min.css">
<!--Floating WhatsApp javascript-->
<script type="text/javascript" src="https://rawcdn.githack.com/rafaelbotazini/floating-whatsapp/3d18b26d5c7d430a1ab0b664f8ca6b69014aed68/floating-wpp.min.js"></script>
<script>
$(function() {
$('#WAButton').floatingWhatsApp({
phone: '5561999136506', //WhatsApp Business phone number International format-
//Get it with Toky at https://toky.co/en/features/whatsapp.
headerTitle: 'Alguma dúvida?', //Popup Title
popupMessage: 'Olá, como posso te ajudar?', //Popup Message
showPopup: true, //Enables popup display
buttonImage: '<img src="Imagens/IconeWPP.png" />', //Button Image
//headerColor: 'crimson', //Custom header color
//backgroundColor: 'crimson', //Custom background button color
position: "right"
});
});
</script>
<!--Div where the WhatsApp will be rendered-->
<div id="WAButton" style="font-family: Lato;"></div>
<!-- FIM: WPP -->
<!-- COMECO: rodapeh -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- FIM: do rodapeh -->
</body>
</html>
<file_sep>/3d.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0">
<!-- <meta media screen and (min-width: 640px) and (max-width: 1920) {
@viewport { width: 1280px; }> -->
<title>Br.ino - 3D</title>
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<body>
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php"?>
</header>
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSe7W8j00zXNgAmJC5hju4IOyrzw9DaCImkFOA1dx6SjAuTaSQ/viewform?embedded=true" width="100%" height="500px" frameborder="0" marginheight="0" marginwidth="0">Carregando…</iframe>
</body>
<!-- ********* rodapeh ********* -->
<footer align="left">
<?php include "rodape.php"?>
</footer>
<!-- fim do rodapeh -->
<meta name="description" content="">
</html><file_sep>/oficinas.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Br.ino - Oficinas</title>
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<body style="margin: 0;">
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<!-- ********* Começo das oficinas ********* -->
<section class="ATutoriais">
<div style="position: relative; height: 2vw"></div>
<h2 class="TitATutoriais">Oficinas</h2>
<div style="position: relative; height: 2vw"></div>
<table class="TableTut">
<!-- Regulamentos -->
<tr>
<table class="BoxLongoCinzaEscuro">
<tr>
<th class="DescricaoTutVerde">
<div style="position: relative; height: 1vw"></div>
<i class="fas fa-tags ImagemRegulamento"></i>
<div style="position: relative; height: 1vw"></div>
<p class="NomeTut">Regulamento códigos promocionais</p>
<p class="textoCinzaGrande">* Descontos não acumulativos<br>* Códigos válidos por 30 dias</p>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<style>
.BoxLongoCinzaEscuro{
background-color: #474747;
margin-left: 20%;
width: 60%;
}
.ImagemRegulamento{
color:#efefef;
font-size: 5em;
position:relative;
}
.textoCinzaGrande{
color: #efefef;
font-size: 0.9em;
line-height: 1em;
}
@media screen and (max-width: 650px) {
.ImagemRegulamento{
font-size: 2em;
}
.BoxLongoCinzaEscuro{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
}
</style>
<table class="BoxLongoVerde">
<tr class="DescricaoTutVerde">
<th>
<br>
<p class="NomeTut">Estamos sem oficinas no momento!</p>
<br>
<p class="textoCinzaGrande">Em breve novas oficinas serão adicionadas!</p>
<br><br>
</th>
</tr>
</table>
<!--
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<div style="position: relative; height: 1vw"></div>
<p class="NomeTut">Automação residencial</p>
<p class="textoCinza">Venha aprender a fazer automações!</p>
<ul class="textoCinza">
<li> <strong>Onde?</strong> Asa Sul CLS 306, Bl. C, Loja 6, Sobreloja - Brasília, DF
</li>
<li> <strong>Quando?</strong> 20 de julho, 9h30-12h30
</li>
</ul>
<div style="position: relative; height: 2vw"></div>
<div align="center" class="BotaoInscriCinza"><a href="https://www.sympla.com.br/automacao-residencial__558777" target="_blank">Saiba Mais</a></div>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="https://www.sympla.com.br/automacao-residencial__558777" alt="inscrições"><i class="fas fa-home ImagemTutCinza"></i></a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
<!-- Colonia -->
<!--
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="https://www.sympla.com.br/colonia-de-ferias-do-brino__537825" alt="inscrições"><i class="fas fa-cogs ImagemTut"></i></a>
</th>
<th class="DescricaoTutCinza">
<div style="position: relative; height: 1vw"></div>
<p class="NomeTut">Colônia de férias</p>
<p class="textoVerde">Venha aprender mais sobre o universo maker!</p>
<ul class="textoVerde">
<li> <strong>Onde?</strong> Asa Sul CLS 306, Bl. C, Loja 6, Sobreloja - Brasília, DF
</li>
<li> <strong>Quando?</strong> 22 a 26 de julho, 13h30-18h30
</li>
</ul>
<div style="position: relative; height: 2vw"></div>
<div align="center" class="BotaoInscriVerde"><a href="https://www.sympla.com.br/colonia-de-ferias-do-brino__537825" target="_blank">Saiba Mais</a></div>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
-->
<div style="position: relative; height: 3px"></div>
</table>
<div style="position: relative; height: 3px"></div>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
a{
text-decoration: none;
color: inherit;
}
.BotaoInscriVerde{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 150px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
}
.BotaoInscriVerde:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.BotaoInscriVerde:hover{
background: #efefef;
color: #38b54f;
border:1px solid #38b54f;
}
.BotaoInscriCinza{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #efefef;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 150px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
}
.BotaoInscriCinza:active{
cursor:pointer;
position:relative;
background: #efefef;
color: #38b54f;
top:1px;
}
.BotaoInscriCinza:hover{
background: #38b54f;
color: #efefef;
border:1px solid #efefef;
}
.textoVerde{
color: #38b54f;
font-size: 0.6em;
line-height: 1em;
}
.textoCinza{
color: #efefef;
font-size: 0.6em;
line-height: 1em;
}
.ATutoriais{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/BGTutoriais.jpg");
background-attachment: fixed;
padding: 0;
}
.TitATutoriais{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
color:#efefef;
width: 40%;
font-family: Coolvetica;
}
.TableTut{
width:60%;
text-align: center;
}
.BoxLongoCinza{
background-color: #efefef;
margin-left: 20%;
width: 60%;
}
.BoxLongoVerde{
background-color: #38b54f;
margin-left: 20%;
width: 60%;
}
.FotoTut{
width:50%;
}
.ImagemTut{
color:#38b54f;
font-size: 10em;
position:relative;
}
.ImagemTutCinza{
color:#efefef;
font-size: 10em;
position:relative;
}
@media screen and (max-width: 650px) {
.ImagemTut, .ImagemTutCinza{
font-size: 2em;
}
.BoxLongoCinza, .BoxLongoVerde{
width: 10%;
margin-left: auto;
margin-right: auto;
}
.FotoTut{
width: 30%;
}
}
.DescricaoTutCinza{
color: #38b54f;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
}
.DescricaoTutVerde{
color: #efefef;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
width: 50%;
}
.NomeTut{
font-weight: 900;
font-size: 1.7em;
line-height: 1em;
}
@media screen and (max-width: 850px) {
.ATutoriais{
background-attachment: inherit;
}
.TitATutoriais{
left: 0;
text-align: center;
font-size: 50px;
width: 100%;
}
.TableTut{
width: 95%;
}
.BoxLongoCinza{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.BoxLongoVerde{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.NomeTut{
font-weight: 700;
font-size: 1em;
line-height: .7em;
}
}
</style>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/entrevista4.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0, ">
<title>Mês das Mulheres #4</title>
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<body>
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php"?>
</header>
<!-- ********* Titulo ********* -->
<section class="titulo">
<!-- espaco -->
<div style="position: relative; height:5vw"></div>
<h1 class="linhaTitUm">Entrevista<br>com<br><span style="color: #38b54f; font-family: Coolvetica;">Paola e Alice</span></h1>
<!-- espaco -->
<div style="position: relative; height: 4vw"></div>
</section>
<!-- ********* Video ********* -->
<section class="video" id="video">
<!-- Espacamento antes do titulo -->
<div style="position: relative; height: 8vw"></div>
<img src="Imagens/PalomaRocha.png" alt="<NAME>" class="imagemMulher">
<img src="Imagens/AliceBorges.png" alt="<NAME>" class="imagemMulher">
<!-- espaco no fim do BG -->
<div style="height: 2vw"></div>
</section>
<!-- ********* texto sobre ********* -->
<section class="bgTexto">
<!-- espaco -->
<div style="height: 1vw"></div>
<p class="textop"> Para comemorar o mês das mulheres (pq só um dia é muito pouco) o Br.ino preparou uma série de postagens e entrevistas sobre mulheres que lutam contra os estereótipos e conquistam seu espaço na área da tecnologia.<br><br>
Pra fechar com chave de ouro nossa homenagem ao mês das mulheres, entrevistamos 2 ex-participantes do projeto MENINAS.COMP, uma iniciativa que fomenta a inclusão de meninas de escolas públicas na computação! Leia a entrevista e conheça mais sobre esse projeto que é inspiração para todos nós!<br>
<a href="http://meninas.cic.unb.br" alt="meninas.comp"> Clique aqui para saber mais!</a>
<br><br>
</p>
<h3 class="tituloMenor">Leia a entrevista:</h3><br><br>
<p class="textop">
<strong>1 - Como você começou no mundo da TI? Com quantos anos? </strong><br>
<strong>Paloma: </strong>"Comecei justamente com o projeto das meninas.comp aos meus 15 anos. Todo ano na minha antiga escola ocorre uma feira de ciências. E fui olhar a apresentação das meninas, já que tinha algumas amigas participando. Lá eu conheci o projeto e gostei bastante. Logo depois o professor Carlos me chamou para ir em uma reunião, para ver como tudo funcionava. E nesse dia eu programei pela primeira vez, fiz um Led vermelho acender."<br>
<strong>Alice: </strong>"Eu comecei a partir do projeto edubot da unb com as escolas públicas na minha escola, com 15 anos, logo depois eu entrei no projeto das meninas.comp."<br><br>
<strong>2 - O que te motivou / motiva a entrar nesse mundo tecnológico?</strong><br>
<strong>Paloma: </strong>"A possibilidade de criar projetos que possam ajudar as pessoas e evoluir cada vez mais a tecnologia. Além de entender como funcionam os aparelhos que usamos no nosso dia a dia."<br>
<strong>Alice: </strong>"A possibilidade de fazer várias coisas novas, aprender como um programa funciona e a criatividade de muitos projetos."<br><br>
<strong>3 - Acha que as mulheres estão conseguindo seu espaço nesse mercado?</strong><br>
<strong>Paloma: </strong>"Apesar do número ainda ser muito baixo, o número de mulheres nessa área tem crescido. Elas estão alcançando cargos altos que antes eram preenchidos majoritáriamente por homens."<br>
<strong>Alice: </strong>"Acho sim, pois essa área está ganhando mais visibilidade, elas estão tendo mais informação e contato com essa área da tecnologia, até porque hoje o mundo gira em volta disso."<br><br>
<strong>4 - Hoje em dia , acha que valeu a pena investir sua educação nessa área? </strong><br>
<strong>Paloma: </strong>"É uma área que eu gosto bastante de estudar, descobrir coisas novas. E por agora, creio que está valendo a pena investir."<br>
<strong>Alice: </strong>"Com certeza, porque a partir desse investimento eu pude abrir meus olhos para esse mundo, desenvolver minha criatividade e a capacidade de resolver problemas, fora que eu descobri o que eu quero seguir fazendo."<br><br>
<strong>5 - Como lidou (caso tenha acontecido) com o preconceito de gênero no seu curso ?</strong><br>
<strong>Paloma: </strong>"Na universidade ainda não sofri nenhum preconceito. Porém, quando digo para as pessoas que curso Engenharia de Computação elas se surpreendem, por acharem que somente homens cursam. Dizem que irei me tornar muito masculina como o passar do tempo. Antes eu tentava explicar que o gênero não é requisito para entrar no mundo do TI. Hoje eu só ignoro."<br>
<strong>Alice: </strong>"Não aconteceu ainda de algum ocorrido desse gênero, inclusive fui bem recebida até."<br><br>
<strong>6- O projeto meninas.comp contribui pra sua escolha e facilitou sua entrada? Como funciona o projeto?</strong><br>
<strong>Paloma: </strong>"Sim. Quando cheguei ao ensino médio não fazia ideia de qual curso escolher. Nada era muito atrativo. Porém, no meu primeiro ano (2015), conheci o projeto e achei muito interessante. Foi graças ao meninas.comp que finalmente decidi o que queria cursar. Com esse projeto, também me senti mais próxima da UnB, pois todo ano participamos da semana de extensão. E por ter um maior contato com professoras e alunas da UnB, dessa área, me senti mais motivada para entrar na universidade.
A introdução do projeto no Centro de Ensino Médio Paulo Freire ocorreu por volta de 2014. Lá temos um professor responsável, <NAME>, nosso professor de matemática. É feita uma seleção das meninas que são boas em matemática e encontros são realizados toda sexta-feira, no período contrário ao da aula, com duração aproximada de 1:30 h/2:00h. Todo início de ano fazemos uma reunião para decidirmos cada projeto em que iremos trabalhar. E todo ano apresentamos eles na Semana Nacional de Ciência e Tecnologia.
O objetivo do projeto é atrair mais meninas para essa área de TI. Ele foi criado pelas professoras Aletéia, Maristela e <NAME>."<br>
<strong>Alice: </strong>"Contribuiu muito pois foi a partir dele que eu descobri o que eu queria fazer na faculdade. O projeto funciona com o as meninas que entram nele onde aprendemos a usar o arduino como base dos nossos projetos, aprendemos a programar, fazer a ligação eletrônica necessária e então a partir disso pensamos em projetos que podemos fazer a partir do que a gente aprendeu e então aprendendo mais com o desenvolvimento deste."<br><br>
Fique ligado pra ver mais exemplos de mulheres que manjam muito de tecnologia!!</p>
<p class='textop'>Confira também a nossa primeira entrevista com <a href="entrevista1" style="text-decoration=none;color:#38b54f;"><NAME></a>!</p>
<!-- espaco -->
<div style="height: 9vw"></div>
</section>
</body>
<style>
body{
margin:0px;
padding:0px;
}
.imagemMulher{
width: 30%;
margin-left: 35%;
}
.espaco{
width: 4%;
}
.titulo{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/Computador.jpg");
}
.tituloMenor{
color: #000;
margin-left: 20%;
}
h1.linhaTitUm{
font-size: 6em;
line-height: 0.9em;
font-weight: 400;
color: #ffffff;
position: relative;
left: 30%;
width: 70%;
font-family: Coolvetica;
}
@media screen and (max-width: 500px) {
img.imagemMulher{
width: 50%;
margin-left: 25%;
}
h1.linhaTitUm{
text-align: center;
font-size: 5em;
left: 0;
width: 100%;
}
h3.tituloMenor{
text-align: center;
margin-left: 0;
}
}
.linhaTitDois{
font-size: 80px;
color: #ffffff;
position: relative;
left: 30%;
width:20%;
}
.video{
background-color: #efefef;
}
.bgTexto{
background-color: #efefef;
}
.textoSob{
width: 100%;
}
.textop{
margin-left: 25%;
margin-right: 25%;
color: #000;
text-align: justify;
}
@media screen and (max-width: 500px) {
p.textop{
margin-left: 15%;
margin-right: 15%;
text-align: center;
}
p.submvvVal{
text-align: center;
}
p.submvv{
text-align: center;
}
h1.titVideo{
font-size: 3em;
margin-left: 0;
text-align: center;
}
}
.bgContato{
background-color: #f2f2f2;
}
@media screen and (max-width: 800px) {
p.linhaVendasUm{
font-size: 15vw;
text-align: center;
left: 0%;
right: 900px;
}
p.linhaVendasDois{
font-size: 13vw;
text-align: center;
left: 0%;
}
}
@font-face {
font-family: Coolvetica;
src: url(Coolvetica.ttf);
}
@font-face {
font-family: Lato;
src: url(Lato.ttf);
}
h1, h2, h3, h4{
font-family: Coolvetica;
font-size: 3em;
}
p, input, li, textarea, ol, spam, table, th, tr, header{
font-family: Lato;
font-size: 1em;
}
</style>
<!-- ********* rodapeh ********* -->
<footer align="left">
<?php include "rodape.php" ?>
</footer>
<!-- fim do rodapeh -->
<meta name="description" content="Conheça o software que visa a democratização da robótica e do movimento maker diminuindo as barreiras para o aprendizado!!!">
</html>
<file_sep>/SAFA.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Br.ino + SAFA</title>
</head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<body>
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
}
body{
margin:0px;
padding:0px;
}
</style>
<!-- *************** Chamada para a apostila *************** -->
<section class="ChamadaSection">
<!-- espaco -->
<div style="position: relative; height:3vw"></div>
<section>
<p class="LinhaUmChamada">Conheça o<br><spam style="font-family: Coolvetica;color: #38b54f;">Br.ino</spam></p>
</section>
<!-- espaco -->
<div style="position: relative; height: 6vh"></div>
<!-- Chamada de botão começar-->
<a href="sobre" target="_blank" title="sobre"><div align="center" class="botaoChamada">Sobre</div></a>
<!-- espaco -->
<div style="position: relative; height: 8vw"></div>
</section>
<style>
.ChamadaSection{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/FundoSAFA3.png");
background-attachment: fixed;
}
.LinhaUmChamada{
margin: 0;
font-size: 8vw;
line-height: 8vw;
font-weight: 800;
color: #ffffff;
position: relative;
text-align: center;
font-family: Coolvetica;
}
.botaoChamada{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 200px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.botaoChamada:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.botaoChamada:hover{
background: #efefef;
color: #38b54f;
border:1px solid #38b54f;
}
@media screen and (max-width: 850px) {
.LinhaUmChamada{
font-size: 12vw;
line-height: 13vw;
}
.ChamadaSection{
background-attachment: inherit;
}
}
</style>
<!-- ********* O que é o brino ********* -->
<section class="OQueE">
<div style="position: relative; height: 1vw"></div>
<h2 class="TitOQueE">Br.ino na Sagrada Família</h2>
<div style="position: relative; height: 2vw"></div>
<div class="h_iframe" align="center">
<img class="ratio" src="http://brino.cc/Imagens/BG/BgS1.jpg" alt="Video Brino"/>
<iframe scrolling="no" src="https://www.youtube.com/embed/FeEPSbaoYbU" frameborder="0" allowfullscreen></iframe>
</div>
<div style="position: relative; height: 3vw"></div>
</section>
<style>
.TitOQueE{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
letter-spacing: 3px;
color:#efefef;
width: 40%;
font-family: Coolvetica;
}
.OQueE{
background-color: #38b54f;
}
.h_iframe {position:relative;}
.h_iframe .ratio {display:block;width:70%;height:70%;}
.h_iframe iframe {position:absolute;top:0;width:70%; height:100%;right: 15%;}
@media screen and (max-width: 850px) {
.TitOQueE{
left: 0;
text-align: center;
font-size: 30px;
width: 100%;
}
}
</style>
<!-- ********* A equipe ********* -->
<section class="AEquipe">
<div style="position: relative; height: 2vw"></div>
<h2 class="TitAEquipe">Turmas</h2>
<div style="position: relative; height: 2vw"></div>
<table class="TableEquipe">
<!-- Series atendidas -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="DescricaoEquipeCinza">
<p class="NomeEquipe">Avisos</p>
<!-- <p>As aulas terão início dia 16 de março de 2020</p>
<p>As inscrições nas turmas de robótica podem ser realizadas até o dia 27 de março de 2020</p>
<br>-->
<p>Em caso de dúvidas não hesite em entrar em contato</p>
<p><NAME> - (61) 99296-1002</p>
<p><EMAIL></p>
<div style="position: relative; height: 1vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Fund1 -->
<tr>
<table class="BoxLongoVerde">
<tr class="TrBox">
<th class="DescricaoEquipeVerde">
<p class="NomeEquipe">Fundamental I</p>
<p>Para alunos da Educação Infantil V e do 1° (primeiro) ao 5° (quinto) ano do Ensino Fundamental.</p>
<ul>
<li>Turma A: Horário a definir</li>
<li>Turma B: Horário a definir</li>
</ul>
<p>Investimento mensal: R$160,00</p>
<a href="https://forms.gle/i11SZ5xrSrwmvecb8" target="_blank" title="SeInscrever"><div align="center" class="botaoChamada">Sugerir Horário</div></a>
<div style="position: relative; height: 1vw"></div>
</th>
<th class="FotoEquipe">
<img src="Imagens/OrniOvo.png" alt="Fund1" class="ImagemEquipe">
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Fund2 -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoEquipe">
<img src="Imagens/OrniKid.png" alt="Fund2" class="ImagemEquipe">
</th>
<th class="DescricaoEquipeCinza">
<p class="NomeEquipe">Fundamental II</p>
<p>Para alunos do 6° (sexto) ao 9° (nono) ano do Ensino Fundamental.</p>
<ul>
<li>Turma C: Horário a definir</li>
<li>Turma D: Horário a definir</li>
</ul>
<p>Investimento mensal: R$170,00</p>
<a href="https://forms.gle/i11SZ5xrSrwmvecb8" target="_blank" title="SeInscrever"><div align="center" class="botaoChamadaVerde">Sugerir Horário</div></a>
<div style="position: relative; height: 1vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Contrato -->
<tr>
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoEquipeVerde">
<p class="NomeEquipe">Contrato</p>
<p>Tenha acesso ao contrato:</p>
<a href="#" target="_blank" alt="Baixar"><div align="center" class="botaoChamada">Em breve</div></a>
<div style="position: relative; height: 1vw"></div>
</th>
<th class="FotoEquipe">
<img src="Imagens/ContratoCinza.png" alt="Contrato" class="ImagemEquipe">
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Aula teste -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoEquipe">
<img src="Imagens/OrniBig.png" alt="Fund2" class="ImagemEquipe">
</th>
<th class="DescricaoEquipeCinza">
<p class="NomeEquipe">Aula aberta</p>
<p>O brino irá ministrar uma aula aberta para todos os alunos do fundamental que tiverem interesse em saber mais sobre como funcionará a robótica no Colégio Sagrada Família.</p>
<ul>
<li>Turma A: Horário a Definir</li>
<li>Turma B: Horário a Definir</li>
</ul>
<p>Aula grátis!</p>
<a href="#" target="_blank" title="SeInscrever"><div align="center" class="botaoChamadaVerde">Em breve</div></a>
<div style="position: relative; height: 1vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
.AEquipe{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/FundoSAFA2.png");
background-attachment: fixed;
padding: 0;
}
.TitAEquipe{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
color:#efefef;
width: 40%;
font-family: Coolvetica;
letter-spacing: 3px;
}
.TableEquipe{
width:60%;
text-align: center;
}
.BoxLongoCinza{
background-color: #efefef;
margin-left: 20%;
width: 60%;
}
.BoxLongoVerde{
background-color: #38b54f;
margin-left: 20%;
width: 60%;
}
.FotoEquipe{
width:20%;
margin-left: 5%;
margin-right: 5%;
}
.ImagemEquipe{
width: 60%;
}
.DescricaoEquipeCinza{
color: #38b54f;
font-size: 1.5em;
font-weight: 500;
line-height: 1.2em;
font-family: Coolvetica;
width: 50%;
}
.DescricaoEquipeVerde{
color: #efefef;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
width: 50%;
}
.NomeEquipe{
font-weight: 900;
font-size: 1.7em;
line-height: 1em;
letter-spacing: 3px;
}
@media screen and (max-width: 850px) {
.AEquipe{
background-attachment: inherit;
}
.TitAEquipe{
left: 0;
text-align: center;
font-size: 50px;
width: 100%;
}
.TableEquipe{
width: 95%;
}
.BoxLongoCinza{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.BoxLongoVerde{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.NomeEquipe{
font-weight: 700;
font-size: 1em;
line-height: .7em;
}
th.DescricaoEquipeVerde{
width: 100%;
display: block;
}
}
</style>
<!-- ********* Visao, missao e valores ******** -->
<section style="background-color: #38b54f">
<div style="position: relative; height: 1vw"></div>
<h2 class="TitOQueE">Método de ensino</h2>
<div style="position: relative; height: 1vw"></div>
<table class="TableValores">
<tr>
<!-- Missão -->
<th class="ThValores">
<table>
<tr>
<th>
<img src="Imagens/Gamificar.png" alt="Missão" class="ImagemValores">
</th>
</tr>
<tr>
<th>
<h3 class="SubTitValores">Gamificação</h3>
</th>
</tr>
<tr>
<th>
<p class="TextoValores">
Os jogos, por si só, já envolvem um aprendizado, uma vez que para jogar é necessário entender a dinâmica e regras que os antecedem. “Os jogos são interessantes por natureza, através deles é possível despertar a curiosidade dos alunos e direcioná-los para novos caminhos do aprender”, afirma Francisco Tupy, professor de tecnologia educacional.<br>
Os games aproximam os alunos da sala de aula, mesmo quando o jogo não está presente fisicamente. Para ensinar não é preciso ter um videogame na sala de aula, é possível simplesmente falar sobre o jogo ou mostrar um vídeo sobre ele. Isso é como se eu estivesse trazendo o mundo dos alunos para o mundo da escola!
</p>
</th>
</tr>
</table>
</th>
<!-- Visão -->
<th class="ThValores">
<table>
<tr>
<th>
<img src="Imagens/Projeto.png" alt="Missão" class="ImagemValores">
</th>
</tr>
<tr>
<th>
<h3 class="SubTitValores">Projetos</h3>
</th>
</tr>
<tr>
<th>
<p class="TextoValores">
Um projeto é algo que os alunos fazem depois de aprender conteúdo para demonstrar compreensão. Embora muitas tarefas de desempenho sejam projetadas para exigir o trabalho do aluno que se conecta ao “mundo real”, o trabalho resultante ainda é um projeto.<br>
Em uma abordagem de aprendizado baseada em projetos, os alunos são apresentados a um problema fortemente conectado ao mundo além da sala de aula, um problema prático.<br>
Em uma época de altos desafios e testes constantes, a educação passou a significar conhecer as respostas. PBL (Problem Based Learning) é sobre aprender a fazer grandes perguntas para pensar mais profundamente sobre um assunto e resolver problemas complexos!
</p>
</th>
</tr>
</table>
</th>
<!-- Valores -->
<th class="ThValores">
<table>
<tr>
<th>
<img src="Imagens/Grupo.png" alt="Missão" class="ImagemValores">
</th>
</tr>
<tr>
<th>
<h3 class="SubTitValores">Grupos</h3>
</th>
</tr>
<tr>
<th>
<p class="TextoValores">
Promove o aprendizado em conjunto e o compartilhamento de ideias entre os alunos. Isso é importante para o aluno para o desenvolvimento de suas características sociais.
Esse tipo de metodologia torna o aluno ativo em seu processo de aprendizagem, dando a ele muito mais autonômia dentro e fora de sala.
</p>
</th>
</tr>
</table>
</th>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
<a href="https://forms.gle/i11SZ5xrSrwmvecb8" target="_blank" title="SeInscrever"><div align="center" class="botaoChamada">Sugerir Horário</div></a>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
a{
text-decoration: none;
color: inherit;
}
.TableValores{
width: 90%;
margin-left: 5%;
}
.ThValores{
width: 30%;
vertical-align: top;
}
.ImagemValores{
width: 40%;
}
.SubTitValores{
color: #efefef;
font-size: 2em;
font-weight: 800;
line-height: 0;
font-family: Coolvetica;
}
.TextoValores{
color: #efefef;
font-size: 1.3em;
line-height: 1.2em;
font-weight: 500;
margin-left: 5%;
margin-right: 5%;
font-family: Lato;
text-align: justify;
}
.botaoChamada{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #efefef;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 250px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.botaoChamada:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.botaoChamada:hover{
background: #38b54f;
color: #efefef;
border:2px solid #efefef;
}
.botaoChamadaVerde{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 250px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.botaoChamadaVerde:active{
cursor:pointer;
position:relative;
background: #efefef;
color: #38b54f;
top:1px;
}
.botaoChamadaVerde:hover{
background: #efefef;
color: #38b54f;
border:2px solid #38b54f;
}
@media screen and (max-width: 850px) {
.ThValores{
display: block;
width: 100%;
margin-bottom: 20%;
}
.TextoValores{
width: 90%;
margin-left: 5%;
}
}
</style>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</body>
</html>
<file_sep>/404.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0">
<!-- <meta media screen and (min-width: 640px) and (max-width: 1920) {
@viewport { width: 1280px; }> -->
<title>Br.ino</title>
<!-- Declaracao fav icon -->
<link rel="shortcut icon" href="Imagens/logo.png" />
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<!-- Define o BG da pagina (uma folha de papel amarelado) -->
<body background="Imagens/BG/404.jpg" style="background-repeat: no-repeat;
background-size: cover;">
<!-- O titulo da pagina -->
<h1 align="center" style="color: #575757;">404 not found</h1>
<h1 align="center" style="color: #575757;">O seu link não foi achado</h1>
<!-- Uma breve piada apos o titulo -->
<h4 align="center" style="color: #575757;">Procuramos bastante, juro =/</h4>
<!-- Um div com a imagem e a legenda dela -->
<div align="center">
<!-- Um link na imagem q leva pra pagina inicial -->
<a href="index.php" title="Home page">
<img src="Imagens/Link.png" alt="link" width="60%">
</a>
<!-- A legenda da imagem -->
<figcaption>O link irá guia-lo para a página inicial</figcaption>
</div>
<!-- A citacao -->
<blockquote style=" font-family: Lato;
font-size: 2.8vh;
font-style: normal;
font-variant: normal;
line-height: 2.9vh;
text-align: center;
font-weight: bold;
color: #575757;">
"O problema com os programadores é que você nunca consegue saber o que eles estão fazendo antes de ser tarde demais."<br><br> - <NAME>
</blockquote>
<br>
<!-- A mensagem do final -->
<h3 align="center" style="color: #575757; font-weight: bold;">Essa frase explica bem o porque dessa página ^^</h3>
<h4 align="center" style="color: #575757; font-weight: bold;">Tenha um bom dia ¯\_(ツ)_/¯</h4>
</body>
</html><file_sep>/jogos/Movimento.php
<html class=" js">
<head>
<title> Br.ino - Movimento</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<!--[if IE]><script src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.3/excanvas.min.js"></script><![endif]-->
<script type="text/javascript" src="Movimento_arquivos/RobotLib.js"></script>
<script type="text/javascript" src="Movimento_arquivos/RobotKeyLib.js"></script>
<script language="JavaScript">
<!-- Begin
var simtime = 20 // defines how often robot simulation updated
var robot // define robot object
var active = false // is robot active?
var speeds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // default speeds of left and right motors for each movement
var inBoxIds = ["robLeftFor", "robLeftLeft", "robLeftRight", "robLeftBack", "robLeftStop", "robRightFor", "robRightLeft", "robRightRight", "robRightBack", "robRightStop"]
// names of input boxes used for speeds
var actionNo = 5 // default action number is 5 = stop
var raceOn = false // no race
var raceTime = 0 // used to measure time taken to go round track
function checkKeySpecial() {
// keySpecial has value of a key that has been pressed ... detect if it is special and act ,,
switch (keySpecial) {
case 68 : // d or D means focus on defining speeds ... initially left speed for forward
case 100 : focusOn(0)
break
case 70 : // 'f' or 'F' mean go forward .. so set forward mode
case 102 : checkStr()
setchecked(1)
break
case 76 : // 'l' or 'L' means turn left ... set left mode
case 108 : checkStr()
setchecked(2)
break
case 82 : // r or R means set right mode
case 114 : checkStr()
setchecked(3)
break
case 66 : // 'b' or 'B' means go Backward ... set back mode
case 98 : checkStr()
setchecked(4)
break
case 83 : // S means set stop mode
case 115 :
checkStr()
setchecked(5)
break
case 87 : // W w means toggle the revise Wire box
case 119 :
checkStr()
document.getElementById("LMBack").checked = !document.getElementById("LMBack").checked
// invert checked status of the left motor reverse checkbox
deFocus()
break
case 71 : // 'g' or 'G' mean go racing
case 103 : race()
break
case 85 : // 'u' or 'U' mean toggle return race
case 117 : checkStr()
document.getElementById("raceBack").checked = !document.getElementById("raceBack").checked
deFocus()
break
case 65 : // 'a' or 'A' means set main arens
case 97 : checkStr()
setEnv(0)
break
case 84 : // t or T means toggle track
case 116 : checkStr()
setEnv(1)
//checkTrack(true, false)
break
case 72 : // H means toggle hills
case 104 : checkStr()
setEnv(2)
//checkTrack(false, true)
break
default : checkKeyRest() // call general function which moves the robot if press IJKM etc...
}
keySpecial = 0 // have used keySpecial ... now set to 0 so dont do again.
}
function moveTheRobot() {
// function to move the robot using the speeds defined for the current selected mode
checkStrings() // update the speeds based on what users have put in the input boxes
checkKeySpecial() // check if key has been pressed
lspeed = ( ( document.getElementById("LMBack").checked ) ? 1 : -1) * speeds[actionNo-1]
// Get Left Speed by reading value from relevant LeftSpeed box and mult by -1 if not reversed wires
rspeed = speeds[actionNo+4]
// get Right speed
if (active) { // if user has pressed start
if (raceOn) raceTime++ // if racing, increment time taken
robot.robotDraw(false) // remove robot from current location
robot.moveRobot(lspeed, rspeed) // move it, according to speed
redrawEnvironment(robot.ctx) // redraw environment as erasing robot may remove part of track etc
robot.robotDraw(true) // draw robot in new positon
if (raceOn) checkRaceEnd() // if racing, see if reached end
}
}
function checkRaceEnd() {
if (raceOn && inRaceEnd(robot.robotx, robot.roboty, document.getElementById("raceBack").checked) ) {
// call library file to see if robot is in the area which marks the end of the race
raceOn = false // if so, stop racing
actionNo = 5 // set stop mode
document.getElementById("p1").innerHTML="Terminado em "+(0.5*raceTime/simtime).toFixed(1)+"s"
} // report how long taken
}
function race() {
// function to start race
actionNo = 5 // put robot in stop mode
robot.raceStartPos(document.getElementById("raceBack").checked == false)
document.getElementById("p1").innerHTML="" // clear message about how long taken...
raceOn = true // start to race
raceTime = 0
actionNo = 1
redrawEnvironment(robot.ctx) // draw environment with robot at start
}
function setRobotTimer() {
// set up timer, and fact that moveTheRobot function is called every simtime seconds...
setInterval(function(){moveTheRobot()},simtime);
}
function setchecked(sval) {
// function called when user pressed Forward/Left etc button, or press F L etc: sval is which mode
if (sval > 0 ) { // first ensure only one checkbox is checked
document.getElementById("ForCheck").checked=(sval==1); // is sval = 1, then is Forward
document.getElementById("LeftCheck").checked=(sval==2);
document.getElementById("RightCheck").checked=(sval==3);
document.getElementById("BackCheck").checked=(sval==4);
document.getElementById("StopCheck").checked=(sval==5);
actionNo = sval // and remember which mode
}
}
function setEnv(which) {
// setup the environment ... 0 is basic arena, 1 is one with track
if (which>=0) { // first set relevant checkbox
document.getElementById("arena").checked = (which == 0)
document.getElementById("addTrack").checked = (which == 1)
// document.getElementById("withHills").checked = (which == 2) // dont include hills this time
}
var rvis = (which > 0) ? "visible" : "hidden"
document.getElementById("rbLabel").style.visibility = rvis
document.getElementById("raceBack").style.visibility = rvis
document.getElementById("getSet").style.visibility = rvis
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
raceTrack (document.getElementById("addTrack").checked, false, canvas.width, canvas.height)
// if track mode, then set up the track, with no hills
robot.speedControl = document.getElementById("addTrack").checked==false
// no speed control in track mode
redrawEnvironment(robot.ctx) // draw the environment
}
function load() {
// load function - called when page loaded
window.defaultStatus="RJM's Simple Robot System";
checkBrowser()
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
robot = new aRobot(50, 50, 10, ctx) // create the robot
document.getElementById("LMBack").checked=false // set not reverse motor
document.getElementById("raceBack").checked=false // set no race track
setchecked(5) // set robot stop mode
addKeySpecial() // allow keyboard commands
addMouseDown(canvas) // and mouse click to move robot
oneRobot = true
handleResize(); // cope if browser resizes
setGrayBack() //set grey background
setEnv(0) // define basic arena
active = true
setRobotTimer() // set timer for moving robot
// document.getElementById("myCanvasSYS").focus() // focus on canvas
focusOn(0) // focus on first speed
}
function handleResize(evt) {
// function to cope when browser resized
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100;
doResize(newWidth)
}
window.addEventListener('resize', handleResize);
// End -->
</script>
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()">
<div class="no-js">
<!-- Fallback content here -->
<h1>Desculpe-nos, mas você precisa ativar o JavaScript do seu navegador para ter acesso a este exercício.</h1>
</div>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="js">
<table width="90%" style="margin-left: 5%; margin-right: 5%; margin-top: 2%; margin-bottom: 2%">
<tr>
<!-- Lado esquerdo -->
<td width="40%" style="vertical-align: top;" class="ColapsarColuna">
<h1 id="w0">Movimentando o robô</h1>
<p>Defina a velocidade das rodas do robô para que ele possa:<br>
<ul>
<li>Ir para frente</li>
<li>Virar para a esquerda</li>
<li>Virar para a direita</li>
<li>Ir para trás</li>
<li>Parar</li>
</ul>
Para isso altere a velocidade dos motores, utilizando sempre números inteiros</p>
<p>Aperte os botões (ir para a frente, virar para a direita, etc) para que o robô execute cada uma das funções programadas</p>
<p>Você pode utilizar a pista de corrida para testar seu controle, para isso basta utilizar a tecla de atalho T.</p>
<h2>Atalhos</h2>
<p>F -> Ir para frente<br>L -> Virar para a esquerda<br>R -> Virar para a direita<br>B -> Ir para trás<br>S - > Parar </p>
<h2>Atividades</h2>
<p>Primeiro defina as velocidade dos motores para cada um dos comandos do robô. Logo em seguida confira se eles estão funcionando conforme o esperado.</p>
<p>Logo em seguida pressione T para alterar para a pista de corrida e guie o robô até o fim do percurso!</p>
</td>
<td width="60%" style="padding-left: 3%; vertical-align: top;" class="ColapsarColuna">
<table width="100%">
<tr>
<td width="100%">
<div class="robot" width="100%">
<form name="controlsys" width="100%">
<canvas style="border-style: solid; border-width: medium; border-color: #38b54f;" id="myCanvasSYS" name="myCanvasSYS" width="756" height="300"></canvas>
<table width="90%" style="margin-right: 10%;">
<tr>
<td style="width: 50%;">
<p><input type="button" id="ForCheck" value="Ir para frente" onclick="setchecked(1);"></p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor Esquerdo<input type="text" id="robLeftFor" size="2" tabindex="1" value="0"> Motor Direito<input type="text" id="robRightFor" size="2" tabindex="2" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p><input type="button" id="LeftCheck" value="Virar para a esquerda" onclick="setchecked(2);"></p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor Esquerdo<input type="text" id="robLeftLeft" size="2" tabindex="3" value="0"> Motor Direito<input type="text" id="robRightLeft" size="2" tabindex="4" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p><input type="button" id="RightCheck" value="Virar para a direita" onclick="setchecked(3);"></p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor Esquerdo<input type="text" id="robLeftRight" size="2" tabindex="5" value="0"> Motor Direito<input type="text" id="robRightRight" size="2" tabindex="6" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p><input type="button" id="BackCheck" value="Ir para trás" onclick="setchecked(4);"></p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor Esquerdo<input type="text" id="robLeftBack" size="2" tabindex="7" value="0"> Motor Direito<input type="text" id="robRightBack" size="2" tabindex="8" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p><input type="button" id="StopCheck" value="Parar" onclick="setchecked(5);"></p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor Esquerdo<input type="text" id="robLeftStop" size="2" tabindex="9" value="0"> Motor Direito<input type="text" id="robRightStop" size="2" tabindex="10" value="0"></p>
</td>
</tr>
<tr>
<td>
<p>Inverter Motor Esquerdo<input type="checkbox" id="LMBack"></p>
<p>Arena<input type="checkbox" id="arena" checked="checked" onchange="setEnv(0)">
; Pista<input type="checkbox" id="addTrack" onchange="setEnv(1)"> </p>
<p><input type="button" id="getSet" value="Começar Corrida" onclick="race();" style="visibility: hidden;">
<input type="checkbox" id="raceBack" style="visibility:hidden">
<label id="rbLabel" style="visibility: hidden;">Inverter corrida</label></p>
<p id="p1"></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></p>
<style>
.ColapsarColuna{
display: table-cell;
}
@media only screen and (max-width: 900px){
td.ColapsarColuna{
display: block;
width: 96%;
margin-left: 2%;
margin-right: 2%;
}
}
</style>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/tutoriais.php
<!doctype html>
<html>
<head>
<?php
if(isset($_GET["file"])){
// Get parameters
$file = $_GET["file"]; // Decode URL-encoded string
$filepath = "downloads/" . $file;
echo "<meta http-equiv=\"refresh\" content=\"0;url=https://brino.cc/baixar.php?file=".$file."\" target = \"_blank\"/>";
}
?>
<meta charset="utf-8">
<title>Br.ino - Tutoriais</title>
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<body style="margin: 0;">
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<!-- ********* Começo dos tutoriais ********* -->
<section class="ATutoriais">
<div style="position: relative; height: 2vw"></div>
<h2 class="TitATutoriais">Tutoriais</h2>
<div style="position: relative; height: 2vw"></div>
<table class="TableTut">
<!-- Piscar LED -->
<tr>
<div id="DownloadPiscarLED">
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#Newsletter" title="Assistir vídeo" onclick="window.open('https://youtu.be/D_5iq2NYqAA');">
<img src="Imagens/Tutoriais/LED.png" alt="LED" class="ImagemTut">
</a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Piscar LED</p>
<p>Aprenda a controlar a placa Arduino para piscar seu LED interno e um LED externo com um código simples!</p>
<a href="#Piscar" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<a href="#Newsletter" title="Asistir vídeo" onclick="window.open('https://youtu.be/D_5iq2NYqAA');"><i class="fab fa-youtube" style="position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</div>
</tr>
<!-- Ligar luz com botao -->
<tr class="BoxLongoVerde">
<section id="LigarLuzComBotao">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Ligar luz com botão </p>
<p>Aprenda a usar um botão em uma entrada digital e a utiliza-la para acender um LED! </p>
<a href="#Botao" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<a href="#Newsletter" title="Asistir vídeo" onclick="window.open('https://youtu.be/nSGLoOBeZm4');"><i class="fab fa-youtube" style="position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://youtu.be/nSGLoOBeZm4');">
<img src="Imagens/Tutoriais/BOTAO.png" title="Ligar luz com botão" class="ImagemTut">
</a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- LDR -->
<tr>
<section id="DownloadLDR">
<table class="BoxLongoCinza">
<tr class="TrBox">
<th class="FotoTut">
<a href="#Newsletter" title="Asistir vídeo" onclick="window.open('https://youtu.be/P6-mqcg1Nlk');">
<img src="Imagens/Tutoriais/LDR.png" title="LDR" class="ImagemTut">
</a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">LDR</p>
<p>Aprenda a realizar leituras analógicas utilizando um sensor fotossensível (LDR).</p>
<a href="#LDR" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<a href="#Newsletter" title="Asistir vídeo" onclick="window.open('https://youtu.be/P6-mqcg1Nlk');"><i class="fab fa-youtube" style="position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Buzzer -->
<tr>
<section id="DownloadBuzzer">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Buzzer</p>
<p>Construa melodias simples com o buzzer!</p>
<a href="#Buzzer" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<a href="#Newsletter" title="Asistir vídeo" onclick="window.open('https://youtu.be/L6lu4H_UfRk');"><i class="fab fa-youtube" style="position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Newsletter" title="Asistir vídeo" onclick="window.open('https://youtu.be/L6lu4H_UfRk');">
<img src="Imagens/Tutoriais/BUZZER.png" title="Buzzer" class="ImagemTut">
</a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Ultrassonico -->
<tr>
<section id="UltrassomMemoria">
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#Newsletter" title="Baixar material" onclick="window.open('https://youtu.be/ZNtwvWiyU28');">
<img src="Imagens/Tutoriais/HC-SR04.png" title="Ultrassonico" class="ImagemTut">
</a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Ultrassom + Memória</p>
<p>Realize medidas com o sensor de distância HC-SR04 e salve na memória do Arduino.</p>
<a href="#Ultrassonico" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<a href="#Newsletter" title="Baixar material" onclick="window.open('https://youtu.be/ZNtwvWiyU28');"><i class="fab fa-youtube" style="position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Potenciometro -->
<tr>
<section id="ServoComPotenciometro">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Servo com potênciometro</p>
<p>Aprenda a controlar um servo motor com a leitura analógica de um potenciômetro!</p>
<a href="#Servo" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#efefef; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Servo" title="Baixar material">
<img src="Imagens/Tutoriais/POTENCIOMETRO.png" title="Potenciometro" class="ImagemTut">
</a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Carrinho -->
<tr>
<section id="Carrinho">
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#CarrinhoPDF" title="Baixar material">
<img src="Imagens/Tutoriais/L293D.png" title="L293D" class="ImagemTut">
</a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Carrinho</p>
<p>Construa seu próprio carrinho com dois motores e uma ponte H dupla para controlá-los.</p>
<a href="#CarrinhoPDF" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Biblioteca -->
<tr>
<section id="BibliotecaAdicionar">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Adicionar biblioteca</p>
<p>Aprenda a adicionar biblitecas a IDE brino!</p>
<a href="#BibliotecaAdicionarPDF" title="Baixar material"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#efefef; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#BibliotecaAdicionarPDF" title="Baixar material">
<img src="Imagens/Tutoriais/BibliotecaIco.png" title="Biblioteca" class="ImagemTut">
</a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
</table>
<!----------------------- PROJETOS ------------------->
<div style="position: relative; height: 2vw"></div>
<h2 class="TitATutoriais">Projetos</h2>
<div style="position: relative; height: 2vw"></div>
<table class="TableTut">
<!-- Girassol -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#Newsletter" onclick="window.open('https://github.com/BrinoOficial/Girassol');"><img src="Imagens/Tutoriais/Girassol.png" alt="Controle" class="ImagemTut"></a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Girassol</p>
<p>Construa seu girassol com o Arduino</p>
<a href="#Newsletter" onclick="window.open('https://github.com/BrinoOficial/Girassol');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Sonar -->
<tr class="BoxLongoVerde">
<section id="DownloadMaquinaDeBolhas">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Sonar</p>
<p>Construa um sonar e uma interface gráfica com ajuda do Processing</p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/Sonar');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/Sonar');"><img src="Imagens/Tutoriais/Sonar.png" alt="Sonar" class="ImagemTut"></a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Painel solar -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/PainelSolar');"><img src="Imagens/Tutoriais/PainelSolar.png" alt="Painel" class="ImagemTut"></a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Painel solar</p>
<p>Posicione automaticamente um painel solar </p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/PainelSolar');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Teremim -->
<tr class="BoxLongoVerde">
<section id="DownloadMaquinaDeBolhas">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Teremim</p>
<p>Construa esse instrumento musical inteiramente eletrônico</p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/MiniTeremimArduino');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/MiniTeremimArduino');"><img src="Imagens/Tutoriais/Teremim.png" alt="Teremim" class="ImagemTut"></a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Apontador Laser -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/PanTiltApontadorLaser');"><img src="Imagens/Tutoriais/laser.png" alt="laser" class="ImagemTut"></a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Apontador laser</p>
<p>Construa um apontador laser controlado por um joystick</p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/PanTiltApontadorLaser');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Teimosinha -->
<tr class="BoxLongoVerde">
<section id="DownloadMaquinaDeBolhas">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Teimosinha</p>
<p>Crie essa caixa que se desliga sozinha</p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/Teimosinha');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/Teimosinha');"><img src="Imagens/Tutoriais/Box.png" alt="Teimosinha" class="ImagemTut"></a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Controle capacitivo -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/ControleCapacitivo/wiki');"><img src="Imagens/Tutoriais/Controle.png" alt="Controle" class="ImagemTut"></a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Controle Capacitivo</p>
<p>Utilize o seu Arduino como joystick com frutas e legumes</p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/ControleCapacitivo/wiki');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Maquina de bolhas -->
<tr class="BoxLongoVerde">
<section id="DownloadMaquinaDeBolhas">
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoTutVerde">
<p class="NomeTut">Máquina de bolhas</p>
<p>Projeto de uma máquina com braço robótico para fazer bolhas iradas quando um botão é pressionado. </p>
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/AIncrivelMaquinaDeBolhas/wiki');"><i class="fab fa-github" style=" position:relative; top: 0.7vw; color:#ffffff; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
<th class="FotoTut">
<a href="#Newsletter"onclick="window.open('https://github.com/BrinoOficial/AIncrivelMaquinaDeBolhas/wiki');"><img src="Imagens/Tutoriais/Bolhas.png" alt="Máquina de bolhas" class="ImagemTut"></a>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
<!-- Jogo do caminho -->
<tr>
<section id="JogoDoCaminho">
<table class="BoxLongoCinza">
<tr>
<th class="FotoTut">
<a href="#JogoDoCaminhoPDF"><img src="Imagens/Tutoriais/JogoDoCaminho.png" alt="Jogo do caminho" class="ImagemTut"></a>
</th>
<th class="DescricaoTutCinza">
<p class="NomeTut">Jogo do caminho</p>
<p>Crie um jogo incrível para trabalhar coordenação motora.</p>
<a href="#JogoDoCaminhoPDF"><i class="fas fa-file-pdf" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 50px;"></i></a>
<div style="position: relative; height: 2vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</section>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
.ATutoriais{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/BGTutoriais.jpg");
background-attachment: fixed;
padding: 0;
}
.TitATutoriais{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
color:#efefef;
width: 40%;
font-family: Coolvetica;
}
.TableTut{
width:60%;
text-align: center;
}
.BoxLongoCinza{
background-color: #efefef;
margin-left: 20%;
width: 60%;
}
.BoxLongoVerde{
background-color: #38b54f;
margin-left: 20%;
width: 60%;
}
.FotoTut{
width:50%;
}
.ImagemTut{
width: 60%;
}
.DescricaoTutCinza{
color: #38b54f;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
}
.DescricaoTutVerde{
color: #efefef;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
width: 50%;
}
.NomeTut{
font-weight: 900;
font-size: 1.7em;
line-height: 1em;
}
@media screen and (max-width: 850px) {
.ATutoriais{
background-attachment: inherit;
}
.TitATutoriais{
left: 0;
text-align: center;
font-size: 50px;
width: 100%;
}
.TableTut{
width: 95%;
}
.BoxLongoCinza{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.BoxLongoVerde{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.NomeTut{
font-weight: 700;
font-size: 1em;
line-height: .7em;
}
}
</style>
<!-- Pedir email -->
<div id="Newsletter" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Deseja ficar por dentro dos novos materiais?</h2>
</div>
<!-- Form do phpList Newsletter -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=3" name="subscribeform" class="formPopUp">
<div class="required"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" required class="attributeinput" size="40" placeholder="Seu nome..." id="attribute1" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required"><label for="email">Email</label></div>
<input type=email name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script><input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="list[2]" value="signup" /><input type="hidden" name="listname[2]" value="newsletter"/><div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div><input type=submit name="subscribe" value="Ficar por dentro!" onClick="return checkform();"></form>
<div>
<h2 style="color:#EFEFEF;">Receba as novidades que mais te interessam!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Piscar -->
<div id="Piscar" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<!-- Form do phpList baixar material -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/1.Piscar.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial Piscar!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Botao -->
<div id="Botao" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/2.LigarLuzComBotao.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial Botão!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download LDR -->
<div id="LDR" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/3.LeituraAnalogicaParaUsb.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial LDR!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Buzzer -->
<div id="Buzzer" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/4.Buzzer.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial Buzzer!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Ultrassonico -->
<div id="Ultrassonico" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/5.UltrassomEMemoria.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial Ultrassonico!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Servo -->
<div id="Servo" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/6.ServoControladoPorPotenciometro.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial Servo!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Carrinho -->
<div id="CarrinhoPDF" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/7.Carrinho.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial Carrinho!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Biblioteca -->
<div id="BibliotecaAdicionarPDF" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/InstalandoBiblioteca.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial de bibliotecas!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download JogoDoCaminho -->
<div id="JogoDoCaminhoPDF" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=1" name="subscribeform" class="formPopUp">
<div class="required texto"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" requiredss placeholder="Seu nome..." class="attributeinput" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required texto"><label for="email">Email</label></div>
<input type="email" name=email required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="hidden" name="htmlemail" value="1" />
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Tutoriais/JogoDoCaminho.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[5]" value="signup" />
<input type="hidden" name="listname[5]" value="Download material"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o tutorial do Jogo Do Caminho!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!--CSS do formulario -->
<style>
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=email], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #38b54f;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #655b4a;
}
.texto{
color: #efefef;
}
.in {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
margin-left: auto;
margin-right: auto;
display: inline-block;
border: 1px solid #ccc;
border-radius: 15px;
box-sizing: border-box;
font-family: Coolvetica;
font-size: 17px;
}
/* Style do botao */
.BotaoForm {
width: 30%;
background-color: #38b54f;
color: #efefef;
padding: 14px 20px;
margin: 8px 0;
border: 0;
border-radius: 5px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
font-family: Coolvetica;
border:1px solid rgba(0,0,0,0);
}
.BotaoForm:hover {
background-color: #efefef;
border:1px solid #38b54f;
color: #38b54f;
}
.modalDialog {
position: fixed;
font-family: lato;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity:1;
pointer-events: auto;
}
.modalDialog > div {
width: 60%;
position: relative;
margin: 10% auto;
margin-bottom: 0;
margin-top: 0;
padding: 5px 20px 13px 20px;
border-radius: 5px;
background-color: #38b54f;
}
.close {
color: #efefef;
line-height: 25px;
float: right;
text-decoration: none;
font-weight: bold;
}
.formPopUp{
background: rgba(0,0,0,0.7);
width: 60%;
padding: 5px 20px 13px 20px;
margin: 10% auto;
margin-bottom: 0;
margin-top: 0;
}
section{
padding: 0;
}
@media screen and (max-width: 700px) {
.modalDialog > div {
width: 90%;
}
.formPopUp{
width: 90%;
padding: 20px 0 20px 0;
}
}
</style>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/acessoCurso.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Acesso Curso</title>
</head>
<meta http-equiv="refresh" content=1;url="https://app.nutror.com/v3/curso/8866b2a8a580c5fc4bdb0f9cddc64ce592492f13/mini-curso-de-robotica-e-metodologias-ativas">
<body>
</body>
</html><file_sep>/download.php
<!doctype html>
<html>
<head>
<?php
if(isset($_GET["file"])){
// Get parameters
$file = $_GET["file"]; // Decode URL-encoded string
$filepath = "downloads/" . $file;
echo "<meta http-equiv=\"refresh\" content=\"0;url=https://brino.cc/baixar.php?file=".$file."\" target = \"_blank\"/>";
}
?>
<meta charset="utf-8">
<title>IDE Br.ino</title>
<meta http-equiv="Content-Language" content="pt-br">
</head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<body>
<?php include_once("analyticstracking.php") ?>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<style>
section.module.parallax {
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
</style>
<!-- Header -->
<section class="Header">
<!-- espaco -->
<div style="position: relative; height:2vw"></div>
<h2 class="linhaDownloadUm">Mais prática e<spam style="color: #38b54f;"> rápida </spam></h2>
<ul class="anchorList" style="list-style-type: none; padding: 0;">
<!-- Chamada de botão download-->
<li style="width: 100%; margin: 0;"><a href="#NossaIDE"><div align="center" class="botaoDownload">Baixar</div></a></li>
</ul>
<!-- espaco -->
<div style="position: relative; height: 10vw"></div>
</section>
<style>
body{
margin:0px;
padding:0px;
}
.linhaDownloadUm{
font-size: 10vw;
line-height: 1.2em;
font-family: Coolvetica;
color: #ffffff;
position: relative;
text-align: center;
}
.linhaDownloadDois{
font-size: 8vw;
color: #ffffff;
position: relative;
text-align: center;
}
.Header{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/usandoIDE.jpg");
background-attachment: fixed;
}
.botaoDownload{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#efefef;
background: #38b54f;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 150px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
}
.botaoDownload:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.botaoDownload:hover{
background: #efefef;
color: #38b54f;
border:1px solid #38b54f;
}
a{
text-decoration: none;
color: inherit;
}
@media screen and (max-width: 850px) {
.linhaDownloadUm{
font-family: Coolvetica;
}
.Header{
background-attachment: inherit;
}
}
</style>
<!-- Diferenciais da IDE -->
<section class="diferenciais texto" style="padding-top: 5vw; padding-bottom: 5vw;">
<h2 class="texto tituloDiferenciais">Conheça a nossa IDE</h2>
<table width="100%">
<tr>
<th style="width: 30%;">
<h2 class="TitCarac">Intuitiva</h2>
<br>
<img src="Imagens/QuebraCabeca.gif" alt="Quebracabeça se montando" class="GIFSIDE"/>
</th>
<th style="width: 30%;">
<h2 class="TitCarac">Leve</h2>
<br>
<img src="Imagens/PenaCaindo.gif" alt="Quebracabeça se montando" class="GIFSIDE"/>
</th>
<th style="width: 30%;">
<h2 class="TitCarac">Elegante</h2>
<br>
<img src="Imagens/Gentleman.gif" alt="Quebracabeça se montando" class="GIFSIDE"/>
</th>
</tr>
</table>
</section>
<style>
.TitCarac{
font-size: 2em;
line-height: 1em;
}
.diferenciais{
background-color: #38b54f;
}
.tituloDiferenciais{
padding-left: 1em;
padding-top: 1vw;
padding-bottom: 2vw;
}
.GIFSIDE{
width: 40%;
}
@media screen and (max-width: 850px) {
.TitCarac{
font-size: 1em;
line-height: 1em;
}
.tituloDiferenciais{
padding-left: 0;
padding-top: 0;
padding-bottom: 0;
text-align: center;
}
.GIFSIDE{
width: 70%;
}
}
</style>
<!-- Sobre a IDE -->
<section class="sobreAIDE">
<table style="width: 100%;">
<tr>
<th class="sobreAIDE">
<img src="Imagens/IDERolando.gif" alt="IDE Rolando o texto" class="IdeGif"/>
</th>
<td class="sobreAIDE">
<p class="textoSobreAIDE">
Programar Arduino com nosso ambiente de desenvolvimento é uma experiência sem igual. Nosso software é completamente traduzido para o português, com palavras-chave intuitivas que facilitam a compreensão da lógica de programação. Além disso, pode-se mesclar códigos em linguagem Arduino com as instruções em português. Tudo para tornar o processo de aprendizagem mais acessível e interessante!<br/>
<br>
Lembre-se que este programa é <strong>grátis</strong> e <strong>open-source</strong>, então, não deixe de experimentá-lo!
</p>
</td>
</tr>
</table>
</section>
<style>
.sobreAIDE{
background-color: #efefef;
}
td.sobreAIDE{
width: 60%;
}
td.sobreAIDE:first-child{
width: 40%;
}
.textoSobreAIDE{
color: #000;
font-family: Lato;
font-size: 1.3em;
margin-right: 9%;
margin-left: 5%;
margin-top: 6vw;
margin-bottom: 5vw;
text-align: left;
text-align: justify;
text-justify: inter-word;
}
.IdeGif{
width: 60%;
margin-left: 25%;
}
@media screen and (max-width: 850px) {
td.sobreAIDE{
width: 100%;
display: block;
}
th.sobreAIDE{
width: 100%;
display: block;
}
.IdeGif{
width: 40%;
margin-top: 10vw;
margin-bottom: 5vw;
margin-left: auto;
margin-right: auto;
}
p.textoSobreAIDE{
text-align: center;
margin-left: 3%;
margin-right: 3%;
}
}
</style>
<!-- Baixar a IDE -->
<section class="baixarIDE" id="NossaIDE">
<table width="100%">
<tr width="100%">
<th class="DownloadDaIde">
<table width="100%">
<tr>
<th class=" boxEsquerda">
<img src="Imagens/linux-logo.png" alt="Logo Linux" style="width: 20%;"/>
<h2 class="texto">Linux</h2>
<p class="texto">
<strong>Br.ino IDE 3.0.7</strong><br><br>
Resolução de bugs<br>
Monitor serial melhorado<br>
<br>
<br>
</p>
<!-- Chamada de botão começar-->
<div align="center" class="botaoChamada" id="myBtn"><a href="#DownloadLinuxModal">Baixar</a></div>
</th>
</tr>
</table>
</th>
<th class="DownloadDaIde">
<table width="100%">
<tr>
<th class=" boxDireita">
<img src="Imagens/windows-logo.png" alt="Logo Windows" style="width: 20%;"/>
<h2 class="texto">Windows</h2>
<p class="texto">
<strong>Br.ino IDE 3.0.7</strong><br><br>
Resolução de bugs<br>
Perfomace melhorada<br>
Mais estável<br>
</p>
<!-- Chamada de botão começar-->
<div align="center" class="botaoChamada"><a href="#DownloadWindowsModal">Baixar</a></div>
</th>
</tr>
</table>
</th>
</tr>
</table>
</section>
<style>
.baixarIDE{
background-color: #38b54f;
padding-top: 2vw;
}
.boxEsquerda{
padding-left: 20%;
padding-right: 5%;
}
.boxDireita{
padding-left: 5%;
padding-right: 20%;
}
.texto{
color: #efefef;
font-family: Lato;
}
h2.texto{
font-size: 3em;
font-weight: 800;
margin: 0;
}
.DownloadDaIde{
width: 50%;
}
.botaoChamada{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #38b54f;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 150px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
margin-top: 3vw;
margin-bottom: 4vw;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.botaoChamada:active{
cursor:pointer;
position:relative;
background: #efefef;
color: #38b54f;
top:1px;
}
.botaoChamada:hover{
background: #38b54f;
color: #efefef;
border:1px solid #efefef;
}
@media screen and (max-width: 850px) {
h2.texto{
font-size: 2em;
line-height: 2.3em;
}
th.DownloadDaIde{
display: block;
width: 100%;
}
th.boxEsquerda{
padding-left: 0;
padding-right: 0;
padding-bottom: 15%;
padding-top: 5%;
width: 100%;
}
th.boxDireita{
padding-left: 0;
padding-right: 0;
padding-bottom: 10%;
width: 100%;
}
}
</style>
<!-- Ebook gratuito -->
<section style="background-color: #efefef" id="ebook">
<br><br>
<h2 class="titApostila">E-book gratuito</h2>
<br>
<table>
<tr>
<th class="EbookGratuito">
<img src="Imagens/ebook.png" alt="Ebook" class="ImagemEbook">
</th>
<th class="EbookGratuito">
<p class="textoApostila">Agregando à filosofia de que <strong>qualquer um pode aprender robótica</strong>, Br.ino disponibiliza um <strong>e-book totalmente grátis!</strong> Deixe de lado as dificuldades e comece agora! Aprenda Arduino de forma prática e simples!</p>
<!-- espaco -->
<div style="position: relative; height: 5vw"></div>
<!-- Chamada de botão download-->
<div style="width: 100%; margin: 0;" id="myBtn"><a href="#DownloadApostilaModal"><div align="center" class="botaoDownload">Baixar</div></a></div>
</th>
</tr>
</table>
<br><br>
</section>
<style>
.titApostila{
color: #38b54f;
margin-left: 15%;
position: relative;
width: 80%;
font-family: Coolvetica;
font-size: 3em;
font-weight: 800;
}
.textoApostila{
margin: 0;
margin-left: 9%;
margin-right: 9%;
color: #000;
text-align: left;
text-align: justify;
text-justify: inter-word;
font-family: Lato;
font-size: 1.3em;
font-weight: normal;
}
.ImagemEbook{
width: 100%;
}
.EbookGratuito{
width: 50%;
}
@media screen and (max-width: 850px) {
.titApostila{
margin-left: 0;
text-align: center;
font-size: 2em;
line-height: 1em;
}
th.EbookGratuito{
display: block;
width: 100%;
}
.ImagemEbook{
width: 80%;
padding-bottom: 5%;
}
}
</style>
<!-- ********* Infografico ********* -->
<section style="background-color: #efefef;">
<!--
<img src="Imagens/infografico.jpg" width="100%">-->
<div style="color: #cccccc; text-align: center; margin-left: 15%; margin-right: 15%;">
<h2 class="Erros"><a href="https://github.com/BrinoOficial/BrinoPy/wiki/Corre%C3%A7%C3%A3o-de-erros" target="_blank">Caso ocorra algum erro durante a instalação clique aqui!</a></h2>
</div>
<br><br><br>
</section>
<style>
.Erros{
font-size: 2em;
font-weight: 800;
font-family: Coolvetica;
line-height: 1em;
}
</style>
<!-- ********* Modal ********* -->
<!-- Download linux -->
<div id="DownloadLinuxModal" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<!-- Form do phpList baixar IDE (Lin 64) -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=5" name="subscribeform" class="formPopUp">
<div class="required" style="color: #ffffff;"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" required placeholder="Seu nome..." size="40" value="" id="attribute1" class="in attributeinput"/>
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required" style="color: #ffffff;"><label for="email">Email</label></div>
<input type="email" name="email" required placeholder="Seu email..." size="40" id="email" class="in"/>
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="htmlemail" value="1" />
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Brino_3_0_7.tar.gz" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[8]" value="signup" />
<input type="hidden" name="listname[8]" value="Download IDE Br.ino"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input class="BotaoForm" type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando a IDE Brino para linux!<i class="fab fa-linux" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Windows -->
<div id="DownloadWindowsModal" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<!-- Form do phpList baixar IDE (Win 64) -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=5" name="subscribeform" class="formPopUp">
<div class="required" style="color: #ffffff;"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" required placeholder="Seu nome..." size="40" value="" id="attribute1" class="in attributeinput"/>
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required" style="color: #ffffff;"><label for="email">Email</label></div>
<input type="email" name="email" required placeholder="Seu email..." size="40" id="email" class="in"/>
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="htmlemail" value="1" />
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/Brino_3_0_7_Instalador.exe" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[8]" value="signup" />
<input type="hidden" name="listname[8]" value="Download IDE Br.ino"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input class="BotaoForm" type=submit name="subscribe" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando a IDE Brino para Windows!<i class="fab fa-windows" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!-- Download Apostila -->
<div id="DownloadApostilaModal" class="modalDialog">
<div style="margin-top: 5%;">
<a href="#close" title="Close" class="close">X</a>
<h2 style="color: #EFEFEF">Para completar o Download complete os campos abaixo:</h2>
</div>
<!-- Form do phpList baixar apostila -->
<form method="post" action="https://brino.cc/phpList/?p=subscribe&id=4" name="subscribeform" class="formPopUp">
<div class="required" style="color: #ffffff;"><label for="attribute1">Nome completo</label></div>
<input type="text" name="attribute1" required placeholder="Seu nome..." class="attributeinput in" size="40" value="" id="attribute1" />
<script language="Javascript" type="text/javascript">addFieldToCheck("attribute1","Nome completo");</script>
<div class="required" style="color: #ffffff;"><label for="email">Email</label></div>
<input type="email" name="email" class="in" required placeholder="Seu email..." size="40" id="email" />
<script language="Javascript" type="text/javascript">addFieldToCheck("email","Email address");</script>
<input type="checkbox" name="TermoLGPD" required/><label style="color:#ffffff;">Ao marcar a caixa ao lado você concorda com a <a href="https://brino.cc/downloads/PoliticaDePrivacidadeBrino.pdf" target="_blank" style="color: #efefef;; text-decoration: underline;">política de privacidade Br.ino</a> atualizada em 24/09/2020 e em receber nossos emails</label>
<input type="hidden" name="htmlemail" value="1" />
<input type="hidden" name="attribute2" class="attributeinput" size="40" value="https://brino.cc/downloads/EbookBrinoFree.pdf" id="attribute2" /><script language="Javascript" type="text/javascript">addFieldToCheck("attribute2","URL download");</script></td></tr>
<input type="hidden" name="list[7]" value="signup" />
<input type="hidden" name="listname[7]" value="Ebook Br.ino"/>
<div style="display:none"><input type="text" name="VerificationCodeX" value="" size="20"></div>
<input type="submit" name="subscribe" class="BotaoForm" value="Baixar" onClick="return checkform();">
</form>
<div>
<h2 style="color:#EFEFEF;">Você está baixando o Ebook Brino!<i class="fas fa-book" style="font-size:50px; position:relative; float: right; color:#ffffff;"></i></h2>
</div>
</div>
<!--CSS do formulario -->
<style>
.in {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
margin-left: auto;
margin-right: auto;
display: inline-block;
border: 1px solid #ccc;
border-radius: 15px;
box-sizing: border-box;
font-family: Coolvetica;
font-size: 17px;
}
/* Style do botao */
.BotaoForm {
width: 30%;
background-color: #38b54f;
color: #efefef;
padding: 14px 20px;
margin: 8px 0;
border: 0;
border-radius: 5px;
cursor: pointer;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
font-family: Coolvetica;
border:1px solid rgba(0,0,0,0);
}
.BotaoForm:hover {
background-color: #efefef;
border:1px solid #38b54f;
color: #38b54f;
}
.modalDialog {
position: fixed;
font-family: lato;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity:1;
pointer-events: auto;
}
.modalDialog > div {
width: 60%;
position: relative;
margin: 10% auto;
margin-bottom: 0;
margin-top: 0;
padding: 5px 20px 13px 20px;
border-radius: 5px;
background-color: #38b54f;
}
.close {
color: #efefef;
line-height: 25px;
float: right;
text-decoration: none;
font-weight: bold;
}
.formPopUp{
background: rgba(0,0,0,0.5);
width: 60%;
padding: 5px 20px 13px 20px;
margin: 10% auto;
margin-bottom: 0;
margin-top: 0;
}
@media screen and (max-width: 700px) {
.modalDialog > div {
width: 90%;
}
.formPopUp{
width: 90%;
padding: 20px 0 20px 0;
}
}
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=email], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #38b54f;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #655b4a;
}
div.caixa {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<!-- Tamanho do rodapeh -->
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/sobre.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Br.ino - Sobre</title>
</head>
<!-- Acesso aos ícones -->
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<body>
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php" ?>
</header>
<style>
@font-face {
font-family: Coolvetica;
src: url("Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("Fontes/Lato.ttf");
font-display: swap;
}
body{
margin:0px;
padding:0px;
}
</style>
<!-- ********* O que é o brino ********* -->
<style>
.QuemSomos{
width: 80%;
margin: auto;
}
.ColunaQuemSomos{
width:50%;
}
@media screen and (max-width: 1000px) {
table.QuemSomos{
width: 100%;
margin: auto;
}
th.ColunaQuemSomos{
display: block;
width: 80%;
margin: auto;
margin-bottom: 10%;
}
}
</style>
<section class="OQueE">
<h2 class="TitOQueE">Sobre a Startup</h2>
<div style="position: relative; height: 1vw"></div>
<div class="h_iframe" align="center">
<img class="ratio" src="http://brino.cc/Imagens/BG/BgS1.jpg" alt="Video Brino"/>
<iframe scrolling="no" src="https://www.youtube.com/embed/BNzG8pgsjsg?modestbranding=1&autohide=1&showinfo=1&controls=1" frameborder="0" allowfullscreen></iframe>
</div>
<div style="position: relative; height: 10vw"></div>
<table class="QuemSomos">
<tr>
<th class="ColunaQuemSomos">
<p style=" font-size: 1em; width: 100%; margin: auto;font-family: Lato;">
Somos a startup brasiliense que ajuda escolas e educadores a preparar aulas mais tecnológicas, criativas e engajadoras ! Para enfrentar os desafios educacionais do século XXI, desenvolvemos um método de ensinar que usa Robótica, Movimento Maker, Metodologias Ativas e Plataformas Digitais como poderosas ferramentas pedagógicas.</br></br>Nosso foco está no trabalho com educadores e instituições de ensino que desejam inovar. Por isso, oferecemos capacitações online, ferramentas de ensino de programação, mentorias e cursos de Educação Tecnológica para todo Brasil!
</p>
</th>
<th class="ColunaQuemSomos">
<video autoplay loop muted playsinline width="50%">
<source src="Imagens/QuemSomos.mp4" type="video/mp4">
</video>
</th>
</tr>
</table
<div style="position: relative; height: 15vw"></div>
</section>
<style>
.TitOQueE{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
color:#38b54f;
width: 40%;
font-family: Coolvetica;
}
.OQueE{
background-color: #efefef;
}
.h_iframe {position:relative;}
.h_iframe .ratio {display:block;width:70%;height:70%;}
.h_iframe iframe {position:absolute;top:0;width:70%; height:100%;right: 15%;}
@media screen and (max-width: 850px) {
.TitOQueE{
left: 0;
text-align: center;
font-size: 30px;
width: 100%;
}
}
</style>
<!-- ********* Onde já atuamos ********* -->
<style>
.EscolasSec{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/BGEscolasParceiras.jpg");
background-attachment: fixed;
padding: 0;
margin: 0;
}
.Parceiros{
width: 70%;
margin-left: 15%;
}
.container{
width: 400px;
height: 400px;
margin-left: auto;
margin-right: auto;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-perspective: 1000px;
perspective: 1000px;
}
.front,
.back{
-webkit-transition: -webkit-transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: -webkit-transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
-o-transition: transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: transform .7s cubic-bezier(0.4, 0.2, 0.2, 1), -webkit-transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
text-align: center;
height: 100%;
width: 100%;
color: #fff;
font-size: 1.5rem;
}
.front{
background-color: #efefef;
}
.back{
background-color: #38b54f;
}
.front:after{
position: absolute;
top: 0;
left: 0;
z-index: 1;
width: 100%;
height: 100%;
content: '';
display: block;
opacity: .6;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
border-radius: 10px;
}
.container:hover .front,
.container:hover .back{
-webkit-transition: -webkit-transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: -webkit-transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
-o-transition: transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
transition: transform .7s cubic-bezier(0.4, 0.2, 0.2, 1), -webkit-transform .7s cubic-bezier(0.4, 0.2, 0.2, 1);
}
.back{
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.inner{
-webkit-transform: translateY(-50%) translateZ(60px) scale(0.94);
transform: translateY(-50%) translateZ(60px) scale(0.94);
top: 50%;
position: absolute;
left: 0;
width: 100%;
padding: 2rem;
-webkit-box-sizing: border-box;
box-sizing: border-box;
outline: 1px solid transparent;
-webkit-perspective: inherit;
perspective: inherit;
z-index: 2;
}
.container .back{
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.container .front{
-webkit-transform: rotateY(0deg);
transform: rotateY(0deg);
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.container:hover .back{
-webkit-transform: rotateY(0deg);
transform: rotateY(0deg);
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.container:hover .front{
-webkit-transform: rotateY(-180deg);
transform: rotateY(-180deg);
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
}
@media screen and (max-width: 1000px) {
table.Parceiros{
width: 100%;
margin: auto;
}
th.colunaEscolas{
display: block;
margin-bottom: 10%;
}
}
@media screen and (max-width: 500px) {
div.container{
width: 300px;
height: 300px;
}
}
</style>
<section class="EscolasSec">
<div style="position: relative; height: 2vw"></div>
<h2 class="TitAEquipe">Onde atuamos</h2>
<div style="position: relative; height: 2vw"></div>
<table class="Parceiros">
<tr>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- <NAME> -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardLeo.png" alt="<NAME>" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://www.leonardoonline.com.br/"><h2><NAME></h2></a>
<p>Aulas de robótica no contraturno com enfoque na OBR.</p>
<p>2019-2020</p>
</div>
</div>
</div>
</th>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- Escola Jardim do Eden -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardEJE.png" alt="<NAME>" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://eje.com.br/"><h2><NAME></h2></a>
<p>Aulas de robótica no contraturno.</p>
<p>2020-2020</p>
</div>
</div>
</div>
</th>
</tr>
</table>
<div style="position: relative; height: 1.5vw"></div>
<table class="Parceiros">
<tr>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- COLEGIO BATISTA -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardBatista.png" alt="Colégio Batista de Brasília" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://www.cbbrasilia.com.br/"><h2>Colégio Batista de Brasília</h2></a>
<p>Aulas de robótica na grade curricular.</p>
<p>2020-2020</p>
</div>
</div>
</div>
</th>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- SAFA -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardSAFA.png" alt="SAFA" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="http://safa.com.br/site/"><h2>Centro Educacional Sagrada Família</h2></a>
<p>Aulas de robótica no contraturno.</p>
<p>2020-2020</p>
</div>
</div>
</div>
</th>
</tr>
</table>
<div style="position: relative; height: 1.5vw"></div>
<table class="Parceiros">
<tr>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- Aspalha -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardR2.png" alt="R2" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://producoesr2.com.br/"><h2>R2 + Escola Classe Aspalha</h2></a>
<p>Aulas de robótica na grade curricular por meio de parceria com a R2 Produções.</p>
<p>2020-2020</p>
</div>
</div>
</div>
</th>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- COLETIVO DA CIDADE -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardColetivoDaCidade.png" alt="ONG Coletivo da Cidade" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="http://www.coletivodacidade.org/"><h2>ONG Coletivo da Cidade</h2></a>
<p>Aulas voluntarias de robótica.</p>
<p>2019-2020</p>
</div>
</div>
</div>
</th>
</tr>
</table>
<div style="position: relative; height: 1vw"></div>
<table class="Parceiros">
<tr>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- COLEGIO BATISTA -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardLabHacker.png" alt="LabHacker do Bem" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://labhackerdobem.org/"><h2>LabHacker do bem</h2></a>
<p>Aulas voluntarias de robótica.</p>
<p>2019-2020</p>
</div>
</div>
</div>
</th>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- Limpidus -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardLimpidus.png" alt="Limpidus" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://www.limpidus.com.br/"><h2>Limpidus</h2></a>
<p>Capacitação empresarial.</p>
<p>2018</p>
</div>
</div>
</div>
</th>
</tr>
</table>
<div style="position: relative; height: 1vw"></div>
<table class="Parceiros">
<tr>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!-- Engie -->
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/EngieLogo.png" alt="Engie" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://www.engie.com.br/"><h2>Engie Brasil</h2></a>
<p>Curso de robótica e cultura empresarial online.</p>
<p>2020-2021</p>
</div>
</div>
</div>
</th>
<th class="colunaEscolas" ontouchstart="this.classList.toggle('hover');">
<!--
<div class="container">
<div class="front">
<div class="inner">
<img src="Imagens/Atuamos/CardLimpidus.png" alt="Limpidus" style="width:70%;height:70%;margin-top: 15%;">
</div>
</div>
<div class="back">
<div class="inner">
<a href="https://www.limpidus.com.br/"><h2>Limpidus</h2></a>
<p>Capacitação empresarial.</p>
<p>2018</p>
</div>
</div>
</div>
-->
</th>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
</section>
<!-- ********* Visao, missao e valores ******** -->
<section style="background-color: #46b24f">
<div style="position: relative; height: 5vw"></div>
<table class="TableValores">
<tr>
<!-- Missão -->
<th class="ThValores">
<table width="100%">
<tr>
<th>
<img src="Imagens/Mapa.gif" height="150px">
</th>
</tr>
<tr>
<th>
<h3 class="SubTitValores">Missão</h3>
</th>
</tr>
<tr>
<th>
<p class="TextoValores">
Democratizar o ensino de robótica de forma intuitiva e acessível para jovens!
</p>
</th>
</tr>
</table>
</th>
<!-- Visão -->
<th class="ThValores">
<table width="100%">
<tr>
<th>
<img src="Imagens/maozinhas.gif" height="150px">
</th>
</tr>
<tr>
<th>
<h3 class="SubTitValores">Visão</h3>
</th>
</tr>
<tr>
<th>
<p class="TextoValores">
Ser uma empresa referência no ensino de robótica e ter parcerias com instituições públicas e privadas de todo o cenário nacional.
</p>
</th>
</tr>
</table>
</th>
<!-- Valores -->
<th class="ThValores">
<table width="100%">
<tr>
<th>
<img src="Imagens/Binoculos.gif" height="150px">
</th>
</tr>
<tr>
<th>
<h3 class="SubTitValores">Valores</h3>
</th>
</tr>
<tr>
<th>
<p class="TextoValoresLista">
Honestidade<br>
Respeito<br>
Transparência<br>
Inovação<br>
Persistência<br>
Open-source
</p>
</th>
</tr>
</table>
</th>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
<a href="https://brino.cc/index.php#contato" title="Tutoriais"><div align="center" class="botaoChamada">Entrar em Contato</div></a>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
a{
text-decoration: none;
color: inherit;
}
.TableValores{
width: 70%;
margin-left: 15%;
}
.ThValores{
width: 20%;
vertical-align: top;
}
.ImagemValores{
width: 60%;
}
.SubTitValores{
color: #efefef;
font-size: 2em;
font-weight: 800;
line-height: 0;
font-family: Coolvetica;
}
.TextoValores{
color: #efefef;
font-size: 1em;
font-weight: 500;
margin-left: 20%;
margin-right: 20%;
font-family: Lato;
text-align: justify;
}
.TextoValoresLista{
color: #efefef;
font-size: 1em;
font-weight: 500;
margin-left: 20%;
margin-right: 20%;
font-family: Lato;
text-align: center;
}
.botaoChamada{
font:normal 30px Arial, Helvetica, sans-serif;
font-style:normal;
color:#38b54f;
background: #efefef;
/* Espessura contorno e cor */
border:1px solid #efefef;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
/* Raio vertices */
-webkit-border-radius:7px 7px 7px 7px;
/* Largura */
width: 250px;
padding:5px 7px;
cursor:pointer;
margin:0 auto;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.botaoChamada:active{
cursor:pointer;
position:relative;
background: #38b54f;
color: #efefef;
top:1px;
}
.botaoChamada:hover{
background: #38b54f;
color: #efefef;
border:2px solid #efefef;
}
@media screen and (max-width: 850px) {
.ThValores{
display: block;
width: 100%;
margin-bottom: 20%;
}
.TextoValores{
width: 80%;
margin-left: 10%;
}
.TextoValoresLista{
width: 80%;
margin-left: 10%;
}
}
</style>
<!-- ********* A equipe ********* -->
<section class="AEquipe">
<div style="position: relative; height: 2vw"></div>
<h2 class="TitAEquipe">A Equipe</h2>
<div style="position: relative; height: 2vw"></div>
<table class="TableEquipe">
<!-- Gabriel -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoEquipe">
<img src="../Imagens/Equipe/GP.png" alt="Gabriel" class="ImagemEquipe">
</th>
<th class="DescricaoEquipeCinza">
<p class="NomeEquipe"><NAME></p>
<p>Diretor Financeiro</p>
<a href="https://www.linkedin.com/in/gabriel-rodrigues-pacheco-3713a7136" target="_blank"><i class="fab fa-linkedin" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 30px;"></i></a>
<div style="position: relative; height: 1vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Mohana -->
<tr>
<table class="BoxLongoVerde">
<tr class="TrBox">
<th class="DescricaoEquipeVerde">
<p class="NomeEquipe"><NAME></p>
<p>Diretora de Projetos</p>
<a href="https://www.linkedin.com/in/mohana-kruger-9915aa132" target="_blank"><i class="fab fa-linkedin" style=" position:relative; top: 0.7vw; color:#efefef; font-size: 30px;"></i></a>
<div style="position: relative; height: 1vw"></div>
</th>
<th class="FotoEquipe">
<img src="../Imagens/Equipe/MK.png" alt="Mohana" class="ImagemEquipe">
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Rafael -->
<tr>
<table class="BoxLongoCinza">
<tr>
<th class="FotoEquipe">
<img src="../Imagens/Equipe/RM.png" alt="Mohana" class="ImagemEquipe">
</th>
<th class="DescricaoEquipeCinza">
<p class="NomeEquipe"><NAME></p>
<p>Diretor de Marketing</p>
<a href="https://www.linkedin.com/in/rafael-mascarenhas-80a543138" target="_blank"><i class="fab fa-linkedin" style=" position:relative; top: 0.7vw; color:#38b54f; font-size: 30px;"></i></a>
<div style="position: relative; height: 1vw"></div>
</th>
</tr>
</table>
<div style="position: relative; height: 3px"></div>
</tr>
<!-- Victor -->
<tr>
<table class="BoxLongoVerde">
<tr>
<th class="DescricaoEquipeVerde">
<p class="NomeEquipe"><NAME></p>
<p>Diretor Executivo</p>
<a href="https://www.linkedin.com/in/victor-rodrigues-pacheco-040a36138" target="_blank"><i class="fab fa-linkedin" style=" position:relative; top: 0.7vw; color:#efefef; font-size: 30px;"></i></a>
<div style="position: relative; height: 1vw"></div>
</th>
<th class="FotoEquipe">
<img src="../Imagens/Equipe/VP.png" alt="Victor" class="ImagemEquipe">
</th>
</tr>
</table>
</tr>
</table>
<div style="position: relative; height: 5vw"></div>
</section>
<style>
.AEquipe{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/BGEquipe.jpg");
background-attachment: fixed;
padding: 0;
}
.TitAEquipe{
position: relative;
left: 15vw;
font-size: 3em;
line-height: 1em;
color:#efefef;
width: 40%;
font-family: Coolvetica;
}
.TableEquipe{
width:60%;
text-align: center;
}
.BoxLongoCinza{
background-color: #efefef;
margin-left: 20%;
width: 60%;
}
.BoxLongoVerde{
background-color: #38b54f;
margin-left: 20%;
width: 60%;
}
.FotoEquipe{
width:50%;
}
.ImagemEquipe{
width: 60%;
}
.DescricaoEquipeCinza{
color: #38b54f;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
}
.DescricaoEquipeVerde{
color: #efefef;
font-size: 1.5em;
font-weight: 500;
line-height: 1.5em;
font-family: Coolvetica;
width: 50%;
}
.NomeEquipe{
font-weight: 900;
font-size: 1.7em;
line-height: 1em;
}
@media screen and (max-width: 850px) {
.AEquipe{
background-attachment: inherit;
}
.TitAEquipe{
left: 0;
text-align: center;
font-size: 30px;
width: 100%;
}
.TableEquipe{
width: 95%;
}
.BoxLongoCinza{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.BoxLongoVerde{
width: 95%;
margin: 0;
margin-left: 2.5%;
}
.NomeEquipe{
font-weight: 700;
font-size: 1em;
line-height: .7em;
}
}
</style>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</body>
</html>
<file_sep>/contato.php
<?php
$email=$_GET['emailContato'];
$nome=$_GET['name'];
$to=$_GET['recipient'];
$subject = $_GET['subject']." de ".$nome;
$message = $_GET["message"]."\n\n".$email;
$headers = "From: ".$nome."<".$email.">";
$headers2 = "From: Br.ino <".$to.">";
$confirm="Obrigado por entrar em contato com o suporte do Br.ino! Recebemos a sua mensagem e a responderemos o mais rápido possível.\n\nAtt,\nBr.ino";
mail($email, "Suporte Brino", $confirm, $headers2);
mail("<EMAIL>", $subject, $message, $headers);
echo ("<script LANGUAGE='JavaScript'>
window.alert('E-mail enviado!');
window.location.href='http://brino.cc';
</script>");
?><file_sep>/jogos/EviteParedes.php
<html class=" js">
<head>
<title> Br.ino - Evite Paredes </title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<script type="text/javascript" src="EviteParedes_arquivos/RobotLib.js"></script>
<script type="text/javascript" src="EviteParedes_arquivos/RobotKeyLib.js"></script>
<script language="JavaScript">
<!-- Begin
var simtime = 20 // defines how often robot simulation updated
var robot // define robot object
var active = false // by default not moving
var speeds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // array of speeds for the different situations
var inBoxIds = ["robLeftNoObj", "robLeftLeft", "robLeftRight", "robLeftBoth", "robRightNoObj", "robRightLeft", "robRightRight", "robRightBoth"]
// names associated with the boxes for entering these speeds
var whereFocus = 0 // which is the current input field
var raceOn = false // race is off initially
var raceTime = 0 // how long has race been on - default 0
var distanceTravelled = 0 // for finding how far gone
var trackingDistance = false
function checkKeySpecial() {
// keySpecial has value of a key thathas been pressed ... detect if it is special and act ,,
switch (keySpecial) {
case 68 : // 'd' or 'D' mean focus on defining first speed : wall on left
case 100 : focusOn(0)
break
case 87 : // W 38 means toggle the revise Wire box
case 119 :
checkStr()
document.getElementById("LMBack").checked = !document.getElementById("LMBack").checked
deFocus()
break
case 83 : // S 38 means toggle stop start
case 115 :
checkStr()
setchecked()
deFocus()
break
case 85 : // 'u' or 'U' mean toggle return race
case 117 : checkStr()
if (document.getElementById("addTrack").checked)
document.getElementById("raceBack").checked = !document.getElementById("raceBack").checked
deFocus()
break
case 72 : // 'h' or 'H' mean how far moved option (also raceBack)
case 104 : checkStr()
if (document.getElementById("comparena").checked)
document.getElementById("raceBack").checked = !document.getElementById("raceBack").checked
deFocus()
break
case 65 : // 'a' or 'A' means set main arens
case 97 : checkStr()
setEnv(0)
break
case 67 : // 'c' or 'C' means set complex arens
case 99 : checkStr()
setEnv(1)
break
case 84 : // T means set track
case 116 : checkStr()
setEnv(2)
break
case 76 :
case 108 : // l or L to toggle Line to Follow mode
checkStr()
setEnv(3)
break
default : checkKeyRest() // call general function which moves the robot if press IJKM etc...
}
keySpecial = 0 // have used keySpecial ... now set to 0 o dont do again.
}
// function to draw environment
function getState() {
// determine the state of the robot on the basis of its sensors
// get each sensor reading ... if less than 100 then sensor is seeing wall
if ( (robot.getSensor(0)<=100) && (robot.getSensor(2)<=100) ) actionNo = 4 // both sensors see wall
else if (robot.getSensor(2)<=100) actionNo = 3 // right only
else if (robot.getSensor(0)<=100) actionNo = 2 // left only
else actionNo = 1 // nothing seen
if (document.getElementById("addLine").checked) actionNo = 5 - actionNo
}
function checkRaceEnd() {
// if racing, check to see if reached the area which marks the race end
if (raceOn && inRaceEnd(robot.robotx, robot.roboty, document.getElementById("raceBack").checked) ) {
raceOn = false // if so stop
active = false
document.getElementById("p1").innerHTML="Finished after "+(0.5*raceTime/simtime).toFixed(1)+"s"
} // report how long it took
}
function checkDistanceEnd() {
active = (raceTime < 1000)
document.getElementById("p1").innerHTML="Distância percorrida "+((active) ? "até agora " : " em 1000 passos ")+distanceTravelled.toFixed(0)
// report how far travelled
if (active == false) document.getElementById("StopCheck").value="Começar"
}
function moveTheRobot() {
checkStrings() // update speeds array from text boxes
checkKeySpecial() // first look for any keys the user has pressed
if (active) {
if (raceOn || trackingDistance) raceTime++ // if racing or tracking time, increment time taken
getState() // identify state from sensors ... sets actionNo
// load up speeds (noting if left motor is wired backwards) for this actionNo
lspeed = ( ( document.getElementById("LMBack").checked ) ? 1 : -1) * speeds[actionNo-1]
rspeed = speeds[actionNo+3]
robot.robotDraw(false) // remove robot from current place
var rpos = [robot.robotx, robot.roboty] // remember current position
robot.moveRobot(lspeed, rspeed) // move it to new position based on speeds
redrawEnvironment(robot.ctx) // redraw environment behind it and then draw robot
if (trackingDistance) {
distanceTravelled += distance(rpos[0], rpos[1], robot.robotx, robot.roboty)
checkDistanceEnd()
}
else if (raceOn) checkRaceEnd() // if racing check if at the end
}
}
function setRobotTimer() {
// set up the timer for animating the robot, and the function called every simtime intervals
setInterval(function(){moveTheRobot()},simtime);
}
function race() {
active = false
if (document.getElementById("raceBack").checked) { // if racing backwards
robot.robotx = 400 // start in green area facing left
robot.roboty = 150
robot.angle = Math.PI
}
else {
robot.robotx = 50 // start in red area facing right
robot.roboty = 50
robot.angle = 0
}
document.getElementById("p1").innerHTML="" // clear message
raceOn = true // set racing
raceTime = 0 // clear timer
active = true // set active
// drawEnvironment() // and draw robot in start place
}
function setchecked() {
// when start/stop button pressed, toggle state and update caption on button
trackingDistance = false
active = !active
if (document.getElementById("addTrack").checked) {
document.getElementById("StopCheck").value=((active) ? "parar" : "começar");
if (active) race()
}
else {
document.getElementById("StopCheck").value="Precione para "+(active ? "parar" : "começar");
if (document.getElementById("raceBack").checked) {
distanceTravelled = 0
trackingDistance = true
raceTime = 0
}
}
}
function updatePrompts(rMode) {
var prStrs = []
if (rMode==3) prStrs = ["Seguidor de linha", "Quando ambos sensores detectam a linha", "Quando o sensor esquerdo detecta a linha",
"Quando o sensor direito detecta a linha", "Quando a linha não é detectada"]
else prStrs = ["Evitar Paredes", "Quando nenhum obstáculo é detectado :", "Quando o obstáculo está à esquerda :",
"Quando o obstáculo está à direita : ", "Quando o obstáculo está em ambos os lados :"]
document.getElementById("w0").innerHTML=prStrs[0]
document.getElementById("w1").innerHTML=prStrs[1]
document.getElementById("w2").innerHTML=prStrs[2]
document.getElementById("w3").innerHTML=prStrs[3]
document.getElementById("w4").innerHTML=prStrs[4]
var rvis = (rMode == 2 || rMode == 1) ? "visible" : "hidden"
var rlab = (rMode == 2) ? "Inverter trajeto" : (rMode==1) ? "Distância percorrida" : ""
document.getElementById("rbLabel").style.visibility = rvis
document.getElementById("rbLabel").innerHTML = rlab
document.getElementById("raceBack").style.visibility = rvis
document.getElementById("p1").innerHTML=""
}
function setEnv(which) {
// set the environment depending on which
if (which>=0) {
document.getElementById("arena").checked = (which == 0) // blank arena
document.getElementById("comparena").checked = (which == 1) // with little spikes
document.getElementById("addTrack").checked = (which == 2) // with track
document.getElementById("addLine").checked = (which == 3) // add path to Follow
document.getElementById("p1").innerHTML="" // clear any message
}
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
active = false // stop robot
document.getElementById("StopCheck").value= ((which == 2) ? "Começar" : "Começar")
if (which == 2) document.getElementById("raceBack").checked=false
raceTrack (document.getElementById("addTrack").checked, false, canvas.width, canvas.height)
// add / remove track
if (which == 0 || which == 3) basicEnvironment(canvas.width, canvas.height)
else if (which == 1) advancedEnvironment(canvas.width, canvas.height)
addPathToFollow (which == 3, canvas.width, canvas.height)
if (which == 3) robot.defineSensors([6, 0, 6])
else robot.defineSensors([1, 0, 1])
updatePrompts(which)
robot.speedControl = document.getElementById("addTrack").checked==false
// no speed control by default
redrawEnvironment(ctx) // draw the environment
}
function load() {
// load function - called when page loaded
active = false
window.defaultStatus="RJM's Simple Robot System";
checkBrowser()
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
robot = new aRobot(50, 50, 10, ctx) // define the robot
document.getElementById("LMBack").checked=false // clear options
document.getElementById("raceBack").checked=false
oneRobot = true
addMouseDown (canvas) // allow mouse presses to reposition robot
addKeySpecial() // allow user to command using keys
setGrayBack() // grey background
handleResize(); // in case browser resized
setEnv(0) // set basic environment
setRobotTimer()
focusOn(0)
}
function handleResize(evt) {
// function to cope when browser resized
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100;
doResize(newWidth)
}
window.addEventListener('resize', handleResize);
// End -->
</script>
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()">
<div class="no-js">
<!-- Fallback content here -->
<h1>Desculpe-nos, mas você precisa ativar o JavaScript do seu navegador para ter acesso a este exercício.</h1>
</div>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="js">
<table width="90%" style="margin-left: 5%; margin-right: 5%; margin-top: 2%; margin-bottom: 2%">
<tr>
<!-- Lado esquerdo -->
<td width="40%" style="vertical-align: top;" class="ColapsarColuna">
<h1 id="w0">Evitar Paredes</h1>
<p>Ajuste a velocidade dos motores do robô para definir seu comportamento. Configure este protótipo para se adaptar às leituras do sensor de obstáculos acoplados ao projeto. </p>
<p> A velocidade pode ser definida como um número inteiro entre -40 e 40. </p>
<p>Você pode selecionar a <i>Arena vazia</i> ou a <i>Arena complexa</i>: Na complexa é possível observar o quão longe o robô vai em 1000 passos.</p>
<p>Você também pode selecionar a <i>Pista</i>, em que temos um circuito para ser resolvido pelo robô.</p>
<p>Por último, também é possível optar pelo "Seguidor de linha", onde o sensor informa a detecção de uma linha. Altere as velocidades para que o robô siga a linha.</p>
<br>
<h2>Atalhos</h2>
<p>Precione D para definir a velocidade (Utilize TAB para mover para a próxima); <br>
Utilize S para iniciar/pausar o robô;</p><br>
<h2>Atividades</h2>
<p>Na Área Vazia</p>
<p>1. Explorar o que acontece quando adicionamos valores de velocidade aos motores</p>
<p>2. Fazer o robô ir para a frente</p>
<p>3. Fazer o robô ir para trás</p>
<p>4. Fazer o robô virar para direita</p>
<p>5. fazer o robô virar para a esquerda</p>
<p>6. Explorar a "abertura" da curva com base na diferença entre os valores de cada motor. O que acontece quando colocamos velocidades diferentes em cada motor? Quando a diferença é maior, o que acontece? E quando essa diferença é menor?</p>
<p>Na Área Complexa</p>
<p> Experimentar os parâmetros de velocidade para explorar o novo terreno. Em seguida, avalie se estes valores são uma boa solução para o problema. Seu robô ficou preso em alguma etapa? A distância percorrida foi satisfatória?</p>
<p>Na Pista</p>
<p>Qual o menor tempo que seu robô leva para cumprir este percurso? E o percurso inverso?</p>
<p>No Seguidor de Linha</p>
<p>Por fim, selecione o "Seguidor de linha" e faça o robô seguir a linha.</p>
</td>
<!-- Lado direito -->
<td width="60%" style="padding-left: 3%; vertical-align: top;" class="ColapsarColuna">
<table width="100%">
<tr>
<td width="100%">
<div class="robot" width="100%">
<form name="controlsys" width="100%">
<canvas style="border-style: solid; border-width: medium; border-color: #38b54f;" id="myCanvasSYS" name="myCanvasSYS" width="756" height="300"></canvas>
<table width="100%">
<tr>
<td style="width: 50%;">
<p id="w1">Parede não detectada:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftNoObj" size="3" tabindex="1" value="0">
Motor direito<input type="text" id="robRightNoObj" size="3" tabindex="2" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p id="w2">Parede à esquerda:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftLeft" size="3" tabindex="3" value="0">
Motor direito<input type="text" id="robRightLeft" size="3" tabindex="4" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p id="w3">Parede à direita: </p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftRight" size="3" tabindex="5" value="0">
Motor direito<input type="text" id="robRightRight" size="3" tabindex="6" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p id="w4">Parede em ambos os lados:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftBoth" size="3" tabindex="7" value="0">
Motor direito<input type="text" id="robRightBoth" size="3" tabindex="8" value="0"></p>
</td>
</tr>
</table>
<p><input type="checkbox" id="LMBack">Inverter motor esquerdo</p>
<p><input type="button" id="StopCheck" value="Parar" onclick="setchecked();">
<input type="checkbox" id="raceBack" style="visibility:hidden">
<label id="rbLabel" style="visibility: hidden;"></label></p>
<p><input type="checkbox" id="arena" checked="checked" onchange="setEnv(0)">Arena vazia
<input type="checkbox" id="comparena" onchange="setEnv(1)">Arena complexa</p>
<p><input type="checkbox" id="addTrack" onchange="setEnv(2)"> Pista
<input type="checkbox" id="addLine" onchange="setEnv(3)"> Seguidor de linha
</p>
<p id="p1"></p>
</form>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></p>
</div>
<style>
.ColapsarColuna{
display: table-cell;
}
@media only screen and (max-width: 900px){
td.ColapsarColuna{
display: block;
width: 96%;
margin-left: 2%;
margin-right: 2%;
}
}
</style>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/cadastroListaEbook.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cadastrando</title>
<!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
</head>
<body onload="mandar()">
<div id="mc_embed_signup">
<form action="https://gmail.us20.list-manage.com/subscribe?u=966c215d16c90fd5585eb1f86&id=82d614c535" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" novalidate>
<div id="mc_embed_signup_scroll">
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">E-mail <span class="asterisk">*</span>
</label>
<input type="email" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-FNAME">Nome <span class="asterisk">*</span>
</label>
<input type="text" name="FNAME" class="required" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Sobrenome </label>
<input type="text" value="" name="LNAME" class="" id="mce-LNAME">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_9d79f6998cfef13a20370b64e_4004fd6a42" tabindex="-1" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='ADDRESS';ftypes[3]='address';fnames[4]='PHONE';ftypes[4]='phone'; /**
* Translated default messages for the $ validation plugin.
* Locale: PT_PT
*/
$.extend($.validator.messages, {
required: "Campo de preenchimento obrigatório.",
remote: "Por favor, corrija este campo.",
email: "Por favor, introduza um endereço eletrónico válido.",
url: "Por favor, introduza um URL válido.",
date: "Por favor, introduza uma data válida.",
dateISO: "Por favor, introduza uma data válida (ISO).",
number: "Por favor, introduza um número válido.",
digits: "Por favor, introduza apenas dígitos.",
creditcard: "Por favor, introduza um número de cartão de crédito válido.",
equalTo: "Por favor, introduza de novo o mesmo valor.",
accept: "Por favor, introduza um ficheiro com uma extensão válida.",
maxlength: $.validator.format("Por favor, não introduza mais do que {0} caracteres."),
minlength: $.validator.format("Por favor, introduza pelo menos {0} caracteres."),
rangelength: $.validator.format("Por favor, introduza entre {0} e {1} caracteres."),
range: $.validator.format("Por favor, introduza um valor entre {0} e {1}."),
max: $.validator.format("Por favor, introduza um valor menor ou igual a {0}."),
min: $.validator.format("Por favor, introduza um valor maior ou igual a {0}.")
});}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
<script>
function mandar(){
var em = document.getElementById('mce-EMAIL');
em.value=("<?echo $_POST['email']?>");
document.getElementById('mce-FNAME').value=("<?echo $_POST['name']?>");
document.forms[0].submit();
var add = document.referrer.split('?')[0];
window.location.href = add+"?file=<?echo $_POST['file']?>";
}
</script>
</body>
</html><file_sep>/jogos/Labirinto.php
<html class=" js">
<head>
<title> Br.ino - Labirinto</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<script type="text/javascript" src="Labirinto_arquivos/RobotLib.js"></script>
<script type="text/javascript" src="Labirinto_arquivos/RobotKeyLib.js"></script>
<script language="JavaScript">
<!-- Begin
var simtime = 20 // defines how often robot simulation updated
var robot // define robot object
var active = false // by default not moving
var speeds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // store of values of speeds ... imitially -
var inBoxIds = ["robLeftNoObj", "robLeftLeft", "robLeftCloseLeft", "robLeftRight", "robLeftCloseRight", "robLeftBoth", "robRightNoObj", "robRightLeft", "robRightCloseLeft", "robRightRight", "robRightCloseRight", "robRightBoth"]
// names of boxes into which user types speeds
function checkKeySpecial() {
// keySpecial has value of a key thathas been pressed ... detect if it is special and act ,,
switch (keySpecial) {
case 68 : // D means focus on defining speeds ... initially left
case 100 : focusOn(0)
break
case 83 : // S 38 means set stop mode
case 115 :
checkStr()
setchecked(5)
break
case 65 : // A means set arena
case 97 :
checkStr()
setEnv(0)
deFocus()
break
case 90 : // Z means set maze
case 122 :
checkStr()
setEnv(1)
deFocus()
break
case 87 : // W 38 means toggle the revise Wire box
case 119 :
checkStr()
document.getElementById("LMBack").checked = !document.getElementById("LMBack").checked
deFocus()
break
default : checkKeyRest() // call general function which moves the robot if press IJKM etc...
}
keySpecial = 0 // have used keySpecial ... now set to 0 o dont do again.
}
function getState() {
// identofy state from sensors. Read distance of object from sensor ... 100% means just visible; 70% is closer
var sensClose = 70 // define what means close
if (robot.getSensor(2)<sensClose && robot.getSensor(0)<sensClose) actionNo = 6 // close to both
else if (robot.getSensor(2)<sensClose) actionNo = 5 // close to right
else if (robot.getSensor(2)<=100) actionNo = 4 // just visible on right
else if (robot.getSensor(0)<sensClose) actionNo = 3 // close to left
else if (robot.getSensor(0)<=100) actionNo = 2 // just visible on left
else actionNo = 1 // nothing seen
}
function moveTheRobot() {
checkStrings() // update speeds array from text boxes
checkKeySpecial() // first look for any keys the user has pressed
if (active) {
getState() // set actionNo with state as determined by sensors
lspeed = ( ( document.getElementById("LMBack").checked ) ? 1 : -1) * speeds[actionNo-1]
// set left speed *-1 if left motor not reversed
rspeed = speeds[actionNo+5] // set right speed
robot.robotDraw(false) // remove robot from current place
robot.moveRobot(lspeed, rspeed) // move it to new position based on speeds
redrawEnvironment(robot.ctx) // redraw environment behind it and then draw robot
}
}
function setRobotTimer() {
// set up the timer for animating the robot, and the function called every simtime intervals
setInterval(function(){moveTheRobot()},simtime);
}
function setchecked(sval) {
// when start/stop button pressed, toggle state and update caption on button to start or stop
active = !active
document.getElementById("StopCheck").value=(active ? "Parar" : "Começar");
}
function setEnv(which) {
// function called when user toggles the simple/maze box
document.getElementById("arenaCh").checked = (which == 0)
document.getElementById("mazeCh").checked = (which == 1)
var canvas = document.getElementById("myCanvasSYS");
if (which == 0) basicEnvironment(canvas.width, canvas.height)
else mazeEnvironment(canvas.width, canvas.height)
redrawEnvironment(robot.ctx)
}
function load() {
// load function - called when page loaded
active = false
window.defaultStatus="RJM's Simple Robot System";
checkBrowser()
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
robot = new aRobot(50, 20, 6, ctx) // define robot in arena
robot.defineSensors([2, 0, 2]) // sensors are wall finders with beams
oneRobot = true
document.getElementById("LMBack").checked=false // set check boxes for reverse left motor
addMouseDown (canvas) // allow mouse presses to reposition robot
addKeySpecial() // allow user to command using keys
setGrayBack() // grey background
setEnv(0)
handleResize(); // in case browser resized
setRobotTimer()
focusOn(0)
}
function handleResize(evt) {
// function to cope when browser resized
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100;
doResize(newWidth)
}
window.addEventListener('resize', handleResize);
// End -->
</script>
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()">
<div class="no-js">
<!-- Fallback content here -->
<h1>Desculpe-nos, mas você precisa ativar o JavaScript do seu navegador para ter acesso a este exercício.</h1>
</div>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="js">
<table width="90%" style="margin-left: 5%; margin-right: 5%; margin-top: 2%; margin-bottom: 2%">
<tr>
<!-- Lado esquerdo -->
<td width="40%" style="vertical-align: top;" class="ColapsarColuna">
<h1 id="w0">Labirinto/Siga as paredes</h1>
<p>Defina a velocidade dos motores do robô de acordo com a distância das paredes. A velocidade do robô são números inteiros. Quando quiser testar basta clicar em "Começar"</p>
<p>Macando as checkbox abaixo você pode alterar entre a arena com paredes ou o labirinto.</p>
<h2>Atividades</h2>
<p>Defina a velocidade dos 6 pares de comandos para que o robô seja capaz de seguir a parede.</p>
<p>Logo em seguida selecione a opção labirinto e construa a lógica para que o robô seja capaz de seguir uma parede e até chegar ao outro lado do labirinto.</p>
</td>
<!-- Lado direito -->
<td width="60%" style="padding-left: 3%; vertical-align: top;" class="ColapsarColuna">
<table width="100%">
<tr>
<td width="100%">
<div class="robot" width="100%">
<form name="controlsys" width="100%">
<canvas style="border-style: solid; border-width: medium; border-color: #38b54f;" id="myCanvasSYS" name="myCanvasSYS" width="756" height="300"></canvas>
<table width="100%">
<tr>
<td style="width: 50%;">
<p>Nenhuma parede detectada:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftNoObj" size="2" tabindex="1" value="0"> Motor direito<input type="text" id="robRightNoObj" size="2" tabindex="2" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Parede detectada à esquerda:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftLeft" size="2" tabindex="3" value="0"> Motor direito<input type="text" id="robRightLeft" size="2" tabindex="4" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Parede próxima à esquerda:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftCloseLeft" size="2" tabindex="5" value="0"> Motor direito<input type="text" id="robRightCloseLeft" size="2" tabindex="6" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Parede detectada à direita:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftRight" size="2" tabindex="7" value="0"> Motor direito<input type="text" id="robRightRight" size="2" tabindex="8" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Parede próxima à direita:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftCloseRight" size="2" tabindex="9" value="0"> Motor direito<input type="text" id="robRightCloseRight" size="2" tabindex="10" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Parede detectada em ambos os lados:</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftBoth" size="2" tabindex="11" value="0"> Motor direito<input type="text" id="robRightBoth" size="2" tabindex="12" value="0"></p>
</td>
</tr>
</table>
<p>Inverter motor esquerdo<input type="checkbox" id="LMBack"></p>
<p>Arena fechada<input type="checkbox" id="arenaCh" checked="checked" onchange="setEnv(0)">; Labirinto<input type="checkbox" id="mazeCh" onchange="setEnv(1)"> </p>
<p><input type="button" id="StopCheck" value="Começar" onclick="setchecked();"></p>
</form>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></p>
</div>
<style>
.ColapsarColuna{
display: table-cell;
}
@media only screen and (max-width: 900px){
td.ColapsarColuna{
display: block;
width: 96%;
margin-left: 2%;
margin-right: 2%;
}
}
</style>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/entrevista2.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0, ">
<title>Mês das Mulheres #2</title>
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<body>
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php"?>
</header>
<!-- ********* Titulo ********* -->
<section class="titulo">
<!-- espaco -->
<div style="position: relative; height:5vw"></div>
<h1 class="linhaTitUm">Entrevista<br>com<br><span style="color: #38b54f; font-family: Coolvetica;"><NAME>
</span></h1>
<!-- espaco -->
<div style="position: relative; height: 4vw"></div>
</section>
<!-- ********* Video ********* -->
<section class="video" id="video">
<!-- Espacamento antes do titulo -->
<div style="position: relative; height: 8vw"></div>
<img src="Imagens/GiuliaFricke.png" alt="Giulia" class="imagemMulher">
<!-- espaco no fim do BG -->
<div style="height: 2vw"></div>
</section>
<!-- ********* texto sobre ********* -->
<section class="bgTexto">
<!-- espaco -->
<div style="height: 1vw"></div>
<p class="textop"> Para comemorar o mês das mulheres (pq só um dia é muito pouco) o Br.ino preparou uma série de postagens e entrevistas sobre mulheres que lutam contra os estereótipos e conquistam seu espaço na área da tecnologia.
Para nossa segunda entrevista, convidamos alguém que nos inspirou a começar o projeto, alguém de dentro. Além disso, o dia das mulheres foi também aniversário dela!! Nossa Diretora de Operações:<br>
<b><NAME></b>
é estudante de Engenharia Aeroespacial na Universidade de Brasília. Diretora de Operações na empresa Br.ino. Deu seus primeiros passos com a plataforma Arduino em 2014, e desde 2015, após a primeira participação na olimpíada de robótica, evento o qual obteve medalhas em dois anos consecutivos, tem ministrado oficinas, workshops e palestras em eventos tecnológicos junto aos outros integrantes da empresa.</p><br><br><br><br>
<h3 class="tituloMenor">Leia a entrevista:</h3><br><br>
<p class="textop"><b>1 - Como você começou no mundo da eletrônica? Com quantos anos?</b><br>
"Quando entrei no ensino médio, com 14 anos, vi que alguns amigos meus participavam de competições de robótica. A partir daí comecei a ir em reuniões para saber como era e para matar um pouco da curiosidade. Acabei me apaixonando pela eletrônica e pela idéia de construir algo você mesmo e controlá-lo, porém, tinha um pequeno problema, eu não sabia absolutamente nada de inglês técnico, ou seja, programação era um monstro de 7 cabeças pra mim, contudo o Br.ino me “salvou”, quando vi que existia a possibilidade de programar em português me joguei de cabeça no mundo da T.I, e hoje , já consigo programar tanto em português como em inglês, graças a ferramenta."<br>
<br>
<b>2 - O que te motivou / motiva a entrar nesse mundo tecnológico?</b><br>
"Quando eu nasci , o que não faz tanto tempo, só existiam celulares que enviavam SMS e faziam ligações. Hoje em dia, não se consegue descrever todas as funções desse aparelho eletrônico. O que quero dizer com isso é que o mundo está em constante mudança, e ter a possibilidade de contribuir com essa mudança me faz querer continuar nesse nicho tecnológico, afinal não quero fazer parte da platéia, quero ajudar com o conhecimento que ainda vou obter para contribuir positivamente com o futuro."<br><br>
<b>3 - Acha que as mulheres estão conseguindo seu espaço nesse mercado?</b><br>
"Aos poucos, mas sim. Quando entrei na faculdade de Engenharia , só haviam 10 mulheres entre 150 alunos. Hoje em dia, nas turmas de calouros , esse número já aumentou. Em eventos como a Campus Party, mulheres estão ministrando palestras, workshops, stands e indo em competições. Mesmo que ainda seja muito inferior comparado ao número de homens nos casos acima, a mulher vem demonstrando ser corajosa o bastante para quebrar os paradigmas impostos nela, o que me faz ter orgulho de fazer parte desse time."
<br><br>
<b>4 - Hoje em dia , acha que valeu a pena investir sua educação nessa área?</b><br>
"Com toda certeza. Sem a robótica , sem o Br.ino me mostrando que programação não é nada de outro mundo, não teria desenvolvido e me interessado pela área de exatas da forma que me interessei, sem a didática da robótica, não teria aprendido “brincando” e com certeza seria um estudo repetitivo. Hoje em dia, agradeço pelos meus amigos quando me acolheram na equipe de competição e por terem me ensinado tudo que sei de eletrônica. Se hoje estou cursando Engenharia, é graças à robótica e ao Br.ino , os quais me introduziram nesse mundo."<br><br>
<b>5 - Como lidou (caso tenha acontecido) com o preconceito de gênero no seu curso?</b><br>
"Até hoje, não recebi nenhum tipo de preconceito por conta do meu gênero, o máximo foi : “Nossa, é uma das únicas meninas na sala.” Desde o ínicio sempre recebi o apoio da minha família e dos meus professores, o que fez a diferença na hora de decidir se continuaria ou não na robótica. Contudo, mesmo se não tivesse esse apoio que comentei, teria escolhido a área, acho que o ditado “faça o que ama e não terá de trabalhar nenhum dia sequer” se encaixa bem, se você é apaixonado por alguma profissão, pula de cabeça, só você arcará com as consequências dessa decisão."<br><br>
Fique ligado pra ver mais exemplos de mulheres que manjam muito de tecnologia!!</p>
<p class='textop'>Confira também a nossa primeira entrevista com <a href="entrevista1" style="text-decoration=none;color:#38b54f;"><NAME></a>!</p>
<!-- espaco -->
<div style="height: 9vw"></div>
</section>
</body>
<style>
body{
margin:0px;
padding:0px;
}
.imagemMulher{
width: 30%;
margin-left: 35%;
}
.espaco{
width: 4%;
}
.titulo{
background-position: 50% 50%;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-image: url("Imagens/BG/Computador.jpg");
}
.tituloMenor{
color: #000;
margin-left: 20%;
}
h1.linhaTitUm{
font-size: 6em;
line-height: 0.9em;
font-weight: 400;
color: #ffffff;
position: relative;
left: 30%;
width: 70%;
font-family: Coolvetica;
}
@media screen and (max-width: 500px) {
img.imagemMulher{
width: 50%;
margin-left: 25%;
}
h1.linhaTitUm{
text-align: center;
font-size: 5em;
left: 0;
width: 100%;
}
h3.tituloMenor{
text-align: center;
margin-left: 0;
}
}
.linhaTitDois{
font-size: 80px;
color: #ffffff;
position: relative;
left: 30%;
width:20%;
}
.video{
background-color: #efefef;
}
.bgTexto{
background-color: #efefef;
}
.textoSob{
width: 100%;
}
.textop{
margin-left: 25%;
margin-right: 25%;
color: #000;
text-align: justify;
}
@media screen and (max-width: 500px) {
p.textop{
margin-left: 15%;
margin-right: 15%;
text-align: center;
}
p.submvvVal{
text-align: center;
}
p.submvv{
text-align: center;
}
h1.titVideo{
font-size: 3em;
margin-left: 0;
text-align: center;
}
}
.bgContato{
background-color: #f2f2f2;
}
@media screen and (max-width: 800px) {
p.linhaVendasUm{
font-size: 15vw;
text-align: center;
left: 0%;
right: 900px;
}
p.linhaVendasDois{
font-size: 13vw;
text-align: center;
left: 0%;
}
}
@font-face {
font-family: Coolvetica;
src: url(Coolvetica.ttf);
}
@font-face {
font-family: Lato;
src: url(Lato.ttf);
}
h1, h2, h3, h4{
font-family: Coolvetica;
font-size: 3em;
}
p, input, li, textarea, ol, spam, table, th, tr, header{
font-family: Lato;
font-size: 1em;
}
</style>
<!-- ********* rodapeh ********* -->
<footer align="left">
<?php include "rodape.php" ?>
</footer>
<!-- fim do rodapeh -->
<meta name="description" content="Conheça o software que visa a democratização da robótica e do movimento maker diminuindo as barreiras para o aprendizado!!!">
</html>
<file_sep>/brino/rastrear.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0">
<!-- <meta media screen and (min-width: 640px) and (max-width: 1920) {
@viewport { width: 1280px; }> -->
<title>Br.ino - Rastreio</title>
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<body>
<?php include_once("../analyticstracking.php") ?>
Rastreio
</body>
</html>
<file_sep>/RequerimentoDeMatricula.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>matricula</title>
</head>
<meta http-equiv="refresh" content=1;url="https://docs.google.com/forms/d/e/1FAIpQLSc-1AmXREpG9O9TSJKVLOt_In4dQTWGP5KwxMkuBy3agXfyeQ/viewform?usp=sf_link">
<body>
</body>
</html>
<file_sep>/jogos/ReagindoALuz.php
<html class=" js">
<head>
<title>Br.ino - Reagindo a luz</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Language" content="pt-br">
<script type="text/javascript" src="ReagindoALuz_arquivos/RobotLib.js"></script>
<script type="text/javascript" src="ReagindoALuz_arquivos/RobotKeyLib.js"></script>
<script language="JavaScript">
<!-- Begin
var simtime = 20 // defines how often robot simulation updated
var robot // define robot object
var active = false // by default not moving
var speeds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // copies of speeds - set to zero
var inBoxIds = ["robLeftNoObj", "robLeftLeft", "robLeftCloseLeft", "robLeftRight", "robLeftCloseRight", "robRightNoObj", "robRightLeft", "robRightCloseLeft", "robRightRight", "robRightCloseRight"]
// names of boxes used for inputting speeds
function checkKeySpecial() {
// keySpecial has value of a key that has been pressed ... detect if it is special and act ,,
switch (keySpecial) {
case 68 : // D means focus on defining speeds ... initially left
case 100 : focusOn(0)
break
case 83 : // S 38 means set stop mode
case 115 :
checkStr()
setchecked()
break
case 80 :
case 112 : checkStr()
initialPos()
break
case 66 : // E 38 means toggle environment Wire box
case 98 :
checkStr()
document.getElementById("Beam").checked = !document.getElementById("Beam").checked
checkBeam()
deFocus()
break
case 87 : // W 38 means toggle the revise Wire box
case 119 :
checkStr()
document.getElementById("LMBack").checked = !document.getElementById("LMBack").checked
deFocus()
break
default : checkKeyRest() // call general function which moves the robot if press IJKM etc...
}
keySpecial = 0 // have used keySpecial ... now set to 0 o dont do again.
}
function getState() {
// set actionNo with state of robot - based on sensors
// getSensor(n) gets sensor .... as % of range
var sensClose = 30 // define what means by close
var sensFar = 100 // far ... just detectable
if (robot.getSensor(2)<sensClose) actionNo = 5 // far away on right
else if (robot.getSensor(2)<=sensFar) actionNo = 4 // closer on right
else if (robot.getSensor(0)<sensClose) actionNo = 3 // and on left
else if (robot.getSensor(0)<=sensFar) actionNo = 2
else actionNo = 1 // nothing seen
}
function moveTheRobot() {
checkStrings() // update speeds array from text boxes
checkKeySpecial() // first look for any keys the user has pressed
if (active) {
getState() // identify state from sensors ... sets actionNo
// load up speeds (noting if left motor is wired backwards) for this actionNo
lspeed = ( ( document.getElementById("LMBack").checked ) ? 1 : -1) * speeds[actionNo-1]
rspeed = speeds[actionNo+4]
if (robot.stuck == false) {
robot.robotDraw(false) // clear robot
robot.moveRobot(lspeed, rspeed) // move it
redrawEnvironment(robot.ctx) // draw environment back and robot
}
}
}
function setRobotTimer() {
// set up the timer for animating the robot, and the function called every simtime intervals
setInterval(function(){moveTheRobot()},simtime);
}
function setchecked() {
// when start/stop button pressed, toggle state and update caption on button
active = !active
document.getElementById("StopCheck").value="Aperte para "+(active ? "parar" : "começar");
}
function initialPos() {
// put robot back in its initial position
robot.robotDraw(false) // undraw from current
robot.robotx = 70 // set position and angle
robot.roboty = 60
robot.angle = 0
redrawEnvironment(robot.ctx) // draw environment and robot
robot.stuck = false // unstuck it
}
function checkBeam() {
// user has toggled narrow/wide beam option
var smode = (document.getElementById("Beam").checked) ? 4 : 3 // sensor type is 4 or 3 for wide/narrow
var activewas = active
active = false // stop robot
robot.robotDraw(false) // undraw it
robot.defineSensors([smode, 0, smode]) // set so has beams
redrawEnvironment(robot.ctx) // draw environment and robot
active = activewas // reset active status as it was
}
function load() {
// load function - called when page loaded
active = false
window.defaultStatus="RJM's Simple Robot System";
checkBrowser()
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
document.getElementById("LMBack").checked=false // set checkboxes ... no reverse left motor
document.getElementById("Beam").checked=false // narrwo beam
setGrayBack()
addKeySpecial() // ensure user can press keys
addMouseDown(canvas) // and respond to mouse
robot = new aRobot(70, 60, 12, ctx) // define robot
robot.defineSensors([3, 0, 3]) // with left/right light beams
oneRobot = true // tell library that there is a robot
numLights = 2 // define two lights
lights[0] = new aLight(400, 110, 10, ctx, 0, "red")
lights[1] = new aLight(190, 190, 15, ctx, 1, "red")
handleResize(); // in case browser resized
setRobotTimer() // set simulation timer
focusOn(0)
}
function handleResize(evt) {
// function to cope when browser resized
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100; // adapt camvas width with browser
doResize(newWidth)
}
window.addEventListener('resize', handleResize);
// End -->
</script>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()" style="margin: 0;">
<!-- *************** Rastreador google *************** -->
<?php include_once("../analyticstracking.php") ?>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="no-js">
<!-- Fallback content here -->
<h1>Sentimos muito, mas é preciso usar um navegador com Javascript disponível para acessar esse simulador.</h1>
</div>
<div class="js">
<table style="width: 90%; margin-left: 5%;">
<tr>
<td width="40%" style="vertical-align: top; padding-right: 5%;" class="ColapsarColuna">
<h1>Alcançando a luz</h1>
<p>No campo existem dois pontos de luz que o robô pode detectar com seus dois sensores.
Cabe a você definir as velocidades de cada moto, usando números inteiros, para cada caso.
</p>
<p>Clique em qualquer ponto da arena para reposicionar o robô. Também existem as opções para mudar a área de leitura dos sensores e inverter um dos motores<br></p>
<h2>Atalhos</h2>
<ul>
<li>S => Começar/Parar</li>
<li>P => Voltar a página inicial</li>
<li>W => Inverter motor esquerdo</li>
<li>B => Mudar sensor</li>
<li>D => Definir velocidade (tab para passar para o próximo)</li>
<li>I, J, K, M => Mover o robô </li>
</ul>
<br>
<h2>Atividade</h2>
<p>Defina a velocidade dos motores para cada um dos estados para que o robô chegue na luz.</p>
<p>Mude o tipo de sensor - O resultado fica melhor ou pior?</p>
<p>Tente fazer com que o robô se aproxime da luz e se afaste quando chegar muito perto.</p>
</td>
<td width="60%" style="vertical-align: top;" class="ColapsarColuna">
<br>
<div class="robot">
<form name="controlsys">
<canvas id="myCanvasSYS" name="myCanvasSYS" width="766" height="300"></canvas>
<table width="100%">
<tr>
<td width="50%">
<p>Quando nenhuma luz é detectada:</p>
</td>
<td width="50%">
<p>Motor esquerdo<input type="text" id="robLeftNoObj" size="2" tabindex="1" value="0">Motor direito<input type="text" id="robRightNoObj" size="2" tabindex="2" value="0"></p>
</td>
</tr>
<tr>
<td width="50%">
<p>Quando a luz é vista a esquerda:</p>
</td>
<td width="50%">
<p>Motor esquerdo<input type="text" id="robLeftLeft" size="2" tabindex="3" value="0">Motor direito<input type="text" id="robRightLeft" size="2" tabindex="4" value="0"></p>
</td>
</tr>
<tr>
<td width="50%">
<p>Quando a luz está próxima a esquerda:</p>
</td>
<td width="50%">
<p>Motor esquerdo<input type="text" id="robLeftCloseLeft" size="2" tabindex="5" value="0">Motor direito<input type="text" id="robRightCloseLeft" size="2" tabindex="6" value="0"></p>
</td>
</tr>
<tr>
<td width="50%">
<p>Quando a luz é vista a direita:</p>
</td>
<td width="50%">
<p>Motor esquerdo<input type="text" id="robLeftRight" size="2" tabindex="7" value="0">Motor direito<input type="text" id="robRightRight" size="2" tabindex="8" value="0"></p>
</td>
</tr>
<tr>
<td width="50%">
<p>Quando a luz está próxima a direita:</p>
</td>
<td width="50%">
<p>Motor esquerdo<input type="text" id="robLeftCloseRight" size="2" tabindex="9" value="0">Motor direito<input type="text" id="robRightCloseRight" size="2" tabindex="10" value="0"></p>
</td>
</tr>
</table>
<p>Mudar o sensor <input type="checkbox" id="Beam" onchange="checkBeam()"></p>
<p>Inverter o motor esquerdo<input type="checkbox" id="LMBack" tabindex="11"></p>
<p><input type="button" id="StopCheck" value="Começar" onclick="setchecked();"></p>
<p><input type="button" id="startAgain" value="Voltar para posição inicial" onclick="initialPos();"></p>
</form>
</div>
<div style="clear: both;"></div>
</td>
</tr>
</table>
<p> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></p>
</div>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
</body>
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
.ColapsarColuna{
display: table-cell;
}
@media only screen and (max-width: 900px){
td.ColapsarColuna{
display: block;
width: 96%;
padding-right: 2%;
padding-left: 2%;
}
}
</style>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/brino/versao.php
<?php
echo "3.0.5";
?><file_sep>/jogos/SeguirOBjeto.php
<html class=" js">
<head>
<title> Br.ino - <NAME> </title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
html.js .no-js, html .js { display: none }
html.js .js { display: block }
</style>
<script type="text/javascript"> document.documentElement.className += " js"</script>
<meta charset="utf-8">
<script type="text/javascript" src="SeguirOBjeto_arquivos/RobotLib.js"></script>
<script type="text/javascript" src="SeguirOBjeto_arquivos/RobotKeyLib.js"></script>
<script language="JavaScript">
<!-- Begin
var simtime = 20
var robot
var active = false
var speeds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
var inBoxIds = ["robLeftNoObj", "robLeftLeft", "robLeftCloseLeft", "robLeftRight", "robLeftCloseRight", "robRightNoObj", "robRightLeft", "robRightCloseLeft", "robRightRight", "robRightCloseRight", "objectSpeed"]
var lightAngle = 0, lightxbase = 400
// function to draw environment
function speckeyRobotMove(dx, dy) {
// key robot move and unstuck robot
keyRobotMove(dx, dy)
robot.stuck = false
}
function checkKeySpecial() {
// keySpecial has value of a key thathas been pressed ... detect if it is special and act ,,
switch (keySpecial) {
case 68 : // D means focus on defining speeds ... initially left
case 100 : focusOn(0)
break
case 79 : // D means focus on defining speeds ... initially left
case 111 : focusOn(10)
break
case 83 : // S 38 means set stop mode
case 115 :
checkStr()
setchecked()
break
case 80 :
case 112 : checkStr()
initialPos()
break
case 66 : // E 38 means toggle environment Wire box
case 98 :
checkStr()
document.getElementById("Beam").checked = !document.getElementById("Beam").checked
checkBeam()
deFocus()
break
case 87 : // W 38 means toggle the revise Wire box
case 119 :
checkStr()
document.getElementById("LMBack").checked = !document.getElementById("LMBack").checked
deFocus()
break
default : checkKeyRest()
}
keySpecial = 0 // have used keySpecial ... now set to 0 o dont do again.
}
function getState() {
var sensClose = 70 // robot.robotsz*2
var sensFar = 80
if (robot.getSensor(2)<sensClose) actionNo = 5
else if (robot.getSensor(2)<=sensFar) actionNo = 4
else if (robot.getSensor(0)<sensClose) actionNo = 3
else if (robot.getSensor(0)<=sensFar) actionNo = 2
else actionNo = 1
}
function setLightPosition () {
lights[0].lightx = lightxbase + 100*Math.cos(lightAngle)
lights[0].lighty = 150 + 30*Math.sin(lightAngle)
}
function moveTheRobot() {
checkStrings()
checkKeySpecial()
if (active) {
getState()
lspeed = ( ( document.getElementById("LMBack").checked ) ? 1 : -1) * speeds[actionNo-1]
rspeed = speeds[actionNo+4]
lights[0].lightDraw(false)
lightAngle = lightAngle + speeds[10]*Math.PI/400
if (lightAngle >= 2 * Math.PI) lightAngle -= 2*Math.PI
setLightPosition()
if (robot.stuck & distance(robot.robotx, robot.roboty, lights[0].lightx, lights[0].lighty) < lights[0].lightsz)
robot.robotDraw(false) // undraw robot if stuck because close to light
lights[0].lightDraw(true)
if (robot.stuck == false) {
robot.robotDraw(false)
robot.moveRobot(lspeed, rspeed)
redrawEnvironment(robot.ctx)
}
}
}
function setRobotTimer() {
setInterval(function(){moveTheRobot()},simtime);
}
function setchecked() {
active = !active
document.getElementById("StopCheck").value=(active ? "Parar" : "Começar");
}
function load() {
active = false
window.defaultStatus="RJM's Simple Robot System";
var canvas = document.getElementById("myCanvasSYS");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", doMousedown, false); // define mouse functions
document.getElementById("LMBack").checked=false
document.getElementById("Beam").checked=false
setGrayBack()
addKeySpecial()
addMouseDown(canvas)
robot = new aRobot(70, 150, 12, ctx) // define robot
robot.defineSensors([3, 0, 3]) // so has left right distance sensors
oneRobot = true // tell library that has robot
numLights = 1 // define light to track
lights[0] = new aLight(400, 110, 40, ctx, 0, "red")
setLightPosition()
handleResize();
setRobotTimer()
focusOn(0)
}
function handleResize(evt) {
var robotWrapper = document.getElementsByClassName("robot")[0];
var newWidth = robotWrapper.clientWidth - 100;
lightxbase = newWidth-250
doResize(newWidth)
}
window.addEventListener('resize', handleResize);
function checkBeam() {
var smode = (document.getElementById("Beam").checked) ? 4 : 3
var activewas = active
active = false
robot.robotDraw(false)
robot.defineSensors([smode, 0, smode]) /// so has forward sensor only
robot.robotDraw(true)
redrawEnvironment(robot.ctx)
active = activewas
}
function initialPos() {
robot.robotDraw(false)
robot.robotx = 70
robot.roboty = 150
robot.angle = 0
robot.stuck = false
redrawEnvironment(robot.ctx)
}
// End -->
</script>
<style>
@font-face {
font-family: Coolvetica;
src: url("../Fontes/Coolvetica.ttf");
font-display: swap;
}
@font-face {
font-family: Lato;
src: url("../Fontes/Lato.ttf");
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
color: #38b54f;
}
p,div input, li, ol, spam, table, th, tr, header{
font-family: Lato;
}
body{
margin:0px;
padding:0px;
}
</style>
</head>
<!-- STEP TWO: Add the relevant event handlers to the BODY tag -->
<body onload="load()">
<div class="no-js">
<!-- Fallback content here -->
<h1>Desculpe-nos, mas você precisa ativar o JavaScript do seu navegador para ter acesso a este exercício.</h1>
</div>
<!-- *************** Cabeçalho *************** -->
<header class="module parallax parallax-header">
<?php include "../cabecalho.php" ?>
</header>
<div class="js">
<table width="90%" style="margin-left: 5%; margin-right: 5%; margin-top: 2%; margin-bottom: 2%">
<tr>
<!-- Lado esquerdo -->
<td width="40%" style="vertical-align: top;" class="ColapsarColuna">
<h1>Seguir Objeto</h1>
<p>Na arena há um objeto que deve ser seguido pelo robô (mantendo uma distância constante) sem que eles se encostem.<br>A velocidade dos motores deve ser definida como um valores inteiros entre -40 e 40. É possível também alterar a velocidade do objeto a ser seguido.</p>
<h2>Atividade</h2>
<p>Defina a velocidade dos motores para que ele siga o objeto na velocidade 2 sem que eles se encostem. Após isso altere a velocidade do objeto e verifique se estes ainda não se tocam.</p>
<!-- Lado direito -->
<td width="60%" style="padding-left: 3%; vertical-align: top;" class="ColapsarColuna">
<table width="100%">
<tr>
<td width="100%">
<div class="robot" width="100%">
<form name="controlsys" width="100%">
<canvas id="myCanvasSYS" name="myCanvasSYS" width="766" height="300"></canvas>
<table width="100%">
<tr>
<td style="width: 50%;">
<p>Objeto não detectado :</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftNoObj" size="2" tabindex="1" value="0"> Motor direito<input type="text" id="robRightNoObj" size="2" tabindex="2" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Objeto distante à esquerda :</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftLeft" size="2" tabindex="3" value="0"> Motor direito<input type="text" id="robRightLeft" size="2" tabindex="4" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Objeto próximo à esquerda :</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftCloseLeft" size="2" tabindex="5" value="0"> Motor direito<input type="text" id="robRightCloseLeft" size="2" tabindex="6" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Objeto distante à direita :</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftRight" size="2" tabindex="7" value="0"> Motor direito<input type="text" id="robRightRight" size="2" tabindex="8" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Objeto próximo à direita :</p>
</td>
<td style="width: 50%; text-align: right;">
<p>Motor esquerdo<input type="text" id="robLeftCloseRight" size="2" tabindex="9" value="0"> Motor direito<input type="text" id="robRightCloseRight" size="2" tabindex="10" value="0"></p>
</td>
</tr>
<tr>
<td style="width: 50%;">
<p>Sensores mais largos <input type="checkbox" id="Beam" onchange="checkBeam()"> </p>
</td>
<td style="width: 50%; text-align: right;">
<p>Inverter motor esquerdo<input type="checkbox" id="LMBack" tabindex="11"></p>
<p>Velocidade do objeto<input type="text" id="objectSpeed" size="2" tabindex="12" value="2"></p>
</td>
</tr>
</table>
<p><input type="button" id="StopCheck" value="Começar" onclick="setchecked();"></p>
<p><input type="button" id="startAgain" value="Reposicionar" onclick="initialPos();"></p>
<p id="p1"></p>
</form>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p> Jogo original criado por: <a href="https://www.reading.ac.uk/computer-science/staff/professor-richard-mitchell">Prof <NAME>.</a></p>
</div>
<style>
.ColapsarColuna{
display: table-cell;
}
@media only screen and (max-width: 900px){
td.ColapsarColuna{
display: block;
width: 96%;
margin-left: 2%;
margin-right: 2%;
}
}
</style>
<!-- Alerta -->
<script LANGUAGE='JavaScript'>
window.alert('Você está acessando um jogo Br.ino, ele não possui compatibilidade total com dispositivos móveis');
</script>
</body>
<!-- ********* Rodapeh ********* -->
<footer>
<?php include "../rodape.php" ?>
</footer>
<!-- Fim do rodapeh -->
</html><file_sep>/dicionario.php
<!DOCTYPE html>
<!-- NUMERO ATUAL: 222 -->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=1.0">
<title>Br.ino - Dicionário</title>
<meta charset="utf-8">
</head>
<!-- Começo do corpo -->
<body onload="altura()" onresize="altura()" style="background-color: #efefef; margin: 0;">
<?php include_once("analyticstracking.php") ?>
<header class="module parallax parallax-header">
<?php include "cabecalho.php"?>
</header>
<!-- ********* COMECO DICIONARIO ********* -->
<script>
function mudar(nome) {
var x = document.getElementById(nome);
if (x.style.display === "none") x.style.display = "block";
else x.style.display = "none";
}
</script>
<!-- --------------- ALEATORIO --------------- -->
<h2 class="tituloH2">Aleatório:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(110)"><li><code><b>geradorAleatorio(<entrada>) </b> (randomSeed(<entrada>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="110" style="display: none"><p class="balao"> - Essa função inicia o gerador de números pseudo-aleatórios, fazendo-o começar a contagem a partir de um valor arbitrário. Essa sequência, embora muito longa e aleatória, é sempre a mesma.<br>
Se a sequência de números gerados pela função <b>numeroAleatorio()</b> precisa ser diferente em execuções consecutivas do código, utilize entradas razoavelmente aleatórias, como a função <b>lerAnalogico()</b> em um pino desconectado, como parâmetro do gerardor.<br>
Entretanto, caso seja útil estabelecer sequências pseudo-aleatórias que se repetem com exatidão, é possível utilizar a função <b>geradorAleatorio()</b> com uma constante como parâmetro.<br>
<br><b> Ex.:</b> <br>
  numeroLongo numeroAleat;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   geradorAleatorio(lerAnalogico(0));<br>
  }<br>
<br>
  principal() {<br>
   numeroAleat = numeroAleatorio(300);<br>
    USB.enviar(numeroAleat);<br>
    USB.enviar("\n");<br>
    esperar(50);<br>
   }<br>
<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(111)"><li><code><b>numeroAleatorio(<máximo>) </b> (random(<máximo>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="111" style="display: none"><p class="balao"> - Essa função retorna um valor pseudo-aleatório. É possível utilizar esse comando passando dois parâmetros de execução, o valor mínimo(incluído no intervalo aleatório) e o valor máximo(excluído do intervalo) a ser gerado pela função.<br>
<br><b> Ex.:</b> <br>
  numeroLongo numeroAleat;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   geradorAleatorio(lerAnalogico(0));<br>
  }<br>
<br>
  principal() {<br>
   numeroAleat = numeroAleatorio(300);<br>
    USB.enviar(numeroAleat);<br>
    USB.enviar("\n");<br>
    esperar(50);<br>
   }<br>
<br>
</p></div>
<!-- --------------- ARQUIVO --------------- -->
<!--
<h2 class="tituloH2">Arquivo:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(41)"><li><code><b>SD.abrir(<arquivo>) </b> (SD.open(<arquivo>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="41" style="display: none"><p class="balao">
 Abre o arquivo no cartão SD. Se o arquivo selecionado ainda não existir e ele for aberto no modo de escrita, o arquivo será criado.<br>
<br><b> Sintaxe:</b><br>
  SD.abrir(arquivo);<br>
  SD.abrir(arquivo, modo);<br>
<br>
  -arquivo: Usado para indicar qual o arquivo que deve ser aberto. O nome pode conter o caminho para o arquivo caso ele esteja dentro de uma pasta (para isso é usada a barra '/').<br>
  -modo (opicional): Usado para selecionar qual modo de abertura do arquivo, podendo ser <br>
<br><b> Ex.:</b><br>
  arquivo.abrir();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(41)"><li><code><b>Arquivo <arquivo> </b> (File <arquivo>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="41" style="display: none"><p class="balao">
 Abre o arquivo selecionado pelo usuário.<br>
<br><b> Ex.:</b><br>
  arquivo.abrir();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(46)"><li><code><b>ArquivoGravar(<dado>) </b> (file.write(<dado>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="46" style="display: none"><p class="balao">
 Abre o arquivo no modo de leitura e escrita com o cursor no final do arquivo.<br>
<br><b> Sintaxe:</b><br>
  ArquivoGravar(dados);<br>
  ArquivoGravar(buf, tamanho);<br>
<br>
  -arquivo: uma instância da classe arquivo (retornada por abrir arquivo())<br>
  -dados: byte, letra ou Palavra (letra *) para escrever<br>
  -buf: uma série de caracteres ou bytes<br>
  -tamanho: o número de elementos em buffer<br>
<br><b> Ex.:</b><br>
  arquivoDocumento = SD.abrir(“teste.txt”, ArquivoGravar);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(42)"><li><code><b>criarPasta("diretorio1/diretorio2/….") </b> (SD.mkdir)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="42" style="display: none"><p class="balao">
 Cria um ou mais diretórios no cartão SD. Precisa de um parâmetro que é a pasta, ou diretório da pasta, a ser criada.<br>
<br><b> Sintaxe:</b><br>
  criarPasta(“nomeDoArquivo”);<br>
<br><b> Ex.:</b><br>
  criarPasta(“Arduino”);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(44)"><li><code><b>existe(<nomeDoArquivo>) </b> (exists(<nomeDoArquivo>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="44" style="display: none"><p class="balao"> - Testa se determinado diretório ou arquivo existe. Necessita de um argumento, que é o arquivo que se procura ou o diretório. Aceita percorrer mais de uma pasta por vez.<br>
<br><b> Sintaxe:</b><br>
  existe(nomedoarquivo);<br>
<br><b> Ex.:</b><br>
   existe(PastaRaiz/PastaProcurada/Arquivo.png);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(45)"><li><code><b>fechar(<nomeDoArquivo>) </b> (file.close(<nomeDoArquivo>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="45" style="display: none"><p class="balao">
 Utilizado para fechar uma pasta ou diretório e assegurar que os dados foram corretamente escritos no cartão SD. Utiliza um parâmetro (diretorio) que indica o arquivo que será fechado.<br>
<br><b> Sintaxe:</b><br>
  fechar(nomedoarquivo);<br>
<br><b> Ex.:</b><br>
  fechar(PiscarLED);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(47)"><li><code><b>gravar(<dados>) </b> (print(<dados>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="47" style="display: none"><p class="balao">
 Grava dados no arquivo, que deve estar aberto para edição. Grava números como uma sequência de dígitos, cada um como um caractereda tabela ASCII (por exemplo, o número 123 é enviado como três caracteres ‘1’, ‘2’, ‘3’). <br>
<br><b> Ex.:</b><br>
  gravar(548);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(43)"><li><code><b>removerPasta(diretorio) </b> (SD.rmdir(diretorio))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="43" style="display: none"><p class="balao">
 Remove um ou mais diretórios no cartão SD. Precisa de um parâmetro que é a pasta, ou diretório da pastas, a ser removida.<br>
<br><b> Sintaxe:</b><br>
  removerPasta(nomedoarquivo);<br>
<br><b> Ex.:</b><br>
  removerPasta(PiscarLED);<br>
</p></div>
-->
<!-- --------------- COMPARADORES --------------- -->
<h2 class="tituloH2">Comparadores:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(81)"><li><code><b>== </b> </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="81" style="display: none"><p class="balao">
 Igual a.<br>
<br><b> Ex.:</b><br>
  se(x==y){<br>
   //...<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(82)"><li><code><b><</b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="82" style="display: none"><p class="balao">
 Menor que.<br>
<br><b> Ex.:</b><br>
  enquanto(x<10){<br>
   //...<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(83)"><li><code><b><=</b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="83" style="display: none"><p class="balao">
 Menor que ou igual.<br>
<br><b> Ex.:</b><br>
  enquanto(x<=10){<br>
   //...<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(84)"><li><code><b>></b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="84" style="display: none"><p class="balao">
 Maior que.<br>
<br><b> Ex.:</b><br>
  se(x>y){<br>
   //...<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(85)"><li><code><b>>=</b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="85" style="display: none"><p class="balao">
 Maior que ou igual.<br>
<br><b> Ex.:</b><br>
  faca{<br>
   //...<br>
  }<br>
  enquanto(x>=y)<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(86)"><li><code><b>!= </b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="86" style="display: none"><p class="balao">
 Diferente de.<br>
<br><b> Ex.:</b><br>
  faca{<br>
   //...<br>
  }<br>
  enquanto(x!=y)<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(87)"><li><code><b><expressão booleana> e <expressão booleana></b> (<expressão booleana> && <expressão booleana>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="87" style="display: none"><p class="balao">
 É um operador lógico e resulta em “Verdadeiro” se ambas as condições de entrada serem verdadeiras. Se uma ou as duas forem “Falso” ela irá retornar “Falso”.<br>
<br><b> Ex.:</b><br>
  numero botao = 9;<br>
  numero botao2 = 10;<br>
<br>
  configuracao() {<br>
   definirModo(botao, SAIDA);<br>
   definirModo(botao2, SAIDA);<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   se((lerDigital(botao)==LIGADO) e (lerDigital(botao2)==LIGADO){<br>
    USB.enviarln(“Dois botoes pressionados”);<br>
    esperar(500);<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(88)"><li><code><b><expressão booleana> ou <expressão booleana> </b>(<expressão booleana> || <expressão booleana>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="88" style="display: none"><p class="balao"> É um operador lógico e retorna “Verdadeiro” se um ou os dois dos valores de entrada forem verdadeiros. Ele retorna “Falso” se ambos resultados recebidos forem falsos.<br>
<br><b> Ex.:</b><br>
  numero botao = 9;<br>
  numero botao2 = 10;<br>
<br>
  configuracao() {<br>
   definirModo(botao, SAIDA);<br>
   definirModo(botao2, SAIDA);<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   se((lerDigital(botao)==LIGADO) ou (lerDigital(botao2)==LIGADO){<br>
    USB.enviarln(“Pelo menos um botao pressionado”);<br>
    esperar(500);<br>
   }<br>
  }<br>
</p></div>
<!-- --------------- FUNCOES --------------- -->
<h2 class="tituloH2">Funções:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(203)"><li><code><b><palavra>.comecaCom(<Palavra>) </b>(<palavra>.startsWith(<String>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="203" style="display: none"><p class="balao">
 Compara se uma Palavra começa com outra Palavra com retorno booleano de 1 ou 0<br>
<br> <b>Sintaxe:</b> <br>
minhaPalavra.comecaCom(comparacao);<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   USB.conectar(9600); // Inicia uma comunicação serial<br>
  }<br>
  principal() {<br>
   // Inicia uma variável com a Palavra minhaPalavra com valor 123456<br>
   Palavra minhaPalavra = "123456";<br>
   // Inicia uma variável com a Palavra comparacao com valor 123<br>
   Palavra comparacao = "123";<br>
   // Verifica se a minhaPalavra começa com 123<br>
   USB.enviarln(minhaPalavra.comecaCom(comparacao));<br>
   // Retorna 1 no monitor serial<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(208)"><li><code><b>cronometro() </b>(millis())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="208" style="display: none"><p class="balao">
 Retorna o número de milissegundos passados desde que a placa Arduino começou a executar o programa atual. Sua marcação é muito boa para pequenos periodos de tempo, em casos de tempos maiores (como minutos ou horas) é recomendado o uso de outras soluções (como um Real Time Clock RTC, ou a busca da hora na internet. Esse número irá sofrer overflow (chegar ao maior número possível e então voltar pra zero), após aproximadamente 50 dias.<br>
<br> <b>Sintaxe:</b> <br>
tempo = cronometro();<br>
<br><b> Ex.:</b><br>
  // Declara uma variável chamada tempo<br>
  numeroLongo tempo = 0;<br>
  configuracao() {<br>
   // Inicia a cominicação serial<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   // Envia a varíavel tempo pelo serial<br>
   tempo = cronometro();<br>
   USB.enviarln(tempo);<br>
   // Espera um segundo<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(15)"><li><code><b>definir <nome> <valor> </b> (#define <nome> <valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="15" style="display: none"><p class="balao">
 Usado para atribuir um nome a uma variável constante. Quando o código é compilado todas as ocorrências do <nome> são substituídas pelo <valor>, seja ele um valor valor numérico ou uma palavra ou letra.<br>
<br> <b>Sintaxe:</b><br>
  definir NomeConstante valor;<br>
<br><b> Ex.:</b><br>
  definir LED 3<br>
  \\O compilador substituira qualquer menção do LED pelo valor 3 no tempo de compilação.<br>
  configuracao() {<br>
   definirModo(LED, SAIDA);<br>
  }<br>
  principal() {<br>
   ligar(LED);<br>
   esperar(1000);<br>
   desligar(LED);<br>
   esperar(1000);<br>
  }<br>
<br>
 <b>Obs.:</b> Erro comum: “definir LED 3;”. Esse comando não precisa de ‘;’ no final dele.<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(17)"><li><code><b>enviarBinario(<dataPin>, <clockPin>, <ordem>, <valor>) </b> (shiftOut(<dataPin>, <clockPin>, <ordem>, <valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="17" style="display: none"><p class="balao">
 Essa função manda o valor de um byte a um bit por vez. A ordem de mudança pode ser feita a partir do bit mais significativo ou a partir do menos significativo. Cada bit é enviado, um de cada vez, para um pino de dados.<br>
<br><b> Ex.:</b><br>
  enviarBinario(dataPin, clockPin, Direto, valor);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(13)"><li><code><b>esperar(<inteiro>) </b>(delay(<inteiro>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="13" style="display: none"><p class="balao">
 Pausa o programa por um determinado período de tempo definido em milissegundo (ms). Após a espera ele continua o código normalmente.<br>
<br> <b>Sintaxe:</b> <br>
esperar (milissegundos);<br>
<br><b> Ex.:</b><br>
  // O código pausa o programa por um segundo antes de alternar o pino de saída.<br>
  numero LED = 13; // LED conectado no pino digital 13<br>
<br>
  configuracao() {<br>
   definirModo(LED, SAIDA); // define o pino LED como saida<br>
  }<br>
  principal() {<br>
   // Liga o LED<br>
   ligar(LED);<br>
   // espera 1 segundo<br>
   esperar(1000);<br>
   // Desliga o LED <br>
   desligar(LED);<br>
   // espera 1 segundo<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(202)"><li><code><b>emNumero(<Palavra>) </b>(toInt(<String>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="202" style="display: none"><p class="balao">
 Converte uma Palavra válida em um número inteiro. Para isso a Palavra tem que obrigatoriamente começar com um número. Caso a Palavra não seja válida o retorno será 0.<br>
<br> <b>Sintaxe:</b> <br>
minhaPalavra.emNumero();<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   USB.conectar(9600); // Inicia uma comunicação serial<br>
  }<br>
  principal() {<br>
   // Inicia uma variável com a Palavra 123456<br>
   Palavra minhaPalavra = "123456";<br>
   // Conver´te a palavra para número, subtrai 3 e envia a palavra para o monitor serial<br>
   USB.enviarln(minhaPalavra.emNumero()-3);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(12)"><li><code><b>pararSoar(porta) </b>(noTone(porta))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="12" style="display: none"><p class="balao">
 Comando para o controle do buzzer, caso a porta não esteja “soando” a operação não tem efeito. Necessita de um parâmetro que indica a porta na qual o buzzer está conectado.<br>
<br><b> Ex.:</b><br>
  numero buzzer = 9;<br>
  configuracao(){}<br>
  principal() {<br>
   soar(buzzer, 440);<br>
   esperar(500);<br>
   pararSoar(buzzer);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(14)"><li><code><b>proporcionar(<valor>, <minEntrada>, <maxEntrada>, <minSaida>, <maxSaida>) </b> (map(<valor>, <minEntrada>, <maxEntrada>, <minSaida>, <maxSaida>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="14" style="display: none"><p class="balao">
 Essa função realiza uma operação similar a uma regra de três. Ela realoca um valor de um intervalo dado em proporção a outro intervalo.<br>
<br><b> Ex.:</b><br>
  configuracao() {}<br>
  principal() {<br>
   numero val = lerAnalogico(A0);<br>
   val = proporcionar(val, 0, 1023, 0, 255);<br>
   escreverAnalogico(9, val);<br>
   esperar(30);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(19)"><li><code><b><palavra>.remover(<valor>) </b>(<palavra>.remove(<valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="19" style="display: none"><p class="balao">
 Modifica uma Palavra em local, removendo caracteres do endereço dado até o fim da Palavra, ou até o endereço resultante da soma do valor do primeiro endereço com um valor específico(também fornecido pelo usuário).<br>
<br><b> Ex.:</b><br>
  //X variavel positiva e inteira<br>
  remover(X);<br>
  //X e Y variaveis inteiras e positivas<br>
  remover(X , Y);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(11)"><li><code><b>soar(<porta>, <frequência>) </b>(tone(<porta>, <frequência>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="11" style="display: none"><p class="balao">
 Possui dois parâmetros, o primeiro é a porta e o segundo a frequência que ela deve tocar. A função também aceita um terceira argumento que determina a duração desejada em milésimos de segundo. O Arduino de modo geral aceita frequências entre 31 Hz e 65535 Hz.<br>
<br> <b>Sintaxe:</b><br>
  soar(pino, frequencia);<br>
  soar(pino, frequencia, duracao);<br>
<br>
  pino - o pino o qual gera o soar;<br>
  frequencia - a frequência do tom em hertz - Modulo numero;<br>
  duracao - a duração do tom em milissegundos (opcional) - Modulo numeroLongo;<br>
<br><b> Ex.:</b><br>
  numero buzzer = 9;<br>
  configuracao(){}<br>
  principal() {<br>
   soar(buzzer, 440);<br>
   esperar(500);<br>
   pararSoar(buzzer);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(18)"><li><code><b><palavra>.tamanho() </b> (<palavra>.length())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="18" style="display: none"><p class="balao">
 Retorna o comprimento (número de caracteres) de uma palavra. Necessita de um parâmetro que é a palavra que será medida.<br>
<br><b> Ex.:</b><br>
  Palavra[] nome=”Brino”;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   USB.enviar(“Comprimento da Palavra: ”);<br>
   USB.enviarln(nome.tamanho());<br>
   // Nao se esqueca que as palavras possuem um caractere invisivel no final.<br>
  }<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(204)"><li><code><b><palavra>.terminaCom(<Palavra>) </b>(<palavra>.endsWith(<String>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="204" style="display: none"><p class="balao">
 Compara se uma Palavra termina com outra Palavra com retorno booleano de 1 ou 0<br>
<br> <b>Sintaxe:</b> <br>
minhaPalavra.terminaCom(comparacao);<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   USB.conectar(9600); // Inicia uma comunicação serial<br>
  }<br>
  principal() {<br>
   // Inicia uma variável com a Palavra minhaPalavra com valor 123456<br>
   Palavra minhaPalavra = "123456";<br>
   // Inicia uma variável com a Palavra comparacao com valor 123<br>
   Palavra comparacao = "123";<br>
   // Verifica se a minhaPalavra termina com 123<br>
   USB.enviarln(minhaPalavra.terminaCom(comparacao));<br>
   // Retorna 0 no monitor serial<br>
  }<br>
</p></div>
<!-- --------------- FUNCOES ESSENCIAIS --------------- -->
<h2 class="tituloH2">Funções essenciais:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(20)"><li><code><b>configuracao(){} </b> (void setup(){})</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="20" style="display: none"><p class="balao">
 É responsável por preparar o hardware para a execução do loop principal. O método de configuracao() é executado uma única vez quando o Arduino é ligado ou resetado e é ignorado no decorrer do restando do código. É nele que definimos a conexão com a porta USB, os modos de operação dos pinos, e outros parâmetros que necessitam ser executados apenas uma vez.<br>
 <br><b> Ex.:</b><br>
  configuracao() {<br>
   definirModo(13, SAIDA);<br>
  }<br>
<br>
  principal() {<br>
   ligar(13);<br>
   esperar(1000);<br>
   desligar(13); <br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(21)"><li><code><b>principal(){}</b> (void loop(){})</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="21" style="display: none"><p class="balao">
 O método principal() é um dos mais usados para se colocar a parte principal do programa. Ele é executado a partir do momento que o Arduino é ligado, após a execução da configuração, até o momento em que ele é desligado podendo ser repetido incontáveis vezes. Nele colocamos todas as operações necessárias para o funcionamento contínuo do projeto.<br>
<br><b> Ex.:</b><br>
  numero pinoBotao = 3;<br>
<br>
  // configuracao inicializa da serial e do pinoBotao<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   definirModo(pinoBotao, ENTRADA);<br>
  }<br>
<br>
  // o laco checa o estado do pino<br>
  // e manda para o monitor serial<br>
  principal() {<br>
   se (lerDigital(pinoBotao) == LIGADO)<br>
    USB.escrever('L');<br>
   senao<br>
    USB.escrever('D');<br>
   esperar(1000);<br>
  }<br>
</p></div>
<!-- --------------- I2C --------------- -->
<h2 class="tituloH2">I2C:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(62)"><li><code><b>I2C </b> (Wire)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="62" style="display: none"><p class="balao">
 Essa biblioteca permite comunicações com comunicação I2C/TWI.<br>
<br><b> Ex.:</b><br>
  usar I2C<br>
<br>
  configuracao() {<br>
   I2C.conectar(); <br>
  }<br>
<br>
  byte val = 0;<br>
<br>
  principal() {<br>
   I2C.transmitir(44);<br>
   I2C.escrever(byte(0x00)); <br>
   I2C.escrever(val); <br>
   I2C.pararTransmitir(); <br>
<br>
   val++; <br>
<br>
   se(val == 64) { <br>
    val = 0; <br>
   }<br>
<br>
   delay(500);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(63)"><li><code><b>I2C.conectar </b> (I2C.begin())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="63" style="display: none"><p class="balao">
 Inicia a biblioteca Wire e junta-se ao I2C bus como mestre ou escravo. Isso deverá ser chamado apenas uma vez.<br>
<br><b> Ex.:</b><br>
   I2C.conectar();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(67)"><li><code><b>I2C.disponivel() </b> (I2C.available())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="67" style="display: none"><p class="balao">
 Retorna o número de bytes disponíveis para recuperação com ler(). Isso deve ser chamado em um dispositivo mestre após uma chamada para solicitar() ou em um escravo dentro do manipulador recebido().<br>
<br><b> Ex.:</b><br>
  I2C.disponivel();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(66)"><li><code><b>I2C.escrever(<dado>) </b> (I2C.write(<dado>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="66" style="display: none"><p class="balao">
 Grava dados de um dispositivo escravo em resposta a uma solicitação de um mestre, ou bytes de filas para transmissão de um dispositivo mestre para escravo (chamadas intermediárias para transmitir() e pararTransmitir()).<br>
<br><b> Ex.:</b><br>
  I2C.escrever(valor);<br>
  I2C.escrever(palavra);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(68)"><li><code><b>I2C.ler() </b> (I2C.read())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="68" style="display: none"><p class="balao">
 Lê um byte que foi transmitido de um dispositivo escravo para um mestre depois de uma chamada para solicitar() ou foi transmitido de um mestre para um escravo.<br>
<br><b> Ex.:</b><br>
  I2C.ler();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(65)"><li><code><b>I2C.pararTransmitir() </b> (I2C.endTransmission())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="65" style="display: none"><p class="balao">
 Essa função para a transmissão de um aparelho escravo que fora começada pela função transmitir() e envia os bytes “da fila”.<br>
<br><b> Ex.:</b><br>
  I2C.pararTransmitir();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(71)"><li><code><b>I2C.recebido() </b> (I2C.onReceive())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="71" style="display: none"><p class="balao">
 Registra a função que deve ser chamada quando um aparelho escravo recebe uma transmissão do mestre (comunicação I2C).<br>
<br><b> Ex.:</b><br>
  I2C.recebido();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(70)"><li><code><b>I2C.solicitado() </b> (I2C.onRequest())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="70" style="display: none"><p class="balao">
 Registra uma função que será chamada quando o mestre solicita dados do aparelho escravo.<br>
<br><b> Ex.:</b><br>
  I2C.solicitado();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(69)"><li><code><b>I2C.solicitar() </b> (I2C.requestFrom())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="69" style="display: none"><p class="balao">
 Função utilizada pelo mestre para solicitar bytes de um aparelho escravo.<br>
<br><b> Ex.:</b><br>
  I2C.solicitar();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(64)"><li><code><b>I2C.transmitir() </b> (I2C.beginTransmission())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="64" style="display: none"><p class="balao">
 Inicia a transmissão com o aparelho escravo I2C do endereço dado. Essa função recebe como parâmetro o endereço composto pelos 7 bits do aparelho.<br>
<br><b> Ex.:</b><br>
  I2C.transmitir();<br>
</p></div>
<!-- --------------- INSTRUCOES DE CONTROLE --------------- -->
<h2 class="tituloH2">Instruções de controle:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(108)"><li><code><b>caso <Valor></b> (case <Valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="108" style="display: none"><p class="balao">
  Usado junto do comando "selecionar" indicando os casos em que serão comparados com o valor.<br>
<br><b> Ex.:</b><br>
  numero entrada = 2;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   seletor (entrada) {<br>
    caso 1:<br>
     USB.enviarln("Primeiro caso");<br>
     quebrar;<br>
    caso 2:<br>
     USB.enviarln("Segundo caso");<br>
     quebrar;<br>
    caso 3:<br>
     USB.enviarln("Terceiro caso");<br>
     quebrar;<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(80)"><li><code><b>enquanto(<expressão booleana>) </b> (while(<expressão booleana>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="80" style="display: none"><p class="balao">
 Esse laço de repetição executa um bloco enquanto a condição entre parênteses for verdadeira.<br>
<br><b> Ex.:</b><br>
  numero contador = 0;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   // Conta de 0 a 19<br>
   enquanto(contador < 20){<br>
    USB.enviarln(vontador);<br>
    contador++;<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(205)"><li><code><b>padrao: </b> (default:))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="205" style="display: none"><p class="balao">
 Esse comando é usado junto ao "seletor" (switch). Quando uma entrada no seletor não se encaixa em nenhum dos casos descritos, a seleção escolhe a opção "padrao", caos ela esteja disponível. O uso dela no seletor é opcional. Sua estrutura começa com ela, dentro do seletor, abrindo um bloco com dois pontos (':') e o fechando com o comando "quebrar".<br><b> Ex.:</b><br>
  numero entrada = 2;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   seletor (entrada) {<br>
    caso 1:<br>
     USB.enviarln("Primeiro caso");<br>
     quebrar;<br>
    caso 2:<br>
     USB.enviarln("Segundo caso");<br>
     quebrar;<br>
    padrao:<br>
     USB.enviarln("Caso 3, padrao");<br>
     quebrar;<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(77)"><li><code><b>para(<inicio>; <condicao>; <operacao>) </b> (for(<inicio>; <condicao>; <operacao>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="77" style="display: none"><p class="balao">
 Laço de repetição com 3 parâmetros. Inicio: Indica o valor inicial da variável do laço, condicao: Condição para a execução do método, Operacao: Operação que será realizada na variável para que ele percorra o laço.<br>
<br><b> Ex.:</b><br>
  numero pinoLED= 13;<br>
<br>
  configuracao(){<br>
   definirModo(pinoLED, SAIDA);<br>
  }<br>
<br>
  principal(){<br>
   para (int t=100; t <= 1000; t=t+10){<br>
    ligar(pinoLED);<br>
    esperar(t);<br>
    desligar(pinoLED);<br>
    esperar(t);<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(109)"><li><code><b>quebrar</b> (break)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="109" style="display: none"><p class="balao">
  Incica o fim do bloco caso. Usado junto ao comando "seletor".<br>
<br><b> Ex.:</b><br>
  numero entrada = 2;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   seletor (entrada) {<br>
    caso 1:<br>
     USB.enviarln("Primeiro caso");<br>
     quebrar;<br>
    caso 2:<br>
     USB.enviarln("Segundo caso");<br>
     quebrar;<br>
    caso 3:<br>
     USB.enviarln("Terceiro caso");<br>
     quebrar;<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(78)"><li><code><b>se(<condição>) </b> (if(<condição>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="78" style="display: none"><p class="balao">
 É uma condicional que verifica se a condição entre os parenteses é “Verdadeira” ou “Falsa”, se o resultado for “Verdadeiro” o bloco a seguir é executado, caso contrário ele será ignorado.<br>
<br><b> Ex.:</b><br>
  numero botao = 9;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   definirModo(botao, SAIDA);<br>
  }<br>
  principal() {<br>
   se(lerDigital(botao) == LIGADO){<br>
    USB.enviarln(“O botao foi acionado!”);<br>
   }<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(79)"><li><code><b>senao{} </b> (else{})</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="79" style="display: none"><p class="balao">
 É usado após o bloco de um se() (if()). O bloco desta instrução é executado caso a condição da condicional anterior não tenha sido satisfeita, ou seja, caso o bloco se tenha sido ignorado.<br>
<br><b> Ex.:</b><br>
  numero botao = 9;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   definirModo(botao, SAIDA);<br>
  }<br>
  principal() {<br>
   se(lerDigital(botao) == LIGADO){<br>
    USB.enviarln(“O botao esta ligado!”);<br>
   }<br>
   senao{<br>
    USB.enviarln(“O botao esta desligado”);<br>
   }<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(107)"><li><code><b>seletor(<Variavel>)</b> (switch(<Variavel>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="107" style="display: none"><p class="balao">
  Similar o "se()" o seletor é capaz de atuar similar a um multiplexador, onde a partir e diferentes entradas ele pode selecionar uma das opções.<br>
<br><b> Ex.:</b><br>
  numero entrada = 2;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   seletor (entrada) {<br>
    caso 1:<br>
     USB.enviarln("Primeiro caso");<br>
     quebrar;<br>
    caso 2:<br>
     USB.enviarln("Segundo caso");<br>
     quebrar;<br>
    caso 3:<br>
     USB.enviarln("Terceiro caso");<br>
     quebrar;<br>
   }<br>
  }<br>
</p></div>
<!-- --------------- INTERRUPTORES --------------- -->
<h2 class="tituloH2">Interruptores:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(72)"><li><code><b>conectarInterruptor(<porta>, <funcao>, <modo>) </b> (attachInterrupt(<porta>, <funcao>, <modo>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="72" style="display: none"><p class="balao">
 Especifica uma Rotina de Serviço de Interruptores(ISR, em inglês), já declarada, a avisa quando ocorre um interromper.<br>
<br><b> Sintaxe:</b><br>
  conectarInterruptor(porta, funcao, modo); <br>
<br>
  porta- Variavel que indica a porta usada para a interrupção. No caso do Arduino UNO, 0 corresponde a porta digital 2 e 1 a porta digital 3<br>
  funcao - função chamada quando quando ocorre a interrupção<br>
  modo - Varivel que define o tipo de variação no sinal da porta deve ocorrer para a interrupção ocorrer (DESLIGADO, LIGANDO, DESLIGANDO ou MUDANDO)<br>
<br><b> Ex.:</b><br>
  conectarInterruptor();<br>
<br><b> OBS.:</b> Os comandos interruptores não funcionam em todas as portas do Arduino. Para saber quais pinos de sua placa estão disponíveis para o uso do comando acesse a documentação específica de sua placa. Nas placas Arduino Uno, Arduino Nano e Arduino Mini as portas são a D2 e D3, Já na placa Arduino Mega as portas que podem ser utilizadas para o comando são a D2, D3, D18, D19, D20 e D21.<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(73)"><li><code><b>desconectarInterruptor(<interruptor>) </b> (detachInterrupt(<interruptor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="73" style="display: none"><p class="balao">
 Desliga o interruptor. Essa função possui um parâmetro: o número do interruptor a ser desligado. Ela também não retorna nada. Vale ressaltar que, para o Arduino Due, essa função recebe o argumento que define o número do pino do interruptor a ser desligado.<br>
<br><b> Sintaxe:</b><br>
  desconectarInterruptor (interruptor);<br>
<br>
  -interromper: o número da interrupção para desativar<br>
  -pino: o número do pino da interrupção para desabilitar (apenas Arduino Due).<br>
<br><b> Ex.:</b><br>
  desconectarInterruptor();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(74)"><li><code><b>desligarInterruptores() </b> (noInterrupts())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="74" style="display: none"><p class="balao">
 Esse comando desativa os interruptores (eles podem ser acionados pelo comando ligarInterruptores()). Interruptores permitem que tarefas específicas e importantes possam funcionar em plano de fundo e são ativadas por padrão. Algumas funções não serão executadas enquanto interruptores estão desativados, e informações que estão por vir podem ser ignoradas. Interruptores podem perturbar levemente o andamento do código, mas podem ser desativados para seções críticas do algoritmo.<br>
<br><b> Ex.:</b><br>
  principal(){<br>
   desligarInterruptores();<br>
   // Codigo que não pode ser interrompido<br>
   ligarInterruptores();<br>
   // Resto do codigo<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(75)"><li><code><b>ligarInterruptores() </b> (interrupts())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="75" style="display: none"><p class="balao">
 Esse comando aciona os interruptores (após serem desativados pelo comando desligarInterruptores()). Interruptores permitem que tarefas específicas e importantes possam funcionar em plano de fundo e são ativadas por padrão. Algumas funções não serão executadas enquanto interruptores estão desativados, e informações que estão por vir podem ser ignoradas. Interruptores podem perturbar levemente o andamento do código, mas podem ser desativados para seções críticas do algoritmo. <br>
<br><b> Ex.:</b><br>
  principal(){<br>
   desligarInterruptores();<br>
   // Codigo que não pode ser interrompido<br>
   ligarInterruptores();<br>
   // Resto do codigo<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(76)"><li><code><b>MUDANDO </b> (CHANGING)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="76" style="display: none"><p class="balao">
 Constante válida para um dos argumentos da função conectarInterruptor(). É utilizada para acionar o interruptor sempre que o estado do pino mude de valor.<br>
<br><b> Ex.:</b><br>
  conectarInterruptor(digitalPinToInterrupt(BOTAO), ISR, MUDANDO);<br>
</p></div>
<!-- --------------- LCD --------------- -->
<h2 class="tituloH2">LCD(LiquidCrystal):</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(218)"><li><code><b><nome>.autoRolar() </b> (<nome>.autoscroll())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="218" style="display: none"><p class="balao">
 Ativa a função de rolagem automática do LCD. Esse efeito faz com que cada novo caracter escrito no display ocupe o lugar do anterior e "empurre" todos os outros já no display uma posição para o lado. No caso da direção do texto estar da esquerda para a direita (padrão) a rolagem será para a esquerda, caso a direção do texto seja a oposta a rolagem será para a direita. Seu funciona é oposto ao do pararAutoRolar()<br>
<br><b> Sintaxe:</b><br>
  lcd.autoRolar();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
   // Espera um segundo<br>
   esperar(1000);<br>
   // Comeca o auto rolar do LCD<br>
   lcd.autoRolar();<br>
   lcd.enviar("teste");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(48)"><li><code><b>LCD <nome></b> (LiquidCrystal <nome> ()) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="48" style="display: none"><p class="balao">
 Cria uma variável do tipo LCD. A exibição na tela pode ser controlada usando 4 ou 8 pinos de dados. <br>
<br><b> Sintaxe:</b><br>
  LCD (NP, E, d4, d5, d6, d7)<br>
<br>
  -NP = numero do pino do arduino.<br>
  -E = o numero do pino de controle do LCD. <br>
  -d4, d5, d6, d7 = os números dos pinos Arduino que estão conectados aos pinos de dados correspondentes no LCD.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.conectar(16,1);<br>
   lcd.enviar("ola, mundo!");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(214)"><li><code><b><nome>.conectar(<x>, <y>) </b> (<nome>.begin(<x>. <y>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="214" style="display: none"><p class="balao">
 Inicializa a interface na tela LCD e especifica as dimensões (largura e altura) da tela. conectar() precisa ser chamado antes de qualquer outro comando da biblioteca LCD.<br>
<br><b> Sintaxe:</b><br>
  lcd.conectar(numeroDeColunas, numeroDeLinhas);<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.conectar(15,2);<br>
   lcd.enviar("ola terraqueos!");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(213)"><li><code><b><nome>.cursor() </b> (<nome>.cursor())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="213" style="display: none"><p class="balao">
 Torna o cursor do display LCD visível.<br>
<br><b> Sintaxe:</b><br>
  lcd.cursor();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.conectar(16,1);<br>
   lcd.enviar("ola, mundo!");<br>
   esperar(1000);<br>
   lcd.rolarMensagemDireita();<br>
   // Esconde o cursor do LCD<br>
   lcd.esconderCursor;<br>
   esperar(1000);<br>
   // Apresenta o cursor do LCD<br>
   lcd.cursor;<br>
   esperar(1000);<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(222)"><li><code><b><nome>.criarLetra() </b> (<nome>.createChar())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="222" style="display: none"><p class="balao">
 Cria um caractere (grafo) customizado para ser utilizado no LCD. É possível cusmotizar até 8 caracteres com 5x8 pixels. A aparência de cada caractere customizado é feito em uma lista de 8 bytes. Para mostrar um pixel customizado basta utilizar a função .escrever() passando o index do byte de seu caractere.<br>
Quando se tenta referenciar o caractere "0", se não for uma variável, você necessita fazê-lo como byte, se não o compilador vai apontar um erro.
<br><b> Sintaxe:</b><br>
  lcd.criarLetra(<indexDaLetra>, <caractereCriado>);<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  byte sorriso[8] = {<br>
   B00000,<br>
   B10001,<br>
   B00000,<br>
   B00000,<br>
   B10001,<br>
   B01110,<br>
   B00000,<br>
  };<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Cria o caractere sorriso no index 0<br>
   lcd.criarLetra(0, sorriso);<br>
   // escreve o caractere do index 0 (sorriso) na tela<br>
   lcd.escrever(byte(0));<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(221)"><li><code><b><nome>.direitaPraEsquerda() </b> (<nome>.rightToLeft())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="221" style="display: none"><p class="balao">
 
Define a direção do texto escrito no LCD da direita para a esquerda. Isso quer dizer que cada novo caractere a ser escrito no display vai da esquerda para a direita, mas não afeta o texto anterior.<br>
<br><b> Sintaxe:</b><br>
  lcd.direitaPraEsquerda();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Começa a escrever o texto da direita para a esquerda<br>
   lcd.direitaPraEsquerda();<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(50)"><li><code><b><nome>.enviar </b> (<nome>.print())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="50" style="display: none"><p class="balao">
 Imprime texto no LCD.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.enviar("ola!");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(213)"><li><code><b><nome>.esconderCursor() </b> (<nome>.noCursor())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="213" style="display: none"><p class="balao">
 Esconde o cursor do display LCD.<br>
<br><b> Sintaxe:</b><br>
  lcd.esonderCursor();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.conectar(16,1);<br>
   lcd.enviar("ola, mundo!");<br>
   esperar(1000);<br>
   lcd.rolarMensagemDireita();<br>
   // Esconde o cursor do LCD<br>
   lcd.esconderCursor;<br>
   esperar(1000);<br>
   // Apresenta o cursor do LCD<br>
   lcd.cursor;<br>
   esperar(1000);<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(51)"><li><code><b><nome>.escrever() </b> (<nome>.write())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="51" style="display: none"><p class="balao">
 Escreve um caracter no LCD.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal(){<br>
   se (USB.disponivel()) {<br>
    lcd.escrever(USB.ler());<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(220)"><li><code><b><nome>.esquerdaPraDireita() </b> (<nome>.leftToRight())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="220" style="display: none"><p class="balao">
 
Define a direção do texto escrito no LCD da esquerda para a direita, que é o padrão. Isso quer dizer que cada novo caractere a ser escrito no display vai da direita para a esquerda, mas não afeta o texto anterior.<br>
<br><b> Sintaxe:</b><br>
  lcd.esquerdaPraDireita();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Começa a escrever o texto da esquerda para a direita<br>
   lcd.esquerdaPraDireita();<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(53)"><li><code><b><nome>.limpar () </b> (<name>.clear())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="53" style="display: none"><p class="balao">
 Apaga o que está escrito no LCD.<br>
<br><b> Sintaxe:</b><br>
  lcd.limpar();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.conectar(16,1);<br>
   lcd.enviar("ola, mundo!");<br>
   esperar(1000);<br>
   lcd.limpar();<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(215)"><li><code><b><nome>.origem() </b> (<nome>.home())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="215" style="display: none"><p class="balao">
 Posiciona o cursor no canto superior esquedo do LCD. Ou seja, utiliza essa posição para imprimir os próximos textos a serem inseridos no dispolay. Para também limpar o conteúdo da tela é necessário utilizar a função "limpar()".<br>
<br><b> Sintaxe:</b><br>
  lcd.origem();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
   // Espera um segundo<br>
   esperar(1000);<br>
   // Limpa o conteudo da tela<br>
   lcd.limpar();<br>
   // Volta para o canto superior esquerdo(origem)<br>
   lcd.origem();<br>
   // Imprime "Outra mensagem!"<br>
   lcd.enviar("Outra mensagem!");<br>
   // Apresenta o cursor do LCD<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(219)"><li><code><b><nome>.pararAutoRolar() </b> (<nome>.noAutoscroll())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="219" style="display: none"><p class="balao">
 Desativa a função de rolagem automática do LCD. Esse efeito faz com que cada novo caracter escrito seja apresentado ao lado do anterior. Seu funcionamento é o oposto ao do autoRolar()<br>
<br><b> Sintaxe:</b><br>
  lcd.pararAutoRolar();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
   // Espera um segundo<br>
   esperar(1000);<br>
   // Comeca o auto rolar do LCD<br>
   lcd.autoRolar();<br>
   lcd.enviar("teste");<br>
   esperar(1000);<br>
   // Para o auto rolar do LCD<br>
   lcd.pararAutoRolar();<br>
   lcd.enviar("Ola");<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(217)"><li><code><b><nome>.pararPiscarCursor() </b> (<nome>.noBlink())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="217" style="display: none"><p class="balao">
 Para de mostrar o cursor piscando no LCD. Funciona de maneira oposta ao piscarCursor().<br>
<br><b> Sintaxe:</b><br>
  lcd.pararPiscarCursor();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
   // Espera um segundo<br>
   esperar(1000);<br>
   // Comeca a piscar o cursor<br>
   lcd.PiscarCursor();<br>
   esperar(5000);<br>
   // Para de piscar o cursor<br>
   lcd.pararPiscarCursor();<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(216)"><li><code><b><nome>.piscarCursor() </b> (<nome>.blink())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="216" style="display: none"><p class="balao">
 Mostra um cursor piscando no LCD. Se utilizado com a função cursor() o resultado irá depender do LCD específico utilizado. Funciona de maneira oposta ao pararPiscarCursor().<br>
<br><b> Sintaxe:</b><br>
  lcd.piscarCursor();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,2);<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
   // Espera um segundo<br>
   esperar(1000);<br>
   // Comeca a piscar o cursor<br>
   lcd.piscarCursor();<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(52)"><li><code><b><nome>.posicao(x,y) </b> (<nome>.setCursor(x,y))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="52" style="display: none"><p class="balao">
 É um comando utilizado pela biblioteca do LCD, ele serve para definir a posição do cursor utilizando dois parâmetros, como em um plano cartesiano, x horizontal (Linhas) e y vertical (Colunas).<br>
<br><b> Ex.:</b><br>
  lcd.posicao (0 , 0); //topo esquerda<br>
  lcd.posicao (15 , 0); //topo direita<br>
  lcd.posicao (0 , 1); //inferior esquerda<br>
  lcd.posicao (15 , 1);//inferior direita<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(212)"><li><code><b><nome>.rolarMensagemDireita() </b> (<nome>.scrollDisplayRight())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="212" style="display: none"><p class="balao">
 Movimenta o conteudo do display e o cursor uma casa para a direita.<br>
<br><b> Sintaxe:</b><br>
  lcd.rolarMensagemDireita();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca LCD para ser usada<br>
  usar LCD<br>
<br>
   // Cria um objeto do tipo LCD com o nome lcd conectado as portas declaradas entre parenteses<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   // Declara o tamanho da tela do LCD, isso eh, quantos caracteres cabem nele<br>
   lcd.conectar(16,1);<br>
   // Imprime "Ola mundo"<br>
   lcd.enviar("ola, mundo!");<br>
   // Espera um segundo<br>
   esperar(1000);<br>
   // Rola a mensagem da tela<br>
   lcd.rolarMensagemDireita();<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(212)"><li><code><b><nome>.rolarMensagemEsquerda() </b> (<nome>.scrollDisplayLeft())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="212" style="display: none"><p class="balao">
 Movimenta o conteudo do display e o cursor uma casa para a esquerda.<br>
<br><b> Sintaxe:</b><br>
  lcd.rolarMensagemEsquerda();<br>
<br>
  -lcd = Nome do LCD conectado.<br>
<br><b> Ex.:</b><br>
  usar LCD<br>
<br>
  LCD lcd(12, 11, 10, 5, 4, 3, 2);<br>
<br>
  configuracao(){<br>
   lcd.conectar(16,1);<br>
   lcd.enviar("ola, mundo!");<br>
   esperar(1000);<br>
   lcd.rolarMensagemEsquerda();<br>
  }<br>
<br>
  principal() {}<br>
</p></div>
<!-- --------------- MEMORIA --------------- -->
<h2 class="tituloH2">Memória(EEPROM):</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(38)"><li><code><b>Memoria.escrever(<endereco>, <valor>) </b> (EEPROM.write(<endereco>, <valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="38" style="display: none"><p class="balao">
 Memória de 512 bytes da placa que é capaz de guardar dados mesmo após a placa ser desligada. A função escrever é usada para guardar dados nesta memória.<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   para( numero x = 0; x < 5; x++){<br>
    numero d = lerAnalogico(0);<br>
    Memoria.escrever(x, d);<br>
    USB.enviarln(d);<br>
   }<br>
  }<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(40)"><li><code><b>Memoria.formatar() </b> (for (int i = 0 ; i < EEPROM.length() ; i++) EEPROM.write(i, 0);)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="40" style="display: none"><p class="balao">
 Essa função apaga todos os valores gravados na memória EEPROM.<br>
<br><b> Ex.:</b></b:><br>
  formatar();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(37)"><li><code><b>Memoria.ler() </b> (EEPROM.read())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="37" style="display: none"><p class="balao">
 Lê um byte da EEPROM. EEPROM é uma memória onde dados podem ser armazenados para serem salvos mesmo ao desligar o Arduino.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca Memoria para ser usada<br>
  usar Memoria<br>
<br>
   // Cria duas variáveis e inicializa elas<br>
  numero leitura = 0;<br>
  numero valor = 0;<br>
<br>
  configuracao() {<br>
   // Inicia a comunicação serial<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   // Realiza uma leitura de memoria e armazena o dado na variável Valor<br>
   Valor = Memoria.ler(leitura);<br>
   // Envia a variável leitura pela porta serial<br>
   USB.enviar(leitura);<br>
   // Faz uma tabulação<br>
   USB.enviar("\t");<br>
   // Envia a variável valor pela porta serial<br>
   USB.enviarln(valor);<br>
   // Soma 1 à variável leitura<br>
   leitura = leitura + 1;<br>
   // Verifica se o valor da variável é igual a 512<br>
   se (leitura == 512){<br>
    // Reinicia a variável leitura<br>
    leitura = 0;<br>
   }<br>
   // Espera meio segundo<br>
   esperar(500);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(39)"><li><code><b>Memoria.tamanho() </b> (EEPROM.length())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="39" style="display: none"><p class="balao">
 Retorna o tamanho da memória do arduino usado.<br>
<br><b> Ex.:</b><br>
  enquanto (x < Memoria.tamanho()){}<br>
</p></div>
<!-- --------------- MODIFICADORES --------------- -->
<h2 class="tituloH2">Modificadores:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(10)"><li><code><b>Constante <variável> <nome_variavel> = <valor> </b>(const <variavel> <nome_variavel> = <valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="10" style="display: none"><p class="balao">
 Esse comando é usado junto a declaração de uma variável tornando-a constante, ou seja, o valor dela não poderá ser mudado posteriormente.<br>
<br><b> Ex.:</b><br>
  Constante numeroDecimal PI = 3.14;<br>
  numeroDecimal Raio = 10;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   USB.enviar(“comprimento da circunferencia: ”);<br>
   USB.enviarln(2*PI*Raio);<br>
  }<br>
  principal() {}<br>
<br>
 <b>Obs.:</b> PI = 7; // Nao permitido, voce nao podera mudar a constante ao longo do codigo.<br>
 <b>Obs2.:</b> definir ou Constante<br>
  Você pode usar Constante ou definir para criar constantes numéricas ou de palavras. Para vetores, você precisará usar Constante. Em geral, Constante é preferido sobre definir para declarar constantes.<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(9)"><li><code><b>Modulo <tipoDeVariavel> <nome_variavel></b> (unsigned <tipoDeVariavel> <nome_variavel>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="9" style="display: none"><p class="balao">
 Utilizado para retirar a capacidade de uma variável de armazenar valores negativos, para assim aumentar o seu valor máximo. Utiliza dois parâmetros, o tipo de variável e respectivamente a variável que se deseja atribuir o comando.<br>
<br> <b>Sintaxe:</b><br>
  Modulo TipoDeVariável Nome = Valor;<br>
  TipoDeVariável = de que tipo é sua variável, numero, numeroDecimal, etc.<br>
  Nome = o nome da sua variável TipoDeVariável;<br>
  Valor = o valor associado ao nome.<br>
<br><b> Ex.:</b><br>
  Modulo numero X;<br>
<br><b> Ex2.:</b><br>
  Modulo letra X = 240;<br>
<br><b> Ex3.:</b><br>
  Modulo numeroLongo X = 1000250;<br><br>
 <b>Obs.:</b> Por que usar o Modulo? Além de aumentar o valor positivo que você poderá usar , o Modulo permite que aconteça o comportamento de rolagem.<br>
</p></div>
<!-- --------------- Motor de passo --------------- -->
<h2 class="tituloH2">Motor de passo:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(209)"><li><code><b><nomeMotor>.definirVelocidade(<velocidade>)</b> (<nomeMotor>.setSpeed(<velocidade>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="209" style="display: none"><p class="balao">
 Define a velocidade de um determinado motor de passo. Velocidades muito altas farão ele travar. OBS: Esse comando não faz o motor se mover, para isso use a função "passo()".<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca MotorDePasso para ser usada<br>
  usar MotorDePasso<br>
  // Cria o objeto "motor" passando 5 parâmetros: o primeiro é a quantidade de passos para realizar uma rotação completa e os outros 4 definem as portas que o motor está conectado.<br>
  MotorDePasso motor(512, 8,10,9,11);<br>
<br>
  configuracao() {<br>
   // Definea velocidade do motor em 60<br>
   motor.definirVelocidade(60)<br>
   USB.enviar(“Oi!”);<br>
  }<br>
  principal() {}<br>
   // Dá 5 passos<br>
   motor.passo(5)<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(210)"><li><code><b><usar> MotorDePasso</b> (<usar> Stepper)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="210" style="display: none"><p class="balao">
 Chama a biblioteca "Stepper" para ser utilizada e controlar motores de passo com mais facilitade.<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca MotorDePasso para ser usada<br>
  usar MotorDePasso<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(211)"><li><code><b><nomeMotor>.passo(<quantosPassos>)</b> (<nomeMotor>.setSpeed(<quantosPassos>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="211" style="display: none"><p class="balao">
 Utilizado para que um motor específico dê uma quantidade determinada de "passos". Cada passo é uma rotação completa do motor<br>
<br><b> Ex.:</b><br>
  // Chama a biblioteca MotorDePasso para ser usada<br>
  usar MotorDePasso<br>
  // Cria o objeto "motor" passando 5 parâmetros: o primeiro é a quantidade de passos para realizar uma rotação completa e os outros 4 definem as portas que o motor está conectado.<br>
  MotorDePasso motor(512, 8,10,9,11);<br>
<br>
  configuracao() {<br>
   // Definea velocidade do motor em 60<br>
   motor.definirVelocidade(60)<br>
   USB.enviar(“Oi!”);<br>
  }<br>
  principal() {}<br>
   // Dá 5 passos<br>
   motor.passo(5)<br>
  }<br>
</p></div>
<!-- --------------- OPERADORS --------------- -->
<h2 class="tituloH2">Operadores:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(89)"><li><code><b><valor> + <valor> </b> (<valor> + <valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="89" style="display: none"><p class="balao">
 Esse operador é utilizado para somar dois valores ou variáveis.<br>
<br><b> Ex.:</b><br>
  2 + 3 ;<br>
<br><b> Ex2.:</b><br>
  x + y;<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(90)"><li><code><b><valor> - <valor> </b> (<valor> - <valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="90" style="display: none"><p class="balao">
 Esse operador é utilizado para diminuir um valor de outro ou uma variável de outra.<br>
<br><b> Ex.:</b><br>
  5 - 3;<br>
<br><b> Ex2.:</b><br>
  x - y;<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(91)"><li><code><b><valor> * <valor> </b> (<valor> * <valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="91" style="display: none"><p class="balao">
 Esse operador é utilizado para multiplicar dois valores ou variáveis. <br>
<br><b> Ex.:</b><br>
  2 * 7;<br>
<br><b> Ex2.:</b><br>
  x * y;<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(92)"><li><code><b><valor> / <valor> </b> (<valor> / <valor>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="92" style="display: none"><p class="balao">
 Esse operador é utilizado para dividir dois valores ou variáveis. <br>
<br><b> Ex.:</b><br>
  9 / 7;<br>
<br><b> Ex2.:</b><br>
  x / y;<br>
</p></div>
<!-- --------------- PALAVRAS-CHAVE --------------- -->
<h2 class="tituloH2">Palavras-chave:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(96)"><li><code><b>// </b> (//) ou <b> /* */ </b> (/* */)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="96" style="display: none"><p class="balao">
 Esse comando é usado para fazer um comentário no código, ou seja, um trecho de código que serve como anotação e é ignorado pelo Arduino.<br>
<br><b> Ex.:</b><br>
  // Isso e um exemplo de comentario de uma unica linha<br>
<br><b>Ex2.:</b><br>
  /* Isso e<br>
   um comentario <br>
  que pode ter <br>
  varias linhas */<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(100)"><li><code><b>DESLIGADO </b> (LOW)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="100" style="display: none"><p class="balao"> - Estado desligado, sem voltagem.<br>
<br><b> Ex.:</b><br>
  numero pino = 7;<br>
  Modulo numeroLongo duracao;<br>
<br>
  configuracao(){<br>
   definirModo(pino, ENTRADA);<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   duracao = pulsoEm(pino, DESLIGADO);<br>
   USB.enviarln(duracao);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(102)"><li><code><b>DESLIGANDO </b> (FALLING)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="102" style="display: none"><p class="balao"> - Usada junto ao conjunto de instruções do interruptor para quando o Pino sai do estado LIGADO para DESLIGADO.<br>
<br><b> Ex.:</b> <br>
  conectarInterruptor(7, ISR, DESLIGANDO);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(103)"><li><code><b>DIREITO </b> (LSBFIRST)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="103" style="display: none"><p class="balao"> - Essa constante é argumento da função enviarBinario e define que a ordem de envio dos bits a partir do Bit Menos Significativo, ou seja, o bit mais à direita do byte.<br>
<br><b> Ex.:</b><br>
  numero latPin = 8;<br>
  numero cloPin = 12;<br>
  numero dataPin = 11;<br>
<br>
  configuracao() {<br>
   definirModo(latPin, SAIDA);<br>
   definirModo(cloPin, SAIDA);<br>
   definirModo(dataPin, SAIDA);<br>
  }<br>
  principal() {<br>
   para (int j = 0; j < 256; j++) {<br>
    escreverDigital(latPin, DESLIGADO);<br>
    enviarbinario(dataPin, clockPin, DIREITO, j);<br>
    escreverDigital(latPin, LIGADO);<br>
    esperar(1000);<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(97)"><li><code><b>ENTRADA </b> (INPUT)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="97" style="display: none"><p class="balao"> - Parâmetro que indica entrada, que recebe energia do meio externo. Usado junto ao comando definirModo().<br>
<br><b> Ex.:</b><br>
  numero pinoLED = 13; <br>
  numero botao = 7;<br>
<br>
  configuracao() {<br>
   definirModo(pinoLED, SAIDA); <br>
   definirModo(botao, ENTRADA); <br>
  }<br>
  principal() {<br>
   se(lerDigital(botao) == LIGADO){ <br>
    ligar(pinoLED);<br>
    esperar(1000);<br>
   }<br>
   desligar(pinoLED);<br>
  }<br></p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(201)"><li><code><b>ENTRADA_PULLUP </b> (INPUT_PULLUP)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="201" style="display: none"><p class="balao"> - Parâmetro que indica entrada, que recebe energia do meio externo, acionando o resistor pullup interno de sua placa. Isso funciona como um filtro evitando leituras equivocadas.<br>
<br><b> Ex.:</b><br>
  numero pinoLED = 13; <br>
  numero botao = 7;<br>
<br>
  configuracao() {<br>
   definirModo(pinoLED, SAIDA); <br>
   definirModo(botao, ENTRADA_PULLUP); <br>
  }<br>
  principal() {<br>
   se(lerDigital(botao) == LIGADO){ <br>
    ligar(pinoLED);<br>
    esperar(1000);<br>
   }<br>
   desligar(pinoLED);<br>
  }<br></p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(200)"><li><code><b>ENTRADA_PULLDOWN </b> (INPUT_PULLDOWN)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="200" style="display: none"><p class="balao"> - Parâmetro que indica entrada, que recebe energia do meio externo, acionando o resistor pulldown interno de sua placa. Isso funciona como um filtro evitando leituras equivocadas.<br>
<br><b> Ex.:</b><br>
  numero pinoLED = 13; <br>
  numero botao = 7;<br>
<br>
  configuracao() {<br>
   definirModo(pinoLED, SAIDA); <br>
   definirModo(botao, ENTRADA_PULLDOWN); <br>
  }<br>
  principal() {<br>
   se(lerDigital(botao) == DESLIGADO){ <br>
    ligar(pinoLED);<br>
    esperar(1000);<br>
   }<br>
   desligar(pinoLED);<br>
  }<br></p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(104)"><li><code><b>ESQUERDO </b> (MSBFIRST)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="104" style="display: none"><p class="balao"> - Essa constante é argumento da função enviarBinario e define que a ordem de envio dos bits a partir do Bit Mais Significativo, ou seja, o bit mais à esquerda do byte.<br>
<br><b> Ex.:</b> <br>
  numero laitPin = 8;<br>
  numero cloPin = 12;<br>
  numero dataPin = 11;<br>
<br>
  configuracao() {<br>
   definirModo(latPin, SAIDA);<br>
   definirModo(cloPin, SAIDA);<br>
   definirModo(dataPin, SAIDA);<br>
  }<br>
<br>
  principal() {<br>
   para (int j = 0; j < 256; j++) {<br>
    escreverDigital(laitPin, DESLIGADO);<br>
    enviarbinario(dataPin, clockPin, ESQUERDO, j);<br>
    escreverDigital(laitPin, LIGADO);<br>
    esperar(3000);<br>
   }<br>
<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(94)"><li><code><b>FALSO </b> (False)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="94" style="display: none"><p class="balao">
 Condição booleana de falso, 0.<br>
<br><b> Ex.:</b><br>
  numero botao = 9;<br>
<br>
  configuracao() {<br>
   definirModo(botao, SAIDA);<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   se((lerDigital(botao)==DESLIGADO) == Falso){<br>
    USB.enviarln(“ligado”);<br>
    esperar(500);<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(99)"><li><code><b>LIGADO </b> (HIGH)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="99" style="display: none"><p class="balao"> - Parâmetro de estado, LIGADO. Informa que há voltagem.<br>
<br><b> Ex.:</b><br>
  numero pino = 7;<br>
  Modulo numeroLongo duracao;<br>
<br>
  configuracao() {<br>
   definirModo(pino, ENTRADA);<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   duracao = pulsoEm(pino, LIGADO);<br>
   USB.enviarln(duracao);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(101)"><li><code><b>LIGANDO </b> (RISING)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="101" style="display: none"><p class="balao"> - Usada junto ao conjunto de instruções do interruptor para quando o Pino sai do estado DESLIGADO para LIGADO.<br>
<br><b> Ex.:</b><br>
  conectarInterruptor(13, ISR, LIGANDO);<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(16)"><li><code><b>usar <biblioteca> </b> (#include <biblioteca.h>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="16" style="display: none"><p class="balao">
 Comando utilizado para adicionar uma biblioteca ao código. Necessita de um parâmetro, que é nome da variável a ser acrescentada ao programa.<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverAngulo(180);<br>
   esperar(1000);<br>
   meuServo.escreverAngulo(0);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(95)"><li><code><b>responder </b> (return)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="95" style="display: none"><p class="balao">
 Finaliza a função em que este comando está inserido e retorna um dado para a função que a chamou.<br>
<br><b> Ex.:</b><br>
responder 0;<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(98)"><li><code><b>SAIDA </b> (OUTPUT)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="98" style="display: none"><p class="balao"> - Parâmetro que indica Saída, que emite energia. Usado junto ao definirModo();<br>
<br><b> Ex.:</b><br>
 numero pinoLED = 13; <br>
<br>
  configuracao() {<br>
   definirModo(pinoLED, SAIDA); <br>
  }<br>
  principal() {<br>
   ligar(pinoLED);<br>
   esperar(1000);<br>
   desligar(pinoLED);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(93)"><li><code><b>VERDADEIRO </b> (True)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="93" style="display: none"><p class="balao">
 Definido como uma variável com valor não nulo, geralmente representado pelo número 1.<br>
<br><b> Ex.:</b><br>
  numero botao = 9;<br>
<br>
  configuracao() {<br>
   definirModo(botao, SAIDA);<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   se((lerDigital(botao)==LIGADO) == VERDADEIRO){<br>
    USB.enviarln(“ligado”);<br>
    esperar(500);<br>
   }<br>
  }<br>
</p></div>
<!-- --------------- Porta --------------- -->
<h2 class="tituloH2">Porta:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(34)"><li><code><b>Pinos analógicos:</b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="34" style="display: none"><p class="balao">
 São os pinos com o nome ANALOG IN.Possuem uma letra ‘A’ na frente de cada número. Esses pinos são usados para leitura de sinais analógicos de sensores conectados ao Arduino, e podem ser de quaisquer valores entre 0 a 5 volts. Os pinos analógicos não precisam ser previamente configurados com a função definirModo( ) vez que esses atuam exclusivamente como entradas.<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(33)"><li><code><b>Pinos digitais: </b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="33" style="display: none"><p class="balao">
 São os pinos marcados com o nome “DIGITAL” ou um ‘D’ logo abaixo. Podem ser configurados pela função definirModo() para detectarem ou transmitirem níveis lógicos digitais (Verdadeiro/Falso, 1/0 ou LIGADO/DESLIGADO).<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(28)"><li><code><b>definirModo(<porta>, <modo>) </b> (pinMode(<porta>, <modo>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="28" style="display: none"><p class="balao">)
 Configura uma porta como uma ENTRADA ou SAIDA de dados. Além disso, é possível ativar o resistor pullup e definir, assim, uma ENTRADA_PULLUP. Vale ressaltar que, ao definir uma ENTRADA, o Arduino automaticamente desativará os resistores pullup. <br>
<br><b> Sintaxe:</b><br><br>
  definirModo(pino, modo);<br>
<br>
  -pino: o número do pino cujo modo você deseja configurar<br>
  -modo: ENTRADA, SAIDA ou ENTRADA_PULLUP. <br>
<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   definirModo(13, SAIDA);<br>
  }<br>
<br>
  principal() {<br>
   ligar(13);<br>
   esperar(1000);<br>
   desligar(13);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(32)"><li><code><b>desligar(<porta>) </b> (digitalWrite(<porta>, LOW))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="32" style="display: none"><p class="balao">
 Configura o estado da porta indicada para DESLIGADO. Essa função recebe um parâmetro, o número da porta a ser desligada.<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   definirModo(13, SAIDA); <br>
  }<br>
<br>
  principal() {<br>
   ligar(13); <br>
   esperar(1000); <br>
   desligar(13); <br>
   esperar(1000); <br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(29)"><li><code><b>escreverDigital(<porta>, <LIGADO/DESLIGADO>) </b> (digitalWrite(<porta>, <LIGADO/DESLIGADO>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="29" style="display: none"><p class="balao">
 Grava um valor digital em um pino, ligando-o ou desligando-o. Pode ser usado para acender ou apagar um LED.<br>
<br><b> Sintaxe:</b><br>
<br>
  escreverDigital(pino, valor);<br>
<br>
  -pino: o número do pino<br>
  -valor: LIGADO ou DESLIGADO<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   definirModo(13, SAIDA);<br>
  }<br>
<br>
  principal() {<br>
   escreverDigital(13, LIGADO);<br>
   esperar(3000);<br>
   escreverDigital(13, DESLIGADO);<br>
   esperar(3000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(30)"><li><code><b>escreverAnalogico(<porta>, <valor>) </b> (analogWrite(<porta>, <valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="30" style="display: none"><p class="balao">
 Grava um valor analógico (onda PWM) em um pino. Pode ser usado para acender um LED em diferentes intensidades ou para variar a velocidade de motores.<br>
<br><b> Sintaxe:</b><br>
  escreverAnalogico(pino, valor);<br>
<br>
  pino: o pino para escrever. Tipos de dados permitidos: numero<br>
  valor: numero inteiro entre 0 (sempre desligado) e 255 (sempre ligado)<br>
<br><b> Ex.:</b><br>
  numero PinoLED = 9;<br>
  numero PinoAnalog = 0;<br>
  numero valor = 0;<br>
<br>
  configuracao() {<br>
   definirModo(PinoLED, SAIDA); <br>
  }<br>
<br>
  principal() {<br>
   valor = lerAnalogico(PinoAnalog);<br>
   escreverAnalogico(PinoLED, valor / 4);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(105)"><li><code><b>lerDigital(<porta>) </b> (digitalRead(<porta>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="105" style="display: none"><p class="balao">
 Faz a leitura do valor de uma porta determinada retornando LIGADO ou DESLIGADO.<br>
<br><b> Ex.:</b><br>
  numero LED = 13;<br>
  numero Botao = 7;<br>
  numero estado = 7;<br>
  configuracao() {<br>
   definirModo(LED, SAIDA);<br>
   definirModo(Botao, ENTRADA);<br>
  }<br>
<br>
  principal() {<br>
   estado = lerDigital(Botao);<br>
   Escreve(LED, estado);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(106)"><li><code><b>lerAnalogico(<porta>) </b> (analogRead(<porta>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="106" style="display: none"><p class="balao">
 Faz a leitura do valor de uma porta analógica determinada retornando um valor inteiro entre 0 e 1023, referente a tensão de entrada.<br>
<br><b> Ex.:</b><br>
  numero LDR = 7;<br>
  numero leitura = 0;<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   leitura = lerAnalogico(LDR);<br>
   USB.enviarln(leitura);<br>
   esperar(500);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(31)"><li><code><b>ligar(<porta>) </b> (digitalWrite(<porta>, HIGH))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="31" style="display: none"><p class="balao">
 Configura o estado da porta indicada para LIGADO. Essa função recebe um parâmetro, o número da porta a ser ligada.<br>
<br><b> Ex.:</b><br>
  numero LED = 13;<br>
  configuracao() {<br>
   definirModo(LED, SAIDA);<br>
  }<br>
<br>
  principal() {<br>
   ligar(LED);<br>
   esperar(3000);<br>
   desligar(LED);<br>
   esperar(3000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(36)"><li><code><b>pulsoEm(<Porta>, <valor>, <tempoLimite>) </b> (pulseIn(<Porta>, <valor>, <temoiLimite>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="36" style="display: none"><p class="balao">
 Essa função lê um pulso(LIGADO ou DESLIGADO) em um pino. Por exemplo, se o parâmetro do seu pulsoEm() é LIGADO, a função irá aguardar o estado da porta ser LIGADO, quando isso ocorrer, iniciará a contagem do tempo e ,então, aguardará até que o estado do pino seja DESLIGADO, finalizando a contagem. A função retorna o comprimento o pulso em microssegundos. Vale ressaltar que esta função retorna 0 caso nenhum pulso ocorra dentro do intervalo estabelecido.<br>
<br><b> Sintaxe:</b><br>
  pulsoEm(pino, valor);<br>
  pulsoEm(pino, valor, tempoLimite);<br>
<br>
   -pino: o número do pino no qual você deseja ler o pulso. (numero)<br>
   -valor: tipo de pulso a ler: LIGADO ou DESLIGADO.<br>
   -tempoLimite (opcional): o número de microssegundos para aguardar o pulso para iniciar; O padrão é um segundo (Modulo numeroLongo).<br>
<br><b> Ex.:</b><br>
  numero pino = 7;<br>
  Modulo numeroLongo duracao;<br>
<br>
  configuracao() {<br>
   definirModo(pino, ENTRADA);<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   duracao = pulsoEm(pino, LIGADO);<br>
   USB.enviarln(duracao);<br>
   esperar(1000);<br>
   esperar(duracao);<br>
  } <br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(199)"><li><code><b>Valores analógicos :</b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="199" style="display: none"><p class="balao">
 São aquelas que, ao contrário das grandezas digitais, variam continuamente dentro de uma faixa de valores. O velocímetro de um carro, por exemplo, pode ser considerado analógico, pois o ponteiro gira continuamente conforme o automóvel acelera ou trava. Se o ponteiro girasse em saltos, o velocímetro seria considerado digital.(https://www.arduinoportugal.pt/grandezas-digitais-e-analogicas-e-pwm/)<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(35)"><li><code><b>Valores digitais :</b></code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="35" style="display: none"><p class="balao">
 são aquelas que não variam continuamente no tempo, mas sim em saltos entre valores bem definidos. Um exemplo são os relógios digitais: apesar do tempo em si variar continuamente, o visor do relógio mostra o tempo em saltos de um em um segundo. Um relógio desse tipo nunca mostrará 12,5 segundos, pois, para ele, só existem 12 e 13 segundos. Qualquer valor intermediário não está definido. (https://www.arduinoportugal.pt/grandezas-digitais-e-analogicas-e-pwm/)<br>
</p></div>
<!-- --------------- SERVO --------------- -->
<h2 class="tituloH2">Servo:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(55)"><li><code><b>Servo <nomeServo> </b> (Servo <nomeServo>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="55" style="display: none"><p class="balao">
 Cria o objeto servo para ser utilizado.<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverAngulo(180);<br>
   esperar(1000);<br>
   meuServo.escreverAngulo(0);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(56)"><li><code><b><nomeServo>.conectar (Digital.<porta>) </b> (<nomeServo>.attach (<porta>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="56" style="display: none"><p class="balao">
 Esse comando é utilizado para o controle de servo motores. Ele necessita uma porta que indica em que porta digital o sinal do servo motor está conectado <nomeServo>.conectar(Digital.<porta>) Outra maneira de utilizar o comando inclui mais dois parâmetros <nomeServo>.conectar(Digital.<porta>, <val>). Onde <val> é o valor do sinal, que possui dois padrões: mínimo padrão (544) e o máximo padrão (2400).<br>
<br><b> Sintaxe:</b><br>
  servo.conectar(pin) <br>
  servo.conectar(pin, min, max)<br>
<br>
  -servo: uma variável de tipo Servo<br>
  -pino: o número do pino no qual o servo está ligado<br>
  -min (opcional): a largura do pulso, em microssegundos, correspondente ao ângulo mínimo (0 graus) no servo (padrão para 544)<br>
  -max (opcional): a largura do pulso, em microssegundos, correspondente ao ângulo máximo (180 graus) no servo (padrão para 2400).<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverAngulo(180);<br>
   esperar(1000);<br>
   meuServo.escreverAngulo(0);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(207)"><li><code><b><nomeServo>.conectarServo (<porta>) </b> (<nomeServo>.attach (<porta>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="207" style="display: none"><p class="balao">
 Esse comando é utilizado para o controle de servo motores e possui a mesma funçao que o <nomeServo>.conectar seguindo uma sintaxe um pouco diferente. Ele necessita uma porta que indica em que porta digital o sinal do servo motor está conectado <nomeServo>.conectarServo(<porta>). Outra maneira de utilizar o comando inclui mais dois parâmetros <nomeServo>.conectarServo(<porta>, <val>). Onde <val> é o valor do sinal, que possui dois padrões: mínimo padrão (544) e o máximo padrão (2400).<br>
<br><b> Sintaxe:</b><br>
  servo.conectarServo(pin) <br>
  servo.conectarServo(pin, min, max)<br>
<br>
  -servo: uma variável de tipo Servo<br>
  -pino: o número do pino no qual o servo está ligado<br>
  -min (opcional): a largura do pulso, em microssegundos, correspondente ao ângulo mínimo (0 graus) no servo (padrão para 544)<br>
  -max (opcional): a largura do pulso, em microssegundos, correspondente ao ângulo máximo (180 graus) no servo (padrão para 2400).<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectarServo(5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverAngulo(180);<br>
   esperar(1000);<br>
   meuServo.escreverAngulo(0);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(57)"><li><code><b><nomeServo>.escreverAngulo(<angulo>) </b> (<nomeServo>.write(<angulo>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="57" style="display: none"><p class="balao">
 Envia um sinal ao Servo, controlando o eixo do motor de acordo com ele. Em servos de rotação limitada, esse valor representa o ângulo (em graus) da posição para que o eixo deve ir. Em servos de rotação contínua, esse parâmetro representa a velocidade de rotação, sendo 0 a velocidade máxima de um sentido de rotação, 90 o parâmetro de velocidade nula e 180 o valor máximo de velocidade no sentido oposto.<br>
<br><b> Sintaxe:</b><br>
  servo.escreverAngulo(angulo);<br>
<br>
  -servo: uma variável de tipo Servo<br>
  -ângulo: o valor a ser gravado no servo, de 0 a 180<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverAngulo(180);<br>
   esperar(1000);<br>
   meuServo.escreverAngulo(0);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(58)"><li><code><b><nomeServo>.escreverMicros(<valor>) </b> (writeMicroseconds(<valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="58" style="display: none"><p class="balao">
 Envia um valor em microssegundos para o Servo Motor, controlando seu eixo de rotação de acordo com o sinal enviado. O parâmetro correto geralmente varia entre 1000 e 2000, sendo o primeiro a rotação completa no sentido horário e o segundo a rotação completa no sentido anti-horário. 1500 é o parâmetro que representa a metade do intervalo, e, logo, da rotação.<br>
 Note que alguns fabricantes não seguem o intervalo padrão supracitado, mas normalmente seguem a regra de trabalhar com valores entre 700 e 2300. Busque encontrar os parâmetros limites de seu componente com cuidado, pois forçar o motor a rotacionar além do máximo permitido pelo eixo resulta em situações de alta corrente, que devem ser evitadas.<br>
 Servos de rotação contínua respondem a esta função de forma análoga ao comando escreverAngulo().<br>
<br><b> Sintaxe:</b><br>
<br>
  servo.escreverMicros(uS);<br>
  -servo: uma variável de tipo Servo<br>
  -uS: o valor do parâmetro em microssegundos(numero).<br>
<br><b> Ex.:</b><br>
  usar Servo <br>
<br>
  Servo MeuServo;<br>
<br>
  Configuacao() { <br>
   MeuServo.conectar(Digital.9);<br>
   MeuServo.escreverMicros(1500); <br>
  } <br>
<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(59)"><li><code><b>SERVOFRENTE</b> (1700)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="59" style="display: none"><p class="balao">
 Constante para o controle do servo de rotação contínua que indica ao servo para rodar para frente. É equivalente à um numero com valor de 1700.<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverMicros(SERVOFRENTE);<br>
   esperar(1000);<br>
   meuServo.escreverMicros(SERVOPARAR);<br>
   esperar(1000);<br>
   meuServo.escreverMicros(SERVOTRAS);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(60)"><li><code><b>SERVOPARAR </b> (1500)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="60" style="display: none"><p class="balao">
 Constante para o controle do servo de rotação contínua que indica ao servo para parar de rodar. É equivalente à um numero com valor de 1500.<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverMicros(SERVOFRENTE);<br>
   esperar(1000);<br>
   meuServo.escreverMicros(SERVOPARAR);<br>
   esperar(1000);<br>
   meuServo.escreverMicros(SERVOTRAS);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(61)"><li><code><b>SERVOTRAS </b> (1300) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="61" style="display: none"><p class="balao">
 Constante para o controle do servo de rotação contínua que indica ao servo para rodar para trás. É equivalente à um numero com valor de 1300.<br>
<br><b> Ex.:</b><br>
  usar Servo<br>
<br>
  Servo meuServo;<br>
<br>
  configuracao() {<br>
   meuServo.conectar(digital.5);<br>
  }<br>
  principal() {<br>
   meuServo.escreverMicros(SERVOFRENTE);<br>
   esperar(1000);<br>
   meuServo.escreverMicros(SERVOPARAR);<br>
   esperar(1000);<br>
   meuServo.escreverMicros(SERVOTRAS);<br>
   esperar(1000);<br>
  }<br>
</p></div>
<!-- --------------- TIPOS DE DADOS --------------- -->
<h2 class="tituloH2">Tipos de dados</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(7)"><li><code><b>condicao <nome_variavel></b> (boolean <nome_variavel>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="7" style="display: none"><p class="balao">
 Cria uma variável que é usada para guardar apenas dois valores, Verdadeiro ou Falso, e é muito usada em operações lógicas e controle.<br>
<br><b> Ex.:</b><br>
  condicao chovendo = Verdadeiro;<br>
  condicao sol = Falso<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(1)"><li><code><b>numero <nome_variavel></b> (int <nome_variavel>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul> <div id="1" style="display: none"><p class="balao">
 As variáveis do tipo numero (deve ser escrito dessa forma para ser entendido pelo compilador, sem acento e com letra maiúscula.) são muito usadas pois são capazes de, como o próprio nome sugere, armazenar números inteiros entre -32.768 a 32.767, ou seja, um número de 16 bits.<br>
<br><b> Sintaxe:</b><br>
  numero var = valor <br>
  numero - tipo de variável<br>
  var - o nome da sua variável;<br>
  valor - o valor associado ao nome;<br>
<br><b> Ex.:</b><br>
  numero pinoLED = 13;<br>
<br>
  configuracao() {<br>
   definirModo(pinoLED, SAIDA);<br>
  }<br>
  principal() {<br>
   ligar(PinoLED);<br>
   esperar(1000);<br>
   desligar(PinoLED);<br>
   esperar(1000);<br>
  }<br><br>
<b> Obs.:</b> Quando as variáveis numero excedem sua capacidade máxima ou mínima, elas transbordam, ou seja, o resultado é imprevisível, devendo ser evitado.
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(5)"><li><code><b>letra <nome_variavel> </b>(char <nome_variavel>)</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="5" style="display: none"><p class="balao">
 Essa variável armazena um caractere ASCII (Tabela de conversão de caracteres para números, permitindo que o Arduino as armazene), ou seja, ela é capaz de armazenar qualquer caractere (a, A, 1, &, entre outros). Operações aritméticas podem ser aplicadas sobre esses dados, porém ela será executada com base na tabela ASCII. Seu dado deve vir entre aspas simples (‘ ‘).<br>
<br><b> Ex.:</b><br>
  letra minhaLetra = 'A';<br>
  letra minhaLetra = 65; // ambas atribuições são equivalentes<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(2)"><li><code><b>numeroDecimal <nome_variavel></b> (float <nome_variavel>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="2" style="display: none"><p class="balao">
 Esse tipo de variável é capaz de armazenar números de até 32 bits com um ponto decimal. A matemática com o numeroDecimal é muito mais lenta do que a matemática com numero, na realização de cálculos, por isso, a maioria dos programadores a evita.<br>
<br> <b>Sintaxe:</b><br>
  numeroDecimal var = valor<br>
  numeroDecimal - tipo de variável<br>
  var - o nome da sua variável numeroDecimal;<br>
  valor - o valor associado ao nome;<br>
<br><b> Ex.:</b><br>
  numeroDecimal divisao;<br>
  numeroDecimal calibracaoSensor = 1.117;<br>
<br>
  numero x;<br>
  numero y;<br>
  numeroDecimal z;<br>
<br>
  x = 1;<br>
  y = x / 2; // y contem 0, variáveis do tipo numeros sao incapazes de guardar casas decimais<br>
  z = (numeroDecimal)x / 2.0; // z contem 0.5 (voce devera usar 2.0 , e nao 2);<br>
<br>
<b> Obs.:</b> Se estiver fazendo cálculos com o numeroDecimal, adicione um ponto decimal, caso contrário, ele será tratado como um numero.<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(3)"><li><code><b>numeroLongo <nome_variavel></b> (long <nome_variavel>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="3" style="display: none"><p class="balao">
 Variável utilizada para valores longos, de até 32 bits, podendo variar entre -2,147,483,648 e 2,147,483,647. <br>
<br> <b>Sintaxe:</b><br>
  numeroLongo variav = val<br>
  variav - o nome da sua variável numeroLongo;<br>
  val - o valor associado ao nome.<br>
<br><b> Ex.:</b><br>
  numeroLongo Y = 1050690;
<br><br>
<b> Obs.:</b> Se estiver fazendo matemática com números inteiros, pelo menos um dos números deve ser seguido por um L, forçando-o a ser longo.<br>
<br><b> Ex2.:</b><br>
  numeroLongo VelLuz = 186000L;<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(4)"><li><code><b>numeroLongo numeroLongo <nome_variavel></b> (long long <nome_variavel>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="4" style="display: none"><p class="balao">
 Variável utilizada para valores muito longos, de até 64 bits.<br>
<br><b> Ex.:</b><br>
  numeroLongo numeroLongo Y = 9223372036854775807;
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(6)"><li><code><b>Palavra <nome_variavel></b> (String <nome_variavel>) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="6" style="display: none"><p class="balao">
 Esse tipo especial de variável pode ser comparado a uma série de caracteres. Ela é usada para armazenar palavras e frases. Seu dado deve vir entre aspas duplas (“ ”).
<br><b> Sintaxe:</b><br>
  Todas as seguintes são declarações válidas para Palavra:<br>
  letra Palavra1[15];<br>
  letra Palavra2[6] = {'b', 'r', 'i', 'n', 'o'};<br>
  letra Palavra3[6] = {'b', 'r', 'i', 'n', 'o', '\0'};<br>
  letra Palavra4[ ] = "brino";<br>
  letra Palavra5[6] = "brino";<br>
  letra Palavra6[15] = "brino";<br>
 * Possibilidades de declarar Palavras:<br>
  - Declare uma série de caracteres sem inicializar como no Palavra1;<br>
  - Declare uma série de caracteres (com espaço para um caractere adicional) e o compilador adicionará o caractere nulo necessário, como em Palavra2;<br>
  - Adicione explicitamente o caractere nulo, Palavra3;<br>
  - Inicialize com uma Palavra constante entre aspas; o compilador dimensionará a matriz para ajustar a constante de Palavra e um caractere nulo de término, Palavra4;<br>
  - Inicialize a matriz com um tamanho explícito e constante de Palavra, Palavra5;<br>
  - Inicialize a matriz, deixando espaço extra para uma Palavra maior, Palavra6.<br>
<br><b> Ex.:</b><br>
  letra* minhasPalavras[] = {"Essa e a palavra 1", "Essa e a palavra 2", "Essa e a palavra 3", "Essa e a palavra 4", "Essa e a palavra 5","Essa e a palavra 6"};<br>
<br>
  configuracao(){<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal(){<br>
   para (numero i = 0; i < 6; i++){<br>
    USB.enviarln(minhasPalavras[i]);<br>
    esperar(500);<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(8)"><li><code><b>semRetorno</b> (void) </code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="8" style="display: none"><p class="balao">
 É um tipo de função vazia, utilizado para funções que não se espera resposta.<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
  principal() {<br>
   minhaFuncao();<br>
   esperar(1000);<br>
  }<br>
  semRetorno minhaFuncao(){<br>
   USB.enviarln(“oi”);<br>
  }<br>
</p></div>
<!-- --------------- USB --------------- -->
<h2 class="tituloH2">USB:</h2>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(22)"><li><code><b>USB.conectar</b>(<velocidade>) (Serial.begin(<velocidade>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="22" style="display: none"><p class="balao">
 Configura a velocidade da comunicação Serial em bits por segundo (baud). Para comunicação com o computador o mais usado é 9600 e ele aceita valores como: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800 e 38400. Para outras comunicações, como a com componentes com as portas digitais, velocidades específicas podem ser definidas. Esse comando ainda aceita um segundo comando de configuração (config) que define dados, paridade e bits de parada. Os valores do segundo parámetro podem ser: SERIAL_5N1, SERIAL_6N1, SERIAL_7N1, SERIAL_8N1 (padrão), SERIAL_5N2, SERIAL_6N2, SERIAL_7N2, SERIAL_8N2, SERIAL_5E1, SERIAL_6E1, SERIAL_7E1, SERIAL_8E1, SERIAL_5E2, SERIAL_6E2, SERIAL_7E2, SERIAL_8E2, SERIAL_5O1, SERIAL_6O1, SERIAL_7O1, SERIAL_8O1, SERIAL_5O2, SERIAL_6O2, SERIAL_7O2 e SERIAL_8O2.<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   USB.enviar(“Oi!”);<br>
  }<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(27)"><li><code><b>USB.descarregar() </b> (Serial.flush())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="27" style="display: none"><p class="balao">
 Espera a transmissão serial acabar<br>
<br><b> Ex.:</b><br>
  USB.descarregar();<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(25)"><li><code><b>USB.disponivel() </b> (Serial.available())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="25" style="display: none"><p class="balao">
 Obtém o número de bytes (caracteres) disponíveis para leitura a partir da porta serial. Este é o dado que já é armazenado no buffer de recebimento em série (que contém 64 bytes).<br>
<br><b> Ex.:</b><br>
  numero ByteRecebido = 0;<br>
<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   se (USB.disponivel() > 0) {<br>
    ByteRecebido = USB.ler();<br>
    USB.enviar("Eu recebi: ");<br>
    USB.enviarln(ByteRecebido, DEC);<br>
   }<br>
  }<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(23)"><li><code><b>USB.enviar</b>(<valor>) (Serial.print(<valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="23" style="display: none"><p class="balao">
 Usado para enviar algum dado pela porta Serial. Aceita um segundo argumento opcional que define o formato desejado. Ele pode ser: BIN, OCT, HEX ou DEC. Essa função também retorna o número de bytes escritos, podendo esse valor ser usado ou não. Vale a pena lembrar que para escrever um texto na tela ele deve estar entre aspas (“”).<br>
<br> <b>Sintaxe:</b><br>
  USB.enviar(valor);<br>
  USB.enviar(valor, formato);<br>
<br>
  -valor: o valor a imprimir - qualquer tipo de dado;<br>
  -formato: especifica a base de números (para tipos de dados integrados) ou o número de casas decimais;<br>
<br><b> Ex.:</b> <br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   USB.enviar(“Isso vai aparecer no Monitor Serial”);<br>
  }<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(206)"><li><code><b>USB.escrever</b>(<valor>) (Serial.write(<valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="206" style="display: none"><p class="balao">
 Usado para enviar dados pela porta Serial em forma binária, sendo esses enviados na forma de um byte ou de uma série de bytes. Essa função retorna o número de bytes escritos, podendo esse valor ser usado ou não.<br>
<br> <b>Sintaxe:</b><br>
  USB.escrever(valor);<br>
  USB.escrever(palavra);<br>
  USB.escrever(palavra, comprimento);<br>
<br>
  -valor: o valor a ser enviado;<br>
  -palavra: palavra (string) ou sequencia de dados a ser enviado;<br>
  -comprimento: o número de bytes da palavra a ser enviado;<br>
<br><b> Ex.:</b> <br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   USB.escrever(45); // envia um byte com valor 45 (0b101101)<br>
   Numero enviados = USB.escrever("Ola"); // envia uma palavra "Ola e registra na variavel enviados a quantidade de bytes enviados<br>
  }<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(24)"><li><code><b>USB.enviarln(<valor>) </b>(Serial.println(<valor>))</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="24" style="display: none"><p class="balao">
 Usado para enviar algum dado pela porta Serial e em seguida quebrar a linha. Aceita um segundo argumento opcional que define o formato desejado. Ele pode ser: BIN, OCT, HEX ou DEC. Essa função também retorna o número de bytes escritos, podendo esse valor ser usado ou não. Vale a pena lembrar que para escrever um texto na tela ele deve estar entre aspas (“ ”).<br>
<br> <b>Sintaxe:</b><br>
  USB.enviar(valor);<br>
  USB.enviar(valor, formato);<br>
<br>
  valor: o valor a imprimir - qualquer tipo de dado;<br>
  formato: especifica a base de números (para tipos de dados integrados) ou o número de casas decimais;<br>
<br><b> Ex.:</b><br>
  configuracao() {<br>
   USB.conectar(9600);<br>
   USB.enviarln(“Isso vai aparecer no Monitor Serial e em seguida quebrara a linhal”);<br>
  }<br>
  principal() {}<br>
</p></div>
<ul style="cursor:pointer;" class="descricoes" id="girar" onclick="mudar(26)"><li><code><b>USB.ler() </b> (Serial.read())</code><img src='Imagens/setaDown.png' width='15px' style='position: relative; top: 4px;'/></li></ul><div id="26" style="display: none"><p class="balao">
 Retorna um inteiro com um byte das informações acessíveis na comunicação Serial ou -1 caso não tenha dados disponíveis.<br>
<br><b> Ex.:</b><br>
  dados = USB.ler();<br>
<br><b> Ex2.:</b><br>
  numero dado = 0;<br>
  configuracao() {<br>
   USB.conectar(9600);<br>
  }<br>
<br>
  principal() {<br>
   se (USB.disponivel() > 0) {<br>
    // Le o dado recebido e armazena na variavel<br>
    dado = USB.ler();<br>
    // Mostrar dado recebido<br>
    USB.enviar("Recebido: ");<br>
    USB.enviarln(dado, DEC);<br>
   }<br>
  }<br>
</p></div>
<!-- ********* FIM DICIONARIO ********* -->
<style>
@font-face {
font-family: Coolvetica;
src: url(Coolvetica.ttf);
font-display: swap;
}
@font-face {
font-family: Lato;
src: url(Lato.ttf);
font-display: swap;
}
h1, h2, h3, h4{
font-family: Coolvetica;
font-size: 3em;
}
p, input, li, textarea, ol, spam, table, th, tr, header{
font-family: Lato;
font-size: 1em;
}
h2.tituloH2{
margin: 0;
padding-top: 3vw;
padding-bottom: 3vw;
padding-left: 10%;
width: 90%;
background-color: #38b54f;
color: #efefef;
}
p.balao{
padding-left: 10%;
padding-right: 10%;
padding-top: 2%;
padding-bottom: 2%;
/* background-color: #efefef; */
background: linear-gradient(#e4e4e4, #e4e4e4, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #efefef, #e4e4e4, #e4e4e4);
/* Espessura contorno e cor
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
Raio vertices
-webkit-border-radius:7px 7px 7px 7px;*/
}
ul.descricoes{
margin-left: 12%;
margin-right: 12%;
font-size: 1.5em;
}
@media screen and (max-width: 850px) {
h2.tituloH2{
padding-left: 0%;
width: 100%;
text-align: center;
}
p.balao{
margin-left: 5%;
margin-right: 5%;
}
ul.descricoes{
margin-left: 3%;
margin-right: 3%;
}
}
</style>
</body>
<!-- ********* rodapeh ********* -->
<footer align="left">
<?php include "rodape.php"?>
</footer>
<!-- fim do rodapeh -->
<meta name="description" content="">
</html>
<file_sep>/MulheresInspiradoras.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mulheres Inspiradoras</title>
</head>
<meta http-equiv="refresh" content=1;url="https://redeglobo.globo.com//video/rep-historias-de-classe-gina-vieira-criou-projeto-sobre-mulheres-inspiradoras-6240744.ghtml">
<body>
</body>
</html>
|
ea42e07b001bddeac691ea3700ec6ce0964a266d
|
[
"Hack",
"PHP"
] | 34 |
Hack
|
BrinoOficial/Site
|
ec4b6ce79dad58556384239172f93908c89e78c2
|
14b4467292397c74fcff75e51a46b875e96d7f4c
|
refs/heads/master
|
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Simply unescaping the markup in this HTML example would not yield a
well-formed XML result. By specifying a <literal>text/html</literal>
<option>content-type</option>, we give the processor the ability to perform
appropriate “fixup” on the markup.</para>
</p:documentation>
<p:pipeinfo><wrapper>
<html>
<title>Some title</title>
<h1>Some title</h1>
<p>This is some<br>
HTML text
<p>It isn't well-formed XML<br>
by any stretch of the imagination
</wrapper></p:pipeinfo>
<p:unescape-markup content-type="text/html"/>
</p:pipeline>
<file_sep>VPATH = ../examples
.SUFFIXES: .xml .xpl
all:
@echo Not supported yet.
.xpl.xml:
calabash -oresult=$@ $<
<file_sep><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://www.w3.org/1999/xhtml"
exclude-result-prefixes="h xs"
version="2.0">
<xsl:key name="id" match="*" use="@id|@name"/>
<xsl:template match="/">
<xsl:variable name="chunks">
<xsl:apply-templates select="h:html" mode="chunk"/>
</xsl:variable>
<xsl:result-document href="/tmp/chunk.xml">
<xsl:sequence select="$chunks"/>
</xsl:result-document>
<xsl:apply-templates select="$chunks/h:chunks"/>
<!--
<xsl:sequence select="$chunks"/>
-->
</xsl:template>
<xsl:template match="h:chunks">
<xsl:apply-templates select="h:chunk"/>
</xsl:template>
<xsl:template match="h:chunk">
<xsl:message>writing: <xsl:value-of select="@fn"/></xsl:message>
<xsl:result-document href="{@fn}">
<xsl:apply-templates select="h:html"/>
</xsl:result-document>
<xsl:apply-templates select="h:chunk"/>
</xsl:template>
<xsl:template match="h:head">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:choose>
<xsl:when test="ancestor::h:chunk[2]">
<link rel="up" href="{ancestor::h:chunk[2]/@fn}" title="Up" />
</xsl:when>
<xsl:otherwise>
<link rel="up" href="/" title="Up" />
</xsl:otherwise>
</xsl:choose>
<link rel="prev" title="Previous" href="{preceding::h:chunk[1]/@fn}"/>
<link rel="next" title="Next" href="{following::h:chunk[1]/@fn}"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="h:a[starts-with(@href,'#')]">
<xsl:variable name="target" select="key('id', substring-after(@href,'#'))"/>
<xsl:variable name="id" select="substring-after(@href, '#')"/>
<xsl:choose>
<xsl:when test="count($target) = 1">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:choose>
<xsl:when test="$target/parent::h:body">
<xsl:attribute name="href" select="$target/ancestor::h:chunk[1]/@fn"/>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="href"
select="concat($target/ancestor::h:chunk[1]/@fn, @href)"/>
</xsl:otherwise>
</xsl:choose>
<xsl:apply-templates/>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:message>Cannot patch link: <xsl:value-of select="@href"/>; <xsl:value-of select="count($target)"/> targets.</xsl:message>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="comment()|processing-instruction()|text()">
<xsl:copy/>
</xsl:template>
<!-- ============================================================ -->
<!-- chunking -->
<xsl:template match="h:html" mode="chunk">
<chunks>
<xsl:apply-templates select="h:body" mode="chunk"/>
</chunks>
</xsl:template>
<xsl:template match="h:body" mode="chunk">
<xsl:apply-templates select="h:article" mode="chunk"/>
</xsl:template>
<xsl:template match="h:article[@class='book' or @class='part' or @class='reference']"
mode="chunk">
<xsl:variable name="class" select="@class"/>
<!--
<xsl:message><xsl:value-of select="@class"/></xsl:message>
-->
<chunk fn="{$class}-{count(preceding::h:article[@class=$class])+1}.html">
<html>
<xsl:copy-of select="/h:html/h:head"/>
<body>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:copy-of select="node() except h:article"/>
</xsl:copy>
</body>
</html>
<xsl:apply-templates select="h:article" mode="chunk"/>
</chunk>
</xsl:template>
<xsl:template match="h:article" mode="chunk">
<xsl:variable name="class" select="@class"/>
<!--
<xsl:message><xsl:value-of select="@class"/></xsl:message>
-->
<chunk fn="{$class}-{count(preceding::h:article[@class=$class])+1}.html">
<html>
<xsl:copy-of select="/h:html/h:head"/>
<body>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:copy-of select="node()"/>
</xsl:copy>
</body>
</html>
</chunk>
</xsl:template>
<!-- ============================================================ -->
</xsl:stylesheet>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <option>wrap-result-lines</option> option can make it
easier for other XML processes to work with the lines of non-XML output.
</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:exec command="/bin/ls" result-is-xml="false" args="-l ../docs"
wrap-result-lines="true">
<p:input port="source">
<p:empty/>
</p:input>
</p:exec>
</p:pipeline>
<file_sep><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:db="http://docbook.org/ns/docbook"
xmlns:t="http://docbook.org/xslt/ns/template"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:deltaxml="http://www.deltaxml.com/ns/well-formed-delta-v1"
exclude-result-prefixes="c db t html deltaxml"
version="2.0">
<xsl:import href="/Volumes/Data/docbook/xslt20/xslt/base/html/docbook.xsl"/>
<xsl:import href="xprocns.xsl"/>
<xsl:import href="rngsyntax.xsl"/>
<xsl:param name="resource.root" select="'../'"/>
<xsl:param name="linenumbering" as="element()*">
<ln path="literallayout" everyNth="0"/>
<ln path="programlisting" everyNth="5" width="3" separator=" " padchar=" " minlines="3"/>
<ln path="programlistingco" everyNth="5" width="3" separator=" " padchar=" " minlines="3"/>
<ln path="screen" everyNth="5" width="3" separator=" " padchar=" " minlines="0"/>
<ln path="synopsis" everyNth="0"/>
<ln path="address" everyNth="0"/>
<ln path="epigraph/literallayout" everyNth="0"/>
</xsl:param>
<xsl:param name="refentry.generate.name" select="0"/>
<xsl:param name="refentry.generate.title" select="1"/>
<!-- ============================================================ -->
<xsl:template match="db:step">
<xsl:call-template name="t:inline-monoseq"/>
</xsl:template>
<xsl:template match="db:port">
<xsl:call-template name="t:inline-monoseq"/>
</xsl:template>
<xsl:template match="db:error">
<xsl:variable name="code" select="@code"/>
<xsl:variable name="num" select="count(preceding::db:error[@code=$code])"/>
<a name="err.inline.{@code}{if ($num>0) then concat('.',$num) else ''}"/>
<xsl:choose>
<xsl:when test="node()">
<xsl:apply-templates/>
</xsl:when>
<xsl:otherwise>
<code>err:<xsl:value-of select="$code"/></code>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="db:glossterm">
<xsl:variable name="term" select="string(.)"/>
<xsl:variable name="anchorterm"
select="if (@baseform) then @baseform else normalize-space($term)"/>
<xsl:next-match/>
<xsl:if test="ancestor::db:error
and ($anchorterm = 'static error' or $anchorterm = 'dynamic error')">
<xsl:variable name="code" select="ancestor::db:error[1]/@code"/>
<xsl:text> (</xsl:text>
<!--
<a href="#err.{$code}">
-->
<code class="errqname">
<xsl:text>err:X</xsl:text>
<xsl:value-of select="ancestor::db:error[1]/@code"/>
</code>
<!--
</a>
-->
<xsl:text>)</xsl:text>
</xsl:if>
</xsl:template>
<xsl:template match="db:refclass"/>
<!-- ============================================================ -->
<xsl:template match="c:prettyprint">
<div class="programlisting">
<pre>
<xsl:apply-templates mode="prettyprint"/>
</pre>
</div>
<xsl:if test="matches(base-uri(.), '^.*/examples/.*\.xpl$')">
<div class="exlink">
<a href="build/xpl/{substring-after(base-uri(.),'examples/')}">
<xsl:text>Download pipeline</xsl:text>
</a>
</div>
</xsl:if>
</xsl:template>
<xsl:template match="c:line" mode="prettyprint">
<span class="line">
<xsl:call-template name="linenumber"/>
<span>
<xsl:copy-of select="@class"/>
<xsl:apply-templates/>
</span>
</span>
</xsl:template>
<!-- ============================================================ -->
<xsl:template match="c:prettyprint[@deltaxml:version]">
<xsl:variable name="orig">
<xsl:apply-templates mode="orig"/>
</xsl:variable>
<xsl:variable name="diff">
<xsl:apply-templates mode="diff"/>
</xsl:variable>
<table class="pipelineexample" cellspacing="0" cellpadding="0">
<tr>
<th>Input</th>
<th>→</th>
<th>Output</th>
</tr>
<tr>
<td valign="top">
<div class="programlisting">
<xsl:apply-templates select="$orig/*"/>
</div>
</td>
<td valign="middle"><span class="arrow"> </span></td>
<td valign="top">
<div class="programlisting">
<xsl:apply-templates select="$diff/*"/>
</div>
</td>
</tr>
</table>
</xsl:template>
<xsl:template match="c:suppress-source">
<xsl:variable name="diff">
<xsl:apply-templates select="c:prettyprint[1]/*" mode="orig"/>
</xsl:variable>
<table class="pipelineexample" cellspacing="0" cellpadding="0">
<tr>
<th>Output</th>
</tr>
<tr>
<td valign="top">
<div class="programlisting">
<xsl:apply-templates select="$diff/*"/>
</div>
</td>
</tr>
</table>
</xsl:template>
<xsl:template match="c:suppress-diff">
<xsl:variable name="orig">
<xsl:apply-templates select="c:prettyprint[1]/*" mode="orig"/>
</xsl:variable>
<xsl:variable name="diff">
<xsl:apply-templates select="c:prettyprint[2]/*" mode="orig"/>
</xsl:variable>
<table class="pipelineexample" cellspacing="0" cellpadding="0">
<tr>
<th>Input</th>
<th>→</th>
<th>Output</th>
</tr>
<tr>
<td valign="top">
<div class="programlisting">
<xsl:apply-templates select="$orig/*"/>
</div>
</td>
<td valign="middle"><span class="arrow"> </span></td>
<td valign="top">
<div class="programlisting">
<xsl:apply-templates select="$diff/*"/>
</div>
</td>
</tr>
</table>
</xsl:template>
<xsl:template match="c:line">
<div class="line">
<xsl:call-template name="linenumber"/>
<span>
<xsl:copy-of select="@class"/>
<xsl:apply-templates/>
</span>
</div>
</xsl:template>
<!-- ============================================================ -->
<xsl:template match="c:line" mode="orig">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:choose>
<xsl:when test="@deltaxml:deltaV2='A!=B'">
<xsl:attribute name="class" select="'diff'"/>
<xsl:apply-templates mode="orig"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates mode="orig"/>
</xsl:otherwise>
</xsl:choose>
</xsl:copy>
</xsl:template>
<xsl:template match="c:line[@deltaxml:deltaV2='B']" mode="orig"/>
<xsl:template match="deltaxml:attributes" mode="orig"/>
<xsl:template match="deltaxml:textGroup" mode="orig">
<xsl:apply-templates select="deltaxml:text[@deltaxml:deltaV2='A']" mode="orig"/>
</xsl:template>
<xsl:template match="deltaxml:textGroup[@deltaxml:deltaV2='B']" mode="orig"/>
<xsl:template match="deltaxml:text" mode="orig">
<xsl:apply-templates mode="orig"/>
</xsl:template>
<xsl:template match="*" mode="orig">
<xsl:if test="not(@deltaxml:deltaV2='B')">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates mode="orig"/>
</xsl:copy>
</xsl:if>
</xsl:template>
<xsl:template match="comment()|processing-instruction()|text()" mode="orig">
<xsl:copy/>
</xsl:template>
<!-- ============================================================ -->
<xsl:template match="c:line" mode="diff">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:choose>
<xsl:when test="@deltaxml:deltaV2='A!=B'">
<xsl:attribute name="class" select="'diff'"/>
<xsl:apply-templates mode="diff"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates mode="diff"/>
</xsl:otherwise>
</xsl:choose>
</xsl:copy>
</xsl:template>
<xsl:template match="c:line[@deltaxml:deltaV2='A']" mode="diff">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="class" select="'del'"/>
<xsl:apply-templates mode="diff"/>
</xsl:copy>
</xsl:template>
<xsl:template match="c:line[@deltaxml:deltaV2='B']" mode="diff">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="class" select="'add'"/>
<xsl:apply-templates mode="diff"/>
</xsl:copy>
</xsl:template>
<xsl:template match="deltaxml:attributes" mode="diff"/>
<xsl:template match="deltaxml:textGroup" mode="diff">
<xsl:apply-templates select="deltaxml:text[@deltaxml:deltaV2='B']" mode="diff"/>
</xsl:template>
<xsl:template match="deltaxml:textGroup[@deltaxml:deltaV2='A']" mode="diff"/>
<xsl:template match="deltaxml:text" mode="diff">
<xsl:apply-templates mode="diff"/>
</xsl:template>
<xsl:template match="*" mode="diff">
<xsl:if test="not(@deltaxml:deltaV2='A')">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates mode="diff"/>
</xsl:copy>
</xsl:if>
</xsl:template>
<xsl:template match="comment()|processing-instruction()|text()" mode="diff">
<xsl:copy/>
</xsl:template>
<!-- ============================================================ -->
<xsl:template name="t:css">
<link rel="stylesheet" type="text/css" href="../css/docbook.css"/>
<link rel="stylesheet" type="text/css" href="../css/pygments.css"/>
<link rel="stylesheet" type="text/css" href="../css/xprocbook.css"/>
</xsl:template>
<xsl:template name="linenumber">
<xsl:variable name="line" select="ancestor-or-self::c:line"/>
<xsl:variable name="plines"
select="$line/preceding-sibling::c:line"/>
<xsl:variable name="num" select="count($plines[not(contains(@class,'del'))])+1"/>
<xsl:choose>
<xsl:when test="contains($line/@class, 'del')">
<span class="linenumber"><xsl:text> </xsl:text></span>
<span class="linenumber-separator"><xsl:text> </xsl:text></span>
</xsl:when>
<xsl:when test="$num = 1 or $num mod 5 = 0">
<span class="linenumber">
<xsl:if test="$num < 10"><xsl:text> </xsl:text></xsl:if>
<xsl:if test="$num < 100"><xsl:text> </xsl:text></xsl:if>
<xsl:value-of select="$num"/>
</span>
<span class="linenumber-separator"><xsl:text> </xsl:text></span>
</xsl:when>
<xsl:otherwise>
<span class="linenumber"><xsl:text> </xsl:text></span>
<span class="linenumber-separator"><xsl:text> </xsl:text></span>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we use a more complex expression to group all
paragraphs except the first.</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<p>Some text.</p>
<pre>Some example pre text.</pre>
<p>Some more text.</p>
<p>Yet even more text.</p>
<p>A third paragraph.</p>
</body>
</html>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This is close to what we want, we're successfully grouping all the
paragraphs except the first, but if the goal was to <emphasis>only</emphasis>
wrap the non-first paragraphs, we're getting extra wrappers.</para>
<para>That's because each “first paragraph” forms its own group where the value
of the <option>group-adjacent</option> option is “<literal>false</literal>”.</para>
</p:documentation>
<p:wrap match="h:p" wrapper="div"
wrapper-namespace="http://www.w3.org/1999/xhtml"
group-adjacent="count(preceding-sibling::h:p) > 1"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In practice, the grammar is rarely “inlined” in the pipeline. In this,
and future examples, we'll simply load it from the filesystem.</para>
</p:documentation>
<p:pipeinfo><doc>
<title>Title</title>
<p>Some paragraph.</p>
</doc></p:pipeinfo>
<p:validate-with-relax-ng>
<p:input port="schema">
<p:document href="../docs/grammar.rng"/>
</p:input>
</p:validate-with-relax-ng>
</p:pipeline>
<file_sep>all: examples index.html
index.html: env.xml cwd.xml info.xml
calabash -isource=reference.xml -oresult=$@ ../../xpl/format.xpl
examples:
make -C results
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>XML Schema output is a PSVI which may include both defaulted attributes
and type information. Here we see a default attribute added to the <tag>div</tag>
element.</para>
</p:documentation>
<p:pipeinfo><doc>
<title>Title</title>
<div>
<p>Some paragraph.</p>
</div>
</doc></p:pipeinfo>
<p:validate-with-xml-schema>
<p:input port="schema">
<p:document href="../docs/document.xsd"/>
</p:input>
</p:validate-with-xml-schema>
</p:pipeline>
<file_sep>HOST=http://localhost:8350
# http://microwave:8151/
all: book.html
book.html: $(wildcard *.xml) \
reference
calabash -isource=book.xml ../xpl/format.xpl
chunks: book.html
rm -f chunked/*
cd chunked && saxon ../book.html ../../style/hchunk.xsl
post:
for f in ../css/*.css; do \
post -u admin -p xyzzy -f $$f $(HOST)/post/css/; \
done
for f in images/*.png; do \
post -u admin -p xyzzy -f $$f $(HOST)/post/book/$$f; \
done
for f in chunked/*.html; do \
post -u admin -p xyzzy -f $$f $(HOST)/post/book/; \
done
reference:
make -C core/results
make -C fileutils/results
make -C osutils/results
make -C utils/results
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This example updates the class attributes in a document:</para>
</p:documentation>
<p:pipeinfo>
<div>
<p class="oldclass red">Red.</p>
<p class="oldclass">Old.</p>
<p class="otherclass oldclass">Something else.</p>
</div>
</p:pipeinfo>
<p:string-replace match="*[@class='oldclass']/@class" replace="'newclass'"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>To encode an entire document, place it in a wrapper first.
The easiest way to do that is with <step>p:wrap-sequence</step>.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:href="../docs/document.xml"
cx:diff="false"/>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Then in subsequent steps, such as <step>p:http-request</step>, you
can extract the contents of the wrapper, as necessary.</para>
</p:documentation>
<p:wrap-sequence wrapper="my-wrapper"/>
<p:escape-markup/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>If you load a compact syntax schema with <tag>p:data</tag> (instead
of <tag>p:document</tag>) then XML Calabash will validate with that.</para>
</p:documentation>
<p:pipeinfo><doc>
<title>Title</title>
<p>Some paragraph.</p>
</doc></p:pipeinfo>
<p:validate-with-relax-ng>
<p:input port="schema">
<p:data href="../docs/grammar.rnc"/>
</p:input>
</p:validate-with-relax-ng>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>One use of <step>p:namepace-rename</step> is to move content that
is (or isn't) in a namespace into (or out of) a namespace.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions" cx:diff="false">
<html>
<head>
<title>My Title</title>
</head>
<body>
<p>Hello world.</p>
</body>
</html>
</p:pipeinfo>
<p:namespace-rename from="" to="http://www.w3.org/1999/xhtml"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Validity errors will cause the step to fail if
<option>assert-valid</option> is true.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<title>Title</title>
<not-valid/>
</doc></p:pipeinfo>
<p:try>
<p:group>
<p:validate-with-relax-ng assert-valid="true">
<p:input port="schema">
<p:data href="../docs/grammar.rnc"/>
</p:input>
</p:validate-with-relax-ng>
</p:group>
<p:catch>
<p:identity>
<p:input port="source">
<p:inline>
<failed/>
</p:inline>
</p:input>
</p:identity>
</p:catch>
</p:try>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>You can be more selective by changing <option>match</option>
and other options.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<p>One</p>
<p xml:id='second'>Two</p>
<p>Three</p>
</doc>
</p:pipeinfo>
<p:label-elements match="p" replace="false" label='concat("ID-",$p:index)'/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we select the element with a particular
<att>xml:id</att> where the ID value is an option to the pipeline.
</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions" cx:diff="false">
<doc>
<p xml:id="one">One</p>
<p xml:id="two">Two</p>
<p xml:id="three">Three</p>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In real life it's unlikely that there would be value in having
a default for the 'id' option, but it's convenient for the example.)
</para>
</p:documentation>
<p:option name="id" select="'two'"/>
<p:filter>
<p:with-option name="select"
select="concat('//*[@xml:id="',$id,'"]')"/>
</p:filter>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The simplest use of <step>p:validate-with-xml-schema</step> simply validates
a document.</para>
</p:documentation>
<p:pipeinfo><doc>
<title>Title</title>
<p>Some paragraph.</p>
</doc></p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>FIXME: more examples, showing all the various options and what
they do.</para>
</p:documentation>
<p:validate-with-xml-schema>
<p:input port="schema">
<p:document href="../docs/document.xsd"/>
</p:input>
</p:validate-with-xml-schema>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <att>detailed</att> and <att>status-only</att> attributes aren't
just for authentication. You can use them for unprotected resources as well.
Here's an example that uses <att>detailed</att> on an ordinary resource.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:http-request>
<p:input port="source">
<p:inline>
<c:request href="http://tests.xproc.org/docs/helloworld.xml" method="get"
detailed="true"/>
</p:inline>
</p:input>
</p:http-request>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
name="main" version='1.0'>
<p:input port="source"/>
<p:input port="parameters" kind="parameter"/>
<p:output port="result">
<p:pipe step="style" port="result"/>
</p:output>
<p:xslt name="style">
<p:input port="stylesheet">
<p:document href="docbook.xsl"/>
</p:input>
<p:input port="parameters">
<p:pipe step="main" port="parameters"/>
</p:input>
</p:xslt>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline renames the processing instruction:</para>
</p:documentation>
<p:pipeinfo>
<doc>
<?vocabulary pseudo-docbook?>
<para role="summary">Some text.</para>
<para>Some other text.</para>
</doc>
</p:pipeinfo>
<p:rename match="processing-instruction('vocabulary')" new-name="old-vocabulary"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In the simplest case, <step>p:identity</step> just passes
its input to the result port.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<para>Hello world.</para>
</doc>
</p:pipeinfo>
<p:identity/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This example simply decodes some encoded text:</para>
</p:documentation>
<p:pipeinfo><description>
<p>This is a chunk.</p>
<p>This is a another chunk.</p>
</description>
</p:pipeinfo>
<p:unescape-markup/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>That misses <att>class</att> attributes that contain more than
one value. We can improve on that with a slightly more sophisticated
match pattern.</para>
</p:documentation>
<p:pipeinfo>
<div>
<p class="oldclass red">Red.</p>
<p class="oldclass">Old.</p>
<p class="otherclass oldclass">Something else.</p>
</div>
</p:pipeinfo>
<p:string-replace match="*[contains(@class,'oldclass')]/@class"
replace="'newclass'"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc" version="1.0"
xmlns:s="http://nwalsh.com/ns/steps"
exclude-inline-prefixes="s"
name="main">
<p:serialization port="result" indent="true"/>
<p:pipeline type="s:example">
<p:option name="opt1" required="true"/>
<p:option name="opt2" select="'default'"/>
<p:option name="opt3"/>
<p:option name="opt4"/>
<p:variable name="var" select="'some value'"/>
<p:template>
<p:input port="template">
<p:inline>
<available>
<opt1 available="{$opt1a}">always true, because the caller is required to provide a value</opt1>
<opt2 available="{$opt2a}">always true, because the pipeline provides a default</opt2>
<opt3 available="{$opt3a}">true only if the caller provides a value</opt3>
<opt4 available="{$opt4a}">true only if the caller provides a value</opt4>
<var available="{$vara}">always true, because variables must have values</var>
</available>
</p:inline>
</p:input>
<p:with-param name="opt1a" select="p:value-available('opt1')"/>
<p:with-param name="opt2a" select="p:value-available('opt2')"/>
<p:with-param name="opt3a" select="p:value-available('opt3')"/>
<p:with-param name="opt4a" select="p:value-available('opt4')"/>
<p:with-param name="vara" select="p:value-available('var')"/>
</p:template>
</p:pipeline>
<s:example opt1="reqd" opt3="supplied"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:db="http://docbook.org/ns/docbook"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Another common use is in one of the branches of a
<step>p:choose</step>.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<para>Hello world!</para>
</doc>
</p:pipeinfo>
<p:choose>
<p:when test="/db:*">
<p:xslt>
<p:input port="stylesheet">
<p:document href="docbook.xsl"/>
</p:input>
</p:xslt>
</p:when>
<p:otherwise>
<p:identity/>
</p:otherwise>
</p:choose>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Here's an alternative way to construct the
<step>c:request</step> document:</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions" cx:diff="false">
<doc>
<p>This is what gets sent.</p>
</doc>
</p:pipeinfo>
<p:insert match="/c:request/c:body" position="first-child">
<p:input port="source">
<p:inline>
<c:request href="http://tests.xproc.org/service/echo" method="post">
<c:body content-type="application/xml"/>
</c:request>
</p:inline>
</p:input>
</p:insert>
<p:http-request/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline performs the same function, but inserts absolute
URIs throughout.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:href="../docs/main.xml"/>
<p:add-xml-base relative="false"/>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:pl="http://www.w3.org/XML/XProc/docs/library"
name="main" version="1.0">
<p:input port="source"/>
<p:input port="parameters" kind="parameter"/>
<p:output port="result"/>
<p:serialization port="result" method="xhtml" indent="false"/>
<p:declare-step type="cx:message">
<p:input port="source" sequence="true"/>
<p:output port="result" sequence="true"/>
<p:option name="message" required="true"/>
</p:declare-step>
<p:xinclude name="xinclude" fixup-xml-base="true" fixup-xml-lang="true">
<p:log port="result" href="/tmp/xinclude.xml"/>
</p:xinclude>
<!--
<p:validate-with-relax-ng>
<p:input port="schema">
<p:data href="../schemas/xproc.rnc"/>
</p:input>
</p:validate-with-relax-ng>
-->
<p:xslt name="patchdb">
<p:input port="stylesheet">
<p:document href="../style/patch-db.xsl"/>
</p:input>
</p:xslt>
<p:xslt name="style">
<p:input port="stylesheet">
<p:document href="../style/html.xsl"/>
</p:input>
</p:xslt>
<p:xslt name="chunk">
<p:input port="stylesheet">
<p:document href="../style/hchunk.xsl"/>
</p:input>
</p:xslt>
<p:sink/>
<p:for-each>
<p:iteration-source>
<p:pipe step="chunk" port="secondary"/>
</p:iteration-source>
<p:output port="result">
<p:pipe step="store" port="result"/>
</p:output>
<cx:message>
<p:with-option name="message" select="base-uri(/)"/>
</cx:message>
<p:store name="store" method="xhtml">
<p:with-option name="href" select="base-uri(/)"/>
</p:store>
</p:for-each>
<p:count/>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Without <code><att>detailed</att>="<literal>true</literal>"</code>,
you just get back the resource:</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Just like the first example!</para>
</p:documentation>
<p:http-request>
<p:input port="source">
<p:inline>
<c:request href="http://tests.xproc.org/docs/helloworld.xml" method="get"/>
</p:inline>
</p:input>
</p:http-request>
</p:pipeline>
<file_sep>#!/usr/bin/perl -- # -*- Perl -*-
# Assume the input has already been run through xmllint
use strict;
use English;
# Go around the houses to deal with the fact that someone leaves
# the newline off the last line...
my $xml = "";
while (<>) {
$xml .= $_;
}
my @lines = split(/\n/, $xml);
my @format = ();
shift @lines if $lines[0] =~ /<\?xml\s/;
foreach $_ (@lines) {
my $line = "";
if (/^(\s*)<([^\/\?\!].*?)(\/?)>(.*)$/s) {
my $ws = $1;
my $tag = $2;
my $etag = $3;
my $content = $4;
my $gi = "";
if ($tag =~ /^(\S+)(\s.*)$/) {
$gi = $1;
$_ = $2;
} else {
$gi = $tag;
$_ = "";
}
#open (F, ">>/tmp/prettyprint.log");
#print F "LIST:$_\n";
my @attr = ();
while (/^\s([^=]+)=([\"\'])(.*?)\2(.*)$/) {
print F "ATTR: {$1}, $2, $3 [$4]\n";
push (@attr, "$1=$2$3$2");
$_ = $4;
}
#print F "\n";
#close (F);
my $pos = length($ws) + length($gi) + 2;
my $first = 1;
if ($ws eq ' ' && $gi =~ /^p:/) {
if ($gi eq 'p:input' || $gi eq 'p:output'
|| $gi eq 'p:serialization' || $gi eq 'p:log') {
# nop
} else {
push(@format, '');
}
}
$line = "$ws<$gi";
while (@attr) {
my $att = shift @attr;
if ($first || ($pos + length($att) < 62)) {
$line .= " $att";
$pos += length($att) + 1;
$first = 0;
} else {
push (@format, $line);
$line = " " x (length($ws) + length($gi) + 2);
$line .= $att;
$pos += length($att) + 1;
}
}
$line .= "$etag>$content";
push (@format, $line);
$line = "";
} else {
push (@format, $_);
$line = "";
}
}
my $body = "";
foreach $_ (@format) {
$body .= "$_\n";
}
#print "---\n$body\n---\n";
my $newbody = "";
while ($body =~ /^(.*?)(<.*?>)(.*)$/s) {
my $text = $1;
my $tag = $2;
$body = $3;
$newbody .= pcdata($text) if $text ne '';
#print STDERR "==> $tag\n";
if ($tag =~ /<\?(\S+)(\s+.*)?\?>/) {
$newbody .= "<phrase role='mso'><?</phrase>";
$newbody .= "<phrase role='pitarget'>$1</phrase>";
$newbody .= "<phrase role='pidata'>$2</phrase>";
$newbody .= "<phrase role='msc'>?></phrase>";
} elsif ($tag =~ /<\!--(.*)-->/) {
$newbody .= "<phrase role='mso'><!--</phrase>";
$newbody .= "<tag class='comment'>$1</phrase>";
$newbody .= "<phrase role='msc'>--></phrase>";
} elsif ($tag =~ /<\/((.*?):)?(\S+)>/) {
$newbody .= "<phrase role='mso'></</phrase>";
$newbody .= "<tag class='prefix'>$2</tag><phrase role='colon'>:</phrase>"
if $1 ne '';
$newbody .= "<tag class='localname'>$3</tag><phrase role='msc'>></phrase>";
} elsif ($tag =~ /<([\S:]+?)(\s.*?)?([\/])?>/s) {
my $gi = $1;
my $attr = $2;
my $etag = $3;
$gi =~ /((.*?):)?(\S+)$/;
$newbody .= "<phrase role='mso'><</phrase>";
$newbody .= "<tag class='prefix'>$2</tag><phrase role='colon'>:</phrase>" if $1 ne '';
$newbody .= "<tag class='localname'>$3</tag>";
while ($attr =~ /(\s*)([\S:]+)=([\"\'])(.*?)\3(.*)$/s) {
$text = $1;
my $name = $2;
my $value = $3 . $4 . $3;
$attr = $5;
$newbody .= pcdata($text) if $text ne '';
$name =~ /((.*?):)?(\S+)$/;
my $pfx = $2;
my $lcl = $3;
if ($pfx eq 'xmlns' || ($pfx eq '' && $lcl eq 'xmlns')) {
$newbody .= "<phrase role='nsdecl'>";
}
$newbody .= "<tag class='attribute'>$name</tag>";
$newbody .= "<phrase role='atteq'>=</phrase>";
$value =~ /^([\"\'])(.*)\1$/;
$newbody .= "<phrase role='attq'>$1</phrase>";
$newbody .= attvalue($2);
$newbody .= "<phrase role='attq'>$1</phrase>";
if ($pfx eq 'xmlns' || ($pfx eq '' && $lcl eq 'xmlns')) {
$newbody .= "</phrase>";
}
}
$newbody .= "<phrase role='msc'>$etag></phrase>";
} else {
die "Unparseable: $tag\n";
}
}
my @lines = split(/\n/, $newbody);
print "<c:prettyprint xmlns:c='http://www.w3.org/ns/xproc-step' xmlns='http://docbook.org/ns/docbook'>\n";
foreach $_ (@lines) {
print "<c:line>$_</c:line>\n";
}
print "</c:prettyprint>\n";
sub esc {
my $text = shift;
my $stag = shift;
my $etag = shift;
return "" if $text eq '';
my $esc = "";
while ($text =~ /^(.*?)&(.*?);(.*)$/s) {
$esc .= $1;
my $ent = $2;
$text = $3;
if ($ent =~ /^\#([0-9]+)$/) {
$esc .= "<tag class='numcharref'>$1</tag>";
} elsif ($ent =~ /^\#(x[0-9a-f]+)$/i) {
$esc .= "<tag class='numcharref'>$1</tag>";
} else {
$esc .= "<tag class='genentity'>$ent</tag>";
}
}
my $lines = $esc . $text;
$text = "";
my $pos = index($lines, "\n");
# print STDERR "::: $lines :::\n";
# print STDERR "--- $pos ---\n";
# print STDERR ";;; ", substr($lines, 0, $pos), " ;;;\n";
# print STDERR "*** ", substr($lines, $pos+1), " ***\n";
while ($pos >= 0) {
my $pre = substr($lines, 0, $pos);
$lines = substr($lines, $pos+1);
$text .= $stag . $pre . $etag if $pre ne '';
$text .= "\n";
$pos = index($lines, "\n");
}
$text .= $stag . $lines. $etag if $lines ne '';
return $text;
}
sub pcdata {
my $text = shift;
return esc($text, "<phrase role='pcdata'>", "</phrase>");
}
sub attvalue {
my $text = shift;
return esc($text, "<phrase role='attvalue'>", "</phrase>");
}
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The simplest use of <step>p:validate-with-relax-ng</step> simply validates
a document.</para>
</p:documentation>
<p:pipeinfo><doc>
<title>Title</title>
<p>Some paragraph.</p>
</doc></p:pipeinfo>
<p:identity>
<p:input port="source">
<p:inline>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
<start>
<ref name="doc"/>
</start>
<define name="doc">
<element name="doc">
<optional>
<ref name="title"/>
</optional>
<zeroOrMore>
<ref name="p"/>
</zeroOrMore>
</element>
</define>
<define name="title">
<element name="title">
<text/>
</element>
</define>
<define name="p">
<element name="p">
<text/>
</element>
</define>
</grammar>
</p:inline>
</p:input>
</p:identity>
<p:validate-with-relax-ng>
<p:input port="source">
<p:pipe step="main" port="source"/>
</p:input>
<p:input port="schema"/>
</p:validate-with-relax-ng>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <option>namespace</option> option can be used to specify the
default namespace.</para>
</p:documentation>
<p:pipeinfo><description>
<p>This is a chunk.</p>
<p>This is a another chunk.</p>
</description></p:pipeinfo>
<p:unescape-markup namespace="http://www.w3.org/1999/xhtml"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:ex="http://example.com/pipeline/types"
version='1.0'>
<p:import href="do-stuff-and-rename.xpl"/>
<!-- do some other stuff -->
<ex:do-stuff-and-rename match="h:body/h:p"/>
<!-- do some other stuff -->
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline renames the <att>role</att> attribute to
<att>class</att>:</para>
</p:documentation>
<p:pipeinfo>
<doc>
<?vocabulary pseudo-docbook?>
<para role="summary">Some text.</para>
<para>Some other text.</para>
</doc>
</p:pipeinfo>
<p:rename match="@role" new-name="class"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline adds both <att>role</att> and <att>version</att>
attributes to any matching section.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<section role="introduction">
<para>section content</para>
</section>
<section>
<para>other section content</para>
</section>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <tag>p:set-attributes</tag> step replaces attributes if
they already exist:</para>
</p:documentation>
<p:pipeinfo>
<doc>
<section role="introduction" version="old-version">
<para>section content</para>
</section>
<section version="old-version">
<para>other section content</para>
</section>
</doc>
</p:pipeinfo>
<p:set-attributes match="section[not(@role)]">
<p:input port="attributes">
<p:inline>
<irrelevant-element-name role="new-role" version="new-version"/>
</p:inline>
</p:input>
</p:set-attributes>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Type information doesn't show up in the serialized output, but it
can be used in the pipeline, as we see here:</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<title>Title</title>
<div>
<p>Some paragraph
with a uri: <uri>http://example.com/</uri>.</p>
</div>
</doc></p:pipeinfo>
<p:identity>
<p:input port="source" select="//element(*,xs:anyURI)"/>
</p:identity>
<p:wrap-sequence name="wrapper1" wrapper="uris-before-validation"/>
<p:validate-with-xml-schema>
<p:input port="source">
<p:pipe step="main" port="source"/>
</p:input>
<p:input port="schema">
<p:document href="../docs/document.xsd"/>
</p:input>
</p:validate-with-xml-schema>
<p:identity>
<p:input port="source" select="//element(*,xs:anyURI)"/>
</p:identity>
<p:wrap-sequence name="wrapper2" wrapper="uris-after-validation"/>
<p:wrap-sequence wrapper="uris">
<p:input port="source">
<p:pipe step="wrapper1" port="result"/>
<p:pipe step="wrapper2" port="result"/>
</p:input>
</p:wrap-sequence>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This examples in this section rely on the fact that the
input document is constructed using an XML feature called external
parsed entities:</para>
<programlisting><![CDATA[<!DOCTYPE book [
<!ENTITY ch01 SYSTEM "chaps/ch01.xml">
<!ENTITY ch02 SYSTEM "chaps/ch02.xml">
<!ENTITY appa SYSTEM "apps/appa.xml">
]>
<book>
<title>Some Title</title>
&ch01;
&ch02;
&appa;
</book>]]></programlisting>
<para>When the parser expands the entities, the base URI of the
parts becomes part of the data model, but it's not reflected in the
serialized form shown below. This is <emphasis>precisely</emphasis>
the problem that <step>p:add-xml-base</step> is designed to address.
</para>
<para>With that caveat, we can see how this pipeline adds
<att>xml:base</att> attributes where necessary in the document.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:href="../docs/main.xml"/>
<p:add-xml-base/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Many processes produce non-XML markup, which has to be encoded.
In this case, the external process does not expect any input, so we
explicitly make the <port>source</port> empty.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:exec command="/bin/ls" result-is-xml="false" args="-l ../docs">
<p:input port="source">
<p:empty/>
</p:input>
</p:exec>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The optional <step>p:exec</step> step runs external processes.
</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
xmlns:c="http://www.w3.org/ns/xproc-step"
cx:diff="true"><c:result><doc>
<p>Some text.</p>
</doc></c:result></p:pipeinfo>
<p:exec command="/bin/cat" result-is-xml="true"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <option>all</option> option can be used to force
<att>xml:base</att> attributes throughout.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:href="../docs/main.xml"/>
<p:add-xml-base relative="false" all="true"/>
</p:pipeline>
<file_sep>all: index.html
.PHONY: examples
index.html: reference.xml \
add-attribute.xml add-xml-base.xml compare.xml count.xml delete.xml \
directory-list.xml error.xml escape-markup.xml exec.xml filter.xml \
hash.xml http-request.xml identity.xml insert.xml label-elements.xml \
load.xml make-absolute-uris.xml namespace-rename.xml pack.xml \
parameters.xml rename.xml replace.xml \
set-attributes.xml sink.xml split-sequence.xml store.xml \
string-replace.xml unescape-markup.xml unwrap.xml uuid.xml \
validate-with-relax-ng.xml validate-with-schematron.xml \
validate-with-xml-schema.xml wrap-sequence.xml wrap.xml \
www-form-urldecode.xml www-form-urlencode.xml xinclude.xml xquery.xml \
xsl-formatter.xml xslt.xml \
examples
calabash -isource=$< -oresult=$@ ../../xpl/format.xpl
examples:
make -C build
<file_sep><c:result xmlns:c="http://www.w3.org/ns/xproc-step"><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:add-attribute match="h:div[h:pre]"
attribute-name="class"
attribute-value="example"/>
</p:pipeline>
</c:result><file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>As we've seen in other examples, <step>p:try</step>/<step>p:catch</step>
can be used to recover from dynamic errors. In this example, we attempt to
load a valid document. If the document isn't valid, we load it anyway, but add
an attribute to the root element (so that subsequent pipeline processing
can tell, presumably).</para>
<para>This document also includes a DTD:</para>
<programlisting
><xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
href="../docs/invalid.xml" parse="text"
/></programlisting>
<para>But it is not valid. (a <tag>para</tag> appears where a
<tag>p</tag> is expected.)</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:option name="href" select="'../docs/invalid.xml'"/>
<p:try>
<p:group>
<p:load dtd-validate="true">
<p:with-option name="href" select="$href"/>
</p:load>
</p:group>
<p:catch>
<p:load dtd-validate="false">
<p:with-option name="href" select="$href"/>
</p:load>
<p:add-attribute match="/*" attribute-name="INVALID"
attribute-value="document-failed-dtd-validation"/>
</p:catch>
</p:try>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This example uses a UUID to generate a globally unique identifier.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions">
<doc>
<id>@@</id>
<p>Some text.</p>
</doc>
</p:pipeinfo>
<p:uuid match="/doc/id/text()" version="4"/>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:db="http://docbook.org/ns/docbook"
xmlns:exf="http://exproc.org/standard/functions"
name="main" version="1.0">
<p:input port="parameters" kind="parameter"/>
<p:import href="/home/ndw/xmlcalabash.com/extension/steps/library-1.0.xpl"/>
<p:import href="/home/ndw/xmlcalabash.com/library/tee.xpl"/>
<p:directory-list include-filter=".*-1.xml$" name="find1">
<p:with-option name="path" select="exf:cwd()"/>
</p:directory-list>
<p:directory-list include-filter=".*-01.xml$" name="find01">
<p:with-option name="path" select="exf:cwd()"/>
</p:directory-list>
<p:wrap-sequence wrapper="irrelevant">
<p:input port="source">
<p:pipe step="find1" port="result"/>
<p:pipe step="find01" port="result"/>
</p:input>
</p:wrap-sequence>
<p:for-each name="stepout">
<p:iteration-source select="//c:file"/>
<!--
<cx:message>
<p:with-option name="message"
select="if (contains(/*/@name, '-01.xml'))
then concat(substring-before(/*/@name, '-01.xml'),'-.*')
else concat(substring-before(/*/@name, '-1.xml'),'-.*')"/>
</cx:message>
-->
<p:directory-list>
<p:with-option name="path" select="exf:cwd()"/>
<p:with-option name="include-filter"
select="if (contains(/*/@name, '-01.xml'))
then concat(substring-before(/*/@name, '-01.xml'),'-.*')
else concat(substring-before(/*/@name, '-1.xml'),'-.*')"/>
</p:directory-list>
<p:for-each>
<p:iteration-source select="//c:file"/>
<p:string-replace match="/*/@href">
<p:input port="source">
<p:inline xmlns:xi="http://www.w3.org/2001/XInclude"
exclude-inline-prefixes="p c cx xs db exf">
<xi:include href="@@"
xpointer="xpath(/*/node^(^))"/>
</p:inline>
</p:input>
<p:with-option name="replace"
select="concat('"', /*/@name, '"')"/>
</p:string-replace>
</p:for-each>
<p:wrap-sequence wrapper="db:wrapper"/>
<p:store>
<p:with-option name="href"
select="if (contains(/*/@name, '-01.xml'))
then concat(exf:cwd(), '/', substring-before(/*/@name, '-01.xml'),'.xml')
else concat(exf:cwd(), '/', substring-before(/*/@name, '-1.xml'),'.xml')">
<p:pipe step="stepout" port="current"/>
</p:with-option>
</p:store>
</p:for-each>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This time we'll load a document that includes a DTD.</para>
<programlisting
><xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
href="../docs/valid.xml" parse="text"
/></programlisting>
<para>This document is valid.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:option name="href" select="'../docs/valid.xml'"/>
<p:load dtd-validate="true">
<p:with-option name="href" select="$href"/>
</p:load>
</p:pipeline>
<file_sep>all: examples index.html
index.html: reference.xml \
recursive-directory-list.xml
calabash -isource=$< -oresult=$@ ../../xpl/format.xpl
examples:
make -C results
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Some non-XML systems require markup to be escaped. This can
be achieved with the <step>p:escape-markup</step> step.
</para>
</p:documentation>
<p:pipeinfo><document>
<para>This is a paragraph of text.</para>
<para>So is this</para>
</document></p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Observe that <step>p:escape-markup</step> <emphasis>does not</emphasis>
escape the document element of its input. It can't. If it did, the output of
the step would not be well-formed XML.</para>
</p:documentation>
<p:escape-markup/>
</p:pipeline>
<file_sep><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:param name="p1" select="'default-p1'"/>
<xsl:param name="p2" select="'default-p2'"/>
<xsl:template match="/">
<doc>
<param p1="{$p1}"/>
<param p2="{$p2}"/>
</doc>
</xsl:template>
</xsl:stylesheet>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
type="cx:http-get"
version="1.0">
<p:output port="result"/>
<p:option name="href" required="true"/>
<p:option name="username"/>
<p:option name="password"/>
<p:identity>
<p:input port="source">
<p:inline><c:request method="GET" href="@@"/></p:inline>
</p:input>
</p:identity>
<p:string-replace match="/c:request/@href">
<p:with-option name="replace"
select="concat('"', $href, '"')"/>
</p:string-replace>
<p:choose>
<p:when test="p:value-available('username')">
<p:add-attribute match="/c:request" attribute-name="username">
<p:with-option name="attribute-value" select="$username"/>
</p:add-attribute>
<p:add-attribute match="/c:request" attribute-name="password">
<p:with-option name="attribute-value" select="$password"/>
</p:add-attribute>
</p:when>
<p:otherwise>
<p:identity/>
</p:otherwise>
</p:choose>
<p:http-request/>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we unwrap <tag>pre</tag> elements from their
containing <tag>div</tag> parents.</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<div>
<p class="add">This is new text.</p>
<p class="del">Some text.</p>
<div>
<pre class="chg">Some pre text.</pre>
</div>
</div>
<div class="del strikeout">
<pre>Some more example pre text.</pre>
</div>
</body>
</html>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Compare these results with <step>p:delete</step>.
</para>
</p:documentation>
<p:unwrap match="h:div[h:pre]"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Better, but now we're clobbering the other values. We
can fix that, too.</para>
</p:documentation>
<p:pipeinfo>
<div>
<p class="oldclass red">Red.</p>
<p class="oldclass">Old.</p>
<p class="otherclass oldclass">Something else.</p>
<p class="someoldclasstoo">Not really old.</p>
</div>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This is still imperfect as it incorrectly replaces
“<literal>someoldclasstoo</literal>” with “<literal>somenewclasstoo</literal>”.
We could improve this further with even more
complex <option>match</option> and <option>replace</option> options.</para>
</p:documentation>
<p:string-replace match="*[contains(@class,'oldclass')]/@class"
replace="concat(substring-before(.,'oldclass'),'newclass',substring-after(.,'oldclass'))"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>If <option>fail-if-not-equal</option> is
“<literal>true</literal>”, then the step fails when the documents
are different.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>Not the same.</para>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>And succeeds if they're the same.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>First para.</para>
<para>Second para.</para>
<para>Third para.</para>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<note>
<para>The <step>p:compare</step> step is
<emphasis>very</emphasis> sensitive to changes in the document.
Changes in the leading and trailing whitespace around the
document element, for example, is enough to make the documents
different. As shown, the “pretty printed” examples in this book would
actually be different because there is extra whitespace inside the
<tag>p:inline</tag> elements.</para>
<para>If you look at the source for the pipelines, you'll see that
we very carefully made the whitespace the same.</para>
</note>
</p:documentation>
<p:try>
<p:group>
<p:compare fail-if-not-equal="true">
<p:input port="alternate">
<p:inline><doc>
<para>First para.</para>
<para>Second para.</para>
<para>Third para.</para>
</doc></p:inline>
</p:input>
</p:compare>
<p:identity>
<p:input port="source">
<p:inline><PASS/></p:inline>
</p:input>
</p:identity>
</p:group>
<p:catch>
<p:identity>
<p:input port="source">
<p:inline><FAIL/></p:inline>
</p:input>
</p:identity>
</p:catch>
</p:try>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>If you only want the XML files, use a filter:</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false' cx:show-source="false">
<doc/>
</p:pipeinfo>
<p:directory-list path="../.." include-filter="^.*\.xml$"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <step>p:insert</step> step inserts one document into
another. You select where and at what position to make the insertion,
before the matched location:</para>
</p:documentation>
<p:pipeinfo>
<doc>
<div>
<p>Play.</p>
</div>
</doc>
</p:pipeinfo>
<p:insert match="/doc/div" position="before">
<p:input port="insertion">
<p:inline>
<p>Hello world.</p>
</p:inline>
</p:input>
</p:insert>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The FOAF (“friend of a friend”) project specifies an
SHA1 checksum as an alternative for email addresses (so that the addresses
can't be harvested by spammers).</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions">
<foaf:Person
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
rdf:about="http://norman.walsh.name/knows/who#norman-walsh">
<foaf:name><NAME></foaf:name>
<foaf:nick>norm</foaf:nick>
<foaf:nick>ndw</foaf:nick>
<foaf:nick>nwalsh</foaf:nick>
<foaf:mbox rdf:resource="mailto:<EMAIL>"/>
<foaf:mbox_sha1sum>@@</foaf:mbox_sha1sum>
</foaf:Person>
</p:pipeinfo>
<p:hash algorithm="sha" version="1" match="/*/foaf:mbox_sha1sum/node()">
<p:with-option name="value" select="/*/foaf:mbox/@rdf:resource"/>
</p:hash>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline counts the number of paragraphs in the document.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>First para.</para>
<para>Second para.</para>
<para>Third para.</para>
</doc>
</p:pipeinfo>
<p:count>
<p:input port="source" select="//para"/>
</p:count>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The preceding example isn't very practical because the replacement
text is static. For a more realistic example, consider this pipeline which
uses XSLT to update the summary paragraph, then uses <step>p:replace</step>
to replace the original with the new version.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<para role="summary">Some text.</para>
<para>Some other text.</para>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>(Though a <step>p:viewport</step> would make more sense here.)</para>
</p:documentation>
<p:xslt>
<p:input port="source" select="//para[@role='summary']"/>
<p:input port="stylesheet">
<p:inline>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="para">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:text>In summary: </xsl:text>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</p:inline>
</p:input>
</p:xslt>
<p:replace match="para[@role='summary']">
<p:input port="source">
<p:pipe step="main" port="source"/>
</p:input>
</p:replace>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:cxf="http://xmlcalabash.com/ns/extensions/fileutils"
name="main" version="1.0">
<p:output port="result"/>
<p:import href="http://xmlcalabash.com/extension/steps/fileutils.xpl"/>
<cxf:head count="0" href="sonnet116.txt"/>
</p:declare-step>
<file_sep>VPATH = ../examples
.SUFFIXES: .xml .xpl
all: head-1.xml head-2.xml head-3.xml head-4.xml \
tail-1.xml tail-2.xml tail-3.xml tail-4.xml \
copy-1.xml
.xpl.xml:
calabash -oresult=$@ $<
<file_sep>* **Author:** <NAME>
* **Date:** 12 October 2011
(This is the initial checkin, the build system and other parts of the system don't work,
may not be checked in, etc. That'll improve over time.)
# XML Pipelines: A Guide to XProc
This repository contains the sources for _XML Pipelines: A Guide to XProc_. You can
read the current draft at http://xprocbook.com/
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>There's nothing much to show, really, <step>p:sink</step> is just
a bit bucket. In this example, we explicitly discard the primary output of
the <step>p:xslt</step> step and return only the content of its secondary
output.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<para>Hello world.</para>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Without the <step>p:sink</step>, the XProc processor would have
complained about the unbound primary output port on the <step>p:xslt</step>
step.</para>
</p:documentation>
<p:xslt name="style">
<p:input port="stylesheet">
<p:inline>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="/">
<xsl:sequence select="."/>
<xsl:result-document href="http://example.com/foo">
<doc>
<p>Secondary result document.</p>
</doc>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>
</p:inline>
</p:input>
</p:xslt>
<p:sink/>
<p:identity>
<p:input port="source">
<p:pipe step="style" port="secondary"/>
</p:input>
</p:identity>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>It can also be used to change the namespace associated with
attributes.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<para href="http://www.w3.org/">Some text.</para>
</doc>
</p:pipeinfo>
<p:namespace-rename from="" to="http://www.w3.org/1999/xlink"
apply-to="attributes"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version='1.0'>
<p:option name="schema"/>
<p:option name="stylesheet"/>
<p:xinclude name="include"/>
<p:load name="load-schema">
<p:with-option name="href" select="$schema"/>
</p:load>
<p:load name="load-stylesheet">
<p:with-option name="href" select="$stylesheet"/>
</p:load>
<p:validate-with-relax-ng>
<p:input port="source">
<p:pipe step="include" port="result"/>
</p:input>
<p:input port="schema">
<p:pipe step="load-schema" port="result"/>
</p:input>
</p:validate-with-relax-ng>
<p:xslt>
<p:input port="stylesheet">
<p:pipe step="load-stylesheet" port="result"/>
</p:input>
</p:xslt>
</p:pipeline>
<file_sep><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:p="http://www.w3.org/ns/xproc"
xmlns:db="http://docbook.org/ns/docbook"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://docbook.org/ns/docbook"
exclude-result-prefixes="db p"
version="2.0">
<xsl:output method="xml" encoding="utf-8" indent="no"
omit-xml-declaration="yes"/>
<xsl:variable name="basename"
select="replace(base-uri(/), '^.*/', '')"/>
<xsl:template match="/">
<wrapper>
<xsl:apply-templates/>
</wrapper>
</xsl:template>
<xsl:template match="p:pipeline|p:declare-step">
<xsl:apply-templates select="p:documentation[db:*]|p:pipeinfo"/>
</xsl:template>
<xsl:template match="p:documentation">
<xsl:copy-of select="*"/>
<xsl:if test="not(preceding-sibling::p:documentation[db:*])">
<xi:include href="examples/{$basename}"/>
</xsl:if>
</xsl:template>
<xsl:template match="p:pipeinfo[not(@cx:parameters='true')]">
<xsl:variable name="num" select="count(preceding::p:pipeinfo)+1"/>
<xi:include href="diffs/{$basename}-{$num}.xml"/>
</xsl:template>
</xsl:stylesheet>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>It's worth observing that matching on attributes is a special case.
Attribute matches replace the value. Any other kind of match replaces
<emphasis>the entire node</emphasis>. Here we find elements that have the
“<literal>oldclass</literal>” value and replace them with the new class.</para>
</p:documentation>
<p:pipeinfo>
<div>
<p class="oldclass red">Red.</p>
<p class="oldclass">Old.</p>
<p class="otherclass oldclass">Something else.</p>
</div>
</p:pipeinfo>
<p:string-replace match="*[@class='oldclass']" replace="'newclass'"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The exit status is available through the non-primary
“<port>exit-status</port>” port.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Because it's an error to leave a primary output port unbound,
in this example we explicitly discard it with <step>p:sink</step>. In
a real pipeline, we'd probably be doing something useful with the output.</para>
</p:documentation>
<p:exec name="ls" command="/bin/ls" result-is-xml="false" args="-l ../docs"
wrap-result-lines="true">
<p:input port="source">
<p:empty/>
</p:input>
</p:exec>
<p:sink/>
<p:identity>
<p:input port="source">
<p:pipe step="ls" port="exit-status"/>
</p:input>
</p:identity>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <step>p:unwrap</step> step uses a
<emphasis>match</emphasis> pattern which can apply at many different depths
in the document tree. In particular, note that the unwrapped content is also
subject to unwrapping.</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<div>
<p class="add">This is new text.</p>
<p class="del">Some text.</p>
<div>
<pre class="chg">Some pre text.</pre>
</div>
</div>
<div class="del strikeout">
<pre>Some more example pre text.</pre>
</div>
</body>
</html>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Using a simple <option>match</option> pattern of <literal>div</literal>
effectively removes <emphasis>every single</emphasis> <tag>div</tag> from
the document.</para>
</p:documentation>
<p:unwrap match="h:div"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Using <option>group-adjacent</option> we can group elements together.
Notice how it's the value of the <option>group-adjacent</option> option that
matters. The expression <code>local-name(.)</code> will be the same for
both <tag>p</tag> elements, so they match.
</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<p>Some text.</p>
<pre>Some example pre text.</pre>
<p>Some more text.</p>
<p>Yet even more text.</p>
</body>
</html>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The first and second paragraphs are not adjacent because a
<tag>pre</tag> intervenes.</para>
</p:documentation>
<p:wrap match="h:p" wrapper="div"
wrapper-namespace="http://www.w3.org/1999/xhtml"
group-adjacent="local-name(.)"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:db="http://docbook.org/ns/docbook"
version='1.0'>
<p:identity>
<p:input port="source" select="//db:para"/>
</p:identity>
<p:count/>
</p:pipeline>
<file_sep>all: examples index.html
index.html: reference.xml \
copy.xml delete.xml head.xml info.xml mkdir.xml move.xml \
tail.xml tempfile.xml touch.xml
calabash -isource=reference.xml -oresult=$@ ../../xpl/format.xpl
examples:
make -C results
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Pipelines can't directly access parameters by name (because the
names of parameters aren't known in advance). To find out what parameters
were passed to the pipeline, the <step>p:parameters</step> step is first
used to create a document, then that document can be interrogated with
XPath.</para>
<para>This pipeline just prints the parameters passed to it (in this case,
<literal>param</literal> with the value “<literal>value</literal>” and
<literal>cx:test</literal> with the value “<literal>othervalue</literal>”).</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:parameters='true'>
<c:param-set xmlns:c="http://www.w3.org/ns/xproc-step">
<c:param name="param" value="value"/>
<c:param name="cx:test" value="othervalue"/>
</c:param-set>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Note that neither the <port>parameters</port> port nor the
<port>result</port> output on <step>p:parameters</step> are
primary, so we must connect to them explicitly.</para>
</p:documentation>
<p:parameters name="params">
<p:input port="parameters">
<p:pipe step="main" port="parameters"/>
</p:input>
</p:parameters>
<p:identity>
<p:input port="source">
<p:pipe step="params" port="result"/>
</p:input>
</p:identity>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>If you have a tool that will allow you to watch HTTP traffic on
the network,
such as <link xlink:href="http://www.tuffcode.com/">HTTP Scoop</link>,
then with it
enabled, you'll see that the XProc processor and the server perform a little
dance:</para>
<orderedlist>
<listitem><para>XProc requests the page,</para></listitem>
<listitem><para>the web server declines, asserting authentication is required</para>
</listitem>
<listitem><para>XProc tries again, sending the credentials</para>
</listitem>
<listitem><para>the web server sends back the representation.</para>
</listitem>
</orderedlist>
<para>By adding <code><att>send-authorization</att>="<literal>true</literal>"</code>,
you can reduce the dance by two steps: the XProc processor will send the
credentials initially and the web server will respond with the representation.
</para>
<para>This only works for basic authentication. If you use basic
authentication you really <emphasis>should</emphasis> use
<uri type="scheme">https:</uri> as passwords are otherwise sent
unencrypted, visible to anyone with traffic monitoring tool as
described above.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:http-request>
<p:input port="source">
<p:inline>
<c:request href="http://tests.xproc.org/docs/basic-auth" method="get"
detailed="true" auth-method="Basic" username="testuser"
password="<PASSWORD>" send-authorization="true"/>
</p:inline>
</p:input>
</p:http-request>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline renames the <tag>para</tag> elements to
<tag>p</tag>:</para>
</p:documentation>
<p:pipeinfo>
<doc>
<?vocabulary pseudo-docbook?>
<para role="summary">Some text.</para>
<para>Some other text.</para>
</doc>
</p:pipeinfo>
<p:rename match="para" new-name="h:p"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>But instead, let's take advantage of the fact that this is a pipeline.
We don't have to do everything all at once.
</para>
</p:documentation>
<p:pipeinfo>
<div>
<p class="oldclass red">Red.</p>
<p class="oldclass">Old.</p>
<p class="otherclass oldclass">Something else.</p>
<p class="someoldclasstoo">Not really old.</p>
</div>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>(This still doesn't handle the case where “<literal>oldclass</literal>”
appears more than once in the attribute value, but I'm willing to live with
that.)</para>
</p:documentation>
<p:string-replace match="*[@class='oldclass']/@class" replace="'newclass'"/>
<p:string-replace match="*[starts-with(@class,'oldclass ')]/@class"
replace="concat('newclass ', substring-after(.,'oldclass '))"/>
<p:string-replace match="*[contains(@class,' oldclass ')]/@class"
replace="concat(substring-before(.,' oldclass '),' newclass ',substring-after(.,' oldclass '))"/>
<p:string-replace match="*[ends-with(@class,' oldclass')]/@class"
replace="concat(substring-before(.,' oldclass'), ' newclass')"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This example posts to an “echo” service that just sends back whatever
it receives.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions" cx:diff="false">
<doc>
<p>This is what gets sent.</p>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>As you can see, we use other XProc steps to build up the request
wrapper for <step>p:http-request</step>.</para>
</p:documentation>
<p:wrap-sequence wrapper="c:body"/>
<p:add-attribute match="/c:body" attribute-name="content-type"
attribute-value="application/xml"/>
<p:wrap-sequence wrapper="c:request"/>
<p:set-attributes match="/c:request">
<p:input port="attributes">
<p:inline>
<dummy href="http://tests.xproc.org/service/echo" method="post"/>
</p:inline>
</p:input>
</p:set-attributes>
<p:http-request/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline adds a <att>class</att> attribute to any
HTML <tag namespace="http://www.w3.org/1999/xhtml">div</tag>
that contains a <tag namespace="http://www.w3.org/1999/xhtml">pre</tag>.
</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<div>
<p>Some text.</p>
<div>
<pre>Some example pre text.</pre>
</div>
</div>
<div>
<pre>Some more example pre text.</pre>
</div>
</body>
</html>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <tag>p:add-attribute</tag> step replaces attributes if they
already exist:</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Other Document</title>
</head>
<body>
<div class="original value">
<pre>Some example pre text.</pre>
</div>
</body>
</html>
</p:pipeinfo>
<p:add-attribute match="h:div[h:pre]"
attribute-name="class"
attribute-value="example"/>
</p:pipeline>
<file_sep>VPATH = ../examples
.SUFFIXES: .xml .xpl
all:
@echo not implemented
.xpl.xml:
calabash -oresult=$@ $<
<file_sep>VPATH = ../examples
.SUFFIXES: .xml .xpl
all:
@echo Not supported yet.
xall: head-1.xml head-2.xml head-3.xml head-4.xml \
tail-1.xml tail-2.xml tail-3.xml tail-4.xml \
copy-1.xml
.xpl.xml:
calabash -oresult=$@ $<
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Unfortunately, the results aren't very useful. By specifying
<att>detailed</att>, we can get more information:</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Now at least we can see the status code.</para>
</p:documentation>
<p:http-request>
<p:input port="source">
<p:inline>
<c:request href="http://tests.xproc.org/docs/basic-auth" method="get"
detailed="true"/>
</p:inline>
</p:input>
</p:http-request>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc" version="1.0"
xmlns:s="http://nwalsh.com/ns/steps"
exclude-inline-prefixes="s"
name="main">
<p:serialization port="result" indent="true"/>
<p:pipeline type="s:mytype">
<p:identity/>
</p:pipeline>
<p:template>
<p:input port="template">
<p:inline>
<available>
<mytype available="{$a1}">true, s:mytype is declared above</mytype>
<notype available="{$a2}">false, there's no declaration for s:notype</notype>
<identity available="{$a3}">always true, all processors support p:identity</identity>
<template available="{$a4}">true only if the p:template step is supported</template>
</available>
</p:inline>
</p:input>
<p:with-param name="a1" select="p:step-available('s:mytype')"/>
<p:with-param name="a2" select="p:step-available('s:notype')"/>
<p:with-param name="a3" select="p:step-available('p:identity')"/>
<p:with-param name="a4" select="p:step-available('p:template')"/>
</p:template>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline replaces the paragraph with the “<literal>summary</literal>”
role with a new paragraph.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<para role="summary">Some text.</para>
<para>Some other text.</para>
</doc>
</p:pipeinfo>
<p:replace match="para[@role='summary']">
<p:input port="replacement">
<p:inline>
<para>Static text.</para>
</p:inline>
</p:input>
</p:replace>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The <step>p:label-elements</step> step is most often used
to add <att>xml:id</att> attributes (or ID attributes with some other
name) to elements. By default, it does this for all elements, replacing
any existing values:</para>
</p:documentation>
<p:pipeinfo>
<doc>
<p>One</p>
<p xml:id='second'>Two</p>
<p>Three</p>
</doc>
</p:pipeinfo>
<p:label-elements/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we specify an explicit base URI.</para>
</p:documentation>
<p:pipeinfo>
<doc>
<link href="../test.xml"/>
<div xml:base="http://example.com/path/">
<link href="relative.xml"/>
</div>
</doc>
</p:pipeinfo>
<p:make-absolute-uris match="@href" base-uri="file:///absolute/path/"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:my-errors="http://www.example.org/error"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>A <step>p:error</step> always fails. In the example below, we
catch it with a <step>p:try</step>.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Without the <step>p:try</step>, the failure would have caused the
pipeline processor to abort the pipeline. How (or if) the processor reports
an error in that case is <glossterm>implementation-defined</glossterm>.
</para>
</p:documentation>
<p:try>
<p:group>
<p:error code="my-errors:fall-down-go-bang">
<p:input port="source">
<p:inline><doc>Nothing to see here.</doc></p:inline>
</p:input>
</p:error>
</p:group>
<p:catch name="uh-oh">
<p:identity>
<p:input port="source">
<p:pipe step="uh-oh" port="error"/>
</p:input>
</p:identity>
</p:catch>
</p:try>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:db="http://docbook.org/ns/docbook"
xmlns:exf="http://exproc.org/standard/functions"
name="main" version="1.0">
<p:input port="parameters" kind="parameter"/>
<p:option name="href" required="true"/>
<p:import href="/home/ndw/xmlcalabash.com/library/eval.xpl"/>
<p:import href="/home/ndw/xmlcalabash.com/extension/steps/library-1.0.xpl"/>
<p:import href="/home/ndw/xmlcalabash.com/extension/steps/namespace-delete.xpl"/>
<p:import href="/home/ndw/xmlcalabash.com/library/tee.xpl"/>
<p:load name="xpl">
<p:with-option name="href" select="concat(exf:cwd(), '../xpl/', $href)"/>
</p:load>
<p:delete match="p:documentation[db:*]"/>
<p:delete match="p:pipeinfo"/>
<p:exec name="input-pipeline"
command="/usr/bin/xmllint" args="--format --nsclean -"/>
<p:exec command="/Volumes/Data/github/xprocbook/bin/prettyprint"
result-is-xml="true">
<p:input port="source" select="/*/*"/>
</p:exec>
<p:identity>
<p:input port="source" select="/*/*"/>
</p:identity>
<p:store>
<p:with-option name="href"
select="concat(exf:cwd(), 'examples/', $href)"/>
</p:store>
<p:store indent="true">
<p:input port="source" select="/*/*">
<p:pipe step="input-pipeline" port="result"/>
</p:input>
<p:with-option name="href"
select="concat(exf:cwd(), 'xpl/', $href)"/>
</p:store>
<p:xslt>
<p:input port="source">
<p:pipe step="xpl" port="result"/>
</p:input>
<p:input port="stylesheet">
<p:document href="../style/extract-example-xml.xsl"/>
</p:input>
</p:xslt>
<p:store>
<p:with-option name="href"
select="concat(exf:cwd(), substring-before($href,'.xpl'), '.xml')"/>
</p:store>
<p:for-each name="for-each">
<p:iteration-source select="//p:pipeinfo[not(@cx:parameters='true')]">
<p:pipe step="xpl" port="result"/>
</p:iteration-source>
<p:variable name="basename"
select="concat($href,'-',p:iteration-position(),'.xml')"/>
<!--
<cx:message>
<p:with-option name="message" select="concat('b: ', $basename)"/>
</cx:message>
-->
<p:choose name="load">
<p:when test="/*/@cx:href">
<p:output port="result"/>
<p:load>
<p:with-option name="href" select="resolve-uri(/*/@cx:href, base-uri(.))"/>
</p:load>
</p:when>
<p:otherwise>
<p:output port="result"/>
<p:identity>
<p:input port="source" select="/p:pipeinfo/*"/>
</p:identity>
</p:otherwise>
</p:choose>
<cx:namespace-delete prefixes="p h cx"
xmlns:h="http://www.w3.org/1999/xhtml"/>
<p:exec command="/usr/bin/xmllint" args="--format --nsclean -"/>
<p:exec command="/Volumes/Data/github/xprocbook/bin/prettyprint"
result-is-xml="true">
<p:input port="source" select="/*/*"/>
</p:exec>
<p:identity name="ppinput">
<p:input port="source" select="/*/*"/>
</p:identity>
<p:identity name="params">
<p:input port="source" select="//p:pipeinfo[@cx:parameters='true']/c:param-set">
<p:pipe step="xpl" port="result"/>
</p:input>
</p:identity>
<cx:eval name="runpipe">
<p:input port="source">
<p:pipe step="load" port="result"/>
</p:input>
<p:input port="pipeline">
<p:pipe step="xpl" port="result"/>
</p:input>
<p:input port="parameters">
<p:pipe step="params" port="result"/>
</p:input>
<p:input port="options">
<p:empty/>
</p:input>
</cx:eval>
<cx:namespace-delete prefixes="p h cx"
xmlns:h="http://www.w3.org/1999/xhtml"/>
<p:exec command="/usr/bin/xmllint" args="--format --nsclean -"/>
<p:exec command="/Volumes/Data/github/xprocbook/bin/prettyprint"
result-is-xml="true">
<p:input port="source" select="/*/*"/>
</p:exec>
<p:identity name="ppoutput">
<p:input port="source" select="/*/*"/>
</p:identity>
<p:choose>
<p:when test="/*/@cx:show-source = 'false'">
<p:xpath-context>
<p:pipe step="for-each" port="current"/>
</p:xpath-context>
<p:identity>
<p:input port="source">
<p:pipe step="ppoutput" port="result"/>
</p:input>
</p:identity>
<p:wrap-sequence wrapper="c:suppress-source"/>
</p:when>
<p:when test="/*/@cx:diff = 'false'">
<p:xpath-context>
<p:pipe step="for-each" port="current"/>
</p:xpath-context>
<p:identity>
<p:input port="source">
<p:pipe step="ppinput" port="result"/>
<p:pipe step="ppoutput" port="result"/>
</p:input>
</p:identity>
<p:wrap-sequence wrapper="c:suppress-diff"/>
</p:when>
<p:otherwise>
<cx:delta-xml>
<p:input port="source">
<p:pipe step="ppinput" port="result"/>
</p:input>
<p:input port="alternate">
<p:pipe step="ppoutput" port="result"/>
</p:input>
<p:input port="dxp">
<p:document href="diff.dxp"/>
</p:input>
</cx:delta-xml>
</p:otherwise>
</p:choose>
<p:store>
<p:with-option name="href"
select="concat(exf:cwd(), 'diffs/', $basename)"/>
</p:store>
</p:for-each>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we load a document specified in an option.
</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:option name="href" select="'../docs/document.xml'"/>
<p:load>
<p:with-option name="href" select="$href"/>
</p:load>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Here we use <step>p:wrap</step> to wrap each <tag>p</tag> in
a <tag>div</tag>.</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<p>Some text.</p>
<pre>Some example pre text.</pre>
<p>Some more text.</p>
<p>Yet even more text.</p>
</body>
</html>
</p:pipeinfo>
<p:wrap match="h:p" wrapper="div" wrapper-namespace="http://www.w3.org/1999/xhtml"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:option name="a" select="'default a'"/>
<p:option name="c" select="'default c'"/>
<p:option name="test" select="'default test'"/>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we package up some options as parameters for
a web service call.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In a real pipeline, we'd almost certainly pass this <tag>c:request</tag>
element on to a <step>p:http-request</step> step, not return it.</para>
</p:documentation>
<p:www-form-urlencode match="/c:request/@href">
<p:input port="source">
<p:inline>
<c:request method="get" href="@@"/>
</p:inline>
</p:input>
<p:with-param name="a" select="$a"/>
<p:with-param name="c" select="$c"/>
<p:with-param name="test" select="$test"/>
</p:www-form-urlencode>
<p:string-replace match="/c:request/@href"
replace="concat('http://example.com/service?', .)"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>A common use of <step>p:identity</step> is to extract some
portion or portions of a document.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions" cx:diff="false">
<doc>
<para>Hello world!</para>
<div>
<para>Work.</para>
<para>Sleep.</para>
<para>Eat.</para>
<para>Play.</para>
</div>
<para>Goodbye, cruel world.</para>
</doc>
</p:pipeinfo>
<p:identity>
<p:input port="source" select="/doc/div"/>
</p:identity>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>When an assertion fails, the error message is sent to the
<port>report</port> port.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<chapter xmlns="http://docbook.org/ns/docbook">
<title>Chapter title</title>
<para>What about this book: <biblioref linkend="bibl"/>.</para>
<bibliography xml:id="bibl">
<bibliomixed xml:id="someid"><abbrev>BOOK</abbrev> Title, Author,
etc.</bibliomixed>
</bibliography>
</chapter></p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>If you want to read the <port>report</port> output, you must specify
that <option>assert-valid</option> is “<literal>false</literal>”, otherwise
the step fails and there's no way to read the <port>report</port> output.
</para>
</p:documentation>
<p:validate-with-schematron name="schematron" assert-valid="false">
<p:input port="schema">
<p:document href="../docs/rules.sch"/>
</p:input>
</p:validate-with-schematron>
<p:sink/>
<p:identity>
<p:input port="source">
<p:pipe step="schematron" port="report"/>
</p:input>
</p:identity>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
name="main" version="1.0">
<p:output port="result"/>
<p:option name="new-class" select="'new-value'"/>
<p:string-replace match="p/@class">
<p:input port="source">
<p:inline><p class="old-value">Some text.</p></p:inline>
</p:input>
<p:with-option name="replace" select="$new-class"/>
</p:string-replace>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
name="main"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>The Schematron language is (XPath) rule based, rather than grammar
based (like XML Schema and RELAX NG). As a consequence, it can be used to test
assertions of arbitrary complexity.</para>
<para>One such example is the DocBook rule about bibliography references.
The DocBook <tag>biblioref</tag> element <emphasis>must</emphasis> point to a
bibliography entry. Grammar-based parsers can check that the IDREF attribute on
a <tag>biblioref</tag> element points to an ID that exists, but they don't check
to see what kind of element has that ID.</para>
<para>Enter Schematron. Here's a simple rule that tests <tag>biblioref</tag>
elements:</para>
<programlisting><![CDATA[<s:pattern name="'biblioref' type constraint">
<s:rule context="db:biblioref[@linkend]">
<s:assert test="local-name(//*[@xml:id=current()/@linkend]) = 'bibliomixed'
and namespace-uri(//*[@xml:id=current()/@linkend])
= 'http://docbook.org/ns/docbook'">@linkend on biblioref must point
to a bibliography entry.</s:assert>
</s:rule>
</s:pattern>
]]></programlisting>
<para>This rule asserts that when a <tag>bibloref</tag> element has a
<att>linkend</att> attribute, that attribute's value must be the
<att>xml:id</att> value of a <tag>bibliomixed</tag> element in the
DocBook namespace. (A slight simplification of
the real rule which checks for a few other elements as well.)</para>
</p:documentation>
<p:pipeinfo><chapter xmlns="http://docbook.org/ns/docbook">
<title>Chapter title</title>
<para>What about this book: <biblioref linkend="someid"/>.</para>
<bibliography>
<bibliomixed xml:id="someid"><abbrev>BOOK</abbrev> Title, Author,
etc.</bibliomixed>
</bibliography>
</chapter></p:pipeinfo>
<p:validate-with-schematron>
<p:input port="schema">
<p:document href="../docs/rules.sch"/>
</p:input>
</p:validate-with-schematron>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:input port="source"/>
<p:output port="result">
<p:pipe step="compare" port="result"/>
</p:output>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline compares its single input document against
a fixed alternative. It returns true if they're the same.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>First para.</para>
<para>Second para.</para>
<para>Third para.</para>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>It returns false if they're different.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>Not the same.</para>
</doc>
</p:pipeinfo>
<p:compare name="compare">
<p:input port="alternate">
<p:inline><doc>
<para>First para.</para>
<para>Second para.</para>
<para>Third para.</para>
</doc></p:inline>
</p:input>
</p:compare>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>What's in my “XProc book” directory? Let's see! (This
example pipeline is in a directory a couple of levels below the
main book directory, hence the “<filename
class="directory">../..</filename>”.)</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false' cx:show-source="false">
<doc/>
</p:pipeinfo>
<p:directory-list path="../.."/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:ex="http://example.com/pipeline/types"
type="ex:do-stuff-and-rename"
version='1.0'>
<p:option name="oldname" required="true"/>
<p:option name="newname" select="'html:div'"/>
<!-- do some stuff -->
<p:rename>
<p:with-option name="match" select="$oldname"/>
<p:with-option name="new-name" select="$newname"/>
</p:rename>
<!-- do some stuff -->
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline deletes elements with a <att>class</att> attribute
that contains the string “<literal>del</literal>”.</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<div>
<p class="add">This is new text.</p>
<p class="del">Some text.</p>
<div>
<pre class="chg">Some pre text.</pre>
</div>
</div>
<div class="del strikeout">
<pre>Some more example pre text.</pre>
</div>
</body>
</html>
</p:pipeinfo>
<p:delete match="*[contains(@class,'del')]"/>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
version='1.0'>
<p:input port="parameters" kind="parameter"/>
<p:output port="result"/>
<p:serialization port="result" indent="true"/>
<p:xslt>
<p:input port="source"><p:inline><doc/></p:inline></p:input>
<p:input port="stylesheet">
<p:document href="show-params.xsl"/>
</p:input>
<p:with-param name="p1" select="'with-param value'"/>
</p:xslt>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>Steps in XProc read either a single document (and specifying
multiple documents is an error) or they read <emphasis>all</emphasis>
the documents sent to them. The <step>p:pack</step> step makes it possible
to group documents from two input streams, allowing you to effectively
read one document at a time.</para>
<para>This example uses <step>p:pack</step> to transform a
4x<replaceable>n</replaceable> table into an <replaceable>n</replaceable>x4
table.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>This is a table.</para>
<table>
<tr><td>A1</td><td>B1</td><td>C1</td></tr>
<tr><td>A2</td><td>B2</td><td>C2</td></tr>
<tr><td>A3</td><td>B3</td><td>C3</td></tr>
<tr><td>A4</td><td>B4</td><td>C4</td></tr>
</table>
</doc>
</p:pipeinfo>
<p:viewport match="table" name="rotate">
<p:identity name="col1">
<p:input port="source" select="/table/tr[1]/td">
<p:pipe step="rotate" port="current"/>
</p:input>
</p:identity>
<p:identity name="col2">
<p:input port="source" select="/table/tr[2]/td">
<p:pipe step="rotate" port="current"/>
</p:input>
</p:identity>
<p:identity name="col3">
<p:input port="source" select="/table/tr[3]/td">
<p:pipe step="rotate" port="current"/>
</p:input>
</p:identity>
<p:identity name="col4">
<p:input port="source" select="/table/tr[4]/td">
<p:pipe step="rotate" port="current"/>
</p:input>
</p:identity>
<p:pack name="c12" wrapper="wrap12">
<p:input port="source">
<p:pipe step="col1" port="result"/>
</p:input>
<p:input port="alternate">
<p:pipe step="col2" port="result"/>
</p:input>
</p:pack>
<p:pack name="c34" wrapper="wrap34">
<p:input port="source">
<p:pipe step="col3" port="result"/>
</p:input>
<p:input port="alternate">
<p:pipe step="col4" port="result"/>
</p:input>
</p:pack>
<p:pack name="c1234" wrapper="wrapper">
<p:input port="source">
<p:pipe step="c12" port="result"/>
</p:input>
<p:input port="alternate">
<p:pipe step="c34" port="result"/>
</p:input>
</p:pack>
<p:for-each>
<p:for-each>
<p:iteration-source select="//td"/>
<p:identity/>
</p:for-each>
<p:wrap-sequence wrapper="tr"/>
</p:for-each>
<p:wrap-sequence wrapper="table"/>
</p:viewport>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc" version="1.0"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
exclude-inline-prefixes="cx"
name="main">
<p:output port="result"/>
<p:serialization port="result" indent="true"/>
<p:template>
<p:input port="source"><p:empty/></p:input>
<p:input port="template">
<p:inline>
<system-properties>
<standard-properties>
<episode>{$episode}</episode>
<language>{$language}</language>
<product-name>{$product-name}</product-name>
<product-version>{$product-version}</product-version>
<vendor>{$vendor}</vendor>
<vendor-uri>{$vendor-uri}</vendor-uri>
<version>{$version}</version>
<xpath-version>{$xpath-version}</xpath-version>
<psvi-supported>{$psvi-supported}</psvi-supported>
</standard-properties>
<calabash-properties>
<general-values>{$general-values}</general-values>
<xpointer-on-text>{$xpointer-on-text}</xpointer-on-text>
<transparent-json>{$transparent-json}</transparent-json>
</calabash-properties>
<unknown-property>{$fred}</unknown-property>
</system-properties>
</p:inline>
</p:input>
<p:with-param name="episode" select="p:system-property('p:episode')"/>
<p:with-param name="language" select="p:system-property('p:language')"/>
<p:with-param name="product-name" select="p:system-property('p:product-name')"/>
<p:with-param name="product-version" select="p:system-property('p:product-version')"/>
<p:with-param name="vendor" select="p:system-property('p:vendor')"/>
<p:with-param name="vendor-uri" select="p:system-property('p:vendor-uri')"/>
<p:with-param name="version" select="p:system-property('p:version')"/>
<p:with-param name="xpath-version" select="p:system-property('p:xpath-version')"/>
<p:with-param name="psvi-supported" select="p:system-property('p:psvi-supported')"/>
<p:with-param name="general-values" select="p:system-property('cx:general-values')"/>
<p:with-param name="xpointer-on-text" select="p:system-property('cx:xpointer-on-text')"/>
<p:with-param name="transparent-json" select="p:system-property('cx:transparent-json')"/>
<p:with-param name="fred" select="p:system-property('cx:fred')"/>
</p:template>
</p:declare-step>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:cx="http://xmlcalabash.com/ns/extensions"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:pl="http://www.w3.org/XML/XProc/docs/library"
name="main" version="1.0">
<p:input port="source">
<p:document href="reference.xml"/>
</p:input>
<p:input port="parameters" kind="parameter"/>
<p:output port="result"/>
<p:xinclude name="xinclude"/>
<p:xslt name="patchdb">
<p:input port="stylesheet">
<p:document href="../../style/patch-db.xsl"/>
</p:input>
</p:xslt>
<p:xslt name="style">
<p:input port="stylesheet">
<p:document href="../../style/html.xsl"/>
</p:input>
</p:xslt>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This example also does a “post”, but it gets back binary.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:http-request>
<p:input port="source">
<p:inline>
<c:request href="http://tests.xproc.org/service/fixed-binary" method="post">
<c:body content-type="application/xml">
<c:any-content/>
</c:body>
</c:request>
</p:inline>
</p:input>
</p:http-request>
<p:string-replace match="/c:body/text()"
replace="'… base64-binary-content-elided …'"/>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version='1.0'>
<p:option name="href"/>
<p:variable name="abshref" select="resolve-uri($href, 'http://example.com/')"/>
<p:load>
<p:with-option name="href" select="$abshref"/>
</p:load>
<p:group>
<p:variable name="version" select="/*/@version"/>
...
</p:group>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:c="http://www.w3.org/ns/xproc-step"
xmlns:ml="http://xmlcalabash.com/ns/extensions/marklogic"
xmlns:exf="http://exproc.org/standard/functions"
exclude-inline-prefixes="c ml exf"
name="main" version="1.0">
<p:output port="result">
<p:pipe step="insert" port="result"/>
</p:output>
<p:option name="href" required="true"/>
<p:import href="/home/ndw/xmlcalabash.com/extension/steps/library-1.0.xpl"/>
<p:variable name="uri"
select="substring-after(resolve-uri($href, exf:cwd()), '/xproc/src')"/>
<p:load>
<p:with-option name="href" select="resolve-uri($href, exf:cwd())"/>
</p:load>
<ml:insert-document name="insert"
user="admin" password="<PASSWORD>" host="localhost" port="7102">
<p:with-option name="uri" select="$uri"/>
</ml:insert-document>
</p:declare-step>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>In this example, we store a document to the filesystem.
</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:show-source='false'>
<doc/>
</p:pipeinfo>
<p:store name="store" href="/tmp/out.xml"/>
<p:identity>
<p:input port="source">
<p:pipe step="store" port="result"/>
</p:input>
</p:identity>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This example is predicated on the notion that the pipeline is
being used to implement some web service end point. The web server packages
up the request in XML and passes it on to our pipeline.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<request xmlns="http://example.com/webservice">
<uri>http://example.com/service</uri>
<params>a=b&c=d&test=this%20or%20that</params>
</request>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>A web service that simply returned its parameters decoded into
a <tag>c:param-set</tag> would be pretty pointless. In a real pipeline, they'd
probably be passed to <step>p:xslt</step> or some other step.</para>
</p:documentation>
<p:www-form-urldecode xmlns:ws="http://example.com/webservice">
<p:with-option name="value" select="/ws:request/ws:params"/>
</p:www-form-urldecode>
</p:pipeline>
<file_sep><p:pipeline xmlns:p="http://www.w3.org/ns/xproc"
xmlns:h="http://www.w3.org/1999/xhtml"
version="1.0">
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>We can jump this last hurdle by changing the
<option>match</option> option so that it doesn't even consider
first paragraphs.</para>
</p:documentation>
<p:pipeinfo>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Document</title>
</head>
<body>
<p>Some text.</p>
<pre>Some example pre text.</pre>
<p>Some more text.</p>
<p>Yet even more text.</p>
<p>A third paragraph.</p>
</body>
</html>
</p:pipeinfo>
<p:wrap match="h:p[count(preceding-sibling::h:p) > 1]" wrapper="div"
wrapper-namespace="http://www.w3.org/1999/xhtml"
group-adjacent="count(preceding-sibling::h:p) > 1"/>
</p:pipeline>
<file_sep><p:declare-step xmlns:p="http://www.w3.org/ns/xproc"
xmlns:db="http://docbook.org/ns/docbook"
version="1.0">
<p:input port="source" sequence="true"/>
<p:output port="result"/>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>This pipeline accepts a sequence of documents and counts the number
of <emphasis>non-</emphasis>DocBook documents in the sequence.</para>
</p:documentation>
<p:pipeinfo xmlns:cx="http://xmlcalabash.com/ns/extensions"
cx:diff='false'>
<doc>
<para>Hello world.</para>
</doc>
</p:pipeinfo>
<p:documentation xmlns="http://docbook.org/ns/docbook">
<para>(FIXME: the example doesn't really get a sequence)</para>
</p:documentation>
<p:split-sequence name="split" test="/db:*"/>
<p:sink/>
<p:count>
<p:input port="source">
<p:pipe step="split" port="not-matched"/>
</p:input>
</p:count>
</p:declare-step>
|
6d778307e6ca6c5fdc17e94e20a53904c5b7bb55
|
[
"Makefile",
"XSLT",
"Markdown",
"Perl",
"XProc"
] | 109 |
Makefile
|
Zearin/xprocbook
|
798d433e1b114aa4867f850d6dee816185354133
|
1eddab90d17052737b8a396a4094b614d18e5fe9
|
refs/heads/master
|
<repo_name>cperry164/ELE8307<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_planet.h
#ifndef SS_PLANET_H
#define SS_PLANET_H
#include "ss_solar_system_constants.h"
#include "camera3d.h"
#include "vecteur3d.h"
#include "vecteur4d.h"
#include "ecran2d.h"
#include "matrice4d.h"
#include "math_constants.h"
#define GRAVITATIONAL_CONSTANT 6.67E-11 // Nm2/kg2
typedef struct {
// Properties
float radius;
float mass;
int color;
float orbit_a;
// Physics
vecteur3d_t center;
vecteur3d_t speed;
// Display
vecteur3d_t screenCenter[2];
int screenRadius[2];
int visible[2];
int current_display_buff, previous_display_buff;
vecteur3d_t light_dir, light_top;
} ss_planet_t;
void ss_planet_init( ss_planet_t *planet, float mass, float radius, float orbit_a, float orbit_t, int color );
void ss_planet_updatePos( ss_planet_t *planet, float dt );
void ss_planet_updateSpeed( ss_planet_t *planet, float dVx, float dVy );
void ss_planet_render( ss_planet_t *planet, camera3d_t *cam );
void ss_planet_draw( ss_planet_t *planet );
void ss_planet_clear( ss_planet_t *planet );
void ss_planet_swapDisplayBuffer( ss_planet_t *planet );
void ss_planet_drawBall( int x0, int y0, int radius, int color );
void ss_planet_drawBall3D( int x0, int y0, int radius, int color, vecteur3d_t *vz, vecteur3d_t *vy );
inline int ss_planet_getBall3DReferenceIntensity( float x, float y, float z, int radius );
int ss_planet_getBall3DIntensity( int x, int y, int radius, matrice4d_t *transform );
void ss_planet_clipSpaceToScreenSpace( vecteur3d_t *pt, vecteur3d_t *result );
#endif //SS_PLANETE_H
<file_sep>/Labo1/sources_vhdl_lab1/ctrl_clavier_mauvais.vhd
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity ctrl_clavier_mauvais is
port (
ps2_clk : in std_logic;
ps2_dat : in std_logic;
usedw : out std_logic_vector(5 downto 0);
key_code : out std_logic_vector(7 downto 0);
rd : in std_logic;
empty : out std_logic;
clk : in std_logic;
rst_n : in std_logic
);
end ctrl_clavier_mauvais;
architecture rtl of ctrl_clavier_mauvais is
signal s_rst : std_logic;
signal s_fifo_wr : std_logic;
signal s_fifo_in : std_logic_vector(7 downto 0);
signal s_fifo_full : std_logic;
signal ps2_bitcount : std_logic_vector(3 downto 0);
signal ps2_word : std_logic_vector(10 downto 0);
signal ps2_bitdone : std_logic;
signal reg_fifo : std_logic_vector(7 downto 0);
component lpm_fifo0
PORT
(
clock : IN STD_LOGIC ;
data : IN STD_LOGIC_VECTOR (7 DOWNTO 0);
rdreq : IN STD_LOGIC ;
wrreq : IN STD_LOGIC ;
empty : OUT STD_LOGIC ;
full : OUT STD_LOGIC ;
q : OUT STD_LOGIC_VECTOR (7 DOWNTO 0);
usedw : OUT STD_LOGIC_VECTOR (5 DOWNTO 0);
aclr : IN STD_LOGIC
);
end component;
begin
u_fifo : lpm_fifo0
port map (
clock => clk,
data => s_fifo_in,
rdreq => rd,
wrreq => s_fifo_wr,
empty => empty,
full => s_fifo_full,
q => key_code,
usedw => usedw,
aclr => s_rst
);
s_fifo_in <= reg_fifo;
s_rst <= not( rst_n );
ACQ_PROCESS : process( clk, rst_n )
begin
if( rst_n = '0' ) then
ps2_bitcount <= (others => '0');
ps2_word <= (others => '0');
ps2_bitdone <= '0';
elsif( clk'event AND clk = '1' ) then
if( ps2_clk = '0' ) then
if( ps2_bitdone = '0' AND ps2_bitcount < 10) then
ps2_bitdone <= '1';
ps2_word <= ps2_dat & ps2_word(10 downto 1);
ps2_bitcount <= ps2_bitcount + 1;
s_fifo_wr <= '0';
elsif( ps2_bitdone = '0' ) then
ps2_bitdone <= '1';
reg_fifo <= ps2_word(9 downto 2);
ps2_bitcount <= "0000";
s_fifo_wr <= '1';
end if;
else
ps2_bitdone <= '0';
s_fifo_wr <= '0';
end if;
end if;
end process;
end rtl;<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_solar_system.h
#ifndef SS_SOLAR_SYSTEM_H
#define SS_SOLAR_SYSTEM_H
#include "ecran2d.h"
#include "ss_solar_system_constants.h"
#include "ss_planet.h"
#include "ss_orbit.h"
#include "camera3d.h"
#include "vecteur3d.h"
#include "vecteur4d.h"
#include "matrice4d.h"
#include "math_constants.h"
#define SOLAR_SYSTEM_NB_PLANETS 9
#define SOLAR_SYSTEM_TIMESTEP_SEC 3600
typedef struct {
camera3d_t camera;
ss_orbit_t orbites[SOLAR_SYSTEM_NB_PLANETS];
ss_planet_t planetes[SOLAR_SYSTEM_NB_PLANETS+1];
int planetes_sorted_indexes[SOLAR_SYSTEM_NB_PLANETS+1];
float dVx[SOLAR_SYSTEM_NB_PLANETS]; // speedVariations
float dVy[SOLAR_SYSTEM_NB_PLANETS];
} ss_solar_system_t;
void ss_solar_system_init( ss_solar_system_t *system );
void ss_solar_system_iterate( ss_solar_system_t *system );
void ss_solar_system_calculateSpeedVariations( ss_solar_system_t *system );
void ss_solar_system_update( ss_solar_system_t *system );
void ss_solar_system_sortPlanets( ss_solar_system_t *system );
#endif<file_sep>/Labo1/sources_vhdl_lab1/decodeur7segment.vhd
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
entity decodeur7segment is
port (
nombre_0a9 : in std_logic_vector(3 downto 0);
segments : out std_logic_vector(6 downto 0)
);
end entity decodeur7segment;
architecture rtl of decodeur7segment is
begin
with( nombre_0a9 ) select
segments <= "0111111" when "0000",
"0000110" when "0001",
"1011011" when "0010",
"1001111" when "0011",
"1100110" when "0100",
"1101101" when "0101",
"1111101" when "0110",
"0000111" when "0111",
"1111111" when "1000",
"1101111" when "1001",
"0000000" when others;
end rtl;
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/vecteur3d.c
#include "vecteur3d.h"
/*********************************************************
vecteur3d_init()
*********************************************************/
void vecteur3d_init( vecteur3d_t *v, float x, float y, float z ) {
v->x = x;
v->y = y;
v->z = z;
}
/*********************************************************
vecteur3d_add()
*********************************************************/
void vecteur3d_add( vecteur3d_t *v, vecteur3d_t *w ) {
v->x = v->x + w->x;
v->y = v->y + w->y;
v->z = v->z + w->z;
}
/*********************************************************
vecteur3d_sub()
*********************************************************/
void vecteur3d_sub( vecteur3d_t *v, vecteur3d_t *w ) {
v->x = v->x - w->x;
v->y = v->y - w->y;
v->z = v->z - w->z;
}
/*********************************************************
vecteur3d_sub()
*********************************************************/
void vecteur3d_mul( vecteur3d_t *v, float k ) {
v->x *= k;
v->y *= k;
v->z *= k;
}
/*********************************************************
vecteur3d_negate()
*********************************************************/
void vecteur3d_negate( vecteur3d_t *v ) {
v->x = -v->x;
v->y = -v->y;
v->z = -v->z;
}
/*********************************************************
vecteur3d_normalize()
*********************************************************/
void vecteur3d_normalize( vecteur3d_t *v ) {
float len;
len = vecteur3d_length(v);
v->x /= len;
v->y /= len;
v->z /= len;
}
/*********************************************************
vecteur3d_length()
*********************************************************/
float vecteur3d_length( vecteur3d_t *v ) {
return (float)sqrt( v->x*v->x + v->y*v->y + v->z*v->z );
}
/*********************************************************
vecteur3d_squaredLength()
*********************************************************/
float vecteur3d_squaredLength( vecteur3d_t *v ) {
return ( v->x*v->x + v->y*v->y + v->z*v->z );
}
/*********************************************************
vecteur3d_dotProduct()
*********************************************************/
float vecteur3d_dotProduct( vecteur3d_t *v, vecteur3d_t *w ) {
return ( v->x*w->x + v->y*w->y + v->z*w->z );
}
/*********************************************************
vecteur3d_crossProduct()
*********************************************************/
void vecteur3d_crossProduct( vecteur3d_t *v, vecteur3d_t *w , vecteur3d_t* result) {
result->x = v->y*w->z - v->z*w->y;
result->y = v->z*w->x - v->x*w->z;
result->z = v->x*w->y - v->y*w->x;
}
/*********************************************************
vecteur3d_angle()
*********************************************************/
float vecteur3d_angle( vecteur3d_t *v, vecteur3d_t *w ) {
// Angle E (0,PI)
float cosA = vecteur3d_dotProduct(v,w) / (vecteur3d_length(v)*vecteur3d_length(w));
return acos(cosA);
}
/*********************************************************
vecteur3d_distance()
distance entre 2 points
*********************************************************/
float vecteur3d_distance( vecteur3d_t *p1, vecteur3d_t *p2 ) {
float dx,dy,dz;
dx = p2->x - p1->x;
dz = p2->z - p1->z;
dy = p2->y - p1->y;
return sqrt( dx*dx + dy*dy + dz*dz );
}
/*********************************************************
vecteur3d_print()
*********************************************************/
void vecteur3d_print( vecteur3d_t *v ) {
printf("(%2.2f, %2.2f, %2.2f)", v->x,v->y,v->z);
}
<file_sep>/Labo2/sources_lab2/vga/hdl/vga.vhd
Library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.std_logic_arith.all;
use IEEE.std_logic_unsigned.all;
--
-- Modified from original (Lab4 ver) by MAD, with 8 color model (32 intensity each) instead of 4x64
--
LIBRARY lpm;
USE lpm.lpm_components.all;
ENTITY vga is
PORT(
-- NIOSII side
reset : in std_logic;
clk : in std_logic;
addr : in std_logic_vector(18 downto 0);
data : in std_logic_vector(31 downto 0);
wr : in std_logic;
busy : out std_logic;
-- SRAM side
SRAM_ADDR : out std_logic_vector(17 downto 0);
SRAM_CE_N : out std_logic;
SRAM_DQ : inout std_logic_vector(15 downto 0);
SRAM_LB_N : out std_logic;
SRAM_OE_N : out std_logic;
SRAM_UB_N : out std_logic;
SRAM_WE_N : out std_logic;
-- VGA side
CLOCK_25 : in std_logic;
VGA_BLANK : out std_logic;
VGA_B : out std_logic_vector(9 downto 0);
VGA_CLK : out std_logic;
VGA_G : out std_logic_vector(9 downto 0);
VGA_HS : out std_logic;
VGA_R : out std_logic_vector(9 downto 0);
VGA_SYNC : out std_logic;
VGA_VS : out std_logic
)
;
END vga;
ARCHITECTURE JPD of vga is
TYPE sm1_type is (read, write1, write2);
SIGNAL sm1 : sm1_type;
SIGNAL current_color : STD_LOGIC_VECTOR(7 downto 0);
SIGNAL start_read : STD_LOGIC;
SIGNAL fifo_in_write, fifo_in_read, fifo_in_full, fifo_in_empty : STD_LOGIC;
SIGNAL fifo_in_input, fifo_in_output : STD_LOGIC_VECTOR(31 DOWNTO 0);
SIGNAL latch_addr : STD_LOGIC_VECTOR(18 DOWNTO 0);
SIGNAL latch_data : STD_LOGIC_VECTOR(31 DOWNTO 0);
SIGNAL delay_start : STD_LOGIC;
SIGNAL nreset,sync_fifo_out : STD_LOGIC;
SIGNAL fifo_out_write, fifo_out_read, fifo_out_full, fifo_out_empty : STD_LOGIC;
SIGNAL fifo_out_input, fifo_out_output : STD_LOGIC_VECTOR(15 DOWNTO 0);
SIGNAL fifo_out_usedw : STD_LOGIC_VECTOR(3 DOWNTO 0);
SIGNAL latch_SRAM_ADDR : STD_LOGIC_VECTOR(17 DOWNTO 0);
SIGNAL latch_SRAM_DQ_wr : STD_LOGIC_VECTOR(15 DOWNTO 0);
SIGNAL latch_SRAM_DQ_rd : STD_LOGIC_VECTOR(15 DOWNTO 0);
SIGNAL latch_SRAM_LB_N : STD_LOGIC;
SIGNAL latch_SRAM_UB_N : STD_LOGIC;
SIGNAL latch_SRAM_OE_N : STD_LOGIC;
SIGNAL latch_SRAM_WE_N : STD_LOGIC;
SIGNAL latch_SRAM_DQ_in : STD_LOGIC;
SIGNAL latch_fifo_out_write, latch_fifo_out_write_d1 : STD_LOGIC;
SIGNAL video_on, video_on_v, video_on_h : STD_LOGIC;
SIGNAL h_count, v_count : STD_LOGIC_VECTOR(9 DOWNTO 0);
SIGNAL H_SYNC, V_SYNC : STD_LOGIC;
SIGNAL write_address, read_address : STD_LOGIC_VECTOR(18 downto 0);
SIGNAL write_data : STD_LOGIC_VECTOR(7 downto 0);
-- COLOR INDEXES
CONSTANT WHITE_COLORINDEX : std_logic_vector(2 downto 0) := "000";
CONSTANT RED_COLORINDEX : std_logic_vector(2 downto 0) := "001";
CONSTANT GREEN_COLORINDEX: std_logic_vector(2 downto 0) := "010";
CONSTANT BLUE_COLORINDEX : std_logic_vector(2 downto 0) := "011";
CONSTANT YELLOW_COLORINDEX : std_logic_vector(2 downto 0) := "100";
CONSTANT BROWN_COLORINDEX : std_logic_vector(2 downto 0) := "101";
CONSTANT CYAN_COLORINDEX : std_logic_vector(2 downto 0) := "110";
CONSTANT PURPLE_COLORINDEX : std_logic_vector(2 downto 0) := "111";
BEGIN
FIFO_IN: LPM_FIFO
generic map (
LPM_WIDTH => 32,
LPM_WIDTHU => 7,
LPM_NUMWORDS => 128,
LPM_SHOWAHEAD => "ON"
)
port map (
DATA => fifo_in_input,
CLOCK => clk,
WRREQ => fifo_in_write,
RDREQ => fifo_in_read,
ACLR => reset,
Q => fifo_in_output,
FULL => fifo_in_full,
EMPTY => fifo_in_empty
);
fifo_in_input <= "00000" & latch_data(7 downto 0) & latch_addr(18 downto 0);
fifo_in_write <= delay_start;
busy <= fifo_in_full;
process(clk,reset)
begin
if (reset = '1') then
delay_start <= '0';
latch_addr <= (others => '0');
latch_data <= (others => '0');
elsif (clk'event and clk='1') then
if (wr='1') then
latch_addr <= addr;
latch_data <= data;
end if;
delay_start <= wr or (delay_start and fifo_in_full);
end if;
end process;
FIFO_OUT: LPM_FIFO_DC
generic map (
LPM_WIDTH => 16,
LPM_WIDTHU => 4,
LPM_NUMWORDS => 16
)
port map (
DATA => fifo_out_input,
WRCLOCK => clk,
RDCLOCK => clock_25,
WRREQ => fifo_out_write,
RDREQ => fifo_out_read,
ACLR => reset,
Q => fifo_out_output,
WRUSEDW => fifo_out_usedw,
WRFULL => fifo_out_full,
RDEMPTY => fifo_out_empty
);
process (reset, clock_25)
begin
if (reset = '1') then nreset <= '0';
elsif (clock_25'event and clock_25='1') then
nreset <= '1';
end if;
end process;
process (nreset,clock_25)
begin
if (nreset='0') then
fifo_out_read <= '0';
sync_fifo_out <= '0';
elsif (clock_25'event and clock_25='1') then
if ((v_count = 479) and (h_count = 638) and (fifo_out_empty = '0')) then
sync_fifo_out <= '1';
end if;
if ( (v_count < 480) and (h_count < 640) and (h_count(0) = '0') ) then
fifo_out_read <= sync_fifo_out;
else
fifo_out_read <= '0';
end if;
end if;
end process;
current_color <= fifo_out_output(7 downto 0) when (h_count(0) = '0') else fifo_out_output(15 downto 8);
write_address <= fifo_in_output(18 downto 0);
write_data <= fifo_in_output(26 downto 19);
SRAM_CE_N <= '0';
process (clk)
begin
if (clk'event and clk='1') then
SRAM_ADDR <= latch_SRAM_ADDR;
if (latch_SRAM_OE_N = '0') then SRAM_DQ <= (others => 'Z');
else SRAM_DQ <= latch_SRAM_DQ_wr;
end if;
SRAM_LB_N <= latch_SRAM_LB_N;
SRAM_UB_N <= latch_SRAM_UB_N;
SRAM_OE_N <= latch_SRAM_OE_N;
latch_SRAM_DQ_rd <= SRAM_DQ;
end if;
end process;
process (reset,clk)
variable next_read_address : std_logic_vector(18 downto 0);
begin
if (reset='1') then
sm1 <= read;
latch_SRAM_ADDR <= (others => '0');
latch_SRAM_DQ_wr <= (others => '0');
latch_SRAM_LB_N <= '0';
latch_SRAM_UB_N <= '0';
latch_SRAM_OE_N <= '0';
latch_SRAM_WE_N <= '1';
latch_fifo_out_write <= '0';
read_address <= (others => '0');
fifo_out_write <= '0';
fifo_in_read <= '0';
elsif (clk'event and clk='1') then
fifo_out_write <= latch_fifo_out_write;
case sm1 is
when read =>
if (fifo_out_usedw(3)='0') then
if (read_address = 307198) then
next_read_address := (others => '0');
else
next_read_address := read_address + 2;
end if;
read_address <= next_read_address;
latch_SRAM_ADDR <= next_read_address(18 downto 1);
latch_fifo_out_write <= '1';
else
latch_fifo_out_write <= '0';
if (fifo_in_empty='0') then
latch_SRAM_ADDR <= write_address(18 downto 1);
latch_SRAM_DQ_wr <= write_data & write_data;
latch_SRAM_LB_N <= write_address(0);
latch_SRAM_UB_N <= not write_address(0);
latch_SRAM_OE_N <= '1';
fifo_in_read <= '1';
sm1 <= write1;
end if;
end if;
when write1 =>
latch_SRAM_WE_N <= '0';
fifo_in_read <='0';
sm1 <= write2;
when write2 =>
latch_SRAM_WE_N <= '1';
if (fifo_out_usedw(3)='0') or (fifo_in_empty='1') then
latch_SRAM_ADDR <= read_address(18 downto 1);
latch_SRAM_DQ_wr <= (others => '0');
latch_SRAM_LB_N <= '0';
latch_SRAM_UB_N <= '0';
latch_SRAM_OE_N <= '0';
sm1 <= read;
else
latch_SRAM_ADDR <= write_address(18 downto 1);
latch_SRAM_DQ_wr <= write_data & write_data;
latch_SRAM_LB_N <= write_address(0);
latch_SRAM_UB_N <= not write_address(0);
fifo_in_read <= '1';
sm1 <= write1;
end if;
end case;
end if;
end process;
process (reset,clk)
begin
if (reset='1') then
SRAM_WE_N <= '1';
elsif (clk'event and clk='0') then
SRAM_WE_N <= latch_SRAM_WE_N;
end if;
end process;
fifo_out_input <= latch_SRAM_DQ_rd;
process (nreset,clock_25)
begin
if (nreset='0') then
VGA_R <= (others => '0');
VGA_G <= (others => '0');
VGA_B <= (others => '0');
elsif (clock_25'EVENT) AND (clock_25='1') then
VGA_R <= (others => '0');
VGA_G <= (others => '0');
VGA_B <= (others => '0');
if (video_on = '1') then
case current_color(7 downto 5) is
when WHITE_COLORINDEX =>
VGA_R <= current_color(4 downto 0) & "00000";
VGA_G <= current_color(4 downto 0) & "00000";
VGA_B <= current_color(4 downto 0) & "00000";
when RED_COLORINDEX =>
VGA_R <= current_color(4 downto 0) & "00000";
when GREEN_COLORINDEX =>
VGA_G <= current_color(4 downto 0) & "00000";
when BLUE_COLORINDEX =>
VGA_B <= current_color(4 downto 0) & "00000";
when YELLOW_COLORINDEX =>
VGA_R <= current_color(4 downto 0) & "00000";
VGA_G <= current_color(4 downto 0) & "00000";
when BROWN_COLORINDEX =>
VGA_R <= "0" & current_color(4 downto 0) & "0000";
VGA_G <= "00" & current_color(4 downto 0) & "000";
VGA_B <= "0000" & current_color(4 downto 0) & "0";
when CYAN_COLORINDEX =>
VGA_G <= current_color(4 downto 0) & "00000";
VGA_B <= current_color(4 downto 0) & "00000";
when PURPLE_COLORINDEX =>
VGA_R <= current_color(4 downto 0) & "00000";
VGA_B <= current_color(4 downto 0) & "00000";
end case;
end if;
end if;
end process;
-- video_on is high only when RGB data is displayed
video_on <= video_on_H AND video_on_V;
process (nreset,clock_25)
begin
if (nreset='0') then
H_SYNC <= '1';
V_SYNC <= '1';
h_count <= (others => '0');
v_count <= "0111011111";
video_on_h <= '1';
video_on_v <= '1';
elsif (clock_25'EVENT) AND (clock_25='1') then
--Generate Horizontal and Vertical Timing Signals for Video Signal
-- H_count counts pixels (640 + extra time for sync signals)
--
-- Horiz_sync ------------------------------------__________--------
-- H_count 0 640 659 755 799
--
IF (h_count = 799) THEN
h_count <= "0000000000";
ELSE
h_count <= h_count + 1;
END IF;
--Generate Horizontal Sync Signal using H_count
IF (h_count <= 755) AND (h_count >= 659) THEN
H_SYNC <= '0';
ELSE
H_SYNC <= '1';
END IF;
--V_count counts rows of pixels (480 + extra time for sync signals)
--
-- Vert_sync -----------------------------------------------_______------------
-- V_count 0 480 493-494 524
--
IF (v_count = 524) AND (h_count = 699) THEN
v_count <= "0000000000";
ELSE
IF (h_count = 699) THEN
v_count <= v_count + 1;
END IF;
END IF;
-- Generate Vertical Sync Signal using V_count
IF (v_count <= 494) AND (v_count >= 493) THEN
V_SYNC <= '0';
ELSE
V_SYNC <= '1';
END IF;
-- Generate Video on Screen Signals for Pixel Data
IF (h_count = 799) THEN
video_on_h <= '1';
ELSIF (h_count = 639) THEN
video_on_h <= '0';
END IF;
IF (h_count = 699) THEN
IF (v_count = 524) THEN
video_on_v <= '1';
ELSIF (v_count = 479) THEN
video_on_v <= '0';
END IF;
END IF;
END IF;
END PROCESS;
VGA_CLK <= not clock_25;
VGA_HS <= H_SYNC;
VGA_VS <= V_SYNC;
VGA_BLANK <= H_SYNC and V_SYNC;
VGA_SYNC <= '0';
END JPD;
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/math_constants.h
#ifndef MATH_CONSTANTS_H
#define MATH_CONSTANTS_H
#define PI 3.141592653589793 // omg vsc
#endif // MATH_CONSTANTS_H
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_solar_system.c
#include "ss_solar_system.h"
#define LINECLIP_CODE_RIGHT 8
#define LINECLIP_CODE_TOP 4
#define LINECLIP_CODE_LEFT 2
#define LINECLIP_CODE_BOTTOM 1
/********************************************************************
ss_solar_system_init()
Solar system initialization. Sets all planets and the sun.
*******************************************************************/
void ss_solar_system_init( ss_solar_system_t *ss ) {
int i;
// Initialize orbits
ss_orbit_init(&ss->orbites[0], MERCURE_ORBIT_A);
ss_orbit_init(&ss->orbites[1], VENUS_ORBIT_A);
ss_orbit_init(&ss->orbites[2], TERRE_ORBIT_A);
ss_orbit_init(&ss->orbites[3], MARS_ORBIT_A);
ss_orbit_init(&ss->orbites[4], JUPITER_ORBIT_A);
ss_orbit_init(&ss->orbites[5], SATURNE_ORBIT_A);
ss_orbit_init(&ss->orbites[6], URANUS_ORBIT_A);
ss_orbit_init(&ss->orbites[7], NEPTUNE_ORBIT_A);
ss_orbit_init(&ss->orbites[8], PLUTON_ORBIT_A);
// Initializes planets
ss_planet_init( &ss->planetes[0], MERCURE_RELATIVE_MASS*EARTH_MASS, MERCURE_RAYON, MERCURE_ORBIT_A, MERCURE_ORBIT_T, COLOR_RED );
ss_planet_init( &ss->planetes[1], VENUS_RELATIVE_MASS*EARTH_MASS, VENUS_RAYON, VENUS_ORBIT_A, VENUS_ORBIT_T, COLOR_GREEN );
ss_planet_init( &ss->planetes[2], TERRE_RELATIVE_MASS*EARTH_MASS, TERRE_RAYON, TERRE_ORBIT_A, TERRE_ORBIT_T, COLOR_BLUE );
ss_planet_init( &ss->planetes[3], MARS_RELATIVE_MASS*EARTH_MASS, MARS_RAYON, MARS_ORBIT_A, MARS_ORBIT_T, COLOR_RED );
ss_planet_init( &ss->planetes[4], JUPITER_RELATIVE_MASS*EARTH_MASS, JUPITER_RAYON, JUPITER_ORBIT_A, JUPITER_ORBIT_T, COLOR_BROWN );
ss_planet_init( &ss->planetes[5], SATURN_RELATIVE_MASS*EARTH_MASS, SATURNE_RAYON, SATURNE_ORBIT_A, SATURNE_ORBIT_T, COLOR_YELLOW );
ss_planet_init( &ss->planetes[6], URANUS_RELATIVE_MASS*EARTH_MASS, URANUS_RAYON, URANUS_ORBIT_A, URANUS_ORBIT_T, COLOR_CYAN );
ss_planet_init( &ss->planetes[7], NEPTUNE_RELATIVE_MASS*EARTH_MASS, NEPTUNE_RAYON, NEPTUNE_ORBIT_A, NEPTUNE_ORBIT_T, COLOR_PURPLE );
ss_planet_init( &ss->planetes[8], PLUTON_RELATIVE_MASS*EARTH_MASS, PLUTON_RAYON, PLUTON_ORBIT_A, PLUTON_ORBIT_T, COLOR_WHITE );
// Sun as the "+1" planet
ss_planet_init( &ss->planetes[9], SOLEIL_RELATIVE_MASS*EARTH_MASS, SOLEIL_RAYON, 0, 0, COLOR_YELLOW );
// Initialize Camera
camera3d_init( &ss->camera );
}
/********************************************************************
ss_solar_system_iterate()
*******************************************************************/
void ss_solar_system_iterate( ss_solar_system_t *system ) {
int i;
int sorted_planet_index;
// Transformer les orbites en lignes pretes pour l'ecran
for( i=0; i< SOLAR_SYSTEM_NB_PLANETS; i++ ) {
ss_orbit_render( &system->orbites[i], &system->camera );
}
// Determiner les params d'affichage des planetes
for( i=0; i< SOLAR_SYSTEM_NB_PLANETS+1; i++ ) {
ss_planet_render( &system->planetes[i], &system->camera );
}
ss_solar_system_sortPlanets(system);
ss_solar_system_calculateSpeedVariations(system);
ss_solar_system_update(system);
// Redessiner les orbites
for( i=0; i< SOLAR_SYSTEM_NB_PLANETS; i++ ) {
ss_orbit_clear( &system->orbites[i] );
ss_orbit_draw( &system->orbites[i] );
ss_orbit_swapDisplayBuffer(&system->orbites[i]);
}
// Redessiner les planetes
for( i=0; i< SOLAR_SYSTEM_NB_PLANETS+1; i++ ) {
sorted_planet_index = system->planetes_sorted_indexes[i];
ss_planet_clear( &system->planetes[sorted_planet_index] );
ss_planet_draw( &system->planetes[sorted_planet_index] );
ss_planet_swapDisplayBuffer(&system->planetes[sorted_planet_index]);
}
}
/********************************************************************
ss_solar_system_calculateSpeedVariations()
*******************************************************************/
void ss_solar_system_calculateSpeedVariations( ss_solar_system_t *system ) {
int i,j;
float dV, dVx, dVy;
vecteur3d_t u; // f dir
vecteur3d_t v1,v2;
float vx, vy;
float r;
for( i=0; i< SOLAR_SYSTEM_NB_PLANETS; i++ ) {
r = vecteur3d_length(&system->planetes[i].center);
u = system->planetes[i].center;
vecteur3d_negate(&u);
vecteur3d_normalize(&u);
dV = GRAVITATIONAL_CONSTANT*(EARTH_MASS*SOLEIL_RELATIVE_MASS)/(r*r);
system->dVx[i] = u.x * dV * SOLAR_SYSTEM_TIMESTEP_SEC;
system->dVy[i] = u.y * dV * SOLAR_SYSTEM_TIMESTEP_SEC;
for( j=0; j<SOLAR_SYSTEM_NB_PLANETS; j++ ) {
if( i != j ) {
u = system->planetes[j].center;
vecteur3d_sub(&u, &system->planetes[i].center);
r = vecteur3d_length(&u);
vecteur3d_normalize(&u);
dV = GRAVITATIONAL_CONSTANT*(system->planetes[j].mass)/(r*r);
system->dVx[i] += u.x * dV * SOLAR_SYSTEM_TIMESTEP_SEC;
system->dVy[i] += u.y * dV * SOLAR_SYSTEM_TIMESTEP_SEC;
}
}
}
}
/********************************************************************
ss_solar_system_update()
Updates the positions of each planet.
*******************************************************************/
void ss_solar_system_update( ss_solar_system_t *ss ) {
int i,j;
float dt_sec = 3600;
for(i=0; i<SOLAR_SYSTEM_NB_PLANETS; i++) {
ss_planet_updateSpeed( &ss->planetes[i], ss->dVx[i], ss->dVy[i] );
ss_planet_updatePos( &ss->planetes[i], SOLAR_SYSTEM_TIMESTEP_SEC );
}
}
/********************************************************************
ss_solar_system_sortPlanets()
Sorts the planet by distance from cam to planet. (desc)
*******************************************************************/
void ss_solar_system_sortPlanets( ss_solar_system_t *system ) {
int i,n,swapped,t;
float d;
float planet_dist[SOLAR_SYSTEM_NB_PLANETS+1];
for( i=0; i<SOLAR_SYSTEM_NB_PLANETS+1; i++ ) {
system->planetes_sorted_indexes[i] = i;
planet_dist[i] = vecteur3d_distance( &system->camera.center, &system->planetes[i].center );
}
n = SOLAR_SYSTEM_NB_PLANETS+1;
do {
swapped = 0;
n--;
for( i=0; i<n; i++ ){
if( planet_dist[i+1] > planet_dist[i] ) {
d = planet_dist[i];
planet_dist[i] = planet_dist[i+1];
planet_dist[i+1] = d;
t = system->planetes_sorted_indexes[i];
system->planetes_sorted_indexes[i] = system->planetes_sorted_indexes[i+1];
system->planetes_sorted_indexes[i+1] = t;
swapped = 1;
}
}
}
while ( swapped == 1 );
}
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_orbit.c
#include "ss_orbit.h"
#define LINECLIP_CODE_RIGHT 8
#define LINECLIP_CODE_TOP 4
#define LINECLIP_CODE_LEFT 2
#define LINECLIP_CODE_BOTTOM 1
/********************************************************************
ss_orbit_init()
*******************************************************************/
void ss_orbit_init( ss_orbit_t *orbit, float orbit_a ) {
int i;
float angle;
// Planet Orbit points
for( i=0; i< SS_ORBIT_NB_DIV; i++ ) {
angle = 2*PI*(i/(float)SS_ORBIT_NB_DIV);
vecteur3d_init( &orbit->orbit_pts[i], orbit_a*cos( angle ), orbit_a*sin( angle ), 0 );
}
orbit->nb_screen_lines[0] = 0;
orbit->nb_screen_lines[1] = 0;
orbit->current_display_buff = 0;
orbit->previous_display_buff = 1;
}
/********************************************************************
Renders the orbit pts to screen lines in the current display
buffer.
*******************************************************************/
void ss_orbit_render( ss_orbit_t *orbit, camera3d_t *camera ) {
int i;
vecteur3d_t s_orbit_pts[SS_ORBIT_NB_DIV];
vecteur4d_t s4_orbit_pts[SS_ORBIT_NB_DIV];
vecteur3d_t v3d;
vecteur4d_t v4d;
matrice4d_t modelViewClip;
ss_orbit_line_t orbitLine;
// Transform orbit points from space to screen
for( i=0; i<SS_ORBIT_NB_DIV; i++ ) {
matrice4d_product_m4d( &camera->projection_matrix, &camera->view_matrix, &modelViewClip );
matrice4d_product_v3d( &modelViewClip, &orbit->orbit_pts[i], &v4d );
s4_orbit_pts[i] = v4d;
vecteur4d_getVecteur3d( &v4d, &v3d );
ss_orbit_clipSpaceToScreenSpace( &v3d, &s_orbit_pts[i] );
}
// Clip lines
for( i=0; i<SS_ORBIT_NB_DIV-1; i++ ) {
if( s4_orbit_pts[i].z > -1 && s4_orbit_pts[i+1].z > -1) {
ss_orbit_line_init( &orbitLine, s_orbit_pts[i].x, s_orbit_pts[i].y, s_orbit_pts[i+1].x, s_orbit_pts[i+1].y );
if(ss_orbit_line_clip(&orbitLine) == 1 ) {
ss_orbit_addLine(orbit, &orbitLine);
}
}
}
if( s4_orbit_pts[i].z > -1 && s4_orbit_pts[0].z > -1) {
ss_orbit_line_init( &orbitLine, s_orbit_pts[i].x, s_orbit_pts[i].y, s_orbit_pts[0].x, s_orbit_pts[0].y );
if(ss_orbit_line_clip(&orbitLine) == 1 ) {
ss_orbit_addLine(orbit, &orbitLine);
}
}
}
/********************************************************************
ss_orbit_addLine()
*******************************************************************/
void ss_orbit_addLine( ss_orbit_t *orbit, ss_orbit_line_t *line ) {
int buff = orbit->current_display_buff;
orbit->screen_lines[buff][orbit->nb_screen_lines[buff]] = *line;
orbit->nb_screen_lines[buff]++;
}
/********************************************************************
ss_orbit_draw()
*******************************************************************/
void ss_orbit_draw( ss_orbit_t *orbit ) {
int i;
int buff = orbit->current_display_buff;
for( i=0; i< orbit->nb_screen_lines[buff]; i++ ) {
ss_orbit_line_draw( &orbit->screen_lines[buff][i], SS_ORBIT_COLOR );
}
}
/********************************************************************
ss_orbit_clear()
*******************************************************************/
void ss_orbit_clear( ss_orbit_t *orbit ) {
int i;
int buff = orbit->previous_display_buff;
for( i=0; i< orbit->nb_screen_lines[buff]; i++ ) {
ss_orbit_line_draw( &orbit->screen_lines[buff][i], 0 );
}
}
/********************************************************************
ss_orbit_swapDisplayBuffer()
*******************************************************************/
void ss_orbit_swapDisplayBuffer( ss_orbit_t *orbit ) {
if( orbit->current_display_buff == 0 ) {
orbit->current_display_buff = 1;
orbit->previous_display_buff = 0;
}
else {
orbit->current_display_buff = 0;
orbit->previous_display_buff = 1;
}
orbit->nb_screen_lines[orbit->current_display_buff] = 0;
}
/********************************************************************
ss_orbit_line_draw()
*******************************************************************/
void ss_orbit_line_init( ss_orbit_line_t *line, int x0, int y0, int x1, int y1 ) {
line->x0 = x0;
line->x1 = x1;
line->y0 = y0;
line->y1 = y1;
}
int abs( int a ) { if( a>=0 ) return a; else return -a; }
void swap( int *a, int *b) {
int t;
t = *a;
*a = *b;
*b = t;
}
/********************************************************************
ss_orbit_line_draw()
- 8bit color (color_index<<5)+intensity
*******************************************************************/
void ss_orbit_line_draw( ss_orbit_line_t *line, int color ) {
int Dx,Dy, steep;
int ystep, xstep,TwoDy, TwoDyTwoDx, E, xDraw, yDraw, x,y;
int x0,y0,x1,y1;
x0 = line->x0;
x1 = line->x1;
y0 = line->y0;
y1 = line->y1;
Dx = x1 - x0;
Dy = y1 - y0;
steep = (abs(Dy) >= abs(Dx));
if (steep) {
swap(&x0, &y0);
swap(&x1, &y1);
// recompute Dx, Dy after swap
Dx = x1 - x0;
Dy = y1 - y0;
}
xstep = 1;
if (Dx < 0) {
xstep = -1;
Dx = -Dx;
}
ystep = 1;
if (Dy < 0) {
ystep = -1;
Dy = -Dy;
}
TwoDy = 2*Dy;
TwoDyTwoDx = TwoDy - 2*Dx; // 2*Dy - 2*Dx
E = TwoDy - Dx; //2*Dy - Dx
y = y0;
for ( x = x0; x != x1; x += xstep) {
if (steep) {
xDraw = y;
yDraw = x;
}
else {
xDraw = x;
yDraw = y;
}
ecran2d_setPixel( xDraw,yDraw, color);
if (E > 0) {
E += TwoDyTwoDx; //E += 2*Dy - 2*Dx;
y = y + ystep;
}
else {
E += TwoDy; //E += 2*Dy;
}
}
}
/*************************************************************
ss_orbit_line_clip
returns '1' if in screen (need to be drawn)
'0' if rejected
************************************************************/
int ss_orbit_line_clip( ss_orbit_line_t *line ) {
int code0, code1, outCode;
int accept = 0;
int done = 0;
float x,y;
int xmin=0, ymin=0, xmax=ECRAN2D_WIDTH, ymax=ECRAN2D_HEIGHT;
int x0, y0, x1, y1;
x0 = line->x0;
y0 = line->y0;
x1 = line->x1;
y1 = line->y1;
code0 = ss_orbit_line_computeClipCode(x0,y0);
code1 = ss_orbit_line_computeClipCode(x1,y1);
do {
if( (code0|code1) == 0 ) {
accept = 1;
done = 1;
}
else if( (code0 & code1) ) {
done = 1;
}
else {
if( code0 )
outCode = code0;
else
outCode = code1;
if( outCode & LINECLIP_CODE_TOP ) {
x = x0 + (x1-x0) * (ymax-y0)/(y1-y0);
y = ymax;
}
else if( outCode & LINECLIP_CODE_BOTTOM ) {
x = x0 + (x1-x0) * (ymin-y0)/(y1-y0);
y = ymin;
}
else if( outCode & LINECLIP_CODE_RIGHT ) {
y = y0 + (y1-y0) * (xmax-x0)/(x1-x0);
x = xmax;
}
else {
y = y0 + (y1-y0) * (xmin-x0)/(x1-x0);
x = xmin;
}
if( outCode == code0 ) {
x0 = x;
y0 = y;
code0 = ss_orbit_line_computeClipCode(x0,y0);
}
else {
x1 = x;
y1 = y;
code1 = ss_orbit_line_computeClipCode(x1,y1);
}
}
}
while ( done != 1 );
if( accept ) {
//ss_solar_system_drawLine( x0,y0,x1,y1, color );
line->x0 = x0;
line->y0 = y0;
line->x1 = x1;
line->y1 = y1;
return 1;
}
return 0;
}
int ss_orbit_line_computeClipCode( float x, float y ) {
int code = 0;
if ( y > ECRAN2D_HEIGHT ) code |= LINECLIP_CODE_TOP;
else if ( y < 0 ) code |= LINECLIP_CODE_BOTTOM;
if ( x > ECRAN2D_WIDTH ) code |= LINECLIP_CODE_RIGHT;
else if ( x < 0 ) code |= LINECLIP_CODE_LEFT;
return code;
}
/********************************************************************
ss_solar_system_clipSpaceToScreenSpace()
Converts clip-space points to screen coordinates.
*******************************************************************/
void ss_orbit_clipSpaceToScreenSpace( vecteur3d_t *pt, vecteur3d_t *result ) {
float i,j;
i = pt->x*ECRAN2D_WIDTH/2 + ECRAN2D_WIDTH/2;
j = -pt->y*ECRAN2D_HEIGHT/2 + ECRAN2D_HEIGHT/2;
vecteur3d_init(result, (int)i,(int)j, 0);
}
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/camera3d.c
#include "camera3d.h"
/*********************************************************
camera3d_init()
*********************************************************/
void camera3d_init( camera3d_t *cam ) {
vecteur3d_init(&cam->center, 0,0,1000000000 );
vecteur3d_init(&cam->dir, 0,0,-1 );
vecteur3d_init(&cam->top, 0,1,0 );
/* vecteur3d_init(&cam->center, 0,-100,0 );
vecteur3d_init(&cam->dir, 0,1,0 );
vecteur3d_init(&cam->top, 0,0,1 );
*/
vecteur3d_init(&cam->center, 1000,0,0 );
vecteur3d_init(&cam->dir, 1,0,0 );
vecteur3d_init(&cam->top, 0,0,1 );
cam->near_dist = CAMERA3D_NEAR_DIST_DEFAULT;
cam->far_dist = CAMERA3D_FAR_DIST_DEFAULT;
cam->zoomx = CAMERA3D_ZOOM_DEFAULT;
cam->zoomy = CAMERA3D_ZOOM_DEFAULT * ECRAN2D_WIDTH/ECRAN2D_HEIGHT;
camera3d_setViewTransform( cam );
camera3d_setProjectionTransform( cam );
}
/*********************************************************
camera3d_setPosition()
Fixe la position de la camera et met a jour la matrice
'vue'.
*********************************************************/
void camera3d_setPosition( camera3d_t *cam, vecteur3d_t *pos ) {
cam->center = *pos;
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_setOrientation()
Fixe l'orientation de la camera et met a jour la
matrice 'projection'
*********************************************************/
void camera3d_setOrientation( camera3d_t *cam, vecteur3d_t *dir, vecteur3d_t *top ) {
cam->dir = *dir;
cam->top = *top;
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_getSideVector()
*********************************************************/
void camera3d_getSideVector( camera3d_t *cam, vecteur3d_t *result ) {
vecteur3d_crossProduct(&cam->top, &cam->dir, result);
}
/*********************************************************
camera3d_getViewTransform()
Calcule la matrice de transformation 'vue' de la
camera a partir de l'orientation et de la position.
*********************************************************/
void camera3d_getViewTransform( camera3d_t *cam, matrice4d_t *result ) {
matrice4d_t tm, rm;
vecteur3d_t side;
vecteur3d_t camTranslation;
camTranslation = cam->center;
vecteur3d_negate(&camTranslation );
matrice4d_setTranslationMatrix(&tm, &camTranslation);
camera3d_getSideVector(cam, &side);
matrice4d_setRotationMatrixXYZ(&rm, &side, &cam->top, &cam->dir );
matrice4d_product_m4d(&rm, &tm, result);
}
/*********************************************************
camera3d_getProjectionTransform()
Calcule la matrice de transformation 'projection'
de la camera a partir des parametres 'zoom', 'far'
et 'near'.
*********************************************************/
void camera3d_getProjectionTransform( camera3d_t *cam, matrice4d_t *result ) {
matrice4d_setProjectionMatrix( result, cam->near_dist, cam->far_dist, cam->zoomx, cam->zoomy );
}
/*********************************************************
camera3d_rotatePitch()
*********************************************************/
void camera3d_rotatePitch( camera3d_t *cam, float angle ) {
matrice4d_t rm;
vecteur3d_t side;
vecteur4d_t v4d;
camera3d_getSideVector(cam, &side);
matrice4d_setRotationMatrixN( &rm, &side, angle );
matrice4d_product_v3d( &rm, &cam->dir, &v4d );
vecteur4d_getVecteur3d( &v4d, &cam->dir);
matrice4d_product_v3d( &rm, &cam->top, &v4d );
vecteur4d_getVecteur3d( &v4d, &cam->top);
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_rotateHeading()
*********************************************************/
void camera3d_rotateHeading( camera3d_t *cam, float angle ) {
matrice4d_t rm;
vecteur4d_t v4d;
matrice4d_setRotationMatrixN( &rm, &cam->top, angle );
matrice4d_product_v3d( &rm, &cam->dir, &v4d );
vecteur4d_getVecteur3d( &v4d, &cam->dir);
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_rotateBank()
*********************************************************/
void camera3d_rotateBank( camera3d_t *cam, float angle ) {
matrice4d_t rm;
vecteur4d_t v4d;
matrice4d_setRotationMatrixN( &rm, &cam->dir, angle );
matrice4d_product_v3d( &rm, &cam->top, &v4d );
vecteur4d_getVecteur3d( &v4d, &cam->top);
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_translateAlongDir()
*********************************************************/
void camera3d_translateAlongDir( camera3d_t *cam, float distance ) {
cam->center.x = cam->center.x + distance*cam->dir.x;
cam->center.y = cam->center.y + distance*cam->dir.y;
cam->center.z = cam->center.z + distance*cam->dir.z;
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_translateAlongTop()
*********************************************************/
void camera3d_translateAlongTop( camera3d_t *cam, float distance ) {
cam->center.x = cam->center.x + distance*cam->top.x;
cam->center.y = cam->center.y + distance*cam->top.y;
cam->center.z = cam->center.z + distance*cam->top.z;
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_translateAlongSide()
*********************************************************/
void camera3d_translateAlongSide( camera3d_t *cam, float distance ) {
vecteur3d_t side;
camera3d_getSideVector(cam, &side);
cam->center.x = cam->center.x + distance*side.x;
cam->center.y = cam->center.y + distance*side.y;
cam->center.z = cam->center.z + distance*side.z;
camera3d_setViewTransform( cam );
}
/*********************************************************
camera3d_setViewTransform()
Calcule la matrice de transformation vue de cette
camera et l'applique a cette derniere.
*********************************************************/
void camera3d_setViewTransform( camera3d_t *cam ) {
camera3d_getViewTransform( cam, &cam->view_matrix );
}
/*********************************************************
camera3d_setProjectionTransform()
Calcule la matrice de transformation projection de
cette camera et l'applique a cette derniere.
*********************************************************/
void camera3d_setProjectionTransform( camera3d_t *cam ) {
camera3d_getProjectionTransform( cam, &cam->projection_matrix );
}
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_win32_main.c
#include "stdio.h"
#include <stdlib.h>
//#include "moteur3d.h"
#include "ss_solar_system.h"
#include "windows.h"
#include "GL/glut.h"
// ------------------------------------------------------------------
// VARIABLES GLOBALES
// ------------------------------------------------------------------
//scene3d_t scene3d;
ss_solar_system_t systemeSolaire;
int time_ms;
/********************************************************************
init()
Fonction d'initialisation d'OpenGL
********************************************************************/
void init(void)
{
objet3d_t obj[16];
lumiere3d_t light[4];
vecteur3d_t center, v1,v2;
vecteur3d_t pts[4];
triangle3d_t tri1;
int i;
// OPENGL //
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (0, 640, 480, 0, 0, 1);
glMatrixMode (GL_MODELVIEW);
glShadeModel(GL_FLAT);
glClear(GL_COLOR_BUFFER_BIT);
time_ms = glutGet(GLUT_ELAPSED_TIME);
// SCENE3D //
ss_solar_system_init(&systemeSolaire);
}
/********************************************************************
display()
Fonction d'affichage openGL
********************************************************************/
void display(void)
{
int i;
if( glutGet(GLUT_ELAPSED_TIME) - time_ms > 30 ) {
//printf("time is %i ms \n", glutGet(GLUT_ELAPSED_TIME));
time_ms = glutGet(GLUT_ELAPSED_TIME);
//camera3d_rotateBank( &scene3d.camera, -0.1 );
}
//glClear(GL_COLOR_BUFFER_BIT);
// Update
/*ss_solar_system_update(&systemeSolaire);
for( i=0; i<SOLAR_SYSTEM_NB_PLANETS; i++ ){
ss_solar_system_drawOrbit(&systemeSolaire, i);
}
ss_solar_system_sortPlanets(&systemeSolaire);
for( i=0; i<SOLAR_SYSTEM_NB_PLANETS+1; i++ ){
ss_solar_system_drawPlanet(&systemeSolaire, systemeSolaire.planetes_sorted_indexes[i]);
}*/
ss_solar_system_iterate(&systemeSolaire);
//ss_solar_system_drawPlanet(&systemeSolaire, -1); // Draw Sun
//ss_solar_system_drawBall(&systemeSolaire, 100,100, 10, 31);
//ss_solar_system_drawBall3D( &systemeSolaire, 100, 100, 50, 31, &systemeSolaire.camera.dir, &systemeSolaire.camera.top );
//ss_solar_system_drawLine(0,0,639,479, 31);
//glutSwapBuffers();
}
/********************************************************************
processNormalKeys()
Ecouteur clavier
********************************************************************/
void processNormalKeys( unsigned char key, int x , int y ) {
switch(key) {
case 'w' :
//printf("W \n");
camera3d_translateAlongDir(&systemeSolaire.camera, 50000000000);
glutPostRedisplay();
break;
case 's' :
//printf("S \n");
camera3d_translateAlongDir(&systemeSolaire.camera, -50000000000);
glutPostRedisplay();
break;
case 'a' :
//printf("A \n");
camera3d_translateAlongSide(&systemeSolaire.camera, -10);
glutPostRedisplay();
break;
case 'd' :
//printf("D \n");
camera3d_translateAlongSide(&systemeSolaire.camera, 10);
glutPostRedisplay();
break;
case 'q' :
//printf("Q \n");
camera3d_rotateHeading(&systemeSolaire.camera, -0.1);
glutPostRedisplay();
break;
case 'e' :
//printf("E \n");
camera3d_rotateHeading(&systemeSolaire.camera, 0.1);
glutPostRedisplay();
break;
}
}
/********************************************************************
processSpecialKeys()
Ecouteur clavier pour touches speciales
GLUT_KEY_F1 F1 function key
GLUT_KEY_F2 F2 function key
GLUT_KEY_F3 F3 function key
GLUT_KEY_F4 F4 function key
GLUT_KEY_F5 F5 function key
GLUT_KEY_F6 F6 function key
GLUT_KEY_F7 F7 function key
GLUT_KEY_F8 F8 function key
GLUT_KEY_F9 F9 function key
GLUT_KEY_F10 F10 function key
GLUT_KEY_F11 F11 function key
GLUT_KEY_F12 F12 function key
GLUT_KEY_LEFT Left function key
GLUT_KEY_RIGHT Up function key
GLUT_KEY_UP Right function key
GLUT_KEY_DOWN Down function key
GLUT_KEY_PAGE_UP Page Up function key
GLUT_KEY_PAGE_DOWN Page Down function key
GLUT_KEY_HOME Home function key
GLUT_KEY_END End function key
GLUT_KEY_INSERT Insert function key
********************************************************************/
void processSpecialKeys( int key, int x , int y ) {
switch(key) {
case GLUT_KEY_LEFT :
//printf("Left \n");
camera3d_rotateBank( &systemeSolaire.camera, 0.1 );
glutPostRedisplay();
break;
case GLUT_KEY_RIGHT :
//printf("Right \n");
camera3d_rotateBank( &systemeSolaire.camera, -0.1 );
glutPostRedisplay();
break;
case GLUT_KEY_UP :
//printf("Up \n");
camera3d_rotatePitch( &systemeSolaire.camera, 0.1 );
glutPostRedisplay();
break;
case GLUT_KEY_DOWN :
//printf("Down \n");
camera3d_rotatePitch( &systemeSolaire.camera, -0.1 );
glutPostRedisplay();
break;
case GLUT_KEY_PAGE_UP :
//printf("PgUp \n");
camera3d_translateAlongTop( &systemeSolaire.camera, 500000000 );
glutPostRedisplay();
break;
case GLUT_KEY_PAGE_DOWN :
//printf("PgDown \n");
camera3d_translateAlongTop( &systemeSolaire.camera, -500000000 );
glutPostRedisplay();
break;
}
}
/********************************************************************
********************************************************************/
void run_loop( void ) {
glutPostRedisplay();
}
/********************************************************************
main()
********************************************************************/
int main(int argc, char **argv)
{
//on initialise glut
glutInit(&argc, argv);
//on spécifie l'emploi du modèle chromatique et du double tampon
//glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB ); // Single buffering
//on spécifie la taille de la fenêtre
glutInitWindowSize(640, 480);
//on spécifie la position de la fenêtre
glutInitWindowPosition(500, 100);
//on crée une fenêtre
glutCreateWindow("ELE8307:: SYSTEME SOLAIRE 3D");
//on initialise
init();
////////////// FONCTIONS DE CALLBACKS ////////////////////////
//
// Les fonctions de callbacks sont des fonctions que le programmeur va spécifier pour
// la lier à un événement (clic, touche appuyée, redimensionnement, etc).
//
glutDisplayFunc(display);
glutIdleFunc( run_loop );
glutKeyboardFunc(processNormalKeys);
glutSpecialFunc(processSpecialKeys);
//void glutKeyboardUpFunc(void (*func)(unsigned char key,int x,int y));
//void glutSpecialUpFunc(void (*func)(int key,int x, int y));
// boucle infinie d'affichage
glutMainLoop();
return 0;
}
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/vecteur3d.h
#ifndef VECTEUR3D_H
#define VECTEUR3D_H
#include "math.h"
/******************************************************************
VECTEUR3D_H
******************************************************************/
typedef struct {
float x;
float y;
float z;
} vecteur3d_t;
void vecteur3d_init( vecteur3d_t *v, float x, float y, float z );
void vecteur3d_add( vecteur3d_t *v, vecteur3d_t *w );
void vecteur3d_sub( vecteur3d_t *v, vecteur3d_t *w );
void vecteur3d_mul( vecteur3d_t *v, float k );
void vecteur3d_negate( vecteur3d_t *v );
void vecteur3d_normalize( vecteur3d_t *v );
float vecteur3d_length( vecteur3d_t *v );
float vecteur3d_squaredLength( vecteur3d_t *v );
float vecteur3d_dotProduct( vecteur3d_t *v, vecteur3d_t *w );
//vecteur3d_t vecteur3d_crossProduct( vecteur3d_t *v, vecteur3d_t *w );
void vecteur3d_crossProduct( vecteur3d_t *v, vecteur3d_t *w , vecteur3d_t* result);
float vecteur3d_angle( vecteur3d_t *v, vecteur3d_t *w );
float vecteur3d_distance( vecteur3d_t *p1, vecteur3d_t *p2 );
void vecteur3d_print( vecteur3d_t *v );
#endif //VECTEUR3D_H
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/matrice4d.h
#ifndef MATRICE4D_H
#define MATRICE4D_H
#include "vecteur3d.h"
#include "vecteur4d.h"
//#include "triangle3d.h"
/******************************************************************
MATRICE4D_H
******************************************************************/
typedef struct {
float m[4][4]; // m[ligne][colone]
} matrice4d_t;
void matrice4d_init( matrice4d_t *m );
void matrice4d_product_m4d( matrice4d_t *m, matrice4d_t *n, matrice4d_t *result );
void matrice4d_product_v4d( matrice4d_t *m, vecteur4d_t *v, vecteur4d_t *result );
void matrice4d_product_v3d( matrice4d_t *m, vecteur3d_t *v, vecteur4d_t *result );
void matrice4d_invert( matrice4d_t *m );
void matrice4d_transpose( matrice4d_t *m, matrice4d_t *result );
void matrice4d_setIdentity( matrice4d_t *m );
void matrice4d_setTranslationMatrix( matrice4d_t *m, vecteur3d_t *v );
void matrice4d_setRotationMatrixX( matrice4d_t *m, float angle );
void matrice4d_setRotationMatrixY( matrice4d_t *m, float angle );
void matrice4d_setRotationMatrixZ( matrice4d_t *m, float angle );
void matrice4d_setRotationMatrixN( matrice4d_t *m, vecteur3d_t *normal, float angle );
void matrice4d_setRotationMatrixXYZ( matrice4d_t *m, vecteur3d_t *X, vecteur3d_t *Y, vecteur3d_t *Z );
void matrice4d_setProjectionMatrix( matrice4d_t *m, float near_dist, float far_dist, float zoomx, float zoomy );
void matrice4d_print( matrice4d_t *m );
#endif // MATRICE4D_H<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ecran2d.c
#include "ecran2d.h"
#ifdef M3D_WIN32_GLUT_DISPLAY
/*********************************************************
ecran2d_setPixel()
*********************************************************/
void ecran2d_setPixel( int x, int y, int color ) {
ecran2d_setColorOpenGL( color );
glBegin(GL_POINTS);
glVertex2f(x, y);
glEnd();
}
/*********************************************************
ecran2d_drawTriangle()
Dessiner un triangle en tracant des lignes verticales
de gauche a droite du triangle.
*********************************************************/
void ecran2d_drawTriangle( triangle3d_t *tri ) {
float a1,a2,a3,at, y1,y2;
float dx1,dx2,dx3;
float s1,s2,s3;
int i,j;
ecran2d_setColorOpenGL( tri->color );
glBegin(GL_POINTS);
triangle3d_sortPointsByX( tri );
dx1 = (tri->pts[2].x - tri->pts[0].x);
dx2 = (tri->pts[1].x - tri->pts[0].x);
dx3 = (tri->pts[2].x - tri->pts[1].x);
if( dx1 != 0 )
a1 = (tri->pts[2].y - tri->pts[0].y) / dx1; // pt[0]-pt[2] ; long side (in x)
if( dx2 != 0 )
a2 = (tri->pts[1].y - tri->pts[0].y) / dx2; // pt[0]-pt[1]
if( dx3 != 0 )
a3 = (tri->pts[2].y - tri->pts[1].y) / dx3; // pt[1]-pt[2]
if( dx2 != 0 ) {
y1 = tri->pts[0].y;
y2 = y1;
for( i= tri->pts[0].x ; i< tri->pts[1].x ; i++ ){
if( y1 < y2 ) {
for( j=y1; j<y2; j++ )
glVertex2f((float)i, (float)j);
}
else {
for( j=y2; j<y1; j++ )
glVertex2f((float)i, (float)j);
}
y1 += a1;
y2 += a2;
}
for( i= tri->pts[1].x ; i< tri->pts[2].x ; i++ ){
if( y1 < y2 ) {
for( j=y1; j<y2; j++ )
glVertex2f((float)i, (float)j);
}
else {
for( j=y2; j<y1; j++ )
glVertex2f((float)i, (float)j);
}
y1 += a1;
y2 += a3;
}
}
else if ( dx2 == 0 ) {
if( tri->pts[0].y < tri->pts[1].y ) {
y1 = tri->pts[0].y;
y2 = tri->pts[1].y;
for( i= tri->pts[0].x ; i< tri->pts[2].x ; i++ ){
for( j=y1; j<y2; j++ )
glVertex2f((float)i, (float)j);
y1 += a1;
y2 += a3;
}
}
else {
y1 = tri->pts[1].y;
y2 = tri->pts[0].y;
for( i= tri->pts[0].x ; i< tri->pts[2].x ; i++ ){
for( j=y1; j<y2; j++ )
glVertex2f((float)i, (float)j);
y1 += a3;
y2 += a1;
}
}
}
glEnd();
}
/*********************************************************
ecran2d_setColorOpenGL()
*********************************************************/
static void ecran2d_setColorOpenGL( int color ) {
float intensite;
intensite = (color%32)/(31.0f);
switch( color/32 ) {
case COLOR_WHITE :
glColor3f(intensite, intensite, intensite);
break;
case COLOR_RED :
glColor3f(intensite, 0.0, 0.0);
break;
case COLOR_GREEN :
glColor3f(0.0, intensite, 0.0);
break;
case COLOR_BLUE :
glColor3f(0.0, 0.0, intensite);
break;
case COLOR_YELLOW :
glColor3f(intensite, intensite, 0.0);
break;
case COLOR_BROWN :
glColor3f(intensite*0.5, intensite*0.25, intensite*0.0625);
break;
case COLOR_CYAN :
glColor3f(0.0, intensite, intensite);
break;
case COLOR_PURPLE :
glColor3f(intensite, 0.0, intensite);
break;
default :
glColor3f(1.0,1.0,1.0);
break;
}
}
#else // NIOS II
void ecran2d_setPixel( int x, int y, int color ) {
IOWR(VGA_0_BASE,(y*640)+x,color);
}
void ecran2d_clear() {
int i,j;
for( i=0; i<ECRAN2D_WIDTH; i++ ){
for( j=0; j<ECRAN2D_HEIGHT; j++ ){
ecran2d_setPixel(i,j,0);
}
}
}
/*inline void ecran2d_setPixel( int x, int y, int color ) {
//IOWR(VGA_0_BASE,(y*640)+x,color);
//IOWR(VGA_0_BASE,(y<<9)+(y<<7)+x,color);
ALT_CI_SETPIXEL_INST((y<<16) + x, color);
}*/
/*********************************************************
ecran2d_drawTriangle()
Dessiner un triangle en tracant des lignes verticales
de gauche a droite du triangle.
*********************************************************/
/*void ecran2d_drawTriangle( triangle3d_t *tri ) {
float a1,a2,a3,at, y1,y2;
float dx1,dx2,dx3;
float s1,s2,s3;
int i,j;
//ecran2d_setColorOpenGL( tri->color );
//glBegin(GL_POINTS);
triangle3d_sortPointsByX( tri );
dx1 = (tri->pts[2].x - tri->pts[0].x);
dx2 = (tri->pts[1].x - tri->pts[0].x);
dx3 = (tri->pts[2].x - tri->pts[1].x);
if( dx1 != 0 )
a1 = (tri->pts[2].y - tri->pts[0].y) / dx1; // pt[0]-pt[2] ; long side (in x)
if( dx2 != 0 )
a2 = (tri->pts[1].y - tri->pts[0].y) / dx2; // pt[0]-pt[1]
if( dx3 != 0 )
a3 = (tri->pts[2].y - tri->pts[1].y) / dx3; // pt[1]-pt[2]
if( dx2 != 0 ) {
y1 = tri->pts[0].y;
y2 = y1;
for( i= tri->pts[0].x ; i< tri->pts[1].x ; i++ ){
if( y1 < y2 ) {
for( j=y1; j<y2; j++ )
ecran2d_setPixel(i,j,tri->color);
}
else {
for( j=y2; j<y1; j++ )
ecran2d_setPixel(i,j,tri->color);
}
y1 += a1;
y2 += a2;
}
for( i= tri->pts[1].x ; i< tri->pts[2].x ; i++ ){
if( y1 < y2 ) {
for( j=y1; j<y2; j++ )
ecran2d_setPixel(i,j,tri->color);
}
else {
for( j=y2; j<y1; j++ )
ecran2d_setPixel(i,j,tri->color);
}
y1 += a1;
y2 += a3;
}
}
else if ( dx2 == 0 ) {
if( tri->pts[0].y < tri->pts[1].y ) {
y1 = tri->pts[0].y;
y2 = tri->pts[1].y;
for( i= tri->pts[0].x ; i< tri->pts[2].x ; i++ ){
for( j=y1; j<y2; j++ )
ecran2d_setPixel(i,j,tri->color);
y1 += a1;
y2 += a3;
}
}
else {
y1 = tri->pts[1].y;
y2 = tri->pts[0].y;
for( i= tri->pts[0].x ; i< tri->pts[2].x ; i++ ){
for( j=y1; j<y2; j++ )
ecran2d_setPixel(i,j,tri->color);
y1 += a3;
y2 += a1;
}
}
}
//glEnd();
}
*/
#endif
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/vecteur4d.c
#include "vecteur4d.h"
/*********************************************************
vecteur4d_init()
*********************************************************/
void vecteur4d_init( vecteur4d_t *v, float x, float y, float z, float w ) {
v->x = x;
v->y = y;
v->z = z;
v->w = w;
}
/*********************************************************
vecteur4d_init_v3d()
*********************************************************/
void vecteur4d_init_v3d( vecteur4d_t *v, vecteur3d_t *u ) {
v->x = u->x;
v->y = u->y;
v->z = u->z;
v->w = 1;
}
/*********************************************************
vecteur4d_getVecteur3d()
*********************************************************/
void vecteur4d_getVecteur3d( vecteur4d_t *v , vecteur3d_t *result ) {
/*result->x = v->x / v->w;
result->y = v->y / v->w;
result->z = v->z / v->w;
*/
if( v->w < 0 ) {
result->x = v->x / -v->w;
result->y = v->y / -v->w;
result->z = v->z / v->w;
}
else {
result->x = v->x / v->w;
result->y = v->y / v->w;
result->z = v->z / v->w;
}
}
void vecteur4d_print( vecteur4d_t *v ) {
printf("(%2.2f, %2.2f, %2.2f, %2.2f)", v->x,v->y,v->z,v->z);
}
<file_sep>/Labo1/sources_vhdl_lab1/ctrl_clavier_tb.vhd
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.std_logic_unsigned.all;
--Entity declaration
ENTITY ctrl_clavier_tb IS
END ctrl_clavier_tb;
ARCHITECTURE tb OF ctrl_clavier_tb IS
-- Component Declaration for the Unit Under Test (UUT)
component ctrl_clavier_tres_mauvais is
port(
ps2_clk : in std_logic;
ps2_dat : in std_logic;
--
usedw : out std_logic_vector(5 downto 0);
key_code : out std_logic_vector(7 downto 0);
rd : in std_logic;
empty : out std_logic;
--
clk : in std_logic;
rst_n : in std_logic
);
end component;
--signal declaration
signal ps2_clk : std_logic := '1';
signal ps2_dat : std_logic;
signal usedw : std_logic_vector(5 downto 0);
signal key_code: std_logic_vector(7 downto 0);
signal rd : std_logic;
signal empty : std_logic;
signal clk : std_logic := '1';
signal rst_n : std_logic;
BEGIN
--component instanciation
U0_ctrl_clavier_tres_mauvais : ctrl_clavier_tres_mauvais
port map (ps2_clk => ps2_clk,
ps2_dat => ps2_dat,
usedw => usedw,
key_code => key_code,
rd => rd,
empty => empty,
clk => clk,
rst_n => rst_n);
clk <= not clk after 10000 ps;
ps2_clk <= not ps2_clk after 33300 ps;
--This process controls every input to the design under test.
do_check_out_result:process
begin
rst_n <= '0';
rd <= '1';
ps2_dat <= '0'; --start bit
wait for 10 ns;
rst_n <= '1';
wait for 56600 ps;
ps2_dat <= '1'; --bit 0
wait for 66600 ps;
ps2_dat <= '0'; --bit 1
wait for 66600 ps;
ps2_dat <= '1'; --bit 2
wait for 66600 ps;
ps2_dat <= '0'; --bit 3
wait for 66600 ps;
ps2_dat <= '1'; --bit 4
wait for 66600 ps;
ps2_dat <= '0'; --bit 5
wait for 66600 ps;
ps2_dat <= '1'; --bit 6
wait for 66600 ps;
ps2_dat <= '1'; --bit 7
wait for 66600 ps;
ps2_dat <= '1'; --parite
wait for 66600 ps;
ps2_dat <= '1'; --stop
wait for 10 ns;
wait;
end process do_check_out_result;
end tb;<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/camera3d.h
#ifndef CAMERA3D_H
#define CAMERA3D_H
#include "vecteur3d.h"
#include "matrice4d.h"
#include "ecran2d.h"
/******************************************************************
CAMERA3D_H
Important : Les matrices de 'vue' est produites a partir de
l'orientation et de la position de la camera.
Lorsque ces valeurs sont modifiees manuellement,
il faut appeller 'camera3d_setViewTransform' pour
mettre a jour la matrices.
Il en est de meme pour la matrice 'projection'
produite a partir des valeurs 'zoom' et 'near/far'.
(camera3d_setProjectionTransform)
******************************************************************/
#define CAMERA3D_NEAR_DIST_DEFAULT 1.0
#define CAMERA3D_FAR_DIST_DEFAULT 1000000.0
#define CAMERA3D_ZOOM_DEFAULT 4.0
typedef struct {
vecteur3d_t center;
vecteur3d_t dir;
vecteur3d_t top;
float near_dist ,far_dist;
float zoomx, zoomy;
matrice4d_t view_matrix;
matrice4d_t projection_matrix;
} camera3d_t;
void camera3d_init( camera3d_t *cam );
void camera3d_setPosition( camera3d_t *cam, vecteur3d_t *pos );
void camera3d_setOrientation( camera3d_t *cam, vecteur3d_t *dir, vecteur3d_t *top );
void camera3d_getSideVector( camera3d_t *cam, vecteur3d_t *result );
void camera3d_getViewTransform( camera3d_t *cam, matrice4d_t *result );
void camera3d_getProjectionTransform( camera3d_t *cam, matrice4d_t *result );
void camera3d_rotatePitch( camera3d_t *cam, float angle );
void camera3d_rotateHeading( camera3d_t *cam, float angle );
void camera3d_rotateBank( camera3d_t *cam, float angle );
void camera3d_translateAlongDir( camera3d_t *cam, float distance );
void camera3d_translateAlongTop( camera3d_t *cam, float distance );
void camera3d_translateAlongSide( camera3d_t *cam, float distance );
void camera3d_setViewTransform( camera3d_t *cam );
void camera3d_setProjectionTransform( camera3d_t *cam );
#endif // CAMERA3D_H<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_solar_system_constants.h
#ifndef SS_SOLAR_SYSTEM_CONSTANTS_H
#define SS_SOLAR_SYSTEM_CONSTANTS_H
#define EARTH_MASS 5.98E24 // kg
#define EARTH_RADIUS 6380000.0 // m
#define ASTRONOMIC_UNIT 149597892000.0 // m
#define SEC_PER_YEAR 31556926.0 // sec/yr
// Rayon des planetes (m)
#define SOLEIL_RAYON 109.0*EARTH_RADIUS
#define MERCURE_RAYON 0.387*EARTH_RADIUS
#define VENUS_RAYON 0.95*EARTH_RADIUS
#define TERRE_RAYON 1.0*EARTH_RADIUS
#define MARS_RAYON 0.53*EARTH_RADIUS
#define JUPITER_RAYON 11.2*EARTH_RADIUS
#define SATURNE_RAYON 9.3*EARTH_RADIUS
#define URANUS_RAYON 4.0*EARTH_RADIUS
#define NEPTUNE_RAYON 3.9*EARTH_RADIUS
#define PLUTON_RAYON 0.18*EARTH_RADIUS
// Orbit radius (demi grand-axe...) (m)
#define MERCURE_ORBIT_A 0.387*ASTRONOMIC_UNIT
#define VENUS_ORBIT_A 0.723*ASTRONOMIC_UNIT
#define TERRE_ORBIT_A 1.0*ASTRONOMIC_UNIT
#define MARS_ORBIT_A 1.524*ASTRONOMIC_UNIT
#define JUPITER_ORBIT_A 5.203*ASTRONOMIC_UNIT
#define SATURNE_ORBIT_A 9.54*ASTRONOMIC_UNIT
#define URANUS_ORBIT_A 19.19*ASTRONOMIC_UNIT
#define NEPTUNE_ORBIT_A 30.06*ASTRONOMIC_UNIT
#define PLUTON_ORBIT_A 39.44*ASTRONOMIC_UNIT
// Orbit Excentricity
#define MERCURE_ORBIT_E 0.206
#define VENUS_ORBIT_E 0.007
#define TERRE_ORBIT_E 0.017
#define MARS_ORBIT_E 0.093
#define JUPITER_ORBIT_E 0.048
#define SATURNE_ORBIT_E 0.056
#define URANUS_ORBIT_E 0.046
#define NEPTUNE_ORBIT_E 0.010
#define PLUTON_ORBIT_E 0.248
// Periodes de revolution (s)
#define MERCURE_ORBIT_T 0.24*SEC_PER_YEAR
#define VENUS_ORBIT_T 0.615*SEC_PER_YEAR
#define TERRE_ORBIT_T 1*SEC_PER_YEAR
#define MARS_ORBIT_T 1.88*SEC_PER_YEAR
#define JUPITER_ORBIT_T 11.86*SEC_PER_YEAR
#define SATURNE_ORBIT_T 29.46*SEC_PER_YEAR
#define URANUS_ORBIT_T 84.04*SEC_PER_YEAR
#define NEPTUNE_ORBIT_T 164.8*SEC_PER_YEAR
#define PLUTON_ORBIT_T 247.7*SEC_PER_YEAR
// Masses relatives a la Terre
#define SOLEIL_RELATIVE_MASS 330000.0
#define MERCURE_RELATIVE_MASS 0.056
#define VENUS_RELATIVE_MASS 0.82
#define TERRE_RELATIVE_MASS 1
#define MARS_RELATIVE_MASS 0.11
#define JUPITER_RELATIVE_MASS 318
#define SATURN_RELATIVE_MASS 95
#define URANUS_RELATIVE_MASS 15
#define NEPTUNE_RELATIVE_MASS 17
#define PLUTON_RELATIVE_MASS 0.002
#endif <file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ecran2d.h
#ifndef ECRAN2D_H
#define ECRAN2D_H
//#include "triangle3d.h"
#ifdef M3D_WIN32_GLUT_DISPLAY
#include "GL/glut.h"
#else
#include "system.h"
#include "io.h"
#endif
/******************************************************************
ECRAN2D_H
******************************************************************/
#define ECRAN2D_WIDTH 640
#define ECRAN2D_HEIGHT 480
#define ECRAN2D_ASPECTRATIO 1.333333333
#define ECRAN2D_CLEARCOLOR 0
// COLOR MODEL COLOR_INDEX(3) & COLOR_INTENSITY(5)
#define COLOR_WHITE 0
#define COLOR_RED 1 //63
#define COLOR_GREEN 2
#define COLOR_BLUE 3 //127
#define COLOR_YELLOW 4 //159
#define COLOR_BROWN 5 //191
#define COLOR_CYAN 6 //223
#define COLOR_PURPLE 7 //255
//void ecran2d_drawTriangle( triangle3d_t *t );
void ecran2d_setPixel( int x, int y, int color );
#ifdef M3D_WIN32_GLUT_DISPLAY
static void ecran2d_setColorOpenGL( int color );
#else
//#define ecran2d_setPixel(x,y,color) IOWR(VGA_0_BASE,(y*640)+x,color) //grrrrr
#endif
void ecran2d_clear( void );
#endif // ECRAN2D_H
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/matrice4d.c
#include "matrice4d.h"
/*********************************************************
matrice4d_init()
*********************************************************/
void matrice4d_init( matrice4d_t *m ){
int i,j;
for( i=0; i<4; i++ )
for( j=0; j<4; j++ )
m->m[i][j] = 0;
}
/*********************************************************
matrice4d_produit_m4d()
*********************************************************/
void matrice4d_product_m4d( matrice4d_t *m, matrice4d_t *n, matrice4d_t *result ) {
int i,j,k;
for( i=0; i<4; i++ ) {
for( j=0; j<4; j++ ) {
result->m[i][j] = 0;
for( k=0; k<4; k++ )
result->m[i][j] += (m->m[i][k]*n->m[k][j]);
}
}
}
/*********************************************************
matrice4d_produit_v4d()
*********************************************************/
void matrice4d_product_v4d( matrice4d_t *m, vecteur4d_t *v, vecteur4d_t *result ) {
int i;
float vect[4];
for( i=0; i<4; i++ ) {
vect[i] = 0;
vect[i] += m->m[i][0]*v->x;
vect[i] += m->m[i][1]*v->y;
vect[i] += m->m[i][2]*v->z;
vect[i] += m->m[i][3]*v->w;
}
result->x = vect[0];
result->y = vect[1];
result->z = vect[2];
result->w = vect[3];
}
/*********************************************************
matrice4d_produit_v3d()
*********************************************************/
void matrice4d_product_v3d( matrice4d_t *m, vecteur3d_t *v, vecteur4d_t *result ) {
int i;
float vect[4];
for( i=0; i<4; i++ ) {
vect[i] = 0;
vect[i] += m->m[i][0]*v->x;
vect[i] += m->m[i][1]*v->y;
vect[i] += m->m[i][2]*v->z;
vect[i] += m->m[i][3]*1;
}
result->x = vect[0];
result->y = vect[1];
result->z = vect[2];
result->w = vect[3];
}
/*********************************************************
matrice4d_invert()
Inverts the 3x3 matrix, for use with matrices of
format show below.
M = [ a b c 0 ]
[ c d e 0 ]
[ f g h 0 ]
[ 0 0 0 1 ]
*********************************************************/
void matrice4d_invert( matrice4d_t *m ) {
int i,j;
float c[3][3];
float adj[3][3];
float det;
// Cofactor Matrix
c[0][0] = ( m->m[1][1]*m->m[2][2] - m->m[1][2]*m->m[2][1] );
c[0][1] = ( m->m[1][0]*m->m[2][2] - m->m[1][2]*m->m[2][0] );
c[0][2] = ( m->m[1][0]*m->m[2][1] - m->m[1][1]*m->m[2][0] );
c[1][0] = ( m->m[0][1]*m->m[2][2] - m->m[0][2]*m->m[2][1] );
c[1][1] = ( m->m[0][0]*m->m[2][2] - m->m[0][2]*m->m[2][0] );
c[1][2] = ( m->m[0][0]*m->m[2][1] - m->m[0][1]*m->m[2][0] );
c[2][0] = ( m->m[0][1]*m->m[1][2] - m->m[0][2]*m->m[1][1] );
c[2][1] = ( m->m[0][0]*m->m[1][2] - m->m[0][2]*m->m[1][0] );
c[2][2] = ( m->m[0][0]*m->m[1][1] - m->m[0][1]*m->m[1][0] );
// Adjoint Matrix
for( i=0; i<3; i++ ) {
for( j=0; j<3; j++ ) {
adj[i][j] = c[j][i];
}
}
det = ( m->m[0][0]*m->m[1][1]*m->m[2][2] + m->m[0][1]*m->m[1][2]*m->m[2][0] + m->m[0][2]*m->m[1][0]*m->m[2][1] )
- ( m->m[0][2]*m->m[1][1]*m->m[2][0] + m->m[0][1]*m->m[1][0]*m->m[2][2] + m->m[0][0]*m->m[1][2]*m->m[2][1] );
for( i=0; i<3; i++ ) {
for( j=0; j<3; j++ ) {
m->m[i][j] = adj[i][j]/det;
}
}
}
/*********************************************************
matrice4d_transpose()
*********************************************************/
void matrice4d_transpose( matrice4d_t *m, matrice4d_t *result ) {
int i,j;
for( i=0; i<4; i++ ){
for( j=0; j<4; j++ ) {
result->m[i][j] = m->m[j][i];
}
}
}
void matrice4d_setIdentity( matrice4d_t *m ){
matrice4d_init( m );
m->m[0][0] = 1;
m->m[1][1] = 1;
m->m[2][2] = 1;
m->m[3][3] = 1;
}
/*********************************************************
matrice4d_setTranslationMatrix()
*********************************************************/
void matrice4d_setTranslationMatrix( matrice4d_t *m, vecteur3d_t *v ) {
matrice4d_init( m );
m->m[0][0] = 1;
m->m[1][1] = 1;
m->m[2][2] = 1;
m->m[3][3] = 1;
m->m[0][3] = v->x;
m->m[1][3] = v->y;
m->m[2][3] = v->z;
}
/*********************************************************
matrice4d_setRotationMatrixX()
*********************************************************/
void matrice4d_setRotationMatrixX( matrice4d_t *m, float angle ) {
matrice4d_init( m );
m->m[0][0] = 1;
m->m[1][1] = cos(angle);
m->m[1][2] = -sin(angle);
m->m[2][1] = sin(angle);
m->m[2][2] = cos(angle);
m->m[3][3] = 1;
}
/*********************************************************
matrice4d_setRotationMatrixY()
*********************************************************/
void matrice4d_setRotationMatrixY( matrice4d_t *m, float angle ) {
matrice4d_init( m );
m->m[1][1] = 1;
m->m[0][0] = cos(angle);
m->m[0][2] = sin(angle);
m->m[2][0] = -sin(angle);
m->m[2][2] = cos(angle);
m->m[3][3] = 1;
}
/*********************************************************
matrice4d_setRotationMatrixZ()
*********************************************************/
void matrice4d_setRotationMatrixZ( matrice4d_t *m, float angle ) {
matrice4d_init( m );
m->m[2][2] = 1;
m->m[0][0] = cos(angle);
m->m[0][1] = -sin(angle);
m->m[1][0] = sin(angle);
m->m[1][1] = cos(angle);
m->m[3][3] = 1;
}
/*********************************************************
matrice4d_setRotationMatrixN()
*********************************************************/
void matrice4d_setRotationMatrixN( matrice4d_t *m, vecteur3d_t *normal, float angle ) {
vecteur3d_t n;
float c,s;
n = *normal;
vecteur3d_normalize(&n);
c = cos(angle);
s = sin(angle);
m->m[0][0] = (n.x*n.x) + (1-n.x*n.x)*c;
m->m[0][1] = (n.x*n.y*(1-c)) - n.z*s;
m->m[0][2] = (n.x*n.z*(1-c)) + n.y*s;
m->m[1][0] = (n.x*n.y*(1-c)) + n.z*s;
m->m[1][1] = n.y*n.y + (1-n.y*n.y)*c;
m->m[1][2] = n.y*n.z*(1-c) - n.x*s;
m->m[2][0] = n.x*n.z*(1-c) - n.y*s;
m->m[2][1] = n.y*n.z*(1-c) + n.x*s;
m->m[2][2] = n.z*n.z + (1-n.z*n.z)*c;
m->m[0][3] = 0;
m->m[1][3] = 0;
m->m[2][3] = 0;
m->m[3][0] = 0;
m->m[3][1] = 0;
m->m[3][2] = 0;
m->m[3][3] = 1;
}
/*********************************************************
matrice4d_setRotationMatrixXYZ()
*********************************************************/
void matrice4d_setRotationMatrixXYZ( matrice4d_t *m, vecteur3d_t *X, vecteur3d_t *Y, vecteur3d_t *Z ) {
m->m[0][0] = X->x;
m->m[0][1] = X->y;
m->m[0][2] = X->z;
m->m[1][0] = Y->x;
m->m[1][1] = Y->y;
m->m[1][2] = Y->z;
m->m[2][0] = Z->x;
m->m[2][1] = Z->y;
m->m[2][2] = Z->z;
m->m[3][3] = 1;
m->m[0][3] = 0;
m->m[1][3] = 0;
m->m[2][3] = 0;
m->m[3][0] = 0;
m->m[3][1] = 0;
m->m[3][2] = 0;
}
/*********************************************************
matrice4d_setProjectionMatrix()
*********************************************************/
void matrice4d_setProjectionMatrix( matrice4d_t *m, float near_dist, float far_dist, float zoomx, float zoomy ) {
matrice4d_init( m );
m->m[0][0] = zoomx;
m->m[1][1] = zoomy;
m->m[2][2] = (far_dist+near_dist)/(far_dist-near_dist);
m->m[2][3] = (2*near_dist*far_dist)/(near_dist-far_dist);
m->m[3][2] = 1;
}
/*********************************************************
matrice4d_print()
*********************************************************/
void matrice4d_print( matrice4d_t *m ) {
int i,j;
for( i=0; i<4; i++ ) {
printf("[ ");
for( j=0; j<4; j++ ){
if( m->m[i][j] < 0 )
printf("%2.2f ", m->m[i][j]);
else
printf(" %2.2f ", m->m[i][j]);
}
printf("] \n");
}
printf("\n");
}
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/ss_orbit.h
#ifndef SS_ORBIT_H
#define SS_ORBIT_H
#include "math.h"
#include "camera3d.h"
#include "vecteur3d.h"
#include "vecteur4d.h"
#include "ecran2d.h"
#include "matrice4d.h"
#include "math_constants.h"
#define SS_ORBIT_NB_DIV 64
#define SS_ORBIT_COLOR 15
typedef struct {
int x0,y0,x1,y1;
} ss_orbit_line_t; // Orbit Screen line segments
typedef struct {
// Space points
vecteur3d_t orbit_pts[SS_ORBIT_NB_DIV];
// Screen Display
ss_orbit_line_t screen_lines[2][SS_ORBIT_NB_DIV];
int nb_screen_lines[2];
int current_display_buff;
int previous_display_buff;
} ss_orbit_t;
void ss_orbit_init( ss_orbit_t *orbit, float orbit_a );
void ss_orbit_render( ss_orbit_t *orbit, camera3d_t *cam );
void ss_orbit_draw( ss_orbit_t *orbit );
void ss_orbit_clear( ss_orbit_t *orbit );
void ss_orbit_swapDisplayBuffer( ss_orbit_t *orbit );
void ss_orbit_addLine( ss_orbit_t *orbit, ss_orbit_line_t *line );
void ss_orbit_line_init( ss_orbit_line_t *line, int x0, int y0, int x1, int y1 );
void ss_orbit_line_draw( ss_orbit_line_t *line, int color );
int ss_orbit_line_clip( ss_orbit_line_t *line );
int ss_orbit_line_computeClipCode( float x, float y );
void ss_orbit_clipSpaceToScreenSpace( vecteur3d_t *pt, vecteur3d_t *result );
#endif
<file_sep>/Labo2/sources_lab2/SolarSystem3D/src/vecteur4d.h
#ifndef VECTEUR4D_H
#define VECTEUR4D_H
#include "vecteur3d.h"
/******************************************************************
VECTEUR4D_H
******************************************************************/
typedef struct {
float x;
float y;
float z;
float w;
} vecteur4d_t;
void vecteur4d_init( vecteur4d_t *v, float x, float y, float z, float w );
void vecteur4d_init_v3d( vecteur4d_t *v, vecteur3d_t *u );
//vecteur3d_t vecteur4d_getVecteur3d( vecteur4d_t *v );
void vecteur4d_getVecteur3d( vecteur4d_t *v , vecteur3d_t *result );
void vecteur4d_print( vecteur4d_t *v );
#endif VECTEUR4D_H
|
3140f4af0f14494378b0d8e97bd927d73641caa7
|
[
"C",
"VHDL"
] | 22 |
C
|
cperry164/ELE8307
|
9dea0d238fdc9601f9703467ddf9a6fbcad6f9ef
|
9c8bcb2d930240e144d8af4aa254e8cecec32173
|
refs/heads/main
|
<repo_name>brennerhaverlock/CryptoLive<file_sep>/fetchETH.js
const request = require('request');
exports.pushUpdates = function() {
return new Promise(function (resolve, reject) {
let ethArr = [];
fetchAPI('https://api.cryptonator.com/api/ticker/eth-usd')
.then(function (res1) {
ethArr.push(JSON.parse(res1).ticker);
return fetchAPI('https://api.cryptonator.com/api/ticker/eth-gbp')
}).then(function (res2) {
ethArr.push(JSON.parse(res2).ticker);
return fetchAPI('https://api.cryptonator.com/api/ticker/eth-eur')
}).then(function (res3) {
ethArr.push(JSON.parse(res3).ticker);
return fetchAPI('https://api.cryptonator.com/api/ticker/eth-jpy')
}).then(function (res4) {
ethArr.push(JSON.parse(res4).ticker);
resolve(ethArr);
});
});
}
function fetchAPI(apiPath) {
return new Promise(function (resolve, reject) {
request(apiPath, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
}<file_sep>/public/js/app.js
const socket = io();
const usdArr = [];
const gbpArr = [];
const eurArr = [];
const jpyArr = [];
socket.on('btc-prices', tickerdata => {
refreshBTCTicker(tickerdata);
});
socket.on('eth-prices', tickerdata => {
refreshETHTicker(tickerdata);
});
socket.on('doge-prices', tickerdata => {
refreshDOGETicker(tickerdata);
});
function refreshBTCTicker(tickerdata) {
const tblBTC = document.getElementById("btc-ticker");
const tblRow = tblBTC.getElementsByTagName("tr");
let rowCnt = 0;
tickerdata.map((item) => {
for (let i = 0; i < tblRow.length; i++) {
const tblCol = tblRow[i].getElementsByTagName("td")[0];
if (tblCol) {
const txtValue = tblCol.getAttribute('data-currency');
if (txtValue === '' || txtValue === item.target) {
tblBTC.deleteRow(i);
}
}
}
const tblBTCbody = document.getElementById('btc-ticker').getElementsByTagName('tbody')[0];
const newRow = tblBTCbody.insertRow(rowCnt);
const cell1 = newRow.insertCell(0);
const cell2 = newRow.insertCell(1);
const cell3 = newRow.insertCell(2);
const cell4 = newRow.insertCell(3);
const cell5 = newRow.insertCell(4);
cell1.innerHTML = printCurrency(item.target);
cell1.setAttribute('data-currency', item.target);
cell2.innerHTML = item.price;
cell3.innerHTML = item.volume;
cell4.innerHTML = item.change;
rowCnt++;
});
}
function refreshETHTicker(tickerdata) {
const tblETH = document.getElementById("eth-ticker");
const tblRow = tblETH.getElementsByTagName("tr");
let rowCnt = 0;
tickerdata.map((item) => {
for (let i = 0; i < tblRow.length; i++) {
const tblCol = tblRow[i].getElementsByTagName("td")[0];
if (tblCol) {
const txtValue = tblCol.getAttribute('data-currency');
if (txtValue === '' || txtValue === item.target) {
tblETH.deleteRow(i);
}
}
}
const tblETHbody = document.getElementById('eth-ticker').getElementsByTagName('tbody')[0];
const newRow = tblETHbody.insertRow(rowCnt);
const cell1 = newRow.insertCell(0);
const cell2 = newRow.insertCell(1);
const cell3 = newRow.insertCell(2);
const cell4 = newRow.insertCell(3);
const cell5 = newRow.insertCell(4);
cell1.innerHTML = printCurrency(item.target);
cell1.setAttribute('data-currency', item.target);
cell2.innerHTML = item.price;
cell3.innerHTML = item.volume;
cell4.innerHTML = item.change;
rowCnt++;
});
}
function refreshDOGETicker(tickerdata) {
const tbldoge = document.getElementById("doge-ticker");
const tblRow = tbldoge.getElementsByTagName("tr");
let rowCnt = 0;
tickerdata.map((item) => {
for (let i = 0; i < tblRow.length; i++) {
const tblCol = tblRow[i].getElementsByTagName("td")[0];
if (tblCol) {
const txtValue = tblCol.getAttribute('data-currency');
if (txtValue === '' || txtValue === item.target) {
tbldoge.deleteRow(i);
}
}
}
const tbldogebody = document.getElementById('doge-ticker').getElementsByTagName('tbody')[0];
const newRow = tbldogebody.insertRow(rowCnt);
const cell1 = newRow.insertCell(0);
const cell2 = newRow.insertCell(1);
const cell3 = newRow.insertCell(2);
const cell4 = newRow.insertCell(3);
const cell5 = newRow.insertCell(4);
cell1.innerHTML = printCurrency(item.target);
cell1.setAttribute('data-currency', item.target);
cell2.innerHTML = item.price;
cell3.innerHTML = item.volume;
cell4.innerHTML = item.change;
rowCnt++;
});
}
function formatDate() {
const date = new Date();
const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
const [{ value: mn },,{ value: day },,{ value: yr},,{ value: hr},,{ value: min},,{ value: sec}] = dateTimeFormat.formatToParts(date);
return `${day}-${mn}-${yr} ${hr}:${min}:${sec}`;
}
function printCurrency(currency) {
switch(currency) {
case 'USD':
return '<span class="currency">$</span>';
case 'GBP':
return '<span class="currency">£</span>';
case 'EUR':
return '<span class="currency">€</span>';
case 'JPY':
return '<span class="currency">¥</span>';
}
}
<file_sep>/README.md
# CryptoLive
Live Crypto Forcasting using Socket IO and NodeJS
|
d3eaa4c64bfec79f0936f443c858cb6f85ce355b
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
brennerhaverlock/CryptoLive
|
5b223007bd4ebb7edb059d9a8210e9371d266445
|
8303c9d7f11f4a2d93a4a255ba349cc51ce1d237
|
refs/heads/main
|
<file_sep>using Sandbox;
using System;
namespace HiddenGamemode
{
partial class Player
{
[NetLocalPredicted] public float FlashlightBattery { get; set; } = 100f;
private Flashlight _worldFlashlight;
private Flashlight _viewFlashlight;
public bool HasFlashlightEntity
{
get
{
if ( IsLocalPlayer )
{
return (_viewFlashlight != null && _viewFlashlight.IsValid());
}
return (_worldFlashlight != null && _worldFlashlight.IsValid());
}
}
public bool IsFlashlightOn
{
get
{
if ( IsLocalPlayer )
return (HasFlashlightEntity && _viewFlashlight.Enabled);
return (HasFlashlightEntity && _worldFlashlight.Enabled);
}
}
public void ToggleFlashlight()
{
ShowFlashlight( !IsFlashlightOn );
}
public void ShowFlashlight( bool shouldShow, bool playSounds = true )
{
if ( IsFlashlightOn )
{
if ( IsServer )
_worldFlashlight.Enabled = false;
else
_viewFlashlight.Enabled = false;
}
if ( IsServer && IsFlashlightOn != shouldShow )
ShowFlashlightLocal( this, shouldShow );
if ( ActiveChild is not Weapon weapon || !weapon.HasFlashlight )
return;
if ( shouldShow )
{
if ( !HasFlashlightEntity )
{
if ( IsServer )
{
_worldFlashlight = new Flashlight();
_worldFlashlight.EnableHideInFirstPerson = true;
_worldFlashlight.LocalRot = EyeRot;
_worldFlashlight.SetParent( weapon, "muzzle" );
_worldFlashlight.LocalPos = Vector3.Zero;
}
else
{
_viewFlashlight = new Flashlight();
_viewFlashlight.EnableViewmodelRendering = true;
_viewFlashlight.WorldRot = EyeRot;
_viewFlashlight.WorldPos = EyePos + EyeRot.Forward * 10f;
}
}
else
{
if ( IsServer )
{
// TODO: This is a weird hack to make sure the rotation is right.
_worldFlashlight.SetParent( null );
_worldFlashlight.LocalRot = EyeRot;
_worldFlashlight.SetParent( weapon, "muzzle" );
_worldFlashlight.LocalPos = Vector3.Zero;
_worldFlashlight.Enabled = true;
}
else
{
_viewFlashlight.Enabled = true;
}
}
if ( IsServer )
{
_worldFlashlight.FogStength = 10f;
_worldFlashlight.UpdateFromBattery( FlashlightBattery );
_worldFlashlight.Reset();
}
else
{
_viewFlashlight.FogStength = 10f;
_viewFlashlight.UpdateFromBattery( FlashlightBattery );
_viewFlashlight.Reset();
}
if ( IsServer && playSounds )
PlaySound( "flashlight-on" );
}
else if ( IsServer && playSounds )
{
PlaySound( "flashlight-off" );
}
}
[ClientRpc]
private void ShowFlashlightLocal( bool shouldShow )
{
ShowFlashlight( shouldShow );
}
private void TickFlashlight()
{
if ( Input.Released(InputButton.Flashlight) )
{
using ( Prediction.Off() )
ToggleFlashlight();
}
if ( IsFlashlightOn )
{
FlashlightBattery = MathF.Max( FlashlightBattery - 10f * Time.Delta, 0f );
using ( Prediction.Off() )
{
if ( IsServer )
{
var shouldTurnOff = _worldFlashlight.UpdateFromBattery( FlashlightBattery );
if ( shouldTurnOff )
ShowFlashlight( false, false );
}
else
{
var viewFlashlightParent = _viewFlashlight.Parent;
if ( ActiveChild is Weapon weapon && weapon.ViewModelEntity != null )
{
if ( viewFlashlightParent != weapon.ViewModelEntity )
{
_viewFlashlight.SetParent( weapon.ViewModelEntity, "muzzle" );
_viewFlashlight.WorldRot = EyeRot;
_viewFlashlight.LocalPos = Vector3.Zero;
}
}
else
{
if ( viewFlashlightParent != null )
_viewFlashlight.SetParent( null );
_viewFlashlight.WorldRot = EyeRot;
_viewFlashlight.WorldPos = EyePos + EyeRot.Forward * 80f;
}
var shouldTurnOff = _viewFlashlight.UpdateFromBattery( FlashlightBattery );
if ( shouldTurnOff )
ShowFlashlight( false, false );
}
}
}
else
{
FlashlightBattery = MathF.Min( FlashlightBattery + 15f * Time.Delta, 100f );
}
}
}
}
<file_sep>
using Sandbox;
using Sandbox.UI;
using Sandbox.UI.Construct;
using System;
namespace HiddenGamemode
{
public class Crosshair : Panel
{
public Panel ChargeBackgroundBar;
public Panel ChargeForegroundBar;
public Panel Charge;
private int _fireCounter;
public Crosshair()
{
StyleSheet.Load( "/ui/Crosshair.scss" );
for ( int i = 0; i < 5; i++ )
{
var p = Add.Panel( "element" );
p.AddClass( $"el{i}" );
}
Charge = Add.Panel( "charge" );
ChargeBackgroundBar = Charge.Add.Panel( "background" );
ChargeForegroundBar = ChargeBackgroundBar.Add.Panel( "foreground" );
}
public override void Tick()
{
base.Tick();
if ( Sandbox.Player.Local is not Player player )
return;
Charge.SetClass( "hidden", true );
if ( player.ActiveChild is Weapon weapon )
{
if ( weapon.ChargeAttackEndTime > 0f && Time.Now < weapon.ChargeAttackEndTime )
{
var timeLeft = weapon.ChargeAttackEndTime - Time.Now;
ChargeForegroundBar.Style.Width = Length.Percent( 100f - ((100f / weapon.ChargeAttackDuration) * timeLeft) );
ChargeForegroundBar.Style.Dirty();
Charge.SetClass( "hidden", false );
}
}
this.PositionAtCrosshair();
SetClass( "fire", _fireCounter > 0 );
if ( _fireCounter > 0 )
_fireCounter--;
}
public override void OnEvent( string eventName )
{
if ( eventName == "fire" )
{
_fireCounter += 2;
}
base.OnEvent( eventName );
}
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
public partial class HideRound : BaseRound
{
[ServerVar( "hdn_host_always_hidden", Help = "Make the host always the hidden." )]
public static bool HostAlwaysHidden { get; set; } = false;
public override string RoundName => "PREPARE";
public override int RoundDuration => 20;
private Deployment _deploymentPanel;
private bool _roundStarted;
[ServerCmd( "hdn_select_deployment" )]
private static void SelectDeploymentCmd( string type )
{
if ( ConsoleSystem.Caller is Player player )
{
if ( Game.Instance.Round is HideRound )
player.Deployment = Enum.Parse<DeploymentType>( type );
}
}
[ClientCmd( "hdn_open_deployment", CanBeCalledFromServer = true) ]
private static void OpenDeploymentCmd( int teamIndex )
{
if ( Game.Instance.Round is HideRound round )
{
round.OpenDeployment( Game.Instance.GetTeamByIndex( teamIndex ) );
}
}
public static void SelectDeployment( DeploymentType type )
{
if ( Sandbox.Player.Local is Player player )
player.Deployment = type;
SelectDeploymentCmd( type.ToString() );
}
public void OpenDeployment( BaseTeam team )
{
CloseDeploymentPanel();
_deploymentPanel = Sandbox.Hud.CurrentPanel.AddChild<Deployment>();
team.AddDeployments( _deploymentPanel, (selection) =>
{
SelectDeployment( selection );
CloseDeploymentPanel();
} );
}
public override void OnPlayerSpawn( Player player )
{
if ( Players.Contains( player ) ) return;
AddPlayer( player );
if ( _roundStarted )
{
player.Team = Game.Instance.IrisTeam;
player.Team.OnStart( player );
if ( player.Team.HasDeployments )
OpenDeploymentCmd( player, player.TeamIndex );
}
base.OnPlayerSpawn( player );
}
protected override void OnStart()
{
Log.Info( "Started Hide Round" );
if ( Host.IsServer )
{
Sandbox.Player.All.ForEach((player) => player.Respawn());
if ( Players.Count == 0 ) return;
// Select a random Hidden player.
var hidden = Players[Rand.Int( Players.Count - 1 )];
if ( HostAlwaysHidden )
{
hidden = Players[0];
}
Assert.NotNull( hidden );
hidden.Team = Game.Instance.HiddenTeam;
hidden.Team.OnStart( hidden );
// Make everyone else I.R.I.S.
Players.ForEach( ( player ) =>
{
if ( player != hidden )
{
player.Team = Game.Instance.IrisTeam;
player.Team.OnStart( player );
}
if ( player.Team.HasDeployments )
OpenDeploymentCmd( player, player.TeamIndex );
} );
_roundStarted = true;
}
}
protected override void OnFinish()
{
Log.Info( "Finished Hide Round" );
CloseDeploymentPanel();
}
protected override void OnTimeUp()
{
Log.Info( "Hide Time Up!" );
Game.Instance.ChangeRound( new HuntRound() );
base.OnTimeUp();
}
private void CloseDeploymentPanel()
{
if ( _deploymentPanel != null )
{
_deploymentPanel.Delete();
_deploymentPanel = null;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox;
namespace HiddenGamemode
{
class IrisTeam : BaseTeam
{
public override string HudClassName => "team_iris";
public override string Name => "I.R.I.S.";
private Battery _batteryHud;
private Radar _radarHud;
public override void SupplyLoadout( Player player )
{
player.ClearAmmo();
player.Inventory.DeleteContents();
player.Inventory.Add( new Pistol(), true );
if ( player.Deployment == DeploymentType.IRIS_ASSAULT )
{
player.Inventory.Add( new SMG(), true );
player.GiveAmmo( AmmoType.Pistol, 120 );
}
else
{
player.Inventory.Add( new Shotgun(), true );
player.GiveAmmo( AmmoType.Buckshot, 16 );
}
}
public override void OnStart( Player player )
{
player.ClearAmmo();
player.Inventory.DeleteContents();
player.SetModel( "models/citizen/citizen.vmdl" );
if ( Host.IsServer )
{
player.RemoveClothing();
player.AttachClothing( "models/citizen_clothes/trousers/trousers.lab.vmdl" );
player.AttachClothing( "models/citizen_clothes/jacket/labcoat.vmdl" );
player.AttachClothing( "models/citizen_clothes/shoes/shoes.workboots.vmdl" );
player.AttachClothing( "models/citizen_clothes/hat/hat_securityhelmet.vmdl" );
}
player.EnableAllCollisions = true;
player.EnableDrawing = true;
player.EnableHideInFirstPerson = true;
player.EnableShadowInFirstPerson = true;
player.Controller = new IrisController();
player.Camera = new FirstPersonCamera();
}
public override void OnJoin( Player player )
{
Log.Info( $"{player.Name} joined the Military team." );
if ( Host.IsClient && player.IsLocalPlayer )
{
_radarHud = Sandbox.Hud.CurrentPanel.AddChild<Radar>();
// TODO: Let's try not having a battery HUD. Does it make it spookier?
//_batteryHud = Sandbox.Hud.CurrentPanel.AddChild<Battery>();
}
base.OnJoin( player );
}
public override void AddDeployments( Deployment panel, Action<DeploymentType> callback )
{
panel.AddDeployment( new DeploymentInfo
{
Title = "ASSAULT",
Description = "Sprints faster and is equipped with a high firerate SMG.",
ClassName = "assault",
OnDeploy = () => callback( DeploymentType.IRIS_ASSAULT )
} );
panel.AddDeployment( new DeploymentInfo
{
Title = "BRAWLER",
Description = "Moves slower and is equipped with a high damage shotgun.",
ClassName = "brawler",
OnDeploy = () => callback( DeploymentType.IRIS_BRAWLER )
} );
}
public override void OnPlayerKilled( Player player )
{
player.GlowActive = false;
}
public override void OnLeave( Player player )
{
Log.Info( $"{player.Name} left the Military team." );
if ( player.IsLocalPlayer )
{
if ( _radarHud != null )
{
_radarHud.Delete( true );
_radarHud = null;
}
if ( _batteryHud != null )
{
_batteryHud.Delete( true );
_batteryHud = null;
}
}
base.OnLeave( player );
}
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
public partial class ScreamAbility : BaseAbility
{
public override float Cooldown => 10;
public override string Name => "Scream";
private string[] _screamSounds = new string[]
{
"scream-01",
"scream-02",
"scream-03",
"scream-04"
};
public override string GetKeybind()
{
return "V";
}
protected override void OnUse( Player player )
{
Log.Info( (Host.IsServer ? "Server: " : "Client: ") + "Time Since Last: " + TimeSinceLastUse );
TimeSinceLastUse = 0;
if ( Host.IsServer )
{
using ( Prediction.Off() )
{
PlayScreamSound( player );
}
}
}
private void PlayScreamSound( Player from )
{
var soundName = Rand.FromArray( _screamSounds );
from.PlaySound( soundName );
}
}
}
<file_sep>using Sandbox;
using System;
namespace HiddenGamemode
{
[Library( "hdn_knife", Title = "Knife" )]
partial class Knife : Weapon
{
public override string ViewModelPath => "weapons/rust_boneknife/v_rust_boneknife.vmdl";
public override float PrimaryRate => 1.0f;
public override float SecondaryRate => 0.3f;
public override bool IsMelee => true;
public override int HoldType => 0;
public override int Bucket => 1;
public override int BaseDamage => 35;
public virtual int MeleeDistance => 80;
public override void Spawn()
{
base.Spawn();
// TODO: EnableDrawing = false does not work.
RenderAlpha = 0f;
SetModel( "weapons/rust_boneknife/rust_boneknife.vmdl" );
}
public virtual void MeleeStrike( float damage, float force )
{
var forward = Owner.EyeRot.Forward;
forward = forward.Normal;
foreach ( var tr in TraceBullet( Owner.EyePos, Owner.EyePos + forward * MeleeDistance, 10f ) )
{
if ( !tr.Entity.IsValid() ) continue;
tr.Surface.DoBulletImpact( tr );
if ( !IsServer ) continue;
using ( Prediction.Off() )
{
var damageInfo = DamageInfo.FromBullet( tr.EndPos, forward * 100 * force, damage )
.UsingTraceResult( tr )
.WithAttacker( Owner )
.WithWeapon( this );
tr.Entity.TakeDamage( damageInfo );
}
}
}
public override void AttackSecondary()
{
StartChargeAttack();
}
public override void AttackPrimary()
{
ShootEffects();
PlaySound( "rust_boneknife.attack" );
MeleeStrike( BaseDamage, 1.5f );
}
public override void OnChargeAttackFinish()
{
ShootEffects();
PlaySound( "rust_boneknife.attack" );
MeleeStrike( BaseDamage * 3f, 1.5f );
}
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
public partial class SenseAbility : BaseAbility
{
public override float Cooldown => 10;
public override string Name => "Sense";
public override string GetKeybind()
{
return "G";
}
protected override void OnUse( Player player )
{
Log.Info( (Host.IsServer ? "Server: " : "Client: ") + "Time Since Last: " + TimeSinceLastUse );
TimeSinceLastUse = 0;
using ( Prediction.Off() )
{
if ( Host.IsClient )
{
_ = StartGlowAbility();
}
else
{
player.PlaySound( $"i-see-you-{Rand.Int(1, 3)}" );
}
}
}
public override float GetCooldown( Player player )
{
if ( player.Deployment == DeploymentType.HIDDEN_BEAST )
return Cooldown * 0.5f;
else if ( player.Deployment == DeploymentType.HIDDEN_ROGUE )
return Cooldown * 2f;
return base.GetCooldown( player );
}
private async Task StartGlowAbility()
{
var players = Game.Instance.GetTeamPlayers<IrisTeam>( true );
players.ForEach( ( player ) =>
{
player.ShowSenseParticles( true );
} );
await Task.Delay( TimeSpan.FromSeconds( Cooldown * 0.5f ) );
players.ForEach( ( player ) =>
{
player.ShowSenseParticles( false );
} );
}
}
}
<file_sep>using Sandbox.UI.Construct;
using Sandbox.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using Sandbox;
namespace HiddenGamemode
{
public class Radar : Panel
{
private readonly Dictionary<Player, RadarDot> _radarDots = new();
public Panel Anchor;
public Radar()
{
StyleSheet.Load( "/ui/Radar.scss" );
SetTemplate( "/ui/Radar.html" );
}
public override void Tick()
{
base.Tick();
if ( Sandbox.Player.Local is not Player localPlayer ) return;
SetClass( "hidden", localPlayer.LifeState != LifeState.Alive );
var deleteList = new List<Player>();
var count = 0;
deleteList.AddRange( _radarDots.Keys );
foreach ( var v in Sandbox.Player.All.OrderBy( x => Vector3.DistanceBetween( x.EyePos, Camera.LastPos ) ) )
{
if ( v is not Player player ) continue;
if ( UpdateRadar( player ) )
{
deleteList.Remove( player );
count++;
}
}
foreach ( var player in deleteList )
{
_radarDots[player].Delete();
_radarDots.Remove( player );
}
}
public RadarDot CreateRadarDot( Player player )
{
var tag = new RadarDot( player )
{
Parent = this
};
return tag;
}
public bool UpdateRadar( Player player )
{
if ( player.IsLocalPlayer || !player.HasTeam || player.Team.HideNameplate )
return false;
if ( player.LifeState != LifeState.Alive )
return false;
if ( Sandbox.Player.Local is not Player localPlayer )
return false;
var radarRange = 2048f;
if ( player.WorldPos.Distance( localPlayer.WorldPos ) > radarRange )
return false;
if ( !_radarDots.TryGetValue( player, out var tag ) )
{
tag = CreateRadarDot( player );
_radarDots[player] = tag;
}
// This is probably fucking awful maths but it works.
var difference = player.WorldPos - localPlayer.WorldPos;
var radarSize = 256f;
var x = (radarSize / radarRange) * difference.x * 0.5f;
var y = (radarSize / radarRange) * difference.y * 0.5f;
var angle = (MathF.PI / 180) * (Camera.LastRot.Yaw() - 90f);
var x2 = x * MathF.Cos( angle ) + y * MathF.Sin( angle );
var y2 = y * MathF.Cos( angle ) - x *MathF.Sin( angle );
tag.Style.Left = (radarSize / 2f) + x2;
tag.Style.Top = (radarSize / 2f) - y2;
tag.Style.Dirty();
return true;
}
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
[Library("flashlight")]
public partial class Flashlight : SpotLightEntity
{
private bool _didPlayFlickerSound;
public Flashlight() : base()
{
Transmit = TransmitType.Always;
InnerConeAngle = 10f;
OuterConeAngle = 20f;
Brightness = 0.7f;
QuadraticAttenuation = 1f;
LinearAttenuation = 0f;
Color = new Color( 0.9f, 0.87f, 0.6f );
Falloff = 4f;
Enabled = true;
DynamicShadows = true;
Range = 512f;
}
public void Reset()
{
_didPlayFlickerSound = false;
}
public bool UpdateFromBattery( float battery )
{
Brightness = 0.01f + ((0.69f / 100f) * battery);
Flicker = (battery <= 10);
if ( IsServer && Flicker && !_didPlayFlickerSound )
{
_didPlayFlickerSound = true;
var sound = PlaySound( "flashlight-flicker" );
sound.SetVolume( 0.5f );
}
return (battery <= 0f);
}
}
}
<file_sep>
using Sandbox;
using Sandbox.UI;
using Sandbox.UI.Construct;
namespace HiddenGamemode
{
public class Abilities : Panel
{
public class AbilityInfo
{
public Panel Panel;
public Panel CooldownPanel;
public Label CooldownLabel;
}
public AbilityInfo Sense;
public AbilityInfo Scream;
public Abilities()
{
Sense = MakeAbilityPanel( "sense" );
Scream = MakeAbilityPanel( "scream" );
}
public override void Tick()
{
if ( Sandbox.Player.Local is not Player player ) return;
if ( player.Team is not HiddenTeam ) return;
SetClass( "hidden", player.LifeState != LifeState.Alive );
UpdateAbility( Sense, player.Sense );
UpdateAbility( Scream, player.Scream );
}
private AbilityInfo MakeAbilityPanel( string className )
{
var ability = new AbilityInfo();
ability.Panel = Add.Panel( $"ability {className}" );
ability.Panel.Add.Panel( $"icon {className}" );
ability.CooldownPanel = ability.Panel.Add.Panel( "cooldown" );
ability.CooldownLabel = ability.CooldownPanel.Add.Label( "0", "text " );
return ability;
}
private void UpdateAbility( AbilityInfo info, BaseAbility ability )
{
if ( Sandbox.Player.Local is not Player player )
return;
info.Panel.SetClass( "hidden", ability == null );
if ( ability == null ) return;
var isUsable = ability.IsUsable( player );
info.Panel.SetClass( "usable", isUsable );
info.CooldownPanel.SetClass( "usable", isUsable );
if ( isUsable )
info.CooldownLabel.Text = ability.GetKeybind();
else
info.CooldownLabel.Text = ((int)ability.GetCooldownTimeLeft( player )).ToString();
}
}
}
<file_sep>using Sandbox;
namespace HiddenGamemode
{
partial class Player
{
private LaserDot _laserDot;
private void CreateLaserDot()
{
DestroyLaserDot();
_laserDot = new LaserDot();
}
private void DestroyLaserDot()
{
if ( _laserDot != null )
{
_laserDot.Delete();
_laserDot = null;
}
}
private void UpdateLaserDot()
{
if ( ActiveChild is Weapon weapon && weapon.HasLaserDot )
{
if ( _laserDot == null )
CreateLaserDot();
var trace = Trace.Ray( EyePos, EyePos + EyeRot.Forward * 4096f )
.UseHitboxes()
.Radius( 2f )
.Ignore( weapon )
.Ignore( this )
.Run();
if ( trace.Hit )
_laserDot.WorldPos = trace.EndPos;
}
else
{
DestroyLaserDot();
}
}
}
}
<file_sep># sbox-hidden
Eliminate the crazy invisible lunatic with the knife, or be him and slay those trying to survive.
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
namespace HiddenGamemode
{
public class LightFlickers
{
private struct LightFlicker
{
public SpotLightEntity Entity;
public float StartBrightness;
public float EndTime;
}
private List<LightFlicker> _flickers = new();
public void Add( SpotLightEntity entity, float flickerTime = 2f)
{
var index = _flickers.FindIndex( ( i ) => i.Entity == entity );
if ( index >= 0 )
{
// Remove any existing flickers for this entity.
var flicker = _flickers[index];
flicker.Entity.Brightness = flicker.StartBrightness;
_flickers.RemoveAt( index );
}
_flickers.Add( new LightFlicker
{
Entity = entity,
StartBrightness = entity.Brightness,
EndTime = Time.Now + flickerTime
} );
}
public void OnTick()
{
var currentTime = Time.Now;
for (var i = _flickers.Count - 1; i >= 0; i--)
{
var flicker = _flickers[i];
if ( flicker.Entity == null || !flicker.Entity.IsValid() )
{
_flickers.RemoveAt( i );
continue;
}
if ( currentTime < flicker.EndTime )
{
flicker.Entity.Brightness = flicker.StartBrightness * MathF.Abs( Noise.Perlin( currentTime * 5f, 0f, 0f ) );
}
else
{
flicker.Entity.Brightness = flicker.StartBrightness;
_flickers.RemoveAt( i );
}
}
}
}
}
<file_sep>namespace HiddenGamemode
{
public enum AmmoType
{
Pistol,
Buckshot
}
}
<file_sep>using Sandbox;
using System;
namespace HiddenGamemode
{
partial class ViewModel : BaseViewModel
{
float walkBob = 0;
public override void UpdateCamera( Camera camera )
{
base.UpdateCamera( camera );
camera.ViewModelFieldOfView = camera.FieldOfView + (FieldOfView - 80);
AddCameraEffects( camera );
}
private void AddCameraEffects( Camera camera )
{
WorldRot = Sandbox.Player.Local.EyeRot;
var speed = Owner.Velocity.Length.LerpInverse( 0, 320 );
var left = camera.Rot.Left;
var up = camera.Rot.Up;
if ( Owner.GroundEntity != null )
{
walkBob += Time.Delta * 25.0f * speed;
}
WorldPos += up * MathF.Sin( walkBob ) * speed * -1;
WorldPos += left * MathF.Sin( walkBob * 0.6f ) * speed * -0.5f;
}
}
}
<file_sep>using Sandbox;
namespace HiddenGamemode
{
[Library( "hdn_smg", Title = "MP5" )]
partial class SMG : Weapon
{
public override string ViewModelPath => "weapons/rust_smg/v_rust_smg.vmdl";
public override float PrimaryRate => 10.0f;
public override float SecondaryRate => 1.0f;
public override int ClipSize => 30;
public override float ReloadTime => 4.0f;
public override bool HasFlashlight => true;
public override bool HasLaserDot => true;
public override int BaseDamage => 5;
public override int Bucket => 2;
public override void Spawn()
{
base.Spawn();
SetModel( "weapons/rust_smg/rust_smg.vmdl" );
}
public override void AttackPrimary()
{
if ( !TakeAmmo( 1 ) )
{
PlaySound( "pistol.dryfire" );
return;
}
Owner.SetAnimParam( "b_attack", true );
ShootEffects();
PlaySound( "rust_smg.shoot" );
ShootBullet( 0.1f, 1.5f, BaseDamage, 3.0f );
}
[ClientRpc]
protected override void ShootEffects()
{
Host.AssertClient();
Particles.Create( "particles/pistol_muzzleflash.vpcf", EffectEntity, "muzzle" );
Particles.Create( "particles/pistol_ejectbrass.vpcf", EffectEntity, "ejection_point" );
if ( Owner == Player.Local )
{
_ = new Sandbox.ScreenShake.Perlin( 0.5f, 4.0f, 1.0f, 0.5f );
}
ViewModelEntity?.SetAnimParam( "fire", true );
CrosshairPanel?.OnEvent( "fire" );
}
public override void TickPlayerAnimator( PlayerAnimator anim )
{
anim.SetParam( "holdtype", 2 );
anim.SetParam( "aimat_weight", 1.0f );
}
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
class HiddenTeam : BaseTeam
{
public override bool HideNameplate => true;
public override string HudClassName => "team_hidden";
public override string Name => "Hidden";
public Player CurrentPlayer { get; set; }
private float _nextLightFlicker;
private Abilities _abilitiesHud;
public override void SupplyLoadout( Player player )
{
player.ClearAmmo();
player.Inventory.DeleteContents();
player.Inventory.Add( new Knife(), true );
}
public override void OnStart( Player player )
{
player.ClearAmmo();
player.Inventory.DeleteContents();
if ( Host.IsServer )
{
player.RemoveClothing();
}
player.SetModel( "models/citizen/citizen.vmdl" );
player.EnableAllCollisions = true;
player.EnableDrawing = true;
player.EnableHideInFirstPerson = true;
player.EnableShadowInFirstPerson = true;
player.Controller = new HiddenController();
player.Camera = new FirstPersonCamera();
}
public override void AddDeployments( Deployment panel, Action<DeploymentType> callback )
{
panel.AddDeployment( new DeploymentInfo
{
Title = "CLASSIC",
Description = "Well rounded and recommended for beginners.",
ClassName = "classic",
OnDeploy = () => callback( DeploymentType.HIDDEN_CLASSIC )
} );
panel.AddDeployment( new DeploymentInfo
{
Title = "BEAST",
Description = "Harder to kill but moves slower. Deals more damage. Sense ability can be used more frequently.",
ClassName = "beast",
OnDeploy = () => callback( DeploymentType.HIDDEN_BEAST )
} );
panel.AddDeployment( new DeploymentInfo
{
Title = "ROGUE",
Description = "Moves faster but easier to kill. Deals less damage. Sense ability can be used less frequently.",
ClassName = "rogue",
OnDeploy = () => callback( DeploymentType.HIDDEN_ROGUE )
} );
}
public override void OnTakeDamageFromPlayer( Player player, Player attacker, DamageInfo info )
{
if ( player.Deployment == DeploymentType.HIDDEN_BEAST )
{
info.Damage *= 0.5f;
}
else if ( player.Deployment == DeploymentType.HIDDEN_ROGUE )
{
info.Damage *= 1.5f;
}
}
public override void OnDealDamageToPlayer( Player player, Player target, DamageInfo info )
{
if ( player.Deployment == DeploymentType.HIDDEN_BEAST )
{
info.Damage *= 1.25f;
}
else if ( player.Deployment == DeploymentType.HIDDEN_ROGUE )
{
info.Damage *= 0.75f;
}
}
public override void OnTick()
{
if ( Host.IsClient )
{
/*
if ( Sandbox.Player.Local is not Player localPlayer )
return;
if ( localPlayer.Team == this )
return;
var hidden = Game.Instance.GetTeamPlayers<HiddenTeam>( true ).FirstOrDefault();
if ( hidden != null && hidden.IsValid() )
{
var distance = localPlayer.Pos.Distance( hidden.Pos );
hidden.RenderAlpha = 0.2f - ((0.2f / 1500f) * distance);
}
*/
}
else
{
if ( Time.Now <= _nextLightFlicker )
return;
var player = CurrentPlayer;
if ( player != null && player.IsValid() )
{
var overlaps = Physics.GetEntitiesInSphere( player.WorldPos, 2048f );
foreach ( var entity in overlaps )
{
// Make sure we don't also flicker flashlights.
if ( entity is SpotLightEntity light && entity is not Flashlight )
{
if ( Rand.Float( 0f, 1f ) >= 0.5f )
Game.Instance.LightFlickers.Add( light, Rand.Float( 0.5f, 2f ) );
}
}
}
_nextLightFlicker = Sandbox.Time.Now + Rand.Float( 2f, 5f );
}
}
public override void OnTick( Player player )
{
if ( player.Input.Pressed( InputButton.Drop ) )
{
if ( player.Sense?.IsUsable( player ) == true )
{
player.Sense.Use( player );
}
}
if ( player.Input.Pressed( InputButton.View ) )
{
if ( player.Scream?.IsUsable( player ) == true )
{
player.Scream.Use( player );
}
}
if ( player.Input.Pressed( InputButton.Use) )
{
if ( player.Controller is not HiddenController controller )
return;
if ( controller.IsFrozen )
return;
var trace = Trace.Ray( player.EyePos, player.EyePos + player.EyeRot.Forward * 40f )
.HitLayer( CollisionLayer.WORLD_GEOMETRY )
.Ignore( player )
.Ignore( player.ActiveChild )
.Radius( 2 )
.Run();
if ( trace.Hit )
controller.IsFrozen = true;
}
}
public override bool PlayPainSounds( Player player )
{
player.PlaySound( "hidden_grunt" + Rand.Int( 1, 2 ) );
return true;
}
public override void OnJoin( Player player )
{
Log.Info( $"{player.Name} joined the Hidden team." );
if ( Host.IsClient && player.IsLocalPlayer )
{
_abilitiesHud = Sandbox.Hud.CurrentPanel.AddChild<Abilities>();
}
player.EnableShadowCasting = false;
player.EnableShadowReceive = false;
player.RenderAlpha = 0.15f;
player.Sense = new SenseAbility();
player.Scream = new ScreamAbility();
CurrentPlayer = player;
base.OnJoin( player );
}
public override void OnLeave( Player player )
{
player.EnableShadowReceive = true;
player.EnableShadowCasting = true;
player.RenderAlpha = 1f;
Log.Info( $"{player.Name} left the Hidden team." );
if ( _abilitiesHud != null && player.IsLocalPlayer )
{
_abilitiesHud.Delete( true );
_abilitiesHud = null;
}
player.Sense = null;
CurrentPlayer = null;
base.OnLeave( player );
}
}
}
<file_sep>battery
{
position: absolute;
top: 108px;
left: 100px;
color: #fff;
width: 256px;
height: 32px;
.outerBar
{
background-color: rgba(50, 50, 50, 0.8);
border-radius: 16px;
margin-top: 16px;
padding: 2px;
width: 200px;
height: 20px;
}
.innerBar
{
border-radius: 16px;
background-color: rgba(102, 130, 161, 0.9);
width: 100%;
min-width: 16px;
height: 100%;
}
.icon
{
background-image: url( /ui/icons/icon-torch.png );
background-size: 100%;
width: 48px;
height: 48px;
}
&.hidden
{
display: none;
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
[Library("laserdot")]
public partial class LaserDot : Entity
{
private Particles _particles;
public LaserDot()
{
Transmit = TransmitType.Always;
if ( IsClient )
{
_particles = Particles.Create( "particles/laserdot.vpcf" );
if ( _particles != null )
_particles.SetEntity( 0, this, true );
}
}
protected override void OnDestroy()
{
_particles?.Destroy( true );
base.OnDestroy();
}
}
}
<file_sep>using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HiddenGamemode
{
public partial class BaseAbility : NetworkClass
{
public virtual float Cooldown => 1;
public virtual string Name => "";
[NetLocalPredicted] public TimeSince TimeSinceLastUse { get; set; }
public BaseAbility()
{
TimeSinceLastUse = -1;
}
public void Use( Player player )
{
OnUse( player );
if ( Host.IsServer )
{
using ( Prediction.Off() )
{
NetworkDirty( "TimeSinceLastUse", NetVarGroup.NetLocalPredicted );
}
}
}
public float GetCooldownTimeLeft( Player player )
{
if ( TimeSinceLastUse == -1 )
return 0;
return GetCooldown( player ) - TimeSinceLastUse;
}
public virtual float GetCooldown( Player player )
{
return Cooldown;
}
public virtual string GetKeybind()
{
return "";
}
public virtual bool IsUsable( Player player )
{
return ( TimeSinceLastUse == -1 || TimeSinceLastUse > GetCooldown( player ) );
}
protected virtual void OnUse( Player player ) { }
}
}
|
1aadf404b6009fcb6ab31168df229c9b718d53f4
|
[
"SCSS",
"C#",
"Markdown"
] | 20 |
SCSS
|
KingofBeast/sbox-hidden
|
8294faeda103c0fef37dc553b9b0108c0ee5209c
|
ffb66d94f8e0c9136460b91c23c747684e4c66f6
|
refs/heads/master
|
<file_sep>use std::char;
use super::constants::*;
use super::error::{Error, Result};
use super::trit;
use super::tryte;
use super::tryte::Tryte;
use super::Ternary;
const SINGLE_RANGE: usize = 243;
const DOUBLE_RANGE: usize = 19_683;
const TRIPLE_RANGE: usize = 1_594_323;
const SINGLE_OFFSET: isize = (SINGLE_RANGE as isize - 1) / 2;
const DOUBLE_OFFSET: isize = (DOUBLE_RANGE as isize - 1) / 2;
const TRIPLE_OFFSET: isize = (TRIPLE_RANGE as isize - 1) / 2;
const SINGLE_MIN: usize = 0;
const SINGLE_MAX: usize = SINGLE_MIN + SINGLE_RANGE - 1;
const DOUBLE_MIN: usize = SINGLE_MAX + 1;
const DOUBLE_MAX: usize = DOUBLE_MIN + DOUBLE_RANGE - 1;
const TRIPLE_MIN: usize = DOUBLE_MAX + 1;
const TRIPLE_MAX: usize = TRIPLE_MIN + TRIPLE_RANGE - 1;
static SINGLE_START_BITMASK: u16 = 0b00_11_11_11_11_11;
static DOUBLE_START_BITMASK: u16 = 0b00_00_11_11_11_11;
static DOUBLE_START_PATTERN: u16 = 0b01_00_00_00_00_00;
static TRIPLE_START_BITMASK: u16 = 0b00_00_00_11_11_11;
static TRIPLE_START_PATTERN: u16 = 0b01_01_00_00_00_00;
static CONTINUATION_BITMASK: u16 = 0b00_11_11_11_11_11;
static CONTINUATION_PATTERN: u16 = 0b11_00_00_00_00_00;
pub fn encode_str(dest: &mut [Tryte], s: &str) -> Result<usize> {
let offset = WORD_LEN;
let mut i = 0;
for c in s.chars() {
let start = i + offset;
let end = start + 3;
let mut slice = &mut dest[start..end];
i += encode_char(slice, c)?;
}
dest[0..offset].read_i64(i as i64)?;
Ok(i)
}
pub fn decode_str(src: &[Tryte]) -> Result<(String, usize)> {
let offset = WORD_LEN;
let len = src[0..offset].into_i64() as usize;
let mut s = String::new();
let mut i = 0;
while i < len {
let start = i + offset;
let end = start + 3;
let slice = &src[start..end];
let (c, j) = decode_char(slice)?;
s.push(c);
i += j;
}
Ok((s, i))
}
pub fn encode_char(dest: &mut [Tryte], c: char) -> Result<usize> {
let codepoint = c as u32;
let (len, codepoint_offset) = match codepoint as usize {
SINGLE_MIN...SINGLE_MAX => Ok((1, SINGLE_OFFSET)),
DOUBLE_MIN...DOUBLE_MAX => Ok((2, DOUBLE_OFFSET)),
TRIPLE_MIN...TRIPLE_MAX => Ok((3, TRIPLE_OFFSET)),
_ => Err(Error::InvalidCharacter(c)),
}?;
let src = {
let mut tmp = [tryte::ZERO; WORD_LEN];
let shifted_codepoint = shift_codepoint(codepoint, codepoint_offset);
tmp.read_i64(shifted_codepoint as i64)?;
tmp
};
match len {
1 => {
dest[0] = src[0];
}
2 => {
let src_0 = src[0].0;
let src_1 = src[1].0;
let double_start_trits = DOUBLE_START_PATTERN | (src_0 & DOUBLE_START_BITMASK);
dest[0] = Tryte(double_start_trits);
let continuation_trits =
CONTINUATION_PATTERN | (src_0 >> 8 | src_1 << 4 & CONTINUATION_BITMASK);
dest[1] = Tryte(continuation_trits);
}
3 => {
let src_0 = src[0].0;
let src_1 = src[1].0;
let src_2 = src[2].0;
let triple_start_trits = TRIPLE_START_PATTERN | (src_0 & TRIPLE_START_BITMASK);
dest[0] = Tryte(triple_start_trits);
let continuation1_trits =
CONTINUATION_PATTERN | (src_0 >> 6 | src_1 << 6 & CONTINUATION_BITMASK);
dest[1] = Tryte(continuation1_trits);
let continuation2_trits =
CONTINUATION_PATTERN | (src_1 >> 4 | src_2 << 8 & CONTINUATION_BITMASK);
dest[2] = Tryte(continuation2_trits);
}
_ => unreachable!(),
}
Ok(len)
}
pub fn decode_char(src: &[Tryte]) -> Result<(char, usize)> {
let mut dest = [tryte::ZERO; WORD_LEN];
let high_trit = src.get_trit(5);
let next_high_trit = src.get_trit(4);
let (codepoint_offset, len) = match (high_trit, next_high_trit) {
(trit::ZERO, _) => {
dest[0] = src[0];
Ok((SINGLE_OFFSET, 1))
}
(trit::POS, trit::ZERO) => {
if src.get_trit(11) != trit::NEG {
return Err(invalid_encoding_from_trytes(&src[1..2]));
}
let double_start_trits = src[0].0 & DOUBLE_START_BITMASK;
let continuation_trits = src[1].0 & CONTINUATION_BITMASK;
let dest0_trits = double_start_trits | (continuation_trits << 8 & tryte::BITMASK);
dest[0] = Tryte(dest0_trits);
let dest1_trits = continuation_trits >> 4;
dest[1] = Tryte(dest1_trits);
Ok((DOUBLE_OFFSET, 2))
}
(trit::POS, trit::POS) => {
if src.get_trit(11) != trit::NEG {
return Err(invalid_encoding_from_trytes(&src[1..2]));
}
if src.get_trit(17) != trit::NEG {
return Err(invalid_encoding_from_trytes(&src[2..3]));
}
let triple_start_trits = src[0].0 & TRIPLE_START_BITMASK;
let continuation1_trits = src[1].0 & CONTINUATION_BITMASK;
let continuation2_trits = src[2].0 & CONTINUATION_BITMASK;
let dest0_trits = triple_start_trits | (continuation1_trits << 6 & tryte::BITMASK);
dest[0] = Tryte(dest0_trits);
let dest1_trits =
continuation1_trits >> 6 | (continuation2_trits << 4 & tryte::BITMASK);
dest[1] = Tryte(dest1_trits);
let dest2_trits = continuation2_trits >> 8;
dest[2] = Tryte(dest2_trits);
Ok((TRIPLE_OFFSET, 3))
}
_ => Err(invalid_encoding_from_trytes(&src[0..1])),
}?;
let shifted_codepoint = dest.into_i64() as i32;
let codepoint = unshift_codepoint(shifted_codepoint, codepoint_offset);
let c = char::from_u32(codepoint).ok_or_else(|| invalid_encoding_from_trytes(src))?;
Ok((c, len))
}
pub fn invalid_encoding_from_trytes(src: &[Tryte]) -> Error {
let mut bytes = Vec::new();
src.write_trits(&mut bytes).expect("error writing trits");
let s = String::from_utf8_lossy(&bytes).into_owned();
Error::InvalidEncoding(s)
}
fn shift_codepoint(codepoint: u32, offset: isize) -> i32 {
(codepoint as i32).wrapping_sub(offset as i32)
}
fn unshift_codepoint(shifted_codepoint: i32, offset: isize) -> u32 {
shifted_codepoint.wrapping_add(offset as i32) as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_encode_decode() {
let mut trytes = [tryte::ZERO; 256];
let s1 = "⸘I like to éat 🍎 and 🍌 wheñ it is 100℉ oütside‽";
let len1 = encode_str(&mut trytes, s1).expect("encoding error");
let (s2, len2) = decode_str(&trytes).expect("decoding error");
assert_eq!(len1, len2);
assert_eq!(s1, &s2[..]);
}
}
<file_sep>use std::fmt;
use std::io;
use std::result;
#[derive(Debug)]
pub enum Error {
FormatError(fmt::Error),
IntegerOutOfBounds(i64, i64, i64),
InvalidBitPattern(u64),
InvalidCharacter(char),
InvalidLength(usize, usize),
InvalidEncoding(String),
InvalidString(String),
IoError(io::Error),
}
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&Error::IntegerOutOfBounds(a1, b1, n1), &Error::IntegerOutOfBounds(a2, b2, n2)) => {
a1 == a2 && b1 == b2 && n1 == n2
}
(&Error::InvalidBitPattern(n1), &Error::InvalidBitPattern(n2)) => n1 == n2,
(&Error::InvalidCharacter(c1), &Error::InvalidCharacter(c2)) => c1 == c2,
(&Error::InvalidLength(e1, a1), &Error::InvalidLength(e2, a2)) => e1 == a1 && e2 == a2,
(&Error::InvalidEncoding(ref s1), &Error::InvalidEncoding(ref s2))
| (&Error::InvalidString(ref s1), &Error::InvalidString(ref s2)) => s1 == s2,
_ => false,
}
}
}
impl Eq for Error {}
pub type Result<T> = result::Result<T, Error>;
impl From<fmt::Error> for Error {
fn from(error: fmt::Error) -> Self {
Error::FormatError(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Error::IoError(error)
}
}
<file_sep>pub const TRIT_BIT_LEN: usize = 2;
pub const HYTE_BIT_LEN: usize = 6;
pub const TRYTE_LEN: usize = 1;
pub const TRYTE_TRIT_LEN: usize = 6;
pub const TRYTE_BIT_LEN: usize = TRYTE_TRIT_LEN * TRIT_BIT_LEN;
pub const HALF_LEN: usize = 2;
pub const HALF_TRIT_LEN: usize = HALF_LEN * TRYTE_TRIT_LEN;
pub const HALF_BIT_LEN: usize = HALF_TRIT_LEN * TRIT_BIT_LEN;
pub const WORD_LEN: usize = 4;
pub const WORD_TRIT_LEN: usize = WORD_LEN * TRYTE_TRIT_LEN;
pub const WORD_BIT_LEN: usize = WORD_TRIT_LEN * TRIT_BIT_LEN;
<file_sep>use super::Tryte;
pub const TRYTE_MIN: Tryte = Tryte(0b11_11_11_11_11_11);
pub const TRYTE_NEG317: Tryte = Tryte(0b11_01_00_01_11_01);
pub const TRYTE_NEG278: Tryte = Tryte(0b11_00_11_11_00_01);
pub const TRYTE_NEG256: Tryte = Tryte(0b11_00_00_11_11_11);
pub const TRYTE_NEG217: Tryte = Tryte(0b11_00_01_00_00_11);
pub const TRYTE_NEG167: Tryte = Tryte(0b11_01_00_11_01_01);
pub const TRYTE_NEG89: Tryte = Tryte(0b00_11_00_11_00_01);
pub const TRYTE_NEG81: Tryte = Tryte(0b00_11_00_00_00_00);
pub const TRYTE_NEG64: Tryte = Tryte(0b00_11_01_11_00_11);
pub const TRYTE_NEG16: Tryte = Tryte(0b00_00_11_01_01_11);
pub const TRYTE_NEG9: Tryte = Tryte(0b00_00_00_11_00_00);
pub const TRYTE_NEG8: Tryte = Tryte(0b00_00_00_11_00_01);
pub const TRYTE_NEG6: Tryte = Tryte(0b00_00_00_11_01_00);
pub const TRYTE_NEG3: Tryte = Tryte(0b00_00_00_00_11_00);
pub const TRYTE_NEG1: Tryte = Tryte(0b00_00_00_00_00_11);
pub const TRYTE_0: Tryte = Tryte(0b00_00_00_00_00_00);
pub const TRYTE_1: Tryte = Tryte(0b00_00_00_00_00_01);
pub const TRYTE_3: Tryte = Tryte(0b00_00_00_00_01_00);
pub const TRYTE_6: Tryte = Tryte(0b00_00_00_01_11_00);
pub const TRYTE_8: Tryte = Tryte(0b00_00_00_01_00_11);
pub const TRYTE_9: Tryte = Tryte(0b00_00_00_01_00_00);
pub const TRYTE_16: Tryte = Tryte(0b00_00_01_11_11_01);
pub const TRYTE_64: Tryte = Tryte(0b00_01_11_01_00_01);
pub const TRYTE_81: Tryte = Tryte(0b00_01_00_00_00_00);
pub const TRYTE_89: Tryte = Tryte(0b00_01_00_01_00_11);
pub const TRYTE_167: Tryte = Tryte(0b01_11_00_01_11_11);
pub const TRYTE_217: Tryte = Tryte(0b01_00_11_00_00_01);
pub const TRYTE_256: Tryte = Tryte(0b01_00_00_01_01_01);
pub const TRYTE_278: Tryte = Tryte(0b01_00_01_01_00_11);
pub const TRYTE_317: Tryte = Tryte(0b01_01_00_11_01_11);
pub const TRYTE_MAX: Tryte = Tryte(0b01_01_01_01_01_01);
pub const TRYTE2_NEG4096: [Tryte; 2] = [TRYTE_278, TRYTE_NEG6];
pub const TRYTE2_NEG512: [Tryte; 2] = [TRYTE_217, TRYTE_NEG1];
pub const TRYTE2_NEG256: [Tryte; 2] = [TRYTE_NEG256, TRYTE_0];
pub const TRYTE2_NEG64: [Tryte; 2] = [TRYTE_NEG64, TRYTE_0];
pub const TRYTE2_NEG16: [Tryte; 2] = [TRYTE_NEG16, TRYTE_0];
pub const TRYTE2_NEG9: [Tryte; 2] = [TRYTE_NEG9, TRYTE_0];
pub const TRYTE2_NEG8: [Tryte; 2] = [TRYTE_NEG8, TRYTE_0];
pub const TRYTE2_NEG1: [Tryte; 2] = [TRYTE_NEG1, TRYTE_0];
pub const TRYTE2_0: [Tryte; 2] = [TRYTE_0, TRYTE_0];
pub const TRYTE2_1: [Tryte; 2] = [TRYTE_1, TRYTE_0];
pub const TRYTE2_8: [Tryte; 2] = [TRYTE_8, TRYTE_0];
pub const TRYTE2_9: [Tryte; 2] = [TRYTE_9, TRYTE_0];
pub const TRYTE2_16: [Tryte; 2] = [TRYTE_16, TRYTE_0];
pub const TRYTE2_64: [Tryte; 2] = [TRYTE_64, TRYTE_0];
pub const TRYTE2_256: [Tryte; 2] = [TRYTE_256, TRYTE_0];
pub const TRYTE2_512: [Tryte; 2] = [TRYTE_NEG217, TRYTE_1];
pub const TRYTE2_4096: [Tryte; 2] = [TRYTE_NEG278, TRYTE_6];
pub const TRYTE4_MIN: [Tryte; 4] = [TRYTE_MIN; 4];
pub const TRYTE4_NEG1073741824: [Tryte; 4] = [TRYTE_89, TRYTE_NEG317, TRYTE_167, TRYTE_NEG3];
pub const TRYTE4_NEG4096: [Tryte; 4] = [TRYTE_278, TRYTE_NEG6, TRYTE_0, TRYTE_0];
pub const TRYTE4_NEG81: [Tryte; 4] = [TRYTE_NEG81, TRYTE_0, TRYTE_0, TRYTE_0];
pub const TRYTE4_NEG64: [Tryte; 4] = [TRYTE_NEG64, TRYTE_0, TRYTE_0, TRYTE_0];
pub const TRYTE4_NEG1: [Tryte; 4] = [TRYTE_NEG1, TRYTE_0, TRYTE_0, TRYTE_0];
pub const TRYTE4_0: [Tryte; 4] = [TRYTE_0; 4];
pub const TRYTE4_1: [Tryte; 4] = [TRYTE_1, TRYTE_0, TRYTE_0, TRYTE_0];
pub const TRYTE4_64: [Tryte; 4] = [TRYTE_64, TRYTE_0, TRYTE_0, TRYTE_0];
pub const TRYTE4_81: [Tryte; 4] = [TRYTE_81, TRYTE_0, TRYTE_0, TRYTE_0];
pub const TRYTE4_4096: [Tryte; 4] = [TRYTE_NEG278, TRYTE_6, TRYTE_0, TRYTE_0];
pub const TRYTE4_1073741824: [Tryte; 4] = [TRYTE_NEG89, TRYTE_317, TRYTE_NEG167, TRYTE_3];
pub const TRYTE4_MAX: [Tryte; 4] = [TRYTE_MAX; 4];
pub const TRYTE12_0: [Tryte; 12] = [TRYTE_0; 12];
pub const BYTES_MIN: [u8; 8] = [
0b11_11_11_11,
0b00_00_11_11,
0b11_11_11_11,
0b00_00_11_11,
0b11_11_11_11,
0b00_00_11_11,
0b11_11_11_11,
0b00_00_11_11,
];
pub const BYTES_NEG1: [u8; 8] = [
0b00_00_00_11,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
];
pub const BYTES_0: [u8; 8] = [
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
];
pub const BYTES_1: [u8; 8] = [
0b00_00_00_01,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
0b00_00_00_00,
];
pub const BYTES_MAX: [u8; 8] = [
0b01_01_01_01,
0b00_00_01_01,
0b01_01_01_01,
0b00_00_01_01,
0b01_01_01_01,
0b00_00_01_01,
0b01_01_01_01,
0b00_00_01_01,
];
pub const WORD_MIN: i64 = -141_214_768_240;
pub const WORD_MAX: i64 = 141_214_768_240;
<file_sep>use std::convert::TryFrom;
use std::cmp::Ordering;
use std::fmt;
use std::ops;
use phf;
use super::tables::*;
use super::error::{Error, Result};
pub const BITMASK: u16 = 0b11;
pub const BIN_ZERO: u16 = 0b00;
pub const BIN_POS: u16 = 0b01;
pub const BIN_INVALID: u16 = 0b10;
pub const BIN_NEG: u16 = 0b11;
pub const CHAR_ZERO: char = '0';
pub const CHAR_POS: char = '1';
pub const CHAR_INVALID: char = '?';
pub const CHAR_NEG: char = 'T';
#[derive(Clone, Copy, Default, Eq, Ord, PartialEq)]
pub struct Trit(pub u16);
pub const ZERO: Trit = Trit(BIN_ZERO);
pub const POS: Trit = Trit(BIN_POS);
pub const NEG: Trit = Trit(BIN_NEG);
impl Trit {
pub fn from_trit4(trit4: u8) -> Result<Self> {
let trit_bits = trit4 as u16 & BITMASK;
if trit_bits == BIN_INVALID {
return Err(Error::InvalidBitPattern(trit_bits as u64));
}
Ok(Trit(trit_bits))
}
fn negation_bits(self) -> u16 {
self.0 << 1 & BITMASK
}
pub fn tcmp(self, rhs: Self) -> Self {
let i = trit2_index(self, rhs);
let bits = TRIT2_TO_CMP[i];
Trit(bits)
}
pub fn add_with_carry(self, rhs: Self, carry_in: Self) -> (Self, Self) {
let i = trit3_index(self, rhs, carry_in);
let (sum, carry) = TRIT3_TO_SUM_AND_CARRY[i];
(Trit(sum), Trit(carry))
}
pub fn into_index(self) -> usize {
self.0 as usize
}
}
fn trit2_index(a: Trit, b: Trit) -> usize {
a.into_index() << 2 | b.into_index()
}
fn trit3_index(a: Trit, b: Trit, c: Trit) -> usize {
a.into_index() << 4 | b.into_index() << 2 | c.into_index()
}
static TRIT_TO_I16: [i16; 4] = [0, 1, 0, -1];
impl Into<i16> for Trit {
fn into(self) -> i16 {
TRIT_TO_I16[self.into_index()]
}
}
static U16_TO_TRIT: [u16; 3] = [BIN_NEG, BIN_ZERO, BIN_POS];
impl TryFrom<i16> for Trit {
type Error = Error;
fn try_from(n: i16) -> Result<Self> {
let uint = (n + 1) as usize;
if uint < 3 {
let bits = U16_TO_TRIT[uint];
Ok(Trit(bits))
} else {
Err(Error::IntegerOutOfBounds(-1, 1, n as i64))
}
}
}
static TRIT_TO_CHAR: [char; 4] = [CHAR_ZERO, CHAR_POS, CHAR_INVALID, CHAR_NEG];
impl Into<char> for Trit {
fn into(self) -> char {
TRIT_TO_CHAR[self.into_index()]
}
}
static CHAR_TO_TRIT: phf::Map<char, u16> = phf_map! {
'T' => BIN_NEG,
'0' => BIN_ZERO,
'1' => BIN_POS,
};
impl TryFrom<char> for Trit {
type Error = Error;
fn try_from(c: char) -> Result<Self> {
if let Some(&bits) = CHAR_TO_TRIT.get(&c) {
Ok(Trit(bits))
} else {
Err(Error::InvalidCharacter(c))
}
}
}
static TRIT_TO_ORDERING: [Ordering; 4] = [
Ordering::Equal,
Ordering::Greater,
Ordering::Equal,
Ordering::Less,
];
impl Into<Ordering> for Trit {
fn into(self) -> Ordering {
TRIT_TO_ORDERING[self.into_index()]
}
}
impl TryFrom<Ordering> for Trit {
type Error = Error;
fn try_from(ordering: Ordering) -> Result<Self> {
match ordering {
Ordering::Less => Ok(NEG),
Ordering::Equal => Ok(ZERO),
Ordering::Greater => Ok(POS),
}
}
}
impl PartialOrd for Trit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let cmp_trit = self.tcmp(*other);
Some(cmp_trit.into())
}
}
impl ops::Neg for Trit {
type Output = Self;
fn neg(self) -> Self::Output {
let bits = self.0 ^ self.negation_bits();
Trit(bits)
}
}
impl ops::Not for Trit {
type Output = Self;
fn not(self) -> Self::Output {
-self
}
}
impl ops::BitAnd for Trit {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
let i = trit2_index(self, rhs);
let bits = TRIT2_TO_AND[i];
Trit(bits)
}
}
impl ops::BitOr for Trit {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
let i = trit2_index(self, rhs);
let bits = TRIT2_TO_OR[i];
Trit(bits)
}
}
impl ops::Mul for Trit {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
let i = trit2_index(self, rhs);
let bits = TRIT2_TO_PRODUCT[i];
Trit(bits)
}
}
impl fmt::Debug for Trit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Trit({:02b})", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trit_into_i16() {
assert_eq!(-1i16, Trit(BIN_NEG).into());
assert_eq!(0i16, Trit(BIN_ZERO).into());
assert_eq!(1i16, Trit(BIN_POS).into());
}
#[test]
fn trit_from_i16() {
assert_eq!(Ok(Trit(BIN_NEG)), Trit::try_from(-1));
assert_eq!(Ok(Trit(BIN_ZERO)), Trit::try_from(0));
assert_eq!(Ok(Trit(BIN_POS)), Trit::try_from(1));
assert!(Trit::try_from(-2).is_err());
assert!(Trit::try_from(2).is_err());
}
#[test]
fn trit_into_char() {
assert_eq!('T', Trit(BIN_NEG).into());
assert_eq!('0', Trit(BIN_ZERO).into());
assert_eq!('1', Trit(BIN_POS).into());
}
#[test]
fn trit_from_char() {
assert_eq!(Ok(Trit(BIN_NEG)), Trit::try_from('T'));
assert_eq!(Ok(Trit(BIN_ZERO)), Trit::try_from('0'));
assert_eq!(Ok(Trit(BIN_POS)), Trit::try_from('1'));
assert!(Trit::try_from('t').is_err());
assert!(Trit::try_from('S').is_err());
assert!(Trit::try_from('2').is_err());
}
#[test]
fn trit_negate() {
assert_eq!(POS, -NEG);
assert_eq!(ZERO, -ZERO);
assert_eq!(NEG, -POS);
}
#[test]
fn trit_and() {
assert_eq!(ZERO, ZERO & ZERO);
assert_eq!(ZERO, ZERO & POS);
assert_eq!(NEG, ZERO & NEG);
assert_eq!(ZERO, POS & ZERO);
assert_eq!(POS, POS & POS);
assert_eq!(NEG, POS & NEG);
assert_eq!(NEG, NEG & ZERO);
assert_eq!(NEG, NEG & POS);
assert_eq!(NEG, NEG & NEG);
}
#[test]
fn trit_or() {
assert_eq!(ZERO, ZERO | ZERO);
assert_eq!(POS, ZERO | POS);
assert_eq!(ZERO, ZERO | NEG);
assert_eq!(POS, POS | ZERO);
assert_eq!(POS, POS | POS);
assert_eq!(POS, POS | NEG);
assert_eq!(ZERO, NEG | ZERO);
assert_eq!(POS, NEG | POS);
assert_eq!(NEG, NEG | NEG);
}
#[test]
fn trit_add() {
assert_eq!((ZERO, ZERO), ZERO.add_with_carry(ZERO, ZERO));
assert_eq!((POS, ZERO), ZERO.add_with_carry(ZERO, POS));
assert_eq!((NEG, ZERO), ZERO.add_with_carry(ZERO, NEG));
assert_eq!((POS, ZERO), ZERO.add_with_carry(POS, ZERO));
assert_eq!((NEG, POS), ZERO.add_with_carry(POS, POS));
assert_eq!((ZERO, ZERO), ZERO.add_with_carry(POS, NEG));
assert_eq!((NEG, ZERO), ZERO.add_with_carry(NEG, ZERO));
assert_eq!((ZERO, ZERO), ZERO.add_with_carry(NEG, POS));
assert_eq!((POS, NEG), ZERO.add_with_carry(NEG, NEG));
assert_eq!((POS, ZERO), POS.add_with_carry(ZERO, ZERO));
assert_eq!((NEG, POS), POS.add_with_carry(ZERO, POS));
assert_eq!((ZERO, ZERO), POS.add_with_carry(ZERO, NEG));
assert_eq!((NEG, POS), POS.add_with_carry(POS, ZERO));
assert_eq!((ZERO, POS), POS.add_with_carry(POS, POS));
assert_eq!((POS, ZERO), POS.add_with_carry(POS, NEG));
assert_eq!((ZERO, ZERO), POS.add_with_carry(NEG, ZERO));
assert_eq!((POS, ZERO), POS.add_with_carry(NEG, POS));
assert_eq!((NEG, ZERO), POS.add_with_carry(NEG, NEG));
assert_eq!((NEG, ZERO), NEG.add_with_carry(ZERO, ZERO));
assert_eq!((ZERO, ZERO), NEG.add_with_carry(ZERO, POS));
assert_eq!((POS, NEG), NEG.add_with_carry(ZERO, NEG));
assert_eq!((ZERO, ZERO), NEG.add_with_carry(POS, ZERO));
assert_eq!((POS, ZERO), NEG.add_with_carry(POS, POS));
assert_eq!((NEG, ZERO), NEG.add_with_carry(POS, NEG));
assert_eq!((POS, NEG), NEG.add_with_carry(NEG, ZERO));
assert_eq!((NEG, ZERO), NEG.add_with_carry(NEG, POS));
assert_eq!((ZERO, NEG), NEG.add_with_carry(NEG, NEG));
}
#[test]
fn trit_mul() {
assert_eq!(ZERO, ZERO * ZERO);
assert_eq!(ZERO, ZERO * POS);
assert_eq!(ZERO, ZERO * NEG);
assert_eq!(ZERO, POS * ZERO);
assert_eq!(POS, POS * POS);
assert_eq!(NEG, POS * NEG);
assert_eq!(ZERO, NEG * ZERO);
assert_eq!(NEG, NEG * POS);
assert_eq!(POS, NEG * NEG);
}
#[test]
fn trit_cmp() {
assert!(ZERO == ZERO);
assert!(ZERO < POS);
assert!(ZERO > NEG);
assert!(POS > ZERO);
assert!(POS > NEG);
assert!(POS == POS);
assert!(NEG < ZERO);
assert!(NEG < POS);
assert!(NEG == NEG);
}
}
<file_sep>use phf;
use super::trit::CHAR_INVALID;
use super::error::{Error, Result};
static CHAR_TO_HYTE: phf::Map<char, u8> = phf_map! {
'm' => 0b11_11_11,
'l' => 0b11_11_00,
'k' => 0b11_11_01,
'j' => 0b11_00_11,
'i' => 0b11_00_00,
'h' => 0b11_00_01,
'g' => 0b11_01_11,
'f' => 0b11_01_00,
'e' => 0b11_01_01,
'd' => 0b00_11_11,
'c' => 0b00_11_00,
'b' => 0b00_11_01,
'a' => 0b00_00_11,
'0' => 0b00_00_00,
'A' => 0b00_00_01,
'B' => 0b00_01_11,
'C' => 0b00_01_00,
'D' => 0b00_01_01,
'E' => 0b01_11_11,
'F' => 0b01_11_00,
'G' => 0b01_11_01,
'H' => 0b01_00_11,
'I' => 0b01_00_00,
'J' => 0b01_00_01,
'K' => 0b01_01_11,
'L' => 0b01_01_00,
'M' => 0b01_01_01,
};
pub fn try_from_char(c: char) -> Result<u8> {
CHAR_TO_HYTE
.get(&c)
.cloned()
.ok_or_else(|| Error::InvalidCharacter(c))
}
lazy_static! {
static ref HYTE_TO_CHAR: [char; 64] = {
let mut table = [CHAR_INVALID; 64];
table[0b11_11_11] = 'm';
table[0b11_11_00] = 'l';
table[0b11_11_01] = 'k';
table[0b11_00_11] = 'j';
table[0b11_00_00] = 'i';
table[0b11_00_01] = 'h';
table[0b11_01_11] = 'g';
table[0b11_01_00] = 'f';
table[0b11_01_01] = 'e';
table[0b00_11_11] = 'd';
table[0b00_11_00] = 'c';
table[0b00_11_01] = 'b';
table[0b00_00_11] = 'a';
table[0b00_00_00] = '0';
table[0b00_00_01] = 'A';
table[0b00_01_11] = 'B';
table[0b00_01_00] = 'C';
table[0b00_01_01] = 'D';
table[0b01_11_11] = 'E';
table[0b01_11_00] = 'F';
table[0b01_11_01] = 'G';
table[0b01_00_11] = 'H';
table[0b01_00_00] = 'I';
table[0b01_00_01] = 'J';
table[0b01_01_11] = 'K';
table[0b01_01_00] = 'L';
table[0b01_01_01] = 'M';
table
};
}
pub fn into_char(hyte: u8) -> char {
let i = hyte as usize;
HYTE_TO_CHAR[i]
}
<file_sep>use std::convert::TryInto;
use std::fmt;
use std::io;
use std::ops;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use super::constants::*;
use super::error::{Error, Result};
use super::trit;
use super::trit::Trit;
use super::hyte;
pub use super::constants::TRYTE_TRIT_LEN as TRIT_LEN;
pub const BITMASK: u16 = 0b11_11_11_11_11_11;
pub const HYTE_BITMASK: u8 = 0b11_11_11;
const SIGN_BITMASK: u16 = 0b10_10_10_10_10_10;
#[derive(Clone, Copy, Default, Eq, PartialEq)]
pub struct Tryte(pub u16);
pub const ZERO: Tryte = Tryte(trit::BIN_ZERO);
impl Tryte {
pub fn get_trit(self, i: usize) -> Trit {
let shf = (i as u16) * 2;
let bits = self.0 >> shf & trit::BITMASK;
Trit(bits)
}
pub fn set_trit(self, i: usize, trit: Trit) -> Self {
let shf = (i as u16) * 2;
let zero_bits = !(0b11 << shf);
let tryte_bits = self.0 & zero_bits;
let trit_bits = trit.0 << shf;
let bits = (tryte_bits | trit_bits) & BITMASK;
Tryte(bits)
}
pub fn from_bytes<R: ReadBytesExt>(reader: &mut R) -> Result<Self> {
let bits = reader.read_u16::<LittleEndian>()?;
let tryte = Tryte(bits);
for i in 0..TRIT_LEN {
let trit = tryte.get_trit(i);
let trit_bits = trit.0;
if trit_bits == trit::BIN_INVALID {
return Err(Error::InvalidBitPattern(trit_bits as u64));
}
}
Ok(tryte)
}
pub fn write_bytes<W: WriteBytesExt>(&self, writer: &mut W) -> Result<()> {
Ok(writer.write_u16::<LittleEndian>(self.0)?)
}
fn from_hytes(low_hyte: u8, high_hyte: u8) -> Self {
let bits = (high_hyte as u16) << HYTE_BIT_LEN | (low_hyte as u16);
Tryte(bits)
}
fn low_hyte(self) -> u8 {
self.0 as u8 & HYTE_BITMASK
}
fn high_hyte(self) -> u8 {
(self.0 >> HYTE_BIT_LEN) as u8 & HYTE_BITMASK
}
fn hytes(self) -> (u8, u8) {
(self.low_hyte(), self.high_hyte())
}
pub fn low_trit4(self) -> u8 {
self.0 as u8
}
fn negation_bits(self) -> u16 {
self.0 << 1 & SIGN_BITMASK
}
pub fn add_with_carry(self, rhs: Self, carry: Trit) -> (Self, Trit) {
let mut tryte = ZERO;
let mut carry = carry;
for i in 0..TRIT_LEN {
let a = self.get_trit(i);
let b = rhs.get_trit(i);
let (c, new_carry) = a.add_with_carry(b, carry);
tryte = tryte.set_trit(i, c);
carry = new_carry;
}
(tryte, carry)
}
pub fn from_hyte_str(s: &str) -> Result<Self> {
if s.len() != 2 {
return Err(Error::InvalidLength(2, s.len()));
}
let mut chars = s.chars();
let high_char = chars
.next()
.ok_or_else(|| Error::InvalidString(s.to_owned()))?;
let low_char = chars
.next()
.ok_or_else(|| Error::InvalidString(s.to_owned()))?;
let high_hyte = hyte::try_from_char(high_char)?;
let low_hyte = hyte::try_from_char(low_char)?;
let tryte = Self::from_hytes(low_hyte, high_hyte);
Ok(tryte)
}
pub fn write_hytes<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
let (low_hyte, high_hyte) = self.hytes();
let low_char = hyte::into_char(low_hyte);
let high_char = hyte::into_char(high_hyte);
write!(writer, "{}{}", high_char, low_char)
}
}
impl From<Trit> for Tryte {
fn from(trit: Trit) -> Self {
Tryte(trit.0)
}
}
impl TryInto<Trit> for Tryte {
type Error = Error;
fn try_into(self) -> Result<Trit> {
let bits = self.0;
if bits == trit::BIN_INVALID || bits > trit::BIN_NEG {
Err(Error::InvalidBitPattern(bits as u64))
} else {
Ok(Trit(bits))
}
}
}
impl ops::Neg for Tryte {
type Output = Self;
fn neg(self) -> Self::Output {
let bits = self.0 ^ self.negation_bits();
Tryte(bits)
}
}
impl fmt::Debug for Tryte {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Tryte({:012b})", self.0)
}
}
impl fmt::Display for Tryte {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (low_hyte, high_hyte) = self.hytes();
let low_char = hyte::into_char(low_hyte);
let high_char = hyte::into_char(high_hyte);
write!(f, "{}{}", high_char, low_char)
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::test_constants::*;
use std::io::Cursor;
#[test]
fn tryte_into_trit() {
assert_eq!(Ok(trit::NEG), TRYTE_NEG1.try_into());
assert_eq!(Ok(trit::ZERO), TRYTE_0.try_into());
assert_eq!(Ok(trit::POS), TRYTE_1.try_into());
assert!(<Tryte as TryInto<Trit>>::try_into(TRYTE_NEG64).is_err());
assert!(<Tryte as TryInto<Trit>>::try_into(TRYTE_64).is_err());
}
#[test]
fn tryte_from_trit() {
assert_eq!(TRYTE_NEG1, trit::NEG.into());
assert_eq!(TRYTE_0, trit::ZERO.into());
assert_eq!(TRYTE_1, trit::POS.into());
}
#[test]
fn tryte_from_bytes() {
assert_eq!(Ok(TRYTE_MIN), from_bytes(0b11_11_11_11, 0b00_00_11_11));
assert_eq!(Ok(TRYTE_NEG64), from_bytes(0b01_11_00_11, 0b00_00_00_11));
assert_eq!(Ok(TRYTE_NEG1), from_bytes(0b00_00_00_11, 0b00_00_00_00));
assert_eq!(Ok(TRYTE_0), from_bytes(0b00_00_00_00, 0b00_00_00_00));
assert_eq!(Ok(TRYTE_1), from_bytes(0b00_00_00_01, 0b00_00_00_00));
assert_eq!(Ok(TRYTE_64), from_bytes(0b11_01_00_01, 0b00_00_00_01));
assert_eq!(Ok(TRYTE_MAX), from_bytes(0b01_01_01_01, 0b00_00_01_01));
assert!(from_bytes(0b01_01_10_01, 0b00_00_01_01).is_err());
}
fn from_bytes(low: u8, high: u8) -> Result<Tryte> {
let mut cursor = Cursor::new(vec![low, high]);
Ok(Tryte::from_bytes(&mut cursor)?)
}
#[test]
fn tryte_write_bytes() {
assert_eq!(vec![0b11_11_11_11, 0b00_00_11_11], get_bytes(TRYTE_MIN));
assert_eq!(vec![0b01_11_00_11, 0b00_00_00_11], get_bytes(TRYTE_NEG64));
assert_eq!(vec![0b00_00_00_11, 0b00_00_00_00], get_bytes(TRYTE_NEG1));
assert_eq!(vec![0b00_00_00_00, 0b00_00_00_00], get_bytes(TRYTE_0));
assert_eq!(vec![0b00_00_00_01, 0b00_00_00_00], get_bytes(TRYTE_1));
assert_eq!(vec![0b11_01_00_01, 0b00_00_00_01], get_bytes(TRYTE_64));
assert_eq!(vec![0b01_01_01_01, 0b00_00_01_01], get_bytes(TRYTE_MAX));
}
fn get_bytes(tryte: Tryte) -> Vec<u8> {
let mut bytes = vec![];
tryte.write_bytes(&mut bytes).unwrap();
bytes
}
#[test]
fn tryte_display_hytes() {
assert_eq!("mm", format!("{}", TRYTE_MIN));
assert_eq!("bj", format!("{}", TRYTE_NEG64));
assert_eq!("0a", format!("{}", TRYTE_NEG1));
assert_eq!("00", format!("{}", TRYTE_0));
assert_eq!("0A", format!("{}", TRYTE_1));
assert_eq!("BJ", format!("{}", TRYTE_64));
assert_eq!("MM", format!("{}", TRYTE_MAX));
}
#[test]
fn tryte_from_hyte_str() {
assert_eq!(Ok(TRYTE_MIN), Tryte::from_hyte_str("mm"));
assert_eq!(Ok(TRYTE_NEG64), Tryte::from_hyte_str("bj"));
assert_eq!(Ok(TRYTE_NEG1), Tryte::from_hyte_str("0a"));
assert_eq!(Ok(TRYTE_0), Tryte::from_hyte_str("00"));
assert_eq!(Ok(TRYTE_1), Tryte::from_hyte_str("0A"));
assert_eq!(Ok(TRYTE_64), Tryte::from_hyte_str("BJ"));
assert_eq!(Ok(TRYTE_MAX), Tryte::from_hyte_str("MM"));
assert!(Tryte::from_hyte_str("").is_err());
assert!(Tryte::from_hyte_str("M").is_err());
assert!(Tryte::from_hyte_str("MMM").is_err());
assert!(Tryte::from_hyte_str("NN").is_err());
}
#[test]
fn tryte_negate() {
assert_eq!(TRYTE_MIN, -TRYTE_MAX);
assert_eq!(TRYTE_NEG64, -TRYTE_64);
assert_eq!(TRYTE_NEG1, -TRYTE_1);
assert_eq!(TRYTE_0, -TRYTE_0);
assert_eq!(TRYTE_1, -TRYTE_NEG1);
assert_eq!(TRYTE_64, -TRYTE_NEG64);
assert_eq!(TRYTE_MAX, -TRYTE_MIN);
assert_eq!(TRYTE_MAX, -TRYTE_MIN);
assert_eq!(TRYTE_64, -TRYTE_NEG64);
assert_eq!(TRYTE_1, -TRYTE_NEG1);
assert_eq!(TRYTE_0, -TRYTE_0);
assert_eq!(TRYTE_NEG1, -TRYTE_1);
assert_eq!(TRYTE_NEG64, -TRYTE_64);
assert_eq!(TRYTE_MIN, -TRYTE_MAX);
}
#[test]
fn tryte_add() {
assert_eq!(
(TRYTE_0, trit::ZERO),
TRYTE_1.add_with_carry(TRYTE_NEG1, trit::ZERO)
);
assert_eq!(
(TRYTE_0, trit::ZERO),
TRYTE_64.add_with_carry(TRYTE_NEG64, trit::ZERO)
);
assert_eq!(
(TRYTE_0, trit::ZERO),
TRYTE_MAX.add_with_carry(TRYTE_MIN, trit::ZERO)
);
assert_eq!(
(TRYTE_MIN, trit::ZERO),
TRYTE_MIN.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_NEG64, trit::ZERO),
TRYTE_NEG64.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_NEG1, trit::ZERO),
TRYTE_NEG1.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_0, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_1, trit::ZERO),
TRYTE_1.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_64, trit::ZERO),
TRYTE_64.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_MAX, trit::ZERO),
TRYTE_MAX.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_MIN, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_MIN, trit::ZERO)
);
assert_eq!(
(TRYTE_NEG64, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_NEG64, trit::ZERO)
);
assert_eq!(
(TRYTE_NEG1, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_NEG1, trit::ZERO)
);
assert_eq!(
(TRYTE_0, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_0, trit::ZERO)
);
assert_eq!(
(TRYTE_1, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_1, trit::ZERO)
);
assert_eq!(
(TRYTE_64, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_64, trit::ZERO)
);
assert_eq!(
(TRYTE_MAX, trit::ZERO),
TRYTE_0.add_with_carry(TRYTE_MAX, trit::ZERO)
);
}
}
<file_sep>This started out as part of [btm](https://github.com/jdanford/btm) but will gradually be fleshed out into a standalone library with documentation and more tests.
<file_sep>#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
#![cfg_attr(feature = "cargo-clippy",
allow(cast_lossless, cast_possible_truncation, cast_possible_wrap, cast_sign_loss,
missing_docs_in_private_items))]
#![allow(unused)] // still need to write more tests :(
#![feature(try_from)]
#![feature(plugin)]
#![plugin(phf_macros)]
extern crate byteorder;
#[macro_use]
extern crate lazy_static;
extern crate phf;
pub mod error;
pub mod constants;
pub mod test_constants;
pub mod tables;
pub mod trit;
mod hyte;
pub mod tryte;
pub mod text;
use std::convert::TryFrom;
use std::io;
use std::ops::{BitAnd, BitOr, Mul, Neg};
use byteorder::{ReadBytesExt, WriteBytesExt};
pub use self::error::{Error, Result};
pub use self::trit::Trit;
pub use self::tryte::Tryte;
pub trait Ternary {
fn trit_len(&self) -> usize;
fn tryte_len(&self) -> usize;
fn get_trit(&self, usize) -> Trit;
fn set_trit(&mut self, usize, trit: Trit);
fn get_tryte(&self, usize) -> Tryte;
fn set_tryte(&mut self, usize, tryte: Tryte);
fn range(&self) -> i64 {
let base = 3_i64;
let exp = self.trit_len() as u32;
base.pow(exp)
}
fn min_value(&self) -> i64 {
-(self.range() - 1) / 2
}
fn max_value(&self) -> i64 {
(self.range() - 1) / 2
}
fn clear(&mut self) {
for i in 0..self.tryte_len() {
self.set_tryte(i, tryte::ZERO);
}
}
fn read_bytes<R: ReadBytesExt>(&mut self, reader: &mut R) -> Result<()> {
for i in 0..self.tryte_len() {
let tryte = Tryte::from_bytes(reader)?;
self.set_tryte(i, tryte);
}
Ok(())
}
fn write_bytes<W: WriteBytesExt>(&self, writer: &mut W) -> Result<()> {
for i in 0..self.tryte_len() {
let tryte = self.get_tryte(i);
tryte.write_bytes(writer)?;
}
Ok(())
}
fn into_i64(&self) -> i64 {
let mut n = 0_i64;
for i in (0..self.trit_len()).rev() {
let trit = self.get_trit(i);
let t: i16 = trit.into();
n = n * 3 + t as i64;
}
n
}
fn read_i64(&mut self, n: i64) -> Result<()> {
if n < self.min_value() || self.max_value() < n {
return Err(Error::IntegerOutOfBounds(
self.min_value(),
self.max_value(),
n,
));
}
let sign_trit = if n < 0 { trit::NEG } else { trit::POS };
let mut n_pos = n.abs();
for i in 0..self.trit_len() {
let rem_trit = match n_pos % 3 {
1 => trit::POS,
0 => trit::ZERO,
_ => {
n_pos += 1;
trit::NEG
}
};
let trit = sign_trit * rem_trit;
self.set_trit(i, trit);
n_pos /= 3;
}
Ok(())
}
fn read_hytes(&mut self, mut s: &str) -> Result<()> {
let len = self.tryte_len() * 2;
if s.len() != len {
return Err(Error::InvalidLength(len, s.len()));
}
for i in (0..self.tryte_len()).rev() {
let (substr, s_rest) = s.split_at(2);
s = s_rest;
let tryte = Tryte::from_hyte_str(substr)?;
self.set_tryte(i, tryte);
}
Ok(())
}
fn write_hytes<W: io::Write>(&self, writer: &mut W) -> Result<()> {
for i in (0..self.tryte_len()).rev() {
let tryte = self.get_tryte(i);
tryte.write_hytes(writer)?;
}
Ok(())
}
fn read_trits(&mut self, s: &str) -> Result<()> {
if s.len() != self.trit_len() {
return Err(Error::InvalidLength(self.trit_len(), s.len()));
}
for (i, c) in s.chars().rev().enumerate() {
let trit = Trit::try_from(c)?;
self.set_trit(i, trit);
}
Ok(())
}
fn write_trits<W: io::Write>(&self, writer: &mut W) -> Result<()> {
for i in (0..self.trit_len()).rev() {
let trit = self.get_trit(i);
let c: char = trit.into();
write!(writer, "{}", c)?;
}
Ok(())
}
}
pub fn compare<T: Ternary + ?Sized>(lhs: &T, rhs: &T) -> Trit {
let mut cmp_trit = trit::ZERO;
for i in (0..lhs.trit_len()).rev() {
let a = lhs.get_trit(i);
let b = rhs.get_trit(i);
cmp_trit = a.tcmp(b);
if cmp_trit != trit::ZERO {
break;
}
}
cmp_trit
}
pub fn negate<T: Ternary + ?Sized>(dest: &mut T, src: &T) {
zip_trytes(dest, src, Tryte::neg)
}
pub fn and<T: Ternary + ?Sized>(dest: &mut T, lhs: &T, rhs: &T) {
zip2_trits(dest, lhs, rhs, Trit::bitand)
}
pub fn or<T: Ternary + ?Sized>(dest: &mut T, lhs: &T, rhs: &T) {
zip2_trits(dest, lhs, rhs, Trit::bitor)
}
pub fn tcmp<T: Ternary + ?Sized>(dest: &mut T, lhs: &T, rhs: &T) {
zip2_trits(dest, lhs, rhs, Trit::tcmp)
}
pub fn tmul<T: Ternary + ?Sized>(dest: &mut T, lhs: &T, rhs: &T) {
zip2_trits(dest, lhs, rhs, Trit::mul)
}
fn read_trits<T: Ternary + ?Sized>(dest: &mut T, trits: &[Trit]) -> Result<()> {
if trits.len() != dest.trit_len() {
return Err(Error::InvalidLength(dest.trit_len(), trits.len()));
}
for (i, &trit) in trits.iter().enumerate() {
dest.set_trit(i, trit);
}
Ok(())
}
pub fn add<T: Ternary + ?Sized>(dest: &mut T, lhs: &T, rhs: &T, carry: Trit) -> Trit {
let mut carry = carry;
for i in 0..lhs.trit_len() {
let a = lhs.get_trit(i);
let b = rhs.get_trit(i);
let (c, new_carry) = a.add_with_carry(b, carry);
carry = new_carry;
dest.set_trit(i, c);
}
carry
}
pub fn multiply<T: Ternary + ?Sized>(dest: &mut T, lhs: &T, rhs: &T) {
let len = rhs.trit_len();
for i in 0..len {
let sign = rhs.get_trit(i);
let carry = add_mul(dest, lhs, sign, i);
dest.set_trit(i + len, carry);
}
}
fn add_mul<T: Ternary + ?Sized>(dest: &mut T, src: &T, sign: Trit, offset: usize) -> Trit {
let mut carry = trit::ZERO;
for i in 0..src.trit_len() {
let a = dest.get_trit(i + offset);
let b = src.get_trit(i);
let (c, new_carry) = a.add_with_carry(b * sign, carry);
carry = new_carry;
dest.set_trit(i + offset, c);
}
carry
}
pub fn shift<T: Ternary + ?Sized>(dest: &mut T, src: &T, offset: isize) {
let src_len = src.trit_len();
let dest_len = src_len * 3;
let dest_offset = offset + src_len as isize;
for i in 0..src_len {
let i_dest = i as isize + dest_offset;
if i_dest < 0 || dest_len as isize <= i_dest {
continue;
}
let trit = src.get_trit(i);
dest.set_trit(i_dest as usize, trit);
}
}
fn zip_trits<T, F>(dest: &mut T, lhs: &T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Trit) -> Trit,
{
for i in 0..lhs.trit_len() {
let trit = lhs.get_trit(i);
dest.set_trit(i, f(trit));
}
}
fn zip_trytes<T, F>(dest: &mut T, lhs: &T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Tryte) -> Tryte,
{
for i in 0..lhs.tryte_len() {
let tryte = lhs.get_tryte(i);
dest.set_tryte(i, f(tryte));
}
}
fn zip2_trits<T, F>(dest: &mut T, lhs: &T, rhs: &T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Trit, Trit) -> Trit,
{
for i in 0..rhs.trit_len() {
let a = lhs.get_trit(i);
let b = rhs.get_trit(i);
let c = f(a, b);
dest.set_trit(i, c);
}
}
fn zip2_trytes<T, F>(dest: &mut T, lhs: &T, rhs: &T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Tryte, Tryte) -> Tryte,
{
for i in 0..rhs.tryte_len() {
let a = lhs.get_tryte(i);
let b = rhs.get_tryte(i);
let c = f(a, b);
dest.set_tryte(i, c);
}
}
fn mutate_trits<T, F>(lhs: &mut T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Trit) -> Trit,
{
for i in 0..lhs.trit_len() {
let trit = lhs.get_trit(i);
lhs.set_trit(i, f(trit));
}
}
fn mutate_trytes<T, F>(lhs: &mut T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Tryte) -> Tryte,
{
for i in 0..lhs.tryte_len() {
let tryte = lhs.get_tryte(i);
lhs.set_tryte(i, f(tryte));
}
}
fn mutate2_trits<T, F>(lhs: &mut T, rhs: &T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Trit, Trit) -> Trit,
{
for i in 0..rhs.trit_len() {
let a = lhs.get_trit(i);
let b = rhs.get_trit(i);
let c = f(a, b);
lhs.set_trit(i, c);
}
}
fn mutate2_trytes<T, F>(lhs: &mut T, rhs: &T, f: F)
where
T: Ternary + ?Sized,
F: Fn(Tryte, Tryte) -> Tryte,
{
for i in 0..rhs.tryte_len() {
let a = lhs.get_tryte(i);
let b = rhs.get_tryte(i);
let c = f(a, b);
lhs.set_tryte(i, c);
}
}
impl Ternary for [Tryte] {
fn trit_len(&self) -> usize {
self.tryte_len() * tryte::TRIT_LEN
}
fn tryte_len(&self) -> usize {
self.len()
}
fn get_trit(&self, i: usize) -> Trit {
let (tryte_index, trit_index) = indices(i);
let tryte = self[tryte_index];
tryte.get_trit(trit_index)
}
fn set_trit(&mut self, i: usize, trit: Trit) {
let (tryte_index, trit_index) = indices(i);
let tryte = self[tryte_index];
self[tryte_index] = tryte.set_trit(trit_index, trit);
}
fn get_tryte(&self, i: usize) -> Tryte {
self[i]
}
fn set_tryte(&mut self, i: usize, tryte: Tryte) {
self[i] = tryte;
}
}
fn indices(i: usize) -> (usize, usize) {
let tryte_index = i / tryte::TRIT_LEN;
let trit_index = i % tryte::TRIT_LEN;
(tryte_index, trit_index)
}
#[cfg(test)]
mod tests {
use super::*;
use super::test_constants::*;
use std::io::Cursor;
#[test]
fn ternary_into_i64() {
assert_eq!(WORD_MIN, TRYTE4_MIN.into_i64());
assert_eq!(-1i64, TRYTE4_NEG1.into_i64());
assert_eq!(0i64, TRYTE4_0.into_i64());
assert_eq!(1i64, TRYTE4_1.into_i64());
assert_eq!(WORD_MAX, TRYTE4_MAX.into_i64());
}
#[test]
fn ternary_read_i64() {
assert_eq!(&TRYTE4_MIN, &tryte4_from_int(WORD_MIN).unwrap()[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_from_int(-1).unwrap()[..]);
assert_eq!(&TRYTE4_0, &tryte4_from_int(0).unwrap()[..]);
assert_eq!(&TRYTE4_1, &tryte4_from_int(1).unwrap()[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_from_int(WORD_MAX).unwrap()[..]);
assert!(tryte4_from_int(i64::min_value()).is_err());
assert!(tryte4_from_int(i64::max_value()).is_err());
}
fn tryte4_from_int(n: i64) -> Result<Vec<Tryte>> {
try_with_cloned_trytes(&TRYTE4_0, |ternary| ternary.read_i64(n))
}
#[test]
fn ternary_read_bytes() {
assert_eq!(&TRYTE4_MIN, &tryte4_from_bytes(&BYTES_MIN).unwrap()[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_from_bytes(&BYTES_NEG1).unwrap()[..]);
assert_eq!(&TRYTE4_0, &tryte4_from_bytes(&BYTES_0).unwrap()[..]);
assert_eq!(&TRYTE4_1, &tryte4_from_bytes(&BYTES_1).unwrap()[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_from_bytes(&BYTES_MAX).unwrap()[..]);
}
fn tryte4_from_bytes(bytes: &[u8]) -> Result<Vec<Tryte>> {
try_with_cloned_trytes(&TRYTE4_0, |ternary| {
ternary.read_bytes(&mut Cursor::new(bytes))
})
}
#[test]
fn ternary_write_bytes() {
assert_eq!(&BYTES_MIN, &get_bytes(&TRYTE4_MIN[..])[..]);
assert_eq!(&BYTES_NEG1, &get_bytes(&TRYTE4_NEG1[..])[..]);
assert_eq!(&BYTES_0, &get_bytes(&TRYTE4_0[..])[..]);
assert_eq!(&BYTES_1, &get_bytes(&TRYTE4_1[..])[..]);
assert_eq!(&BYTES_MAX, &get_bytes(&TRYTE4_MAX[..])[..]);
}
fn get_bytes(trytes: &[Tryte]) -> Vec<u8> {
let mut bytes = vec![];
trytes.write_bytes(&mut bytes).unwrap();
bytes
}
#[test]
fn ternary_read_hytes() {
assert_eq!(&TRYTE4_MIN, &tryte4_from_hyte_str("mmmmmmmm").unwrap()[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_from_hyte_str("0000000a").unwrap()[..]);
assert_eq!(&TRYTE4_0, &tryte4_from_hyte_str("00000000").unwrap()[..]);
assert_eq!(&TRYTE4_1, &tryte4_from_hyte_str("0000000A").unwrap()[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_from_hyte_str("MMMMMMMM").unwrap()[..]);
}
fn tryte4_from_hyte_str(s: &str) -> Result<Vec<Tryte>> {
try_with_cloned_trytes(&TRYTE4_0, |ternary| ternary.read_hytes(s))
}
#[test]
fn ternary_display_hytes() {
assert_eq!("mmmmmmmm", get_hyte_str(&TRYTE4_MIN[..]));
assert_eq!("0000000a", get_hyte_str(&TRYTE4_NEG1[..]));
assert_eq!("00000000", get_hyte_str(&TRYTE4_0[..]));
assert_eq!("0000000A", get_hyte_str(&TRYTE4_1[..]));
assert_eq!("MMMMMMMM", get_hyte_str(&TRYTE4_MAX[..]));
}
fn get_hyte_str(trytes: &[Tryte]) -> String {
let mut bytes = Vec::new();
trytes.write_hytes(&mut bytes).unwrap();
String::from_utf8_lossy(&bytes).into_owned()
}
#[test]
fn ternary_read_trits() {
assert_eq!(
&TRYTE4_MIN,
&tryte4_from_trit_str("TTTTTTTTTTTTTTTTTTTTTTTT").unwrap()[..]
);
assert_eq!(
&TRYTE4_NEG1,
&tryte4_from_trit_str("00000000000000000000000T").unwrap()[..]
);
assert_eq!(
&TRYTE4_0,
&tryte4_from_trit_str("000000000000000000000000").unwrap()[..]
);
assert_eq!(
&TRYTE4_1,
&tryte4_from_trit_str("000000000000000000000001").unwrap()[..]
);
assert_eq!(
&TRYTE4_MAX,
&tryte4_from_trit_str("111111111111111111111111").unwrap()[..]
);
}
fn tryte4_from_trit_str(s: &str) -> Result<Vec<Tryte>> {
try_with_cloned_trytes(&TRYTE4_0, |ternary| ternary.read_trits(s))
}
#[test]
fn ternary_display_trits() {
assert_eq!("TTTTTTTTTTTTTTTTTTTTTTTT", get_trit_str(&TRYTE4_MIN[..]));
assert_eq!("00000000000000000000000T", get_trit_str(&TRYTE4_NEG1[..]));
assert_eq!("000000000000000000000000", get_trit_str(&TRYTE4_0[..]));
assert_eq!("000000000000000000000001", get_trit_str(&TRYTE4_1[..]));
assert_eq!("111111111111111111111111", get_trit_str(&TRYTE4_MAX[..]));
}
fn get_trit_str(trytes: &[Tryte]) -> String {
let mut bytes = Vec::new();
trytes.write_trits(&mut bytes).unwrap();
String::from_utf8_lossy(&bytes).into_owned()
}
#[test]
fn ternary_cmp() {
assert_eq!(trit::ZERO, compare(&TRYTE4_0[..], &TRYTE4_0[..]));
assert_eq!(trit::NEG, compare(&TRYTE4_0[..], &TRYTE4_MAX[..]));
assert_eq!(trit::POS, compare(&TRYTE4_0[..], &TRYTE4_MIN[..]));
assert_eq!(trit::POS, compare(&TRYTE4_MAX[..], &TRYTE4_0[..]));
assert_eq!(trit::POS, compare(&TRYTE4_MAX[..], &TRYTE4_MIN[..]));
assert_eq!(trit::ZERO, compare(&TRYTE4_MAX[..], &TRYTE4_MAX[..]));
assert_eq!(trit::NEG, compare(&TRYTE4_MIN[..], &TRYTE4_0[..]));
assert_eq!(trit::NEG, compare(&TRYTE4_MIN[..], &TRYTE4_MAX[..]));
assert_eq!(trit::ZERO, compare(&TRYTE4_MIN[..], &TRYTE4_MIN[..]));
}
#[test]
fn ternary_negate() {
assert_eq!(&TRYTE4_MIN, &tryte4_negate(&TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_negate(&TRYTE4_1)[..]);
assert_eq!(&TRYTE4_0, &tryte4_negate(&TRYTE4_0)[..]);
assert_eq!(&TRYTE4_1, &tryte4_negate(&TRYTE4_NEG1)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_negate(&TRYTE4_MIN)[..]);
}
fn tryte4_negate(trytes: &[Tryte]) -> Vec<Tryte> {
with_cloned_trytes2(&TRYTE4_0, trytes, negate)
}
#[test]
fn ternary_and() {
assert_eq!(&TRYTE4_0, &tryte4_and(&TRYTE4_0, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_and(&TRYTE4_0, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_and(&TRYTE4_0, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_0, &tryte4_and(&TRYTE4_MAX, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_and(&TRYTE4_MAX, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_and(&TRYTE4_MAX, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_and(&TRYTE4_MIN, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_and(&TRYTE4_MIN, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_and(&TRYTE4_MIN, &TRYTE4_MIN)[..]);
}
fn tryte4_and(trytes1: &[Tryte], trytes2: &[Tryte]) -> Vec<Tryte> {
with_cloned_trytes3(&TRYTE4_0, trytes1, trytes2, and)
}
#[test]
fn ternary_or() {
assert_eq!(&TRYTE4_0, &tryte4_or(&TRYTE4_0, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_or(&TRYTE4_0, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_0, &tryte4_or(&TRYTE4_0, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_or(&TRYTE4_MAX, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_or(&TRYTE4_MAX, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_or(&TRYTE4_MAX, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_0, &tryte4_or(&TRYTE4_MIN, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_or(&TRYTE4_MIN, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_or(&TRYTE4_MIN, &TRYTE4_MIN)[..]);
}
fn tryte4_or(trytes1: &[Tryte], trytes2: &[Tryte]) -> Vec<Tryte> {
with_cloned_trytes3(&TRYTE4_0, trytes1, trytes2, or)
}
#[test]
fn ternary_tcmp() {
assert_eq!(&TRYTE4_MIN, &tryte4_tcmp(&TRYTE4_MIN, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_tcmp(&TRYTE4_MAX, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_tcmp(&TRYTE4_NEG1, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tcmp(&TRYTE4_0, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_1, &tryte4_tcmp(&TRYTE4_1, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_tcmp(&TRYTE4_0, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_tcmp(&TRYTE4_0, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_1, &tryte4_tcmp(&TRYTE4_0, &TRYTE4_NEG1)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_tcmp(&TRYTE4_0, &TRYTE4_1)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tcmp(&TRYTE4_MIN, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tcmp(&TRYTE4_MAX, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tcmp(&TRYTE4_NEG1, &TRYTE4_NEG1)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tcmp(&TRYTE4_1, &TRYTE4_1)[..]);
}
fn tryte4_tcmp(trytes1: &[Tryte], trytes2: &[Tryte]) -> Vec<Tryte> {
with_cloned_trytes3(&TRYTE4_0, trytes1, trytes2, tcmp)
}
#[test]
fn ternary_tmul() {
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_MIN, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_MAX, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_NEG1, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_0, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_1, &TRYTE4_0)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_tmul(&TRYTE4_MIN, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_tmul(&TRYTE4_MAX, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_tmul(&TRYTE4_NEG1, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_0, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_1, &tryte4_tmul(&TRYTE4_1, &TRYTE4_MAX)[..]);
assert_eq!(&TRYTE4_MAX, &tryte4_tmul(&TRYTE4_MIN, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_MIN, &tryte4_tmul(&TRYTE4_MAX, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_1, &tryte4_tmul(&TRYTE4_NEG1, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_0, &tryte4_tmul(&TRYTE4_0, &TRYTE4_MIN)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_tmul(&TRYTE4_1, &TRYTE4_MIN)[..]);
}
fn tryte4_tmul(trytes1: &[Tryte], trytes2: &[Tryte]) -> Vec<Tryte> {
with_cloned_trytes3(&TRYTE4_0, trytes1, trytes2, tmul)
}
#[test]
fn ternary_multiply() {
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_NEG4096, &TRYTE2_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_NEG1, &TRYTE2_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_0, &TRYTE2_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_1, &TRYTE2_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_4096, &TRYTE2_0)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_0, &TRYTE2_NEG4096)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_0, &TRYTE2_NEG1)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_0, &TRYTE2_1)[..]);
assert_eq!(&TRYTE4_0, &tryte4_mul(&TRYTE2_0, &TRYTE2_4096)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG4096, &TRYTE2_1)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_mul(&TRYTE2_NEG1, &TRYTE2_1)[..]);
assert_eq!(&TRYTE4_1, &tryte4_mul(&TRYTE2_1, &TRYTE2_1)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_4096, &TRYTE2_1)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_1, &TRYTE2_NEG4096)[..]);
assert_eq!(&TRYTE4_NEG1, &tryte4_mul(&TRYTE2_1, &TRYTE2_NEG1)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_1, &TRYTE2_4096)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG4096, &TRYTE2_NEG1)[..]);
assert_eq!(&TRYTE4_1, &tryte4_mul(&TRYTE2_NEG1, &TRYTE2_NEG1)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_4096, &TRYTE2_NEG1)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG1, &TRYTE2_NEG4096)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG1, &TRYTE2_4096)[..]);
assert_eq!(&TRYTE4_64, &tryte4_mul(&TRYTE2_8, &TRYTE2_8)[..]);
assert_eq!(&TRYTE4_64, &tryte4_mul(&TRYTE2_NEG8, &TRYTE2_NEG8)[..]);
assert_eq!(&TRYTE4_NEG64, &tryte4_mul(&TRYTE2_8, &TRYTE2_NEG8)[..]);
assert_eq!(&TRYTE4_NEG64, &tryte4_mul(&TRYTE2_NEG8, &TRYTE2_8)[..]);
assert_eq!(&TRYTE4_81, &tryte4_mul(&TRYTE2_9, &TRYTE2_9)[..]);
assert_eq!(&TRYTE4_81, &tryte4_mul(&TRYTE2_NEG9, &TRYTE2_NEG9)[..]);
assert_eq!(&TRYTE4_NEG81, &tryte4_mul(&TRYTE2_9, &TRYTE2_NEG9)[..]);
assert_eq!(&TRYTE4_NEG81, &tryte4_mul(&TRYTE2_NEG9, &TRYTE2_9)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_8, &TRYTE2_512)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG8, &TRYTE2_NEG512)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_8, &TRYTE2_NEG512)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG8, &TRYTE2_512)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_512, &TRYTE2_8)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG512, &TRYTE2_NEG8)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_512, &TRYTE2_NEG8)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG512, &TRYTE2_8)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_16, &TRYTE2_256)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG16, &TRYTE2_NEG256)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_16, &TRYTE2_NEG256)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG16, &TRYTE2_256)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_256, &TRYTE2_16)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG256, &TRYTE2_NEG16)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_256, &TRYTE2_NEG16)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG256, &TRYTE2_16)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_64, &TRYTE2_64)[..]);
assert_eq!(&TRYTE4_4096, &tryte4_mul(&TRYTE2_NEG64, &TRYTE2_NEG64)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_64, &TRYTE2_NEG64)[..]);
assert_eq!(&TRYTE4_NEG4096, &tryte4_mul(&TRYTE2_NEG64, &TRYTE2_64)[..]);
}
fn tryte4_mul(trytes1: &[Tryte], trytes2: &[Tryte]) -> Vec<Tryte> {
with_cloned_trytes3(&TRYTE4_0, trytes1, trytes2, multiply)
}
#[test]
fn ternary_shift() {
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000000000000000000000001T000110T001100T011000T",
),
tryte4_shift("1T000110T001100T011000T1", -25)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000000000000000000000001T000110T001100T011000T1",
),
tryte4_shift("1T000110T001100T011000T1", -24)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000000000000000000000001T000110T001100T011000T10",
),
tryte4_shift("1T000110T001100T011000T1", -23)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000000000000000000001T000110T001100T011000T100",
),
tryte4_shift("1T000110T001100T011000T1", -22)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000000000000000000001T000110T001100T011000T1000",
),
tryte4_shift("1T000110T001100T011000T1", -21)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000000000000000000001T000110T001100T011000T10000",
),
tryte4_shift("1T000110T001100T011000T1", -20)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000000000000000001T000110T001100T011000T100000",
),
tryte4_shift("1T000110T001100T011000T1", -19)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000000000000000001T000110T001100T011000T1000000",
),
tryte4_shift("1T000110T001100T011000T1", -18)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000000000000000001T000110T001100T011000T10000000",
),
tryte4_shift("1T000110T001100T011000T1", -17)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000000000000001T000110T001100T011000T100000000",
),
tryte4_shift("1T000110T001100T011000T1", -16)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000000000000001T000110T001100T011000T1000000000",
),
tryte4_shift("1T000110T001100T011000T1", -15)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000000000000001T000110T001100T011000T10000000000",
),
tryte4_shift("1T000110T001100T011000T1", -14)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000000000001T000110T001100T011000T100000000000",
),
tryte4_shift("1T000110T001100T011000T1", -13)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000000000001T000110T001100T011000T1000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -12)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000000000001T000110T001100T011000T10000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -11)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000000001T000110T001100T011000T100000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -10)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000000001T000110T001100T011000T1000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -9)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000000001T000110T001100T011000T10000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -8)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000000001T000110T001100T011000T100000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -7)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000000001T000110T001100T011000T1000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -6)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000000001T000110T001100T011000T10000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -5)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000000001T000110T001100T011000T100000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -4)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000000001T000110T001100T011000T1000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -3)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000000001T000110T001100T011000T10000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -2)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000000001T000110T001100T011000T100000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", -1)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000000001T000110T001100T011000T1000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 0)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000000001T000110T001100T011000T10000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 1)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000000001T000110T001100T011000T100000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 2)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000000001T000110T001100T011000T1000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 3)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000000001T000110T001100T011000T10000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 4)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000000001T000110T001100T011000T100000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 5)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000000001T000110T001100T011000T1000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 6)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000000001T000110T001100T011000T10000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 7)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000000001T000110T001100T011000T100000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 8)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000000001T000110T001100T011000T1000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 9)
);
assert_eq!(
tryte12_from_trit_str(
"000000000000001T000110T001100T011000T10000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 10)
);
assert_eq!(
tryte12_from_trit_str(
"00000000000001T000110T001100T011000T100000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 11)
);
assert_eq!(
tryte12_from_trit_str(
"0000000000001T000110T001100T011000T1000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 12)
);
assert_eq!(
tryte12_from_trit_str(
"000000000001T000110T001100T011000T10000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 13)
);
assert_eq!(
tryte12_from_trit_str(
"00000000001T000110T001100T011000T100000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 14)
);
assert_eq!(
tryte12_from_trit_str(
"0000000001T000110T001100T011000T1000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 15)
);
assert_eq!(
tryte12_from_trit_str(
"000000001T000110T001100T011000T10000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 16)
);
assert_eq!(
tryte12_from_trit_str(
"00000001T000110T001100T011000T100000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 17)
);
assert_eq!(
tryte12_from_trit_str(
"0000001T000110T001100T011000T1000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 18)
);
assert_eq!(
tryte12_from_trit_str(
"000001T000110T001100T011000T10000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 19)
);
assert_eq!(
tryte12_from_trit_str(
"00001T000110T001100T011000T100000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 20)
);
assert_eq!(
tryte12_from_trit_str(
"0001T000110T001100T011000T1000000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 21)
);
assert_eq!(
tryte12_from_trit_str(
"001T000110T001100T011000T10000000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 22)
);
assert_eq!(
tryte12_from_trit_str(
"01T000110T001100T011000T100000000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 23)
);
assert_eq!(
tryte12_from_trit_str(
"1T000110T001100T011000T1000000000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 24)
);
assert_eq!(
tryte12_from_trit_str(
"T000110T001100T011000T10000000000000000000000000000000000000000000000000",
),
tryte4_shift("1T000110T001100T011000T1", 25)
);
}
fn tryte4_shift(trit_str: &str, offset: isize) -> Result<Vec<Tryte>> {
let trytes = tryte4_from_trit_str(trit_str)?;
try_with_cloned_trytes2(&TRYTE12_0, &trytes[..], |dest, src| {
shift(dest, src, offset);
Ok(())
})
}
fn tryte12_from_trit_str(s: &str) -> Result<Vec<Tryte>> {
try_with_cloned_trytes(&TRYTE12_0, |ternary| ternary.read_trits(s))
}
fn clone_slice<T: Clone>(slice: &[T]) -> Vec<T> {
let mut vec = Vec::new();
vec.extend_from_slice(slice);
vec
}
fn with_cloned_trytes<F>(trytes: &[Tryte], mut f: F) -> Vec<Tryte>
where
F: FnMut(&mut [Tryte]),
{
let mut trytes = clone_slice(trytes);
f(&mut trytes[..]);
trytes
}
fn with_cloned_trytes2<F>(trytes1: &[Tryte], trytes2: &[Tryte], mut f: F) -> Vec<Tryte>
where
F: FnMut(&mut [Tryte], &[Tryte]),
{
let mut trytes1 = clone_slice(trytes1);
f(&mut trytes1[..], &trytes2);
trytes1
}
fn with_cloned_trytes3<F>(
trytes1: &[Tryte],
trytes2: &[Tryte],
trytes3: &[Tryte],
mut f: F,
) -> Vec<Tryte>
where
F: FnMut(&mut [Tryte], &[Tryte], &[Tryte]),
{
let mut trytes1 = clone_slice(trytes1);
f(&mut trytes1[..], &trytes2, &trytes3);
trytes1
}
fn try_with_cloned_trytes<F>(trytes: &[Tryte], mut f: F) -> Result<Vec<Tryte>>
where
F: FnMut(&mut [Tryte]) -> Result<()>,
{
let mut trytes = clone_slice(trytes);
f(&mut trytes[..])?;
Ok(trytes)
}
fn try_with_cloned_trytes2<F>(
trytes1: &[Tryte],
trytes2: &[Tryte],
mut f: F,
) -> Result<Vec<Tryte>>
where
F: FnMut(&mut [Tryte], &[Tryte]) -> Result<()>,
{
let mut trytes1 = clone_slice(trytes1);
f(&mut trytes1[..], &trytes2)?;
Ok(trytes1)
}
}
|
d5bd78b8102cfe890626760ad51dc65e732f2315
|
[
"Rust",
"Markdown"
] | 9 |
Rust
|
jdanford/ternary-rs
|
76de3b06d4d2e7504c146da4eefb68a8c39d4ffc
|
f028737ee3e01d4755e2196a24133e82fc26b0e8
|
refs/heads/master
|
<repo_name>adkhn999/firebaseDemo<file_sep>/js/directives.js
/// <reference path="angular.js" />
app
.controller('postCtrl', function() {
var vm = this;
vm.content = 'Lorem ipsum dolor sit amet'+
'consectetur adipisicing elit.'+
'Cumque consequuntur eaque aliquam '+
'velit perspiciatis minima suscipit '+
'quaerat dolor nemo distinctio officiis'+
'harum rem, assumenda, ab rerum. '+
'Maxime molestias minus dignissimos.';
return vm;
})
.directive('post', function() {
return {
restrict: 'AE',
replace: true,
controller: 'postCtrl',
require: 'post',
scope: true,
link: function(scope,element,attribute, controller) {
scope.title = attribute.title;
scope.author = attribute.author;
scope.content = attribute.content == null ? controller.content: attribute.content;
},
templateUrl: 'templates/post.html',
}
})
;<file_sep>/js/controllers.js
app
.controller('mainCtrl', function($scope, $q, Products) {
var firstRun = true;
$scope.loading = true;
$scope.products = [];
function watch() {
var defer = $q.defer();
database.ref().child('/products/').on('child_added', function(snapshot) {
console.log(snapshot.val());
if(snapshot.val() != undefined || snapshot.val() != null){
var product = snapshot.val();
console.log($scope.products);
defer.resolve($scope.products.push(product));
}
});
database.ref().child('/products/').on('child_removed', function(snapshot) {
console.log(snapshot.val());
var product = snapshot.val();
$scope.products.slice($scope.products.indexOf(product.id));
console.log($scope.products);
})
return defer.promise;
}
Products.getProducts().then(function(response) {
console.log(response);
if(response == null) {
$scope.loading = false;
}
});
watch().then(function(response) {
console.log('executed');
$scope.loading = false;
});
$scope.submit = function(parameter) {
var key = database.ref('/products/').push().key;
var updates = {};
updates['/products/'+key] = parameter;
database.ref().update(updates);
}
})
.controller('secCtrl', function($scope, $firebaseArray, Products) {
var array = $firebaseArray(database.ref().child('/products/'));
console.log(array);
$scope.products = array;
$scope.submit = function(parameter) {
var key = database.ref('/products/').push().key;
var updates = {};
updates['/products/'+key] = parameter;
database.ref().update(updates);
}
})
;<file_sep>/js/services.js
app
.service('Products', function($q) {
var obj = {};
obj = {
getProducts: function() {
var defer = $q.defer();
database.ref().child('/products/').once('value', function(snapshot) {
console.log(snapshot.val());
defer.resolve(snapshot.val());
});
return defer.promise;
},
getProductss: function() {
var defer = $q.defer();
database.ref().child('/products/').on('child_added', function(snapshot) {
console.log(snapshot.val());
if(snapshot.val() != undefined || snapshot.val() != null){
defer.resolve(snapshot.val());
}
});
return defer.promise;
}
};
return obj;
})
;
|
1017c6132a675f0b4af8371b4fed52f6071c3ef4
|
[
"JavaScript"
] | 3 |
JavaScript
|
adkhn999/firebaseDemo
|
6c17aecfc98a47cfca38486b32a99caa2898f880
|
15072be8aea36ee83fe1d643cd7894a62a13e5bb
|
refs/heads/master
|
<file_sep>import { combineReducers } from 'redux';
let store;
let dispatch;
export const init = (config) => {
store = config.store;
dispatch = config.dispatch;
};
const generateReducer = (key, defaultState) => {
// 往默认的 state 里添加通用方法
defaultState.set = function(obj) {
if (dispatch) {
dispatch({ type: `${key}/diff`, obj });
} else {
console.error(`Can not found dispatch`);
}
};
// 生成 reducer 方法
const reducer = function(state = defaultState, action) {
if (action.type === `${key}/diff`) {
let value = Object.assign({}, state.value, action.obj);
return Object.assign({}, state, {value});
} else {
return state;
}
};
// 注入 reducer
if (store) {
if (!store.asyncReducers[key]) {
store.asyncReducers[key] = reducer;
store.replaceReducer((reducer => combineReducers({
...reducer
}))(store.asyncReducers));
}
} else {
console.error(`Can not found store`);
}
};
export {
generateReducer
};<file_sep># redux-pkg
针对 Redux 的简单封装,让 redux 的使用不需涉及到多个文件(reducer,action 等),配置一个 store 的 config 即可进行全局的状态管理。
|
6722ab62ab7f68c1d342ba2a13cb9678adcf8963
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
VetaZhang/redux-pkg
|
088f9f987241702210bb8adc5fc00c7afd00e437
|
b6075e6feecfd1edcc4728c6cbc44503d4d60d8d
|
refs/heads/master
|
<repo_name>KristinaAlekyan/Homework-5<file_sep>/Homework-5.js
/*1. Write a function, which will receive a number between 0 to 999,999 and spell out
that number in English.*/
let objNum = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety",
100: "hundred",
1000: "thousand",
};
function numbersToWord(num) {
let unit,
dec,
hund,
spell = "";
if(num < 1000) {
if((num >= 0 && num <= 20) || (num % 10 === 0 && num < 100)) {
spell = objNum[num];
}
if(num > 20 && num < 100 && !(num % 10 === 0 && num < 100)) {
unit = num % 10;
dec = num - unit;
spell = objNum[dec] + " " + objNum[unit];
}
if(num >= 100 && num < 999) {
dec = num % 100;
hund = Math.floor(num / 100);
if(num % 100 === 0) {
spell = objNum[hund] + " " +objNum[100];
}
else spell = objNum[hund] + " " + objNum[100] + " " + numbersToWord(dec);
}
}
else spell = numbersToWord(Math.floor(num / 1000)) + " " + objNum[1000] + " " + numbersToWord(num % 1000);
return spell;
}
console.log(numbersToWord(5));
console.log(numbersToWord(25));
console.log(numbersToWord(504));
console.log(numbersToWord(9003));
console.log(numbersToWord(69203));
console.log(numbersToWord(710520));
/*3. Given a word and a list of possible anagrams, select the correct sublist.*/
function anagramsFromArr(givenString, arr) {
let arrRes = [];
arr.forEach(function(item) {
let newString = '';
if(item.length === givenString.length) {
for(let i = 0; i < item.length; i++) {
if(!(givenString.includes(item[i]))) {
break;
}
newString+=item[i];
}
if(newString.length !== 0){
arrRes.push(newString);
}
}
});
return arrRes;
}
console.log(anagramsFromArr('listen', ['enlists', 'google', 'inlets', 'banana']));
console.log(anagramsFromArr('pencil', ['licnep', 'circular', 'pupil', 'nilcpe', 'leppnec']));
|
4ca511a6842d9d405af70b53ef1ebd4d29fde5f7
|
[
"JavaScript"
] | 1 |
JavaScript
|
KristinaAlekyan/Homework-5
|
e35e8acad6ab122cd0bd6f556db82ea34110a7f3
|
a7e1c26db9cc3a2449fcdd7e74149b7a3b6bdeff
|
refs/heads/master
|
<repo_name>hugoh1995/rails-task-manager<file_sep>/app/views/tasks/show.html.erb
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Description</th>
<th>Creation date</th>
</tr>
<tr>
<td><%= @task.name %></td>
<td><%= @task.description %></td>
<td><%= @task.created_at %></td>
<td><%= link_to "Edit", edit_task_path %></td>
</tr>
</table>
<%= link_to "Back to task list", tasks_path %>
<file_sep>/app/views/tasks/index.html.erb
<div>
<table class="table table-bordered">
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
</tr>
<% @tasks.each do |task| %>
<tr>
<td>
<%= task.id %>
</td>
<td>
<%= task.name %>
</td>
<td>
<%= task.description %>
</td>
<td>
<%= link_to "Show", task_path(task) %>
</td>
<td>
<%= link_to "Delete", task_path(task),
method: :delete,
data: { confirm: "Are you sure?" }%>
</td>
<% end %>
</table>
</div>
|
494450591a35756a2e4b9290823de4a9a8067b79
|
[
"HTML+ERB"
] | 2 |
HTML+ERB
|
hugoh1995/rails-task-manager
|
53818b592dba8aa1c7a833e387164340b04942db
|
9e0eaa2c18c6418793e8a158e733672bfee4ee71
|
refs/heads/master
|
<repo_name>VictorGFM/portal-educacao<file_sep>/Banco de Questões/java/bancodequestoes/ProvaEspecifica.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bancodequestoes;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
/**
*
* @author ThalesGSN
*/
public class ProvaEspecifica extends Prova{
//Variaveis de instancia
/** Numero inteiro que representa o numero de questoes de multipla escolha da prova.*/
private int numMultiplaEscolha;
/** Numero inteiro que representa o numero de questoes de V ou F da prova.*/
private int numVF;
/** Numero inteiro que representa o numero de questoes Abertas da prova.*/
private int numAbertas;
//Construtores
/**
* Para usar com sets e gets.
*/
public ProvaEspecifica() { }
/**
* Contrutor que faz uma prova mista com questoes de qualquer tipo(Multipla escolha, aberta, Verdadeiro ou
* Falso), pegando somente a materia da prova e o numero de questoes de cada tipo, pegando questoes
* aleatoriamente.
* @param materia <i>String</i> Que representa a materia da prova
* @param numMultiplaEscolha <i>Inteiro</i> que representa o numero de questões multipla escolha da prova.
* @param numVF <i>Inteiro</i> que representa o numero de questões Verdadeiro ou Falso da prova.
* @param numAbertas <i>Inteiro</i> que representa o numero de questões abertas da prova.
*/
public ProvaEspecifica(String materia, int numMultiplaEscolha, int numVF, int numAbertas) {
this.materia = materia;
this.numMultiplaEscolha = numMultiplaEscolha;
this.numVF = numVF;
this.numAbertas = numAbertas;
}
/**
* Contrutor que faz uma prova mista com questoes de qualquer tipo(Multipla escolha, aberta, Verdadeiro ou
* Falso), pegando somente a materia da prova e o numero de questoes de cada tipo, pegando questoes
* aleatoriamente e o conteudo definido
* @param materia <i>String</i> Que representa a materia da prova
* @param conteudo <i>String</i> Que representa o conteudo da prova.
* @param numMultiplaEscolha <i>Inteiro</i> que representa o numero de questões multipla escolha da prova.
* @param numVF <i>Inteiro</i> que representa o numero de questões Verdadeiro ou Falso da prova.
* @param numAbertas <i>Inteiro</i> que representa o numero de questões abertas da prova.
*/
public ProvaEspecifica(String materia,String conteudo, int numMultiplaEscolha, int numVF, int numAbertas) {
this.materia = materia;
this.numMultiplaEscolha = numMultiplaEscolha;
this.numVF = numVF;
this.numAbertas = numAbertas;
this.conteudos.add(conteudo);
}
//Sets e Gets
/**
* Retorna o numero de questões multipla escolha da prova.
* @return <i>Inteiro</i> que representa o numero de questoes multipla escolha da prova.
*/
public int getNumMultiplaEscolha() {
return numMultiplaEscolha;
}
/**
* Altera ou define o numero de questões multipla escolha da prova.
* @param numMultiplaEscolha <i>Inteiro</i> que representa o numero de questoes multipla
* escolha da prova.
*/
public void setNumMultiplaEscolha(int numMultiplaEscolha) {
this.numMultiplaEscolha = numMultiplaEscolha;
}
/**
* Retorna o numero de questões verdadeiro ou falso da prova.
* @return <i>Inteiro</i> que representa o numero de questoes verdadeiro ou falso da prova.
*/
public int getNumVF() {
return numVF;
}
/**
* Altera ou define o numero de questões v ou F da prova.
* @param numVF <i>Inteiro</i> que representa o numero de questoes verdadeiro
* ou falso da prova.
*/
public void setNumVF(int numVF) {
this.numVF = numVF;
}
/**
* Retorna o numero de questões abertas da prova.
* @return <i>Inteiro</i> que representa o numero de questoes abertas da prova.
*/
public int getNumAbertas() {
return numAbertas;
}
/**
* Altera ou define o numero de questões abertas da prova.
* @param numAbertas <i>Inteiro</i> numero de questoes abertas da prova.
*/
public void setNumAbertas(int numAbertas) {
this.numAbertas = numAbertas;
}
/**
* Retorna o numero de questões totais da prova da prova.
* @return <i>Inteiro</i> que representa o numero de questoes totais da prova.
*/
public int getNumQuestoes(){
return numMultiplaEscolha + numVF + numAbertas;
}
/**
* Adiciona uma questão qualquer na prova.
* @param questao Objeto questão a ser adicionado na prova
*/
public void addquestao(Questao questao){
super.add(questao);
switch(questao.getTipo()){
case MULTIPLA_ESCOLHA:
numMultiplaEscolha++;
break;
case VERDADEIRO_FALSO:
numVF++;
break;
case ABERTA:
numAbertas++;
break;
}
}
//Metodos herdados de Prova
//@TODO <NAME>
@Override
public boolean gerar() throws SQLException, ParserConfigurationException, SAXException, IOException {
ConexaoBD conn = new ConexaoBD("db4free.net", "agaleracomecou", "b1q0*U0kfKYmWee", "sabadona"
+ "balada");
ResultSet multiplaEscolhaBD = conn.getQuestoes(materia, conteudos,
Questao.MULTIPLA_ESCOLHA, dificuldade);
if(numMultiplaEscolha > multiplaEscolhaBD.getFetchSize())
throw new SQLException("Não existe questoes sufucientes de multipla escolha"
+ " sufucientes no banco.");
ResultSet vOuFBD = conn.getQuestoes(materia, conteudos, Questao.VERDADEIRO_FALSO, dificuldade);
if(numVF > vOuFBD.getFetchSize())
throw new SQLException("Não existe questoes de V ou F"
+ " sufucientes no banco.");
ResultSet abertaBD = conn.getQuestoes(materia, conteudos, Questao.ABERTA, dificuldade);
if(numVF > vOuFBD.getFetchSize())
throw new SQLException("Não existe questoes de abertas"
+ " sufucientes no banco.");
for(int cont = 0; cont < numMultiplaEscolha; cont++){
super.add(new MultiplaEscolha(multiplaEscolhaBD.getString("XML")));
multiplaEscolhaBD.next();
}
for(int cont = 0; cont < numVF; cont++){
super.add(new VOuF(vOuFBD.getString("XML")));
vOuFBD.next();
}
for(int cont = 0; cont < numAbertas; cont++){
super.add(new Aberta(abertaBD.getString("XML")));
vOuFBD.next();
}
return true;
}
}
<file_sep>/Banco de Questões/web/insQuest.php
<?php
include('cabecalho.html');
//Pega os dados via POST.
$estilo = $_POST['estilo-inserir'];
$nivel = $_POST['nivel-inserir'];
$disciplina = $_POST['disciplina-inserir'];
$tema = $_POST['tema-inserir'];
$cabecalho = $_POST['cabecalho-inserir'];
$gabarito = $_POST['gabarito-inserir'];
$criador = $_SERVER['SERVER_ADMIN'];
//Se o estilo da questao escolhida for ME.
if($estilo==0){
//Gera o XML.
$GLOBALS['xml'] = "<questao tipo=\"\"ME\"\" aleatorio=\"\"true\"\">
<dificuldade>".$GLOBALS['nivel']."</dificuldade> <!--dificuldade(1 a 3) -->
<materia>".$GLOBALS['disciplina']."</materia> <!--Materia -->
<conteudo>".$GLOBALS['tema']."</conteudo> <!--Conteudo -->
<enunciado>".$GLOBALS['cabecalho']."</enunciado> <!--enunciado -->";
//Pega as alternativas em um Array.
$alternativa = array();
$radio = $_POST['rdio'];
for($i=0; $i<=4; $i++){
if(array_key_exists('alternativa'.$i, $_POST)){
$alternativa[$i] = $_POST['alternativa'.$i];
if('rdio'+$i==$radio){
$GLOBALS['xml'] .= "<alternativa correta=\"\"true\"\">";
$GLOBALS['xml'] .= $alternativa[$i]."</alternativa>";
}else{
$GLOBALS['xml'] .= "<alternativa correta=\"\"false\"\">";
$GLOBALS['xml'] .= $alternativa[$i]."</alternativa>";
}
}
}
}
//Se o estilo da questao escolhida for VF.
if($estilo==1){
//Gera o XML.
$GLOBALS['xml'] = "<questao tipo=\"\"VF\"\" aleatorio=\"\"true\"\">
<dificuldade>".$GLOBALS['nivel']."</dificuldade> <!--dificuldade(1 a 3) -->
<materia>".$GLOBALS['disciplina']."</materia> <!--Materia -->
<conteudo>".$GLOBALS['tema']."</conteudo> <!--Conteudo -->
<enunciado>".$GLOBALS['cabecalho']."</enunciado> <!--enunciado -->";
//Pega as alternativas em um Array.
$alternativa = array();
for($i=0; $i<=4; $i++){
if(array_key_exists('alternativa'.$i, $_POST)){
$alternativa[$i] = $_POST['alternativa'.$i];
if($_POST['cBox'.$i]=='on'){
$GLOBALS['xml'] .= "<alternativa correta=\"\"true\"\">".$alternativa[$i]."</alternativa>";
}else{
$GLOBALS['xml'] .= "<alternativa>".$alternativa[$i]."</alternativa>";
}
}
}
}
//Se o estilo da questao escolhida for 'aberta'.
if($estilo==2){
//Gera o XML.
$GLOBALS['xml'] = "<questao tipo=\"\"aberta\"\" aleatorio=\"\"true\"\">
<dificuldade>".$GLOBALS['nivel']."</dificuldade> <!--dificuldade(1 a 3) -->
<materia>".$GLOBALS['disciplina']."</materia> <!--Materia -->
<conteudo>".$GLOBALS['tema']."</conteudo> <!--Conteudo -->
<enunciado>".$GLOBALS['cabecalho']."</enunciado> <!--enunciado -->";
}
//Fecha o XML.
$GLOBALS['xml'] .= "</questao>";
//Conecta e escreve no banco de dados.
$conexao = new PDO('mysql:host=localhost; dbname=banco_de_questoes', 'phpmyadmin', 'o9rtjh88');
$sql = "INSERT INTO questoes VALUES ('', '".$disciplina."', '".$tema."', ".$nivel.", ".$estilo.", \"".$GLOBALS['xml']."\", '".$criador."')";
if($conexao->exec($sql)){
$msg = "Questão inserida com sucesso!";
}
else{
$msg = "Questão não inserida!";
}
echo "<div class=\"row center\"><h5 class=\"header col s12 light\">".$msg."</h5><br><br>
<a class=\"waves-effect waves-light btn light-blue darken-4\" href=\"BancoDeQuestoes.php\"
id=\"inserir\">Voltar<i class=\"tiny material-icons white-text text-darken-1\">replay</i>
</a>
</div><br><br>";
include('rodape.html')
?>
<file_sep>/Banco de Questões/web/altera.php
<?php
include('cabecalho.html');
if(isset($_POST['excluir-alterar'])){
//Pega os dados via POST.
$id = $_POST['formID'];
//Conectando e escrevendo no BD
$conexao = new PDO('mysql:host=localhost; dbname=banco_de_questoes', 'phpmyadmin', 'o9rtjh88');
$sql = "DELETE FROM questoes WHERE id=\"".$id."\"";
if($conexao->exec($sql)){
$msg = "Questão apagada com sucesso!";
}else{
$msg = "Questão não apagada!";
}
echo "<div class=\"row center\"><h5 class=\"header col s12 light\">".$msg."</h5><br><br>
<a class=\"waves-effect waves-light btn light-blue darken-4\" href=\"BancoDeQuestoes.php\"
id=\"inserir\">Voltar<i class=\"tiny material-icons white-text text-darken-1\">replay</i></a>
</div><br><br>";
include('rodape.html');
}else{
//Pega os dados via POST.
$id = $_POST['formID'];
$estilo = $_POST['estilo-alterar'];
$nivel = $_POST['nivel-alterar'];
$disciplina = $_POST['disciplina-alterar'];
$tema = $_POST['tema-alterar'];
$cabecalho = $_POST['cabecalho-alterar'];
$gabarito = $_POST['gabarito-alterar'];
$criador = $_SERVER['SERVER_ADMIN'];
//Se o estilo da questao selecionada for ME.
if($estilo==0){
//Gera o XML correspondenete a questao.
$GLOBALS['xml'] = "<questao tipo=\"\"ME\"\" aleatorio=\"\"true\"\">
<dificuldade>".$GLOBALS['nivel']."</dificuldade> <!--dificuldade(1 a 3) -->
<materia>".$GLOBALS['disciplina']."</materia> <!--Materia -->
<conteudo>".$GLOBALS['tema']."</conteudo> <!--Conteudo -->
<enunciado>".$GLOBALS['cabecalho']."</enunciado> <!--enunciado -->";
//Pegando as alternativas em Array.
$alternativa = array();
$radio = $_POST['rdioEdit'];
for($i=0; $i<=4; $i++){ //Trocar para for..of!
if(array_key_exists('alternativaEdit-'.$i, $_POST)){
$alternativa[$i] = $_POST['alternativaEdit-'.$i];
if('rdio'+$i==$radio)
$GLOBALS['xml'] .= "<alternativa correta=\"\"true\"\">";
else
$GLOBALS['xml'] .= "<alternativa>";
$GLOBALS['xml'] .= $alternativa[$i]."</alternativa>";
}
}
}
//Se o estilo da questao selecionada for VF.
if($estilo==1){
//Gera o XML correspondenete a questao.
$GLOBALS['xml'] = "<questao tipo=\"\"VF\"\" aleatorio=\"\"true\"\">
<dificuldade>".$GLOBALS['nivel']."</dificuldade> <!--dificuldade(1 a 3) -->
<materia>".$GLOBALS['disciplina']."</materia> <!--Materia -->
<conteudo>".$GLOBALS['tema']."</conteudo> <!--Conteudo -->
<enunciado>".$GLOBALS['cabecalho']."</enunciado> <!--enunciado -->";
//Pegando as alternativas em Array.
$alternativa = array();
for($i=0; $i<=4; $i++){
if(array_key_exists('alternativaEdit-'.$i, $_POST)){
$alternativa[$i] = $_POST['alternativaEdit-'.$i];
if($_POST['cBoxEdit-'.$i]=='on'){
$GLOBALS['xml'] .= "<alternativa correta=\"\"true\"\">".$alternativa[$i]."</alternativa>";
}else{
$GLOBALS['xml'] .= "<alternativa>".$alternativa[$i]."</alternativa>";
}
}
}
}
//Se o estilo da questao selecionada for 'aberta'.
if($estilo==2){
//Gera o XML correspondenete a questao.
$GLOBALS['xml'] = "<questao tipo=\"\"aberta\"\" aleatorio=\"\"true\"\">
<dificuldade>".$GLOBALS['nivel']."</dificuldade> <!--dificuldade(1 a 3) -->
<materia>".$GLOBALS['disciplina']."</materia> <!--Materia -->
<conteudo>".$GLOBALS['tema']."</conteudo> <!--Conteudo -->
<enunciado>".$GLOBALS['cabecalho']."</enunciado> <!--enunciado -->";
}
//Fecha o XML.
$GLOBALS['xml'] .= "</questao>";
//Conecta e escreve no banco de dados.
$conexao = new PDO('mysql:host=localhost; dbname=banco_de_questoes', 'phpmyadmin', 'o9rtjh88');
$sql = "UPDATE questoes SET Materia='".$disciplina."', Conteudo='".$tema."', Dificuldade='".$nivel."', Tipo='".$estilo."', XML=\"".$GLOBALS['xml']."\" WHERE id='".$id."'";
if($conexao->exec($sql)){
$msg = "Questão alterada com sucesso!";
}else{
$msg = "Questão não alterada!";
}
echo "<div class=\"row center\"><h5 class=\"header col s12 light\">".$msg."</h5><br><br>
<a class=\"waves-effect waves-light btn light-blue darken-4\" href=\"BancoDeQuestoes.php\"
id=\"inserir\">Voltar<i class=\"tiny material-icons white-text text-darken-1\">replay</i></a>
</div><br><br>";
include('rodape.html');
}
?>
<file_sep>/Modelo de Provas e Trabalhos/web/insereBd.php
<?php
$banco = 'Cabecalho';
$link = mysqli_connect("localhost", "root", "", "dados");
if(!$link) {
die('Not connected : ' . mysql_error());
}
$db = mysqli_select_db($link, $banco);
$valor = $_POST['valor'];
$titulo = $_POST['Titulo'];
$turno = $_POST['turno'];
$nQuest = $_POST['nquestao'];
$elab = $_POST['prof'];
$turma = $_POST['turmas'];
$escola = $_POST['instituicao'];
$duracao = $_POST['duracao'];
$dataEntrega = $_POST['dataEntrega'];
$dataRecebimento = $_POST['dataRecebimento'];
$matricula = $_POST['matricula'];
/*$dataP = explode('/', $data);
$dataformatada = $dataP[2].'-'.$dataP[1].'-'.$dataP[0];*/
$query = "INSERT INTO teste (titulo, elaborador, matricula, valor, nQuestoes, turmas, escola, duracao)
VALUES ('$titulo', '$elab', '$matricula', '$valor', '$nQuest', '$turma', '$escola', '$duracao')";
//$query = "INSERT INTO Cabecalho (titulo) VALUES ('$titulo')";
mysqli_query($link, $query) or die("Erro ao guardar Informaçoes");
mysqli_close($link);
echo "informacoes guardadas";
?>
<file_sep>/Banco de Questões/web/geraProva.php
<?php
/*
Este codigo tem como objetivo gerar um arquivo XML contendo as questoes que
abrangem as caracteristicas definidas que deverao estar na prova.
*/
include('cabecalho.html');
echo "<h5 class=\"header col s12 light\" align=\"center\">Prova:</h5>";
$letras = array('a)', 'b)', 'c)', 'd)');
$provaXML = "<prova>";
//Pega os dados.
$disciplinaProduzir = $_POST['disciplina-produzir'];
$facilProduzir = array_key_exists('facil-produzir', $_POST) ? $_POST['facil-produzir'] : null;
$medioProduzir = array_key_exists('medio-produzir', $_POST) ? $_POST['medio-produzir'] : null;
$dificilProduzir = array_key_exists('dificil-produzir', $_POST) ? $_POST['dificil-produzir'] : null;
$abertaProduzir = array_key_exists('dissertativas-produzir', $_POST) ? $_POST['dissertativas-produzir'] : null;
$verdadeiraFalsaProduzir = array_key_exists('v_f-produzir', $_POST) ? $_POST['v_f-produzir'] : null;
$multiplaEscolhaProduzir = array_key_exists('multipla_escolha-produzir', $_POST) ? $_POST['multipla_escolha-produzir'] : null;
$numQuestoesProduzir = array_key_exists('numQuestoes-produzir', $_POST) ? $_POST['numQuestoes-produzir'] : null;
//Gera o SQL.
$sql = "SELECT * FROM questoes WHERE ";
$sql .= "Materia=\"".$disciplinaProduzir."\" AND ";
$nivelQuery = array();
if($facilProduzir=='on') array_push($nivelQuery, '1');
if($medioProduzir=='on') array_push($nivelQuery, '2');
if($dificilProduzir=='on') array_push($nivelQuery, '3');
$nivelQuery = implode(',', $nivelQuery);
$sql .= "Dificuldade IN (".$nivelQuery.") AND ";
$tipoQuery = array();
if($abertaProduzir=='on') array_push($tipoQuery, '0');
if($verdadeiraFalsaProduzir=='on') array_push($tipoQuery, '1');
if($multiplaEscolhaProduzir=='on') array_push($tipoQuery, '2');
$tipoQuery = implode(',', $tipoQuery);
$sql .= "Tipo IN (".$tipoQuery.")";
$conexao = new PDO('mysql:host=localhost; dbname=banco_de_questoes', 'phpmyadmin', 'o9rtjh88');
foreach($conexao->query($sql) as $key=>$consulta){
$xml = simplexml_load_string($consulta['XML']);
$questao = $xml->enunciado."\n\n";
$nAlternativas = 0;
foreach($xml->alternativa as $alternativas){
$questao .= $letras[$nAlternativas].' '.$alternativas."\n";
$nAlternativas++;
}
echo "<div class=\"row\">
<div class=\"col s12\">
<div class=\"row\">
<div class=\"input-field col s12\">
<h6 class=\"header col s12 light\">Questao: ".($key+1)."</h6>
<textarea class=\"materialize-textarea\" id=\"questao-produzida\" name=\"questao-produzida\" readonly>
".$questao."
</textarea>
</div>
</div>
</div>
</div>";
$provaXML .= $consulta['XML'];
}
$provaXML .= "</prova>";
session_start();
$_SESSION['prova'] = $provaXML;
echo "<div align=\"center\">
<a class=\"waves-effect waves-light btn light-blue darken-4\" name=\"salvar-produzida\" align=\"center\" href=\"salvaProva.php\">
Enviar<i class=\"tiny material-icons white-text text-darken-1\">input</i>
</a>
</div>";
include('rodape.html');
?>
<file_sep>/Banco de Questões/java/bancodequestoes/ConexaoBD.java
package bancodequestoes;
import BancoDeDados.Conexao;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Classe que faz todas as interações com o banco de dados na tarefa de <b>Banco de questões</b>,
* realiza as Querys, salva no <b>banco de dados</b> e faz o retorno das informações necessarias.
*
* O objetivo dessa classe é otimizar e simplificar o codigo da classe <b>Questão</b> tornando a mais
* objetiva.
* @author ThalesGSN
*/
public class ConexaoBD extends Conexao {
//Variaveis de instancia
//Construtores
/**
* Construtor vazio para construir o objeto usando sets e gets.
*/
public ConexaoBD() { }
/**
* Construtor que trabalha com três parametros e inicia uma conexão com o <b>banco de dados</b>, nesse objeto.
*
* @param endereco Endereço IP de onde o <b>banco de dados</b> se apresenta.
* @param user <i>String</i> que representa o nome de usuario da conexão.
* @param nomeBD Nome do <b>banco de dados</b>.
* @param senha <i>String</i> que representa a senha da conexão.
* @throws java.sql.SQLException
* Quando ocorre algum erro na conexão com o banco de dados.
*/
public ConexaoBD(String endereco, String user, String senha, String nomeBD) throws SQLException{
super.conectar(endereco, user, senha, nomeBD);
}
//Metodos Uteis
/**
* Seleciona uma questão aleatoria do banco de dados de uma materia qualquer.
* @param materia <i>String</i> que define a materia da questão que vai ser retornada.
* @return <i>ResultSet</i> das questões com a materia especificada.
* @throws SQLException
* Quando ocorre algum erro na conexão com o banco de dados
*/
public ResultSet getQuestoes(String materia) throws SQLException{
return super.enviarQueryResultados("SELECT * FROM questoes WHERE Materia = \'" + materia + "\'"
+ " ORDER BY rand()");
}
/**
* Seleciona uma questão aleatoria do banco de dados de uma materia e de um conteudo
* especificos.
* @param materia <i>String</i> da materia da questão a ser retornada.
* @param conteudos
* @return As questões da materia especificada em ordem aleatoria.
* @throws SQLException
* Quando ocorre algum erro na conexão com o banco de dados.
*/
public ResultSet getQuestoes(String materia, ArrayList<String> conteudos) throws SQLException{
Iterator it = conteudos.iterator();
String query = "SELECT * FROM questoes WHERE Materia = \'" + materia
+ "\' AND conteudo = \'" + it.next() + "\'";
while(it.hasNext()){
query += "\' OR conteudo = \'" + it.next()+ "\'";
}
query += " ORDER BY RAND()";
return super.enviarQueryResultados(query);
}
/**
* Seleciona uma questão aleatoria do banco de dados de uma materia e de um conteudo
* e um tipo especifico.
* @param materia <i>String</i> da materia da questão a ser retornada.
* @param conteudos
* @param dificuldade <i>byte</i> do nivel da dificuldade da questao.
* @return Todas as questões com os requisitos especificados em ordem aleatoria
* @throws SQLException
* Quando ocorre algum erro na conexão com o banco de dados.
*/
public ResultSet getQuestoesGenericas(String materia, ArrayList<String> conteudos, byte dificuldade)
throws SQLException {
Iterator it = conteudos.iterator();
String query = "SELECT * FROM questoes WHERE Materia = \'" + materia
+ "\' AND conteudo = \'" + it.next() + "\'";
while(it.hasNext()){
query += "\' OR conteudo = \'" + it.next()+ "\'";
}
query += "\' AND dificuldade = \' " + dificuldade + " \' ORDER BY RAND()";
return super.enviarQueryResultados(query);
}
/**
* Seleciona uma questão aleatoria do banco de dados de uma materia e de um conteudo
* e um tipo especifico.
* @param materia <i>String</i> da materia da questão a ser retornada.
* @param conteudos
* @param tipo <i>byte</i> do tipo da questão a ser adicionada.
* Veja as constantes da classe questão.
* @param dificuldade <i>byte</i> do nivel da dificuldade da questao.
* @return Todas as questões com os requisitos especificados em ordem aleatoria
* @throws SQLException
* Quando ocorre algum erro na conexão com o banco de dados.
*/
public ResultSet getQuestoes(String materia, ArrayList<String> conteudos, byte tipo, byte dificuldade)
throws SQLException {
Iterator it = conteudos.iterator();
String query = "SELECT * FROM questoes WHERE Materia = \'" + materia
+ "\' AND conteudo = \'" + it.next() + "\'";
while(it.hasNext()){
query += "\' OR conteudo = \'" + it.next()+ "\'";
}
query += "\' AND tipo = \'" + tipo + "\' AND dificuldade = \'" + dificuldade + "\' ORDER BY RAND()";
return super.enviarQueryResultados(query);
}
/**
* Seleciona uma questão aleatoria do banco de dados de uma materia e de um conteudo
* e um tipo especifico.
* @param user
* @return Todas as questões com os requisitos especificados em ordem aleatoria
* @throws SQLException
* Quando ocorre algum erro na conexão com o banco de dados.
* @throws java.security.NoSuchAlgorithmException
*/
public ResultSet getQuestoesUser(User user)
throws SQLException, NoSuchAlgorithmException {
return super.enviarQueryResultados("SELECT * FROM questoes WHERE user = \'" +
Sessao.usuario.getNickname() + "\' ORDER BY ID ASC" );
}
/**
* Adiciona questão no banco de dados a partir de um objeto questão.
* @throws java.sql.SQLException
* Quando ha algum erro na conexão com o banco de dados.
* @param questao
* <i>Questao</i> a ser addicionada no banco de dados.
* @return <i>true</i> se e somente se, a questão for adicionada com sucesso no banco de dados.
*/
public boolean addQuestaobd(Questao questao) throws SQLException{
return super.enviarQuery("INSERT INTO questoes (materia, conteudo, dificuldade, tipo, xml, user) " +
"VALUES (" + "\'" + questao.getMateria() + "\', "
+ "\'" + questao.getConteudo() + "\', "
+ "\'" + questao.getDificuldade() + "\', "
+ "\'" + questao.getTipo() + "\', "
+ "\'" + questao.toXML() + "\'" +
"\'" + Sessao.usuario.getNickname() + "\'" +
")"); //retorna false caso exista algum erro
}
/**
* Deleta uma questão questão no banco de dados a partir de um objeto questão.
* @param id Pega o id da questão
* @throws java.sql.SQLException
* Quando ha algum erro na conexão com o banco de dados.
* @return <i>true</i> se e somente se, a questão for deletada com sucesso no banco de dados.
*/
public boolean deleteQuestaobd(int id) throws SQLException{
return super.enviarQuery("DELETE FROM questoes WHERE id = " + "\'" + id + "\'");
}
/**
*Edita uma questão questão no banco de dados a partir de um objeto questão antigo e um novo, esse objeto
* antigo sera subistituido no banco de dados pelo novo.
* @param id
* Id da quetão a ser alterada
* @param questao
* O novo objeto questao a ser atualizado no banco de dados
* @return <i>true</i> se e somente se, a questão for deletada com sucesso no banco de dados.
* @throws java.sql.SQLException
*/
public boolean editQuestaobd(int id, Questao questao) throws SQLException{
return super.enviarQuery("UPDATE questoes SET materia = \'" + questao.getMateria() + "\',"
+ "conteudo = \'" + questao.getConteudo() + "\',"
+ " dificuldade = \'" + questao.getDificuldade() + "\', "
+ "tipo = " + "\'" + questao.getTipo() + "\',"
+ "xml = " + "\'" + questao.toXML() + "\'"
+ " WHERE ID = " + id + "\'"
); //retorna false caso exista algum erro
}
@Override
public String toString() {
return super.toString();
}
}
<file_sep>/Repositório de Fotos/WEB/repositorio.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Portal Educação</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../../styles/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="../../styles/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link rel="icon" href="../../imgs/logo.png">
<script type="text/javascript" src="mostrar.js"></script>
<!-- CSS -->
<style>
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
</style>
<link href= "../../styles/css/mostrar.css" type="text/css">
</head>
<body>
<!-- NAVBAR -->
<?php
include('../../navbar.php');
?>
<!-- ESPAÇO PARA MARQUEE -->
<div>
</div>
<!-- Modal de login -->
<?php
if(!isset($_SESSION['usuario'])) {
include('../../modal.php');
}
?>
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<br><br>
<h1 class="header center blue-text text-darken-4">Portal Educação</h1>
<div class="row center">
<h5 class="header col s12 light">Um portal com soluções para sistemas educacionais</h5>
</div>
<br><br>
</div>
</div>
<div class="container">
<div class="section">
<!-- CONTEÚDO AQUI -->
<div align="center">
<a class="waves-effect waves-light btn light-blue darken-4" onclick="MOSTRAR()">carômetro</a>
<a class="waves-effect waves-light btn light-blue darken-4" href="WebCam.html">WebCam</a>
<a class="waves-effect waves-light btn light-blue darken-4" href="#">albuns</a>
<a class="waves-effect waves-light btn light-blue darken-4" href="Upload.html">upload de imagens</a>
</div>
<br>
<div style="display:none" id = "inv">
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ADALBERTO_201511130032.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130032<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ALICE_COSTA 201511130024.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130024<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/AMAURY_VIANNA 201511130326.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130326<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ANA_LUISA 201511130016.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130016<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ANDRE_MATHEUS 201411130170.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201411130170<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/BRENO_MARIZ 201511130059.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130059<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/BRENO_PAIVA 201511130067.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130067<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/BRUNO 201511130040.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130040<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/BRYANN_BUENO 201511130342.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130342<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/CARLOS_EDUARDO 201411130197.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201411130197<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ESTER 201511130083.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130083<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/FELIPE 201511130091.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130091<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ADALBERTO_201511130032.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130032<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/GABRIEL_HADDAD 201511130288.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130288<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/GABRIEL_VICTOR 201511130113.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130113<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ADALBERTO_201511130032.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130032<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/ISABELA_CAROLINA 201511130130.jpg" height ="390">
<span class="card-title">Isabela Carolina</span>
</div>
<div class="card-content">
<p>Matrícula: 201511130130<br>
Curso: Informática<br>
Turma :INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/JOAO_PEDRO_ROSA 201511130270.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130270<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/JOAO_PEDRO_SANTOS 201511130300.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130300<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/JOAO_VICTOR 201511130148.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130148<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/LUANA_PINHEIRO_201511130296.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130296<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/LUCAS 201511130261.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130261<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/LUIZ 201511130156.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130156<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/MARCELO201511130180.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130180<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/MARIA_CAROLINA 201511130253.jpg" height ="390">
<span class="card-title">Maria Carolina</span>
</div>
<div class="card-content">
<p>Matrícula: 201511130253<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/MARIA_CAROLINA 201511130253.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130253<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/PAULA_RIBEIRO 201511130245.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130245<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/PEDRO_HENRIQUE 201511130199.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130199<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/PEDRO_OTAVIO 201511130350.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130350<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/RAFAEL_NEVES 201511130237.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130237<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/RAFAEL_HERBERT 201411130235.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201511130235<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/THALES_ALAN 201611130433.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201611130433<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/THALES_GABRIEL 201411130251.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201411130251<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/VICTOR_CESAR 201511130202.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201411130202<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/VICTOR_GABRIEL 201511130210.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201411130210<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
<div class="col s2 m3">
<div class="card">
<div class="card-image">
<img src="INF2A/VITOR_RODARTE 201511130229.jpg" height ="390">
<span class="card-title"><NAME></span>
</div>
<div class="card-content">
<p>Matrícula: 201411130229<br>
Curso: Informática<br>
Turma: INF2A</p>
</div>
<div class="card-action">
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div> <!-- container-->
</div>
</div>
</div>
<!-- -->
<div class="row">
<div class="col s12">
</div>
</div>
</div>
</div>
<?php
include('../../footer.php');
?>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="../../template/js/materialize.js"></script>
<script src="../../template/js/init.js"></script>
<script src="../../index.js"></script>
<script>
function onclick() {
var display = document.getElementById(mydiv).style.display;
if (display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
</script>
</body>
</html>
<file_sep>/Upload/Download.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Portal Educação</title>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="styles/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="styles/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<style type="text/css">
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
</style>
<link rel="icon" href="imgs/logo.png" >
</head>
<body>
<nav class="light-blue darken-4" role="navigation">
<div class="nav-wrapper container">
<!-- MENU SLIDE OUT STRUCTURE-->
<ul id="slide-out" class="side-nav">
<br>
<li>
<div class="logo">
<img class="background center-block responsive" src="imgs/logo.png">
</div>
</li>
<br>
<li><a class="waves-effect" href="index.html">Página Inicial</a></li>
<li><a class="waves-effect" href="#!">Modelo de Provas/Trabalhos</a></li>
<li><a class="waves-effect" href="#!">Fórum</a></li>
<li><a class="waves-effect" href="#!">Download/Upload Aplicativos</a></li>
<li><a class="waves-effect" href="#!">Correção Provas e Trabalhos</a></li>
<li><a class="waves-effect" href="Mural/projeto/index.html">Mural</a></li>
<li><a class="waves-effect" href="#!">Chat</a></li>
<li><a class="waves-effect" href="#!">Repositório de Fotos</a></li>
<li><a class="waves-effect" href="#!">Banco de Questões</a></li>
<li><a class="waves-effect" href="#!">Calendário</a></li>
<!--<li><div class="divider"></div></li>-->
<!--<li><a class="subheader">Subheader</a></li>-->
</ul>
<ul class="left ">
<li>
<button data-activates="slide-out" class="waves-effect waves-light btn-flat button-collapse white-text light-blue darken-4">Menu</button>
</li>
</ul>
<ul class="right ">
<!-- <li><button class="waves-effect waves-light btn-flat white-text light-blue darken-4">Entrar</button></li> -->
<li><a class="waves-effect waves-light btn modal-trigger white-text light-blue darken-3" href="#modal1">Entrar</a></li>
</ul>
</div>
</nav>
<!-- Modal de login -->
<div id="modal1" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Login</h4>
<div class="row">
<p>Insira dados</p>
<form>
<label for="username"><NAME></label>
<input type="text" name="username">
<label for="senha">Senha</label>
<input type="password" name="senha">
<label for="tipoUsuario">Tipo de usuário</label>
<select name="tipoUsuario">
<option value="" disabled selected>Tipo de Usuario</option>
<option value="1">Aluno</option>
<option value="2">Professor</option>
<option value="3">Coordenador</option>
<option value="4">Diretor</option>
</select>
<button class="col s12 btn-flat waves-effect waves-light green white-text" type="submit" name="action">Entrar
<i class="material-icons right">input</i>
</button>
</form>
</div>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat red white-text">Sair</a>
</div>
</div>
<!-- ESPAÇO PARA MARQUEE -->
<div>
</div>
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<br><br>
<h1 class="header center blue-text text-darken-4">Download</h1>
<div class="row center">
<h5 class="header col s12 light">Arquivos Com As Tags Especificadas</h5>
</div>
<br><br>
</div>
</div>
<main>
<div class="container">
<div class="section">
<!-- CONTEÚDO AQUI -->
<?php
date_default_timezone_set("America/Sao_Paulo");
$conexao = mysql_connect('localhost','root','123');
mysql_select_db('teste',$conexao);
$result = mysql_query("SELECT * FROM new_table WHERE status=0");
if($_POST['palavrasChave']!=""){
$tags = explode(',', $_POST['palavrasChave']);
$numCard = 0; //Se houverem 4 cards pula uma linha
$numTags = count($tags); //Se houverem 0 tags lista todos os arquivos
echo '<div class="row">';
while ($arrArq = mysql_fetch_assoc($result)) {
$enc = false;
$tagsArq = explode(',', $arrArq["tags1"]);
foreach ($tags as $t) {
foreach ($tagsArq as $tA) {
if ($t == $tA) {
$enc = true;
$numCard++;
echo '<div class="card sticky-action col s3">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="icon.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4 truncate">' . $arrArq['nome'] . '<i class="material-icons right">more_vert</i></span>
<a class="col btn-large" href="' . $arrArq['path'] . '" download>BAIXAR</a>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">' . $arrArq['nome'] . '<i class="material-icons right">close</i></span>
<p> Tags: ' . $arrArq['tags1'] . '</p>
</div>
</div>';
break;
}
}
if ($numCard == 4) {
echo '</div>
<div class="row">';
}
if ($enc) {
break;
}
}
}
echo '</div>';
} else{
echo '<div class="row">';
while ($arrArq = mysql_fetch_assoc($result)) {
$numCard++;
echo '<div class="card sticky-action col s3">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="icon.png">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4 truncate">' . $arrArq['nome'] . '<i class="material-icons right">more_vert</i></span>
<a class="col btn-large" href="' . $arrArq['path'] . '" download>BAIXAR</a>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">' . $arrArq['nome'] . '<i class="material-icons right">close</i></span>
<p> Tags: ' . $arrArq['tags1'] . '</p>
</div>
</div>';
if ($numCard == 4) {
echo '</div>
<div class="row">';
}
}
echo '</div>';
}
?>
<!-- Não-Tabela-->
</main>
<!-- Footer-->
<footer class="page-footer blue">
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="white-text">Desenvolvedores</h5>
<p class="grey-text text-lighten-4">
Somos a turma de Informática 2A do ano de 2016 do CEFET-MG (Centro Federal de Educação Tecnológica de Minas Gerais) desenvolvendo o trabalho final multidisciplinar de Linguagem de Programação 1 e Aplicações para WEB.
<br><a class="white-text link" href="colaboradores.html">Clique aqui</a> para saber mais
</p>
</div>
<div class="col l3 s12">
<h5 class="white-text">Sobre a Instituição</h5>
<p class="grey-text text-lighten-4">
Centro Federal de Educação Tecnológica de Minas Gerais
<br>Av. Amazonas 5253 - Nova Suiça - Belo Horizonte - MG - Brasil
<br>Telefone: +55 (31) 3319-7000 - Fax: +55 (31) 3319-7001
</p>
</div>
<div class="col l3 s12">
<h5 class="white-text">Recursos</h5>
<ul>
<li><a class="white-text link" href="https://github.com/cefet-inf-2015/portal-educacao/" target="_blank">Github</a></li>
<li><a class="white-text link" href="http://cefetmg.br/" target="_blank">CEFET-MG</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
Made by <a class="blue-text text-lighten-3" href="http://materializecss.com">Materialize</a>
</div>
</div>
</footer>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="template/js/materialize.js"></script>
<script src="template/js/init.js"></script>
<script src="index.js"></script>
</body>
</html><file_sep>/Modelo de Provas e Trabalhos/web/partPHP.php
<?php
// Include the PHPWord.php, all other classes were loaded by an autoloader
require_once 'PHPWord.php';
//require_once 'insereBd.php';
$valor = $_POST['valor'];
$titulo = $_POST['Titulo'];
$turno = $_POST['turno'];
$nQuest = $_POST['nquestao'];
$elab = $_POST['prof'];
$turma = $_POST['turmas'];
$escola = $_POST['instituicao'];
$duracao = $_POST['duracao'];
$dataProva = $_POST['data'];
$dataEntrega = $_POST['dataEntrega'];
$dataRecebimento = $_POST['dataRecebimento'];
$logo = $_FILES['logo']['name'];
$brasao = $_FILES['brasao']['name'];
$foto = $_FILES['foto']['name'];
$tipo = $_POST['tipo'];
$UploadDirectory = 'img/';
$tipoEscola = $_POST['tiopoInsti'];
move_uploaded_file($_FILES['foto']["tmp_name"], $UploadDirectory . $foto);
move_uploaded_file($_FILES['logo']["tmp_name"], $UploadDirectory . $logo);
move_uploaded_file($_FILES['brasao']["tmp_name"], $UploadDirectory . $brasao);
// Create a new PHPWord Object
$PHPWord = new PHPWord();
// Every element you want to append to the word document is placed in a section. So you need a section:
$section = $PHPWord->createSection();
// You can directly style your text by giving the addText function an array:
//$section->addText($titulo, array('align'=>'center','name'=>'Arial', 'size'=>16, 'bold'=>true));
if ($tipo == 'prova') {
$tamanho = array(
'width' => 5000,
'valign' => 'center'
);
$PHPWord->addTableStyle('tableStyle', $tamanho);
$table = $section->addTable();
$table1 = $section->addTable('tableStyle');
$table2 = $section->addTable();
// Add row
$table->addRow();
// Add Cell
$table->addCell(4000)->addImage($UploadDirectory . $foto, array(
'width' => 133,
'height' => 100,
'align' => 'left'
));
$table->addCell(4000)->addImage($UploadDirectory . $logo, array(
'width' => 133,
'height' => 100,
'align' => 'center'
));
$table->addCell(4000)->addImage($UploadDirectory . $brasao, array(
'width' => 133,
'height' => 100,
'align' => 'right'
));
$PHPWord->addFontStyle('myOwnStyle', array(
'align' => 'center',
'name' => 'Arial',
'size' => 12,
'color' => '1B2232'
));
$PHPWord->addParagraphStyle('myOwnP', array(
'align' => 'center',
'spaceAfter' => 100
));
$PHPWord->addParagraphStyle('myOwnP_2', array(
'align' => 'right',
'spaceAfter' => 200
));
// Add row
$table1->addRow();
// Add Cell
$table1->addCell(1500)->addText("\t\t");
$table1->addCell(6000)->addText($escola, 'myOwnStyle', 'myOwnP');
// Add Cell
$table1->addRow();
// Add Cell
$table1->addCell(1500)->addText("\t\t");
$table1->addCell(6000)->addText($titulo, 'myOwnStyle', 'myOwnP');
$table2->addRow();
$table2->addCell(9500)->addText("Aluno(a): " . "NOME DO ALUNO", 'myOwnStyle');
$table2->addCell(2500)->addText("Data: " . $dataProva, 'myOwnStyle');
$table2->addRow();
$table2->addCell(9500)->addText("Professor(a): " . $elab, 'myOwnStyle');
$table2->addCell(2000)->addText("Turma: " . $turma, 'myOwnStyle');
$table2->addRow();
$table2->addCell(9500)->addText("Valor: " . $valor, 'myOwnStyle');
$table2->addCell(2000)->addText("Turno: " . $turno, 'myOwnStyle');
$table2->addRow();
$table2->addCell(9500)->addText("N. de Questoes: " . $nQuest, 'myOwnStyle');
$table2->addCell(2000)->addText("Duracao: " . $duracao . " min", 'myOwnStyle');
// At least write the document to webspace:
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('prova.docx');
} else if ($tipo == 'trabalho') {
$tamanho = array(
'width' => 5000,
'valign' => 'center'
);
$PHPWord->addTableStyle('tableStyle', $tamanho);
$table = $section->addTable();
$table1 = $section->addTable('tableStyle');
$table2 = $section->addTable();
// Add row
$table->addRow();
// Add Cell
$table->addCell(4000)->addImage($UploadDirectory . $foto, array(
'width' => 133,
'height' => 100,
'align' => 'left'
));
$table->addCell(4000)->addImage($UploadDirectory . $logo, array(
'width' => 133,
'height' => 100,
'align' => 'center'
));
$table->addCell(4000)->addImage($UploadDirectory . $brasao, array(
'width' => 133,
'height' => 100,
'align' => 'right'
));
$PHPWord->addFontStyle('myOwnStyle', array(
'align' => 'center',
'name' => 'Arial',
'size' => 12,
'color' => '1B2232'
));
$PHPWord->addParagraphStyle('myOwnP', array(
'align' => 'center',
'spaceAfter' => 100
));
$PHPWord->addParagraphStyle('myOwnP_2', array(
'align' => 'right',
'spaceAfter' => 200
));
// Add row
$table1->addRow();
// Add Cell
$table1->addCell(1500)->addText("\t\t");
$table1->addCell(6000)->addText($escola, 'myOwnStyle', 'myOwnP');
// Add Cell
$table1->addRow();
// Add Cell
$table1->addCell(1500)->addText("\t\t");
$table1->addCell(6000)->addText($titulo, 'myOwnStyle', 'myOwnP');
$table2->addRow();
$table2->addCell(9500)->addText("Aluno(a): " . "puxar do banco de dados", 'myOwnStyle');
$table2->addCell(2000)->addText("Turma: " . $turma, 'myOwnStyle');
$table2->addRow();
$table2->addCell(9500)->addText("Professor(a): " . $elab, 'myOwnStyle');
$table2->addCell(2000)->addText("Turno: " . $turno, 'myOwnStyle');
$table2->addRow();
$table2->addCell(4000)->addText("Data Entrega: " . $dataEntrega, 'myOwnStyle');
$table2->addCell(3000)->addText("N. de Questoes: " . $nQuest, 'myOwnStyle');
$table2->addCell(1000)->addText("Valor: " . $valor, 'myOwnStyle');
$table2->addRow();
$table2->addCell(9500)->addText("Data Recebimento: " . $dataRecebimento, 'myOwnStyle');
$table2->addCell(2000)->addText("Duracao: " . $duracao . " min", 'myOwnStyle');
// At least write the document to webspace:
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('trabalho.docx');
}
?><file_sep>/navbar.php
<nav class="light-blue darken-4" role="navigation">
<div class="nav-wrapper container">
<!-- MENU SLIDE OUT STRUCTURE-->
<ul id="slide-out" class="side-nav">
<br>
<li>
<div class="logo">
<img class="background center-block responsive" src="imgs/logo.png">
</div>
</li>
<br>
<li><a class="waves-effect" href="index.php">Página Inicial</a></li>
<li><a class="waves-effect" href="http:///localhost/portal-educacao/Mural/web/index.php">Mural</a></li>
<li><a class="waves-effect" href="#!">Repositório de Fotos</a></li>
<li><a class="waves-effect" href="Upload/index.html">Download/Upload Aplicativos</a></li>
<?php
if(isset($_SESSION['usuario']) ) {
$data = (array) $_SESSION['usuario'];
switch( $data['permissao']) {
case 3:
case 2:
case 1:
echo '<li><a class="waves-effect" href="#!">Modelo de Provas/Trabalhos</a></li>
<li><a class="waves-effect" href="Correcao/LayoutCorrecaoProvas.html">Correção Provas e Trabalhos</a></li>';
case 0:
echo '<li><a class="waves-effect" href="#!">Calendário</a></li>
<li><a class="waves-effect" href="Chat/index.html">Chat</a></li>
<li><a class="waves-effect" href="Forum/Web/Fórum.html">Fórum</a></li>
<li><a class="waves-effect" href="#!">Banco de Questões</a></li>';
break;
}
}
?>
<!--<li><div class="divider"></div></li>-->
<!--<li><a class="subheader">Subheader</a></li>-->
</ul>
<ul class="left ">
<li>
<button data-activates="slide-out" class="waves-effect waves-light btn-flat button-collapse white-text light-blue darken-4">Menu</button>
</li>
</ul>
<ul class="right ">
<?php
if(!isset($_SESSION['usuario'])) {
echo '<li><a class="waves-effect waves-light btn modal-trigger white-text light-blue darken-3" href="#modal1">Entrar</a></li>';
}
else {
$userData = (array) $_SESSION["usuario"];
echo '<li>Bem vindo(a), '. $userData["primeiroNome"]. '</li>';
echo '<li><a class="waves-effect waves-light btn white-text light-red darken-3" id="logOutBtn">Sair</a></li>';
echo '<div id="msgSaiu"></div>';
}
?>
</ul>
</div>
</nav>
<!-- ESPAÇO PARA MARQUEE-->
<div id="marquee">
<div><span>Portal Educação</span></div>
</div><file_sep>/Upload/Upload.php
<?php
date_default_timezone_set("America/Sao_Paulo");
$UploadDirectory = 'dado/';
$conexao = mysql_connect('localhost', 'root', '123');
mysql_select_db('teste',$conexao);
if (isset($_FILES['upload'])) {
$fileName = $_FILES['upload']['name'];
if (!file_exists($UploadDirectory . $fileName)) {
$tmpName = $_FILES['upload']['tmp_name'];
$fileSize = $_FILES['upload']['size'];
$fileType = $_FILES['upload']['type'];
if (move_uploaded_file($_FILES['upload']["tmp_name"], $UploadDirectory . $fileName)) {
if ($conexao) {
if (mysql_query("INSERT INTO new_table(nome,size,type,path,tags1) VALUES ('$fileName','$fileSize', '$fileType','$UploadDirectory$fileName','$_POST[palavrasChave]')")) {
unset($_FILES['upload']);
header('Location: Inicio.html');
} else {
echo 'Erro no query';
}
} else {
echo 'Erro na conex„o';
}
} else {
echo 'Erro no upload do arquivo!';
}
} else {
echo 'Erro, arquivo jŠ existente';
}
unset($_FILES['upload']);
} else {
echo 'Nenhum arquivo selecionado';
}
?>
|
bab6cf29657e974f6dca5f99f3b7ab2a583bd0b2
|
[
"Java",
"PHP"
] | 11 |
Java
|
VictorGFM/portal-educacao
|
51ab12c51db1130644655dfc909b236227139fcc
|
a6eedb7fc47c1ab8cef4ef09c0826e474d1d710f
|
refs/heads/main
|
<repo_name>julsgasull/FIB-ROB<file_sep>/README.md
# FIB-ROB
Robòtica
|
4ae12ddc9d0794f6452f2866951236d434d1690c
|
[
"Markdown"
] | 1 |
Markdown
|
julsgasull/FIB-ROB
|
7759a4047946b382721a8e98296700f05f4e51a4
|
e27d50dd8edd501096f97c49926b1e0280f279b8
|
refs/heads/master
|
<repo_name>lx11573/qiankun-test<file_sep>/san/src/main.js
/*
* @Author: lyu
* @Date: 2021-07-10 09:24:04
* @LastEditors: lyu
* @FilePath: /qiankun-san/src/main.js
*/
// import { store } from 'san-store'
// import { builder } from 'san-update'
import './public-path'
import { Router } from 'san-router'
import AppComponent from '@/pages/app.san';
let router;
// FIXME 重置 setImmediate, 否则 qiankun 中, 视图无法更新
if (window.__POWERED_BY_QIANKUN__) {
// window.setImmediate = null
}
function render(dom = '#app') {
// san-router
router = new Router();
router.add({
rule: '/san/page1',
Component: AppComponent,
target: dom
})
router.add({
rule: '/san/page2',
Component: () => import('@/pages/page2'),
target: dom
})
router.setMode('html5')
router.listen(() => {
console.log('san-router')
})
router.start()
window.$router = router
// san-store
// store.raw['initName'] = 'initName'
// store.addAction('changeInitName', name => builder().set('initName', name))
}
export async function bootstrap() {
console.log('san bootstrap');
}
export async function mount(props = {}) {
console.log('san mount')
const { container } = props;
const dom = container ? container.querySelector('#app') : '#app'
render(dom)
window.$mainRouter = props.router
}
export async function unmount() {
console.log('san unmount')
router.stop()
router = null
window.$mainRouter = null
}
if (!window.__POWERED_BY_QIANKUN__) {
render()
}
<file_sep>/src/permission.js
/**
* @Author lv
* @Date 2021/6/30 4:19 下午
*/
/*
* @Author: lyu
* @Date: 2021-03-26 15:54:16
* @LastEditTime: 2021-06-30 16:17:31
* @LastEditors: lyu
* @FilePath: /payment-vue-element/src/permission.js
*/
import router from './router'
// if (process.env.NODE_ENV !== 'production') {
// }
router.beforeEach((to, from, next) => {
console.log('main-router')
// start progress bar
// set page title
document.title = to.meta.title || '这是name'
next()
})
router.afterEach(() => {
// finish progress bar
})
<file_sep>/src/router/index.js
/**
* @Author lv
* @Date 2021/6/29 10:47 上午
*/
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Index',
redirect: '/qiankun',
component: () => import('@/index'),
children: [
{
path: 'qiankun',
name: 'Qiankun',
component: () => import('@/views/qiankun'),
children: [
{
path: 'page1',
component: () => import('@/views/qiankun/page1'),
meta: {
title: 'page1'
}
},
{
path: 'page2',
component: () => import('@/views/qiankun/page2'),
meta: {
title: 'page1'
}
}
],
meta: {
title: '首页'
}
},
{
path: '/san/*',
component: () => import('@/views/child'),
meta: {
title: 'san'
}
}
],
meta: {
title: '首页'
}
}
]
})
export default router
<file_sep>/src/views/child.vue
<!-- @Author lv -->
<!-- @Date 2021/6/30 3:08 下午 -->
<template>
<div id="child-container"></div>
</template>
<script>
import { start } from 'qiankun'
export default {
name: "child",
mounted() {
this.$nextTick(() => {
if (!window.qiankunStarted) {
window.qiankunStarted = true
start()
}
})
}
}
</script>
<style scoped lang="scss">
</style>
<file_sep>/src/index.vue
<!-- @Author lv -->
<!-- @Date 2021/7/2 2:50 下午 -->
<template>
<div>
<el-menu mode="horizontal" router>
<el-menu-item index="/qiankun">qiankun 路由</el-menu-item>
<el-menu-item index="/san/page1">san 路由</el-menu-item>
</el-menu>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "index"
}
</script>
<style scoped lang="scss">
</style>
<file_sep>/src/views/qiankun/page2.vue
<!-- @Author lv -->
<!-- @Date 2021/7/10 9:12 上午 -->
<template>
<div>page2</div>
</template>
<script>
export default {
name: "page2"
}
</script>
<style scoped lang="scss">
</style>
<file_sep>/config/chainWebpack.js
/*
* @Author: lyu
* @Date: 2021-03-16 17:05:17
* @LastEditTime: 2021-06-28 16:11:36
* @LastEditors: lyu
* @FilePath: /gxs-user/config/chainWebpack.js
*/
module.exports = function chainWebpack(config) {
// config.when(process.env.NODE_ENV === 'development', config => config.devtool('source-map'))
// it can improve the speed of the first screen, it is recommended to turn on preload
config.plugin('preload').tap(() => [
{
rel: 'preload',
// to ignore runtime.js
// https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
include: 'initial'
}
])
// when there are many pages, it will cause too many meaningless requests
config.plugins.delete('prefetch')
config
.when(process.env.NODE_ENV !== 'development',
config => {
// config.optimization.minimize(false)
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all'
})
// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
config.optimization.runtimeChunk('single')
}
)
}
<file_sep>/src/App.vue
<template>
<div class="qiankun-container">
<router-view />
</div>
</template>
<script>
export default {
name: "main01",
data() {
return {
microAppNum: 1
};
}
};
</script>
<file_sep>/src/views/qiankun.vue
<!-- @Author lv -->
<!-- @Date 2021/6/29 1:46 下午 -->
<template>
<div>
<el-button @click="$router.push('/qiankun/page1')">qiankun 页面 1</el-button>
<el-button @click="$router.push('/qiankun/page2')">qiankun 页面2</el-button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "IndexVue"
}
</script>
<style scoped lang="scss">
</style>
|
aa449fbd6c68c2f5a3356e862031e2ba9f787c6c
|
[
"Vue",
"JavaScript"
] | 9 |
Vue
|
lx11573/qiankun-test
|
5d31e13e713e051d07ff7bcd419bce1f7742cb06
|
1f6ff387215220d57606adc8a6589bfecbe1eaba
|
refs/heads/master
|
<repo_name>corkine/apple-health-data-analysis<file_sep>/main/java/ConvData.java
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ConvData {
private String fileName = "export2.xml";
private int current = 0;
private int all = 0;
private Element readFromFile() throws DocumentException {
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName);
return new SAXReader().read(stream).getRootElement();
}
@SuppressWarnings("unchecked")
private void doLoop(Element root) {
all = root.elements().size();
Map<String, String> map = new HashMap<>();
((List<Element>) root.elements()).forEach(elements -> {
String newLine = readString(elements);
String key = Optional.ofNullable(elements.getName()).orElse("Something");
map.put(key, map.getOrDefault(key, "") + newLine);
current += 1;
System.out.println("Progress: " + (double) current / (double) all);
});
System.out.println("map.keySet() = " + map.keySet());
}
private String readString(Element element) {
String type_ = element.attributeValue("type");
String unit = element.attributeValue("unit");
String value = element.attributeValue("value");
String sourceName = element.attributeValue("sourceName");
String sourceVersion = element.attributeValue("sourceVersion");
String device = element.attributeValue("device");
String creationDate = element.attributeValue("creationDate");
String startDate = element.attributeValue("startDate");
String endDate = element.attributeValue("endDate");
return String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
type_, unit, value, sourceName, sourceVersion, device, creationDate, startDate, endDate);
}
public static void main(String[] args) throws DocumentException {
ConvData father = new ConvData();
Element element = father.readFromFile();
father.doLoop(element);
}
}
<file_sep>/README.md
# Apple Health Data Analysis
> 版本 1.0
## 关于数据
Apple Health 健康应用程序记录了一些数据,包括心率、活动、卡路里消耗、站立、身高、体重、性别、各种营养摄入等等。
数据导出的方法为:健康 -> 健康数据标签 -> 右上角头像标志 -> 导出健康数据按钮。
导出的数据为 zip 压缩文件,有一个叫做 export.xml 的文件。
如果使用了 Apple Watch,那么数据量还是非常丰富的,比如每日站立、每日卡路里、每日活动分钟数。此外,带着手表时每隔五分钟的心率数据、锻炼数据、GPS 记录和时间、消耗卡路里数均记录在此。
如果不是国行,那么还有心率变异性、最大耗氧量的计算。后者需要进行30分钟以上的锻炼,才会生成此数据。
## 处理方法
参见这一篇博客:https://sspai.com/post/42135
### 使用 JavaScript 处理
一般而言,在使用 Python 分析之前,需要导出为 CSV 格式数据,一个最方便的选择是:http://ericwolter.com/projects/health-export.html
但是在线转换有隐私的问题,虽然作者已经保证不收集信息。对我而言,最大的问题,是慢,JavaScript 的速度,对于 365 天的 Apple Watch 数据而言,需要 10 - 20 分钟处理,CPU 占用极高。
### 使用 Python 处理
Github 上有人提供 Python 处理脚本:
https://github.com/tdda/applehealthdata/blob/master/applehealthdata.py
### 使用 Scala 处理
本程序的 /main/scala 文件夹下的 ConvData.scala 可以用来将从苹果健康程序导出的 xml 文件进行解析,转换成为 CSV 文件,方便 Python 进一步的分析。
相比较 JavaScript,Scala 处理速度提升了 10 倍(得益于 JVM 和 DOM4J 库),在具有静态类型检查的同时,语法相较于 Python 更为优雅。
### 使用 Java 处理
本程序的 /main/java/ConvData.java 提供了大部分处理所需要的代码。
## 分析(预计版本 2.0)
分析使用 Python 进行最好,待补充。
## 服务(预计版本 3.0)
本库提供了很多 Entity 类,这些类是为将 XML 数据映射为 POJO,进一步通过 JPA 将数据映射到 MySQL 数据库而准备的。
通过 Python 探索一些合适的指标,然后通过 Hibernate、Spring 和 Spring MVC 提供基于 Web 的服务,前端使用 JavaScript 和 echat.js 进行展示。<file_sep>/main/java/record/BodyMass.java
package record;
public class BodyMass extends Record{
}
<file_sep>/main/scala/ConvData.scala
import java.io.{FileInputStream, FileOutputStream}
import java.nio.file.Paths
import java.util.Optional
import java.util.concurrent.TimeUnit
import org.dom4j.Element
import org.dom4j.io.SAXReader
import scala.io._
val isLazy = true
val needReWrite = false
printf("Config is: \nisLazy -> %s, if true, it means the app will use export.xml file in the root path. else, your need prove the xml file path.\n" +
"needReWrite -> %s, if true, it means if the output file exists, the app will cover it, else the app will append stream to the exist file\n", isLazy, needReWrite)
println("\nThe app will run in 3 secs later..\n")
TimeUnit.SECONDS.sleep(3)
val fileName = if (!isLazy) StdIn.readLine("Input your Apple Health Data xml File Path: >> \n") else "export.xml"
println("Reading from file " + fileName)
val document = new SAXReader().read(getClass.getClassLoader.getResourceAsStream(fileName))
println("Parse with file " + fileName)
val root = document.getRootElement
val total = root.elements().size()
var current = 0
var lastProgress = 0.0
println("Iter with file " + fileName)
var currentFile: (FileOutputStream, String) = (null, "")
root.elements().stream().forEach(record => {
val element = record.asInstanceOf[Element]
if (element.getName.equalsIgnoreCase("record")) {
val key = Some(element.attributeValue("type")).get
if (currentFile._2 != key) {
Optional.ofNullable(currentFile._1).ifPresent(os => {
os.flush(); os.close()
})
currentFile = (getFile(key), key)
}
currentFile._1.write(covData(element).getBytes)
currentFile._1.flush()
current += 1
printProcess()
}}
)
currentFile._1.close()
print("Done!")
def covData(element: Element) = {
val type_ = element.attributeValue("type")
val unit = element.attributeValue("unit")
val value = element.attributeValue("value")
val sourceName = element.attributeValue("sourceName")
val sourceVersion = element.attributeValue("sourceVersion")
//val device = element.attributeValue("device")
val device = "Apple Product"
val creationDate = element.attributeValue("creationDate")
val startDate = element.attributeValue("startDate")
val endDate = element.attributeValue("endDate")
String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
type_, unit, value, sourceName, sourceVersion, device, creationDate, startDate, endDate)
}
def getFile(fName:String) = {
val fileName = fName.replace("HKQuantityTypeIdentifier","") + ".csv"
if (Paths.get(fileName).toFile.exists() && needReWrite) {
println("File exist, reading and reWriting")
val exists = new FileInputStream(fileName)
val newOut = new FileOutputStream(fileName)
newOut.write(exists.read()); newOut.flush()
newOut
} else {
println("Creating new File: "+ fileName +" now...")
new FileOutputStream(fileName)
}
}
def printProcess(): Unit = {
val currentProgress = current.toDouble/total.toDouble
if (currentProgress - lastProgress > 0.1) {
printf("Progress: %.4s\n",currentProgress)
lastProgress = currentProgress
}
}<file_sep>/main/java/record/VO2Max.java
package record;
public class VO2Max extends Record {
private Integer HKVO2MaxTestType;
public Integer getHKVO2MaxTestType() {
return HKVO2MaxTestType;
}
public void setHKVO2MaxTestType(Integer HKVO2MaxTestType) {
this.HKVO2MaxTestType = HKVO2MaxTestType;
}
@Override
public String toString() {
return super.toString() + "::" +
"{ HKVO2MaxTestType=" + HKVO2MaxTestType +
'}';
}
}
<file_sep>/main/java/record/Record.java
package record;
import java.io.Serializable;
import java.util.Date;
public class Record implements Serializable {
private String sourceName;
private String sourceVersion;
private String unit;
private Date creationDate;
private Date startDate;
private Date endDate;
private Double value;
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"sourceName='" + sourceName + '\'' +
", sourceVersion='" + sourceVersion + '\'' +
", unit='" + unit + '\'' +
", creationDate=" + creationDate +
", startDate=" + startDate +
", endDate=" + endDate +
", value=" + value +
'}';
}
public String getSourceName() {
return sourceName;
}
public void setSourceName(String sourceName) {
this.sourceName = sourceName;
}
public String getSourceVersion() {
return sourceVersion;
}
public void setSourceVersion(String sourceVersion) {
this.sourceVersion = sourceVersion;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
|
6689476af23183916bbe682354e02a7f67bbf806
|
[
"Java",
"Markdown",
"Scala"
] | 6 |
Java
|
corkine/apple-health-data-analysis
|
caa221f13a6be7a9bb169fd3712855154907f1dc
|
b34ea7a80aa177522257cafee961aa61c785665c
|
refs/heads/master
|
<repo_name>rbosse/simple-java-buildpack<file_sep>/bin/compile
#!/usr/bin/env bash
# This will create the filesystem for Java and deploy the JVM
# set -e # fail fast
set -o pipefail # do not ignore exit codes when piping output
# set -x # enable debugging
# Configure directories
build_dir=$1
cache_dir=$2
env_dir=$3
echo "-----> Build Dir is " ${build_dir}
echo "-----> Cache Dir is " ${cache_dir}
echo "-----> Env Dir is " ${env_dir}
echo "-----> PWD is $(pwd)"
echo "-----> Finding JVM"
jvmpath=$(find /tmp -name rh-java-11-openjdk-11.0.17.0.8-2.portable.jre.el.x86_64.tar.gz)
echo "-----> JVM ${jvmpath}"
echo "-----> Finding boot.sh"
bootpath=$(find /tmp -name boot.sh)
echo "-----> Boot.sh ${bootpath}"
echo "-----> Installing JVM"
tar -xf ${jvmpath} -C ${build_dir}
echo "-----> Installing boot.sh"
cp ${bootpath} ${build_dir}
ln -s /home/vcap/app/jre/bin/java ${build_dir}/java
# Modify to put the path stuff in the .profile directory. Put a .sh in there and it should run
echo "-----> Build Dir listing = "
ls -l ${build_dir}
echo "-----> Cache Dir listing = "
ls -l ${cache_dir}
echo "-----> Env Dir listing = "
ls -l ${env_dir}
echo "-----> PWD Dir listing = "
find .
# put an env script to set java in the path
# echo export PATH=$PATH:/app/jre1.8.0_91/bin:/app > ${build_dir}/.profile.d/javaenv.sh
echo after compile PATH = $PATH
<file_sep>/README.md
# simple-java-buildpack
basé sur https://github.com/swiftbird/mini-java-buildpack
<file_sep>/.profile.d/javaenv.sh
echo -----> Setting Java in Path
#export PATH=$PATH:/home/vcap/app/jre1.8.0_91/bin:/app
#export JAVA_HOME=/home/vcap/app/jre1.8.0_91
export PATH=$PATH:/home/vcap/app/jre/bin
echo -----> set path
<file_sep>/bin/detect
#!/usr/bin/env bash
# bin/detect <build-dir>
echo "Detect Exiting with a 0 since every detect should be a success... for now"
exit 0
<file_sep>/bin/boot.sh
echo "The Mini Java Buildpack is executing! "
export PATH=$PATH:/home/vcap/app/jre/bin
#echo "-----> All files from . = "
#find .
echo "-----> LS . = "
ls
echo "-----> PWD = "
pwd
echo "-----> java -version = "
java -version
echo "-----> java location = "
find . -name java
echo "-----> find jar = "
find . -maxdepth 1 -name "*.jar"
echo "-----> starting all jars "
#find . -maxdepth 1 -name "*.jar" -exec java -jar {} \& \;
#java -Xmx1024m -jar app1.jar --server.context-path=/ --server.port=8081 &
#sleep 10
#java -Xmx1024m -jar app2.jar --server.context-path=/ --server.port=8082 &
#sleep 10
#java -Xmx1024m -jar gateway.jar --server.context-path=/ --server.port=8080 &
|
d4271321b7f8a05e657b9755e24d3361c2a1db74
|
[
"Markdown",
"Shell"
] | 5 |
Markdown
|
rbosse/simple-java-buildpack
|
a2cc5078e29a21372b11d6501535ccf75f992dd3
|
082406ff4abd956e2bf55ae931e46461233f0230
|
refs/heads/master
|
<repo_name>gfox1527/datafactory-loganlytics-workbook<file_sep>/README.md
# Data Factory / Synapse Pipeline Workbook
A log analytics workbook for monitoring and operating multiple Data factories and Synapse Pipelines. It is used to get an overview of all runs that ADF and Synapse have done.
The workbook supports answering questions:
* Which ADF / Synapse Instance has the most runs?
* Which piplines are succedding or failing?
* What are the longest running pipelines?
* When was the last run?
* Has the last x runs succeed or failed?
* With drill down possiblity to see specific times and states of individual runs and activites
* Which day has had more or less pipelines running
* At what time during the day is my pipelines running?
* Is there more or less data transfered over time
* What errors is thrown?
### **Overview Page**

### **Details Page**

# Setup
## 1. Add dignostic settings from ADF / Synapse
Goto diagnostic settings on your Data factory or Synapse instance and the add diagnostic settings.

Then add ActivityRuns, PipielineRuns, trigger runs and All metrics ( all can be checked ) and send that to the appropriate Log Analytics workspace. Use Resource Specific destination table.

## 2. Add workbook to Log Analytics
1. Goto **Workbooks** (under General)
2. Press **New** button
3. Press **Advance Editor ( </> )**
4. Copy / paste the workbook(DataFactory.workbook) from here into window and press apply
5. **Save** the workbook
# Description of Charts
## Filters

* Time Range : Is the time range of which the workbook will show data
* Data factory: Filter on a specific ADF/Synapse or multipe
* Pipeline : Filter on a specifc pipeline. (IS cascading from Data factory filter)
## Overview Dashboard
### Runs per Synapse/Datafactory

Show number of times a data facory or synapse insatnace has run pipelines. This chart is to get a glimse of which instance is running most pipelines.
### Runs per pieline grouped by status

Show number of times a pipeline has been triggered. This chart is to get a glimse of which pipeline is running the most. Also to see which is failing or succeding.
### Average duration per pipeline

Show average duration of pipelines. This to find long runing pipelines that might need attention.
### Last runs
Gives on overview of the last runs of the pipelines.

* Pipeline : Name of the pipeline
* Resource : Name of the ADF / Synapse instance
* Staus : Last run status
* Start : Last run start time
* Duration : Last run duration
* Last runs : Shows the last runs as a ball. One ball represents a run within the selected Timerange. The latest run is represented by the first ball.
* Link : Link to monitor in ADF for the specific pipeline
It is possible to drill down with in a pipeline to gain more information. Here is one step below that show all the runs that have happened in the specific time range. It show the state, duration starting time and a link to the monitor in adf for that specific pipieline run.

It is also possible to see the activities that the pipeline has done.

### Number of runs per date and Number of runs over time

Shows information regaring pipeline runs per day and per hour (regardless of day).
## Pipeline Details

* Duration over time : Shows duration of the pipeline over time selected
* Copied rows: Shows number of rows copied in copy activity
* Read data/written : Shows amount of data read and written by copy activites
* Files read / written : Shows number of files read and written by copy activites

* Error over time: Show wjhen errors occured
* Errors per Activity type : Show number of errors per activity type
* Errors per failure type : Show number of errors per failure type
* Errors per activity name : Show number of errors per activity
* Last failing activity : List of failed activites with error messages
|
48a5dd10005296ab0f6d4de6fe639a355b22d4be
|
[
"Markdown"
] | 1 |
Markdown
|
gfox1527/datafactory-loganlytics-workbook
|
75f8db6af2afef7c5247486af90d7a76eab2a320
|
63182b09849c6decccb379b3ba7d03df3fc88156
|
refs/heads/master
|
<file_sep>const rootTypes = ['SHARP','InFocus'];
const sub1Types = ['938','918','828','638','V500','V600'];
const sub2Types = ['LCD-60SU470A-01','LCD-60SU470A-01','LCD-70DS8008A-01','LCD-60SU470A-01','LCD-60SU470A-01','LCD-60SU470A-01'];
const data = [
rootTypes.map((v,k)=>{
})
]
|
e4f386c2e082f6b12d6d59414848f514ea7003dd
|
[
"JavaScript"
] | 1 |
JavaScript
|
miaomiaoG/choice
|
8aab8f67910374aebadcc29cff0a3ee80f1ce306
|
c5833da08598a3b86935ba8d4a1cfc825064570a
|
refs/heads/master
|
<file_sep>require 'formula'
class DatomicFree < Formula
homepage 'http://www.datomic.com/'
url 'http://downloads.datomic.com/0.8.4122/datomic-free-0.8.4122.zip'
sha1 '83d13aa53d6d2ab3d61efed02b233ed19f695b34'
def install
prefix.install Dir['*']
inreplace "#{prefix}/config/samples/free-transactor-template.properties" do |s|
s.gsub! /#data-dir=.*$/, "data-dir=#{var}/datomic"
s.gsub! /#log-dir=.*$/, "log-dir=#{var}/log/datomic/"
end
end
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>bin/transactor</string>
<string>#{prefix}/config/samples/free-transactor-template.properties</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>UserName</key>
<string>#{ENV['USER']}</string>
<key>WorkingDirectory</key>
<string>#{prefix}</string>
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>
EOS
end
end
|
9af235604c41d799a29c20fe8b22ffe726784fd0
|
[
"Ruby"
] | 1 |
Ruby
|
jonpither/homebrew
|
8280d761ba22f2b6c684360add2b242e3e9da7de
|
04d160c62d00b8c30c0556b87a0469120f955c22
|
refs/heads/master
|
<file_sep># first-app
first try
|
3011bef6c373887b7e60cbaf3e1dcb740b7265d4
|
[
"Markdown"
] | 1 |
Markdown
|
sugar8/first-app
|
77ed242f0740c1086303b0b1f232c4325b850f90
|
81e0d0bad5013e68e154d43f27f89dedf8a0e2f7
|
refs/heads/master
|
<file_sep>// Arduino pin numbers
const int SW_pin = 3; // digital pin connected to switch output
#define BUTTON 12 // reset pin
#define WIDTH 7 // random width pin
#define COLOR 2 // random color pin
#define X A0 // x axis
#define Y A1 // y axis
unsigned long targetTime=0;
const unsigned long interval=500;
void setup() {
pinMode(SW_pin, INPUT);
digitalWrite(SW_pin, HIGH);
Serial.begin(9600);
pinMode(BUTTON, INPUT);
pinMode(WIDTH, INPUT);
pinMode(COLOR, INPUT);
}
void loop(){
if(digitalRead(SW_pin) == LOW) {
Serial.println("rst");
}
// if(digitalRead(BUTTON)) {
// Serial.println("rst");
// }
if(digitalRead(WIDTH)) {
Serial.println("width");
}
if(digitalRead(COLOR)) {
Serial.println("color");
}
if(millis()>=targetTime){
targetTime= millis()+interval;
Serial.println(String(analogRead(X))+","+String(analogRead(Y)));
}
}
// #define SENSORPINA A0 // x axis
// //TODO: define other sensor inputs
// unsigned long targetTime=0;
// const unsigned long interval=2500; //TODO: How fast should we read
// void setup(){
// // TODO: begin the serial connection with a baudrate of 115200
// }
// void loop(){
// if(millis()>=targetTime){
// targetTime= millis()+interval;
// Serial.println(analogRead(SENSORPINA));
// //TODO: Add other sensor read outs
// //TODO: convert values into a string https://www.arduino.cc/en/Tutorial/StringConstructors
// //TODO: combine them into a string that can be understood by server.js
// //TODO: send the string over serial
// }
// // TODO: Detect if you want to reset the screen(shake the etch-a-sketch)
// // TODO: write the reset message(see server.js) to the serial port
// }
|
956251c236093074079a6c5650509237c978ee73
|
[
"C++"
] | 1 |
C++
|
nnisa/etch-a-sketch
|
31237386fcd11b31386cac02de57d9f0a873f836
|
170988e9726f58e701b4ad57c2d95f317e82f04a
|
refs/heads/master
|
<repo_name>NatashaLBallard/NoLAC<file_sep>/src/main/java/com/nolac/demo/repositories/AppUserRepository.java
package com.nolac.demo.repositories;
import com.nolac.demo.model.AppUser;
import org.springframework.data.repository.CrudRepository;
public interface AppUserRepository extends CrudRepository<AppUser, Long> {
AppUser findByUsername(String s);
}
|
ac978bde11b36891a5406bfc07eb2bc0efb7c2a1
|
[
"Java"
] | 1 |
Java
|
NatashaLBallard/NoLAC
|
ff5fe33c623a0b8ce6c568a15a87a7486f74b85b
|
85719ce42788c1de4bec5bc664c3e3c301ca7f5f
|
refs/heads/master
|
<file_sep>#include "transitivity_reduction.h"
#include "bloom_filter_plus.h"
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
namespace TR {
struct arc_hash {
size_t operator()(const std::array<size_t,2>& a) const
{
const size_t h1 = std::hash<size_t>()(a[0]);
const size_t h2 = std::hash<size_t>()(a[1]);
return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
}
};
// assume adj and inv_adj have arcs incident to each node sorted topologically
std::vector<std::array<size_t,2>> sort_arcs(const adjacency_list& adj, const adjacency_list& inv_adj)
{
struct up_down_node {
up_down_node(const size_t node_nr, const bool down)
: v(node_nr), up_down_flag(down) {}
size_t v : 63;
size_t up_down_flag : 1;
size_t node_nr() const { return v; }
bool up_node() const { return up_down_flag == 0; }
bool down_node() const { return up_down_flag == 1; }
};
auto up_node = [&](const size_t node_nr) {
return up_down_node(node_nr, false);
};
auto down_node = [&](const size_t node_nr) {
return up_down_node(node_nr, true);
};
auto up_down_node_degree = [&](const up_down_node& v) {
if(v.up_node())
return adj.degree(v.node_nr());
else
return inv_adj.degree(v.node_nr());
};
auto up_down_node_order = [&](const up_down_node& v, const up_down_node& w) {
return up_down_node_degree(v) < up_down_node_degree(w);
};
std::vector<up_down_node> node_sorting;
node_sorting.reserve(2*adj.nr_nodes());
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
node_sorting.push_back(up_node(i));
node_sorting.push_back(down_node(i));
}
std::sort(node_sorting.begin(), node_sorting.end(), up_down_node_order);
std::vector<std::array<size_t,2>> arc_order;
std::unordered_set<std::array<size_t,2>, arc_hash> arc_inserted;
arc_inserted.reserve(adj.nr_arcs());
arc_order.reserve(adj.nr_arcs());
for(const auto node : node_sorting)
{
const size_t v = node.node_nr();
if(node.up_node())
{
for(auto arc_it=inv_adj.begin(v); arc_it!=inv_adj.end(v); ++arc_it)
if(arc_inserted.count({*arc_it, v}) == 0)
{
arc_order.push_back({*arc_it, v});
arc_inserted.insert({*arc_it, v});
}
}
else
{
for(auto arc_it=adj.begin(v); arc_it!=adj.end(v); ++arc_it)
if(arc_inserted.count({v, *arc_it}) == 0)
{
arc_order.push_back({v, *arc_it});
arc_inserted.insert({v, *arc_it});
}
}
}
assert(arc_order.size() == adj.nr_arcs());
return arc_order;
}
std::vector<std::array<size_t,2>> transitive_reduction(adjacency_list& adj)
{
adj.sort_arcs_topologically();
adjacency_list inv_adj = adj.inverse_adjacency_list();
inv_adj.sort_arcs_topologically();
std::unordered_map<std::array<size_t,2>, std::array<size_t,2>, arc_hash> arc_iterator_indices;
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
size_t j_idx = 0;
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++arc_it, ++j_idx)
{
assert(arc_iterator_indices.count({i, *arc_it}) == 0);
arc_iterator_indices.insert(std::make_pair(std::array<size_t,2>{i,*arc_it}, std::array<size_t,2>{j_idx, std::numeric_limits<size_t>::max()}));
}
}
for(size_t j=0; j<inv_adj.nr_nodes(); ++j)
{
size_t i_idx = 0;
for(auto arc_it=inv_adj.begin(j); arc_it!=inv_adj.end(j); ++arc_it, ++i_idx)
{
assert(arc_iterator_indices.count({*arc_it, j}) == 1);
auto elem = arc_iterator_indices.find({*arc_it, j});
assert(elem->second[1] == std::numeric_limits<size_t>::max());
elem->second[1] = i_idx;
}
}
two_dimensional_array<char> adj_mask;
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
adj_mask.add_row();
for(size_t j=0; j<adj.degree(i); ++j)
adj_mask.push_back(true);
}
two_dimensional_array<char> inv_adj_mask;
for(size_t i=0; i<inv_adj.nr_nodes(); ++i)
{
inv_adj_mask.add_row();
for(size_t j=0; j<inv_adj.degree(i); ++j)
inv_adj_mask.push_back(true);
}
bloom_filter_plus b(adj, inv_adj);
const std::vector<size_t> topo_order = adj.topological_sorting();
std::vector<size_t> inv_topo_order(topo_order.size());
for(size_t i=0; i<topo_order.size(); ++i)
inv_topo_order[topo_order[i]] = i;
auto is_redundant = [&](const size_t i, const size_t j) -> bool
{
assert(i < adj.nr_nodes());
assert(j < adj.nr_nodes());
assert(i != j);
if(adj.degree(i) > inv_adj.degree(j))
{
auto mask_arc_it = inv_adj_mask.begin(j);
for(auto arc_it=inv_adj.begin(j); arc_it!=inv_adj.end(j); ++arc_it, ++mask_arc_it)
if(*arc_it != i && *mask_arc_it == true && inv_topo_order[*arc_it] > inv_topo_order[i])
if(*arc_it != i && b.query(i, *arc_it) == reach::reachable)
return true;
}
else
{
auto mask_arc_it = adj_mask.begin(i);
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++mask_arc_it, ++arc_it)
{
if(*arc_it != j && *mask_arc_it == true && inv_topo_order[*arc_it] < inv_topo_order[j])
if(b.query(*arc_it, j) == reach::reachable)
return true;
}
}
return false;
};
const std::vector<std::array<size_t,2>> sorted_arcs = sort_arcs(adj, inv_adj);
std::vector<std::array<size_t,2>> reduced_arcs;
for(const auto e : sorted_arcs)
{
const size_t i = e[0];
const size_t j = e[1];
if(is_redundant(i,j))
{
const auto [j_idx, i_idx] = arc_iterator_indices.find({i,j})->second;
adj_mask(i, j_idx) == false;
inv_adj_mask(j, i_idx) == false;
}
else
reduced_arcs.push_back({i, j});
}
return reduced_arcs;
}
}
<file_sep>project(TR)
cmake_minimum_required(VERSION 2.8.12)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
add_library(adjacency_list src/adjacency_list.cpp)
target_include_directories(adjacency_list PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/)
add_library(pruned_path_labeling src/pruned_path_labeling.cpp)
target_include_directories(pruned_path_labeling PUBLIC include/)
target_link_libraries(pruned_path_labeling adjacency_list)
add_library(interval_label src/interval_label.cpp)
target_include_directories(interval_label PUBLIC include/)
target_link_libraries(interval_label adjacency_list)
add_library(bloom_filter_label src/bloom_filter_label.cpp)
target_include_directories(bloom_filter_label PUBLIC include/)
target_link_libraries(bloom_filter_label adjacency_list)
add_library(bloom_filter_plus src/bloom_filter_plus.cpp)
target_include_directories(bloom_filter_plus PUBLIC include/)
target_link_libraries(bloom_filter_plus adjacency_list bloom_filter_label interval_label)
add_library(transitivity_reduction src/transitivity_reduction.cpp)
target_include_directories(transitivity_reduction PUBLIC include/)
target_link_libraries(transitivity_reduction adjacency_list bloom_filter_plus interval_label)
add_subdirectory(test)
<file_sep>#pragma once
#include "adjacency_list.h"
#include "two_dimensional_array.hxx"
#include <vector>
#include <tuple>
namespace TR {
class pruned_path_labeling {
public:
template<typename ARC_ITERATOR>
pruned_path_labeling(ARC_ITERATOR arc_begin, ARC_ITERATOR arc_end, const size_t _minimum_path_length = 10, const size_t _optimal_path_nr = 50);
bool query(const size_t i, const size_t j) const;
private:
void create_index();
void compute_optimal_paths();
std::vector<size_t> multiplied_degree_value() const;
std::vector<size_t> multiplied_degree_order() const;
// graphs
adjacency_list adj;
adjacency_list inv_adj;
// path info
size_t add_new_path();
size_t add_new_path_node(const size_t v);
std::vector<size_t> path_vertices;
std::vector<size_t> path_offsets;
bool query_tmp(const size_t s, const size_t j) const;
//std::vector<size_t> optimal_path(std::vector<char>& mask) const;
std::tuple<two_dimensional_array<size_t>, std::vector<size_t>> optimal_paths(const size_t nr_paths, const size_t min_path_length);
// path reachability label sets
struct reach_index {
unsigned short int path_nr;
size_t path_node_nr;
};
two_dimensional_array<reach_index> reach_from_path;
two_dimensional_array<reach_index> reach_to_path;
// temporary reachability structures used while constructing reachability queries
std::vector<std::vector<reach_index>> reach_from_path_tmp;
std::vector<std::vector<reach_index>> reach_to_path_tmp;
// node reachability label sets
two_dimensional_array<size_t> reach_from_nodes;
two_dimensional_array<size_t> reach_to_nodes;
// temporary reachability structures used while constructing reachability queries
std::vector<std::vector<size_t>> reach_from_nodes_tmp;
std::vector<std::vector<size_t>> reach_to_nodes_tmp;
void convert_reachability_structs();
const int minimum_path_length = 10;
const int optimal_path_nr = 50;
};
template<typename ARC_ITERATOR>
pruned_path_labeling::pruned_path_labeling(ARC_ITERATOR arc_begin, ARC_ITERATOR arc_end, const size_t _minimum_path_length, const size_t _optimal_path_nr)
: minimum_path_length(_minimum_path_length),
optimal_path_nr(_optimal_path_nr),
adj(arc_begin, arc_end),
inv_adj(adj.inverse_adjacency_list())
{
create_index();
}
}
<file_sep>#pragma once
#include "query.h"
#include "adjacency_list.h"
#include "bloom_filter_label.h"
#include "interval_label.h"
namespace TR {
class bloom_filter_plus {
public:
bloom_filter_plus(const adjacency_list& _adj, const adjacency_list& _inv_adj);
template<typename ITERATOR>
bloom_filter_plus(ITERATOR arc_begin, ITERATOR arc_end);
reach query(const size_t v, const size_t w) const;
const adjacency_list& adjacency() const { return adj; }
const adjacency_list& inverse_adjacency() const { return inv_adj; }
private:
const adjacency_list adj;
const adjacency_list inv_adj;
const bloom_filter_label b;
const interval_label i;
mutable std::vector<char> visited;
std::vector<size_t> visited_vertices;
};
template<typename ITERATOR>
bloom_filter_plus::bloom_filter_plus(ITERATOR arc_begin, ITERATOR arc_end)
: adj(arc_begin, arc_end),
inv_adj(adj.inverse_adjacency_list()),
b(adj, inv_adj),
i(adj, inv_adj),
visited(adj.nr_nodes(), false)
{}
}
<file_sep>#include "test.h"
#include "pruned_path_labeling.h"
void test_pruned_path_labeling(const size_t nr_nodes, const size_t avg_out_degree)
{
const auto edges = construct_random_dag(nr_nodes, avg_out_degree);
TR::pruned_path_labeling r(edges.begin(), edges.end());
for(const auto e : edges)
{
test(r.query(e[0], e[1]) == true, "false negative in reachability of random graph");
test(r.query(e[1], e[0]) == false, "false positive in reachability of random graph");
}
}
int main(int argc, char** argv)
{
std::vector<std::array<size_t,2>> edges = {
{0,1},
{1,2},
{2,3}
};
TR::pruned_path_labeling r(edges.begin(), edges.end());
test(r.query(0,1), "edge 0->1 reachability not detected");
test(r.query(0,2), "edge 0->2 reachability not detected");
test(r.query(0,3), "edge 0->3 reachability not detected");
test(r.query(1,2), "edge 1->2 reachability not detected");
test(r.query(1,3), "edge 1->3 reachability not detected");
test(r.query(2,3), "edge 2->3 reachability not detected");
test(!r.query(1,0), "edge 1->0 reachability not detected");
test(!r.query(2,0), "edge 2->0 reachability not detected");
test(!r.query(3,0), "edge 3->0 reachability not detected");
test(!r.query(2,1), "edge 2->1 reachability not detected");
test(!r.query(3,1), "edge 3->1 reachability not detected");
test(!r.query(3,2), "edge 3->2 reachability not detected");
test_pruned_path_labeling(10, 2);
test_pruned_path_labeling(100, 2);
test_pruned_path_labeling(1000, 2);
test_pruned_path_labeling(10000, 2);
test_pruned_path_labeling(100000, 2);
test_pruned_path_labeling(1000000, 2);
test_pruned_path_labeling(10, 200);
test_pruned_path_labeling(100, 200);
test_pruned_path_labeling(1000, 200);
test_pruned_path_labeling(10000, 200);
test_pruned_path_labeling(100000, 200);
test_pruned_path_labeling(1000000, 200);
}
<file_sep>#include "test.h"
#include "adjacency_list.h"
using namespace TR;
void test_topological_sorting(const std::vector<std::array<size_t,2>>& edges)
{
adjacency_list adj(edges.begin(), edges.end());
const auto ts = adj.topological_sorting();
test(ts.size() == adj.nr_nodes(), "topological sorting must have exactly nr nodes entries.");
std::vector<size_t> inv_ts(adj.nr_nodes());
for(size_t i=0; i<adj.nr_nodes(); ++i)
inv_ts[ts[i]] = i;
for(const auto e : edges)
test(inv_ts[e[0]] < inv_ts[e[1]], "topological sorting not valid.");
}
int main(int argc, char** argv)
{
test_topological_sorting(construct_random_dag(10,2));
test_topological_sorting(construct_random_dag(100,2));
test_topological_sorting(construct_random_dag(1000,2));
test_topological_sorting(construct_random_dag(10000,2));
test_topological_sorting(construct_random_dag(100000,2));
test_topological_sorting(construct_random_dag(10,20));
test_topological_sorting(construct_random_dag(100,20));
test_topological_sorting(construct_random_dag(1000,20));
test_topological_sorting(construct_random_dag(10000,20));
test_topological_sorting(construct_random_dag(100000,20));
}
<file_sep>#pragma once
namespace TR {
// return type for reachability queries
enum class reach {
reachable,
unreachable,
undefined
};
}
<file_sep>#include "test.h"
#include "bloom_filter_label.h"
using namespace TR;
void test_bloom_filter_label(const size_t nr_nodes, const size_t out_degree)
{
const auto edges = construct_random_dag(nr_nodes, out_degree);
bloom_filter_label b(edges.begin(), edges.end());
size_t nr_wrong_negatives = 0;
for(const auto e : edges)
{
//test(b.query(e[0], e[1]) == reach::reachable, "false negative in reachability of random graph");
}
const auto test_edges = construct_random_dag(nr_nodes, out_degree);
const adjacency_list adj(edges.begin(), edges.end());
size_t tp = 0, fp = 0, fn = 0, tn = 0;;
for(const auto e : test_edges)
{
const bool gt = reachable(adj, e[0], e[1]);
const reach prediction = b.query(e[0], e[1]);
if(prediction == reach::reachable)
test(gt, "reachability error on random test arcs");
if(prediction == reach::unreachable)
test(!gt, "reachability error on random test arcs");
if(gt && prediction == reach::reachable)
tp++;
if(!gt && prediction == reach::undefined)
fp++;
if(gt && prediction == reach::undefined)
fn++;
if(!gt && prediction == reach::unreachable)
tn++;
}
std::cout << "confusion matrix on random test edges:\n";
print_confusion_matrix(tp, fp, fn, tn);
//std::cout << "on random test edges:\n";
//std::cout << "#errors = " << nr_errors << ", #unreachable = " << nr_unreachable << "\n";
//std::cout << "error % = " << 100.0*double(nr_errors)/double(nr_unreachable) << "\n";
}
int main(int argc, char** argv)
{
test_bloom_filter_label(10, 2);
test_bloom_filter_label(100, 2);
test_bloom_filter_label(1000, 2);
test_bloom_filter_label(10000, 2);
test_bloom_filter_label(100000, 2);
test_bloom_filter_label(1000000, 2);
test_bloom_filter_label(10, 200);
test_bloom_filter_label(100, 200);
test_bloom_filter_label(1000, 200);
test_bloom_filter_label(10000, 200);
test_bloom_filter_label(20000, 200);
test_bloom_filter_label(30000, 200);
test_bloom_filter_label(40000, 200);
}
<file_sep># dag-reachability
Reachability and transitive reduction for DAGs
C++ algorithms for deciding reachability in directed acyclic graphs (DAG) and for computing the [transitive reduction](https://en.wikipedia.org/wiki/Transitive_reduction).
Reachability algorithms are based on [1] and [2].
The transitivity algorithm is based on [3].
## Usage
### Reachability:
```C++
#include "bloom_filter_plus.h"
...
std::vector<std::array<size_t,2>> edges = {{0,1}, {1,2}, {2,3}};
TR::bloom_filter_plus rq(edges.begin(), edges.end());
rq.query(0,2) == reach::reachable; // true
rq.query(2,0) == reach::unreachable; // true
...
```
### Transitive reduction:
```C++
#include "transitivity_reduction.h"
...
std::vector<std::array<size_t,2>> edges = {{0,1}, {1,2}, {2,3}, {0,2}};
const std::vector<std::array<size_t,2>> reduced_edges = TR::transitive_reduction(edges.begin(), edges.end());
reduced_edges = {{0,1}, {1,2}, {2,3}}; // true
...
```
## References
* [1]: [`<NAME>, <NAME>, <NAME>. GRAIL: a scalable index for reachability queries in very large graphs. In The VLDB Journal 2012.`](https://link.springer.com/article/10.1007/s00778-011-0256-4)
* [3]: [`<NAME>, <NAME>, <NAME>, <NAME>. Reachability Querying: Can It Be Even Faster? In IEEE Transactions on Knowledge and Data Engineering 2017.`](https://ieeexplore.ieee.org/document/7750623)
* [3]: [`<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>. One Edge at a Time: A Novel Approach Towards Efficient Transitive Reduction Computation on DAGs . In IEEE Access 2020.`](https://ieeexplore.ieee.org/document/9006804)
<file_sep>#pragma once
#include <vector>
#include <cassert>
namespace TR {
class adjacency_list {
public:
template<typename ARC_ITERATOR>
adjacency_list(ARC_ITERATOR arc_begin, ARC_ITERATOR arc_end);
size_t nr_nodes() const { return node_offsets.size()-1; }
size_t nr_arcs() const { return arcs.size(); }
adjacency_list inverse_adjacency_list() const;
auto begin(const size_t i) { assert(i < nr_nodes()); return arcs.begin() + node_offsets[i]; }
auto end(const size_t i) { assert(i < nr_nodes()); return arcs.begin() + node_offsets[i+1]; }
auto begin(const size_t i) const { assert(i < nr_nodes()); return arcs.begin() + node_offsets[i]; }
auto end(const size_t i) const { assert(i < nr_nodes()); return arcs.begin() + node_offsets[i+1]; }
size_t degree(const size_t i) const { assert(i < nr_nodes()); return node_offsets[i+1] - node_offsets[i]; }
size_t operator()(const size_t i, const size_t idx) const;
std::vector<size_t> topological_sorting() const;
void sort_arcs_topologically();
bool is_dag() const;
private:
std::vector<size_t> arcs;
std::vector<size_t> node_offsets;
};
template<typename ARC_ITERATOR>
adjacency_list::adjacency_list(ARC_ITERATOR arc_begin, ARC_ITERATOR arc_end)
{
std::vector<size_t> node_arc_count;
for(auto arc_it=arc_begin; arc_it!=arc_end; ++arc_it)
{
const size_t i = (*arc_it)[0];
const size_t j = (*arc_it)[1];
if(node_arc_count.size() <= std::max(i,j))
node_arc_count.resize(std::max(i,j)+1, 0);
node_arc_count[i]++;
}
arcs.resize(std::distance(arc_begin, arc_end));
node_offsets.reserve(node_arc_count.size()+1);
node_offsets.push_back(0);
for(const size_t i : node_arc_count)
node_offsets.push_back(node_offsets.back() + i);
std::fill(node_arc_count.begin(), node_arc_count.end(), 0);
for(auto arc_it=arc_begin; arc_it!=arc_end; ++arc_it)
{
const size_t i = (*arc_it)[0];
const size_t j = (*arc_it)[1];
arcs[node_offsets[i] + node_arc_count[i]++] = j;
}
}
}
<file_sep>#include "test.h"
#include "interval_label.h"
using namespace TR;
void test_interval_label(const size_t nr_nodes, const size_t out_degree)
{
const auto edges = construct_random_dag(nr_nodes, out_degree);
interval_label i(edges.begin(), edges.end());
for(const auto e : edges)
test(i.query(e[1], e[0]) == reach::unreachable, "false positive in reachability of random graph");
const auto test_edges = construct_random_dag(nr_nodes, out_degree);
const adjacency_list adj(edges.begin(), edges.end());
size_t tp = 0, fp = 0, fn = 0, tn = 0;;
for(const auto e : test_edges)
{
const bool gt = reachable(adj, e[0], e[1]);
const reach prediction = i.query(e[0], e[1]);
if(prediction == reach::reachable)
test(gt, "reachability error on random test arcs");
if(prediction == reach::unreachable)
test(!gt, "reachability error on random test arcs");
if(gt && prediction == reach::reachable)
tp++;
if(!gt && prediction == reach::undefined)
fp++;
if(gt && prediction == reach::undefined)
fn++;
if(!gt && prediction == reach::unreachable)
tn++;
}
std::cout << "confusion matrix on random test edges:\n";
print_confusion_matrix(tp, fp, fn, tn);
//test(fn == 0, "random edge reachability: unreachable predictions must always be correct.");
}
int main(int argc, char** argv)
{
test_interval_label(10, 2);
test_interval_label(100, 2);
test_interval_label(1000, 2);
test_interval_label(10000, 2);
test_interval_label(100000, 2);
test_interval_label(1000000, 2);
test_interval_label(10, 200);
test_interval_label(100, 200);
test_interval_label(1000, 200);
test_interval_label(10000, 200);
test_interval_label(20000, 200);
test_interval_label(30000, 200);
test_interval_label(40000, 200);
}
<file_sep>#pragma once
#include <string>
#include <stdexcept>
#include <random>
#include <algorithm>
#include <vector>
#include <array>
#include <stack>
#include <queue>
#include "adjacency_list.h"
#include <iostream>
#include <iomanip>
inline void test(const bool predicate, const std::string msg)
{
if(!predicate)
throw std::runtime_error(msg);
}
std::vector<std::array<size_t,2>> construct_random_dag(const size_t nr_nodes, const size_t avg_out_degree)
{
std::cout << "constructing graph with " << nr_nodes << " nodes and out degree of " << avg_out_degree << "\n";
std::random_device rd;
std::mt19937 gen(rd());
std::vector<std::array<size_t,2>> edges;
for(size_t i=0; i+1<nr_nodes; ++i)
{
std::uniform_int_distribution<size_t> distrib(i+1, nr_nodes-1);
for(size_t j=0; j<avg_out_degree; ++j)
{
edges.push_back({i, distrib(gen)});
}
}
std::cout << "#edges = " << edges.size() << "\n";
auto edge_sort = [](const auto a, const auto b) {
if(a[0] == b[0])
return a[1] < b[1];
return a[0] < b[0];
};
std::sort(edges.begin(), edges.end(), edge_sort);
edges.erase(std::unique(edges.begin(), edges.end()), edges.end());
std::cout << "#unique edges = " << edges.size() << "\n";
return edges;
}
bool reachable(const TR::adjacency_list& adj, const size_t i, const size_t j)
{
assert(i < adj.nr_nodes());
assert(j < adj.nr_nodes());
std::vector<char> visited(adj.nr_nodes(), false);
std::stack<size_t> s;
s.push(i);
while(!s.empty())
{
const size_t k = s.top();
s.pop();
visited[k] = true;
if(k == j)
return true;
for(auto arc_it=adj.begin(k); arc_it!=adj.end(k); ++arc_it)
if(!visited[*arc_it])
s.push(*arc_it);
}
return false;
}
std::vector<size_t> shortest_path(const TR::adjacency_list& adj, const size_t i, const size_t j)
{
assert(i < adj.nr_nodes());
assert(j < adj.nr_nodes());
assert(i != j);
assert(reachable(adj, i, j) == true);
std::vector<char> visited(adj.nr_nodes(), false);
std::vector<size_t> parent(adj.nr_nodes(), std::numeric_limits<size_t>::max());
parent[i] = i;
std::queue<size_t> q;
q.push(i);
while(!q.empty())
{
const size_t k = q.front();
q.pop();
visited[k] = true;
if(k == j)
{
std::vector<size_t> path;
size_t l = k;
while(parent[l] != l)
{
path.push_back(l);
l = parent[l];
}
path.push_back(i);
std::reverse(path.begin(), path.end());
return path;
}
for(auto arc_it=adj.begin(k); arc_it!=adj.end(k); ++arc_it)
if(!visited[*arc_it])
{
visited[*arc_it] = true;
parent[*arc_it] = k;
q.push(*arc_it);
}
}
throw std::runtime_error("not found any path");
return {};
}
void print_confusion_matrix(const size_t tp, const size_t fp, const size_t fn, const size_t tn)
{
const size_t width = std::log10(std::max({tp, fp, fn, tn}))+1;
std::cout << "+";
for(size_t i=0; i<width + 2; ++i)
std::cout << "-";
std::cout << "+";
for(size_t i=0; i<width + 2; ++i)
std::cout << "-";
std::cout << "+\n";
std::cout << "| " << std::setw(width) << tp << " | " << std::setw(width) << fp << " |\n";
std::cout << "+";
for(size_t i=0; i<width + 2; ++i)
std::cout << "-";
std::cout << "+";
for(size_t i=0; i<width + 2; ++i)
std::cout << "-";
std::cout << "+\n";
std::cout << "| " << std::setw(width) << fn << " | " << std::setw(width) << tn << " |\n";
std::cout << "+";
for(size_t i=0; i<width + 2; ++i)
std::cout << "-";
std::cout << "+";
for(size_t i=0; i<width + 2; ++i)
std::cout << "-";
std::cout << "+\n";
}
<file_sep>#include "bloom_filter_label.h"
#include <stack>
#include <iostream> // TODO: remove
namespace TR {
template<typename STREAM, typename BIT_SET>
void print_bitset(STREAM& s, BIT_SET b)
{
for(size_t i=0; i<b.size(); ++i)
if(b[i])
std::cout << "1";
else
std::cout << "0";
std::cout << "\n";
}
bloom_filter_label::bloom_filter_label(const adjacency_list& adj, const adjacency_list& inv_adj)
{
create_index(adj, inv_adj);
}
typename bloom_filter_label::bloom_hash bloom_filter_label::init_node_hash_value(const size_t nr_nodes)
{
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<size_t> distrib(0, bloom_filter_width-1);
// the below construction ensures that nearby nodes have the same initial hash value
static size_t c = 0;
static size_t k = distrib(gen);
if(c > nr_nodes / 1024)
{
c = 0;
k = distrib(gen);
}
++c;
bloom_hash h;
//h[distrib(gen)] = 1;
h[k] = 1;
return h;
}
std::tuple<std::vector<size_t>, std::vector<size_t>> bloom_filter_label::vertex_partition(const adjacency_list& adj, const adjacency_list& inv_adj, const size_t nr_partitions) const
{
assert(adj.nr_nodes() > 0);
// construct post order traversal
std::vector<size_t> post_order;
post_order.reserve(adj.nr_nodes());
std::vector<char> visited(adj.nr_nodes(), false);
struct dfs_elem {
size_t node : 63;
size_t push_nr : 1;
};
std::stack<dfs_elem> s;
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
if(inv_adj.degree(i) == 0)
{
s.push({i,0});
while(!s.empty())
{
const size_t i = s.top().node;
const size_t push_nr = s.top().push_nr;
s.pop();
if(push_nr == 0)
{
s.push({i,1});
visited[i] = true;
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++arc_it)
{
if(!visited[*arc_it])
s.push({*arc_it,0});
}
}
else
{
post_order.push_back(i);
}
}
}
}
std::vector<size_t> partition_representative(nr_partitions, std::numeric_limits<size_t>::max());
std::vector<size_t> partition_nrs(adj.nr_nodes());
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
const size_t partition_nr = (i*nr_partitions)/adj.nr_nodes();
assert(partition_nr < nr_partitions);
partition_nrs[post_order[i]] = partition_nr;
if(partition_representative[partition_nr] != std::numeric_limits<size_t>::max())
partition_representative[partition_nr] = post_order[i];
}
return {partition_nrs, partition_representative};
}
std::vector<typename bloom_filter_label::bloom_hash> bloom_filter_label::compute_hashes(const adjacency_list& adj, const adjacency_list& inv_adj)
{
std::vector<bloom_hash> L(adj.nr_nodes());
std::vector<char> visited(adj.nr_nodes(), false);
struct dfs_elem {
size_t node : 63;
size_t push_nr : 1;
};
std::stack<dfs_elem> s;
for(size_t v=0; v<adj.nr_nodes(); ++v)
{
if(inv_adj.degree(v) == 0)
{
assert(visited[v] == false);
s.push({v,0});
while(!s.empty())
{
const size_t i = s.top().node;
const size_t push_nr = s.top().push_nr;
assert(push_nr == 0 || push_nr == 1);
s.pop();
if(push_nr == 0)
{
if(visited[i] == true)
continue;
visited[i] = true;
assert(L[i].count() == 0);
L[i] = init_node_hash_value(adj.nr_nodes());
s.push({i,1});
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++arc_it)
s.push({*arc_it,0});
}
else
{
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++arc_it)
{
assert(visited[*arc_it] == true);
assert(L[i].count() > 0);
assert(L[*arc_it].count() > 0);
L[i] = L[i] | L[*arc_it];
assert((L[i] | L[*arc_it]) == L[i]);
}
}
}
}
}
for(auto& l : L)
{
assert(l.count() > 0);
}
return L;
}
void bloom_filter_label::create_index(const adjacency_list& adj, const adjacency_list& inv_adj)
{
assert(adj.is_dag());
assert(inv_adj.is_dag());
assert(adj.nr_nodes() == inv_adj.nr_nodes());
const auto [vp,vr] = vertex_partition(adj, inv_adj, adj.nr_nodes()/20+1);
L_out = compute_hashes(adj, inv_adj);
L_in = compute_hashes(inv_adj, adj);
}
reach bloom_filter_label::query(const size_t i, const size_t j) const
{
assert(i < L_in.size());
assert(j < L_in.size());
assert(i != j);
if((L_in[i] | L_in[j]) == L_in[j] && (L_out[i] | L_out[j]) == L_out[i])
return reach::undefined;
return reach::unreachable;
}
}
<file_sep>#include "pruned_path_labeling.h"
#include <algorithm>
#include <cmath>
#include <queue>
#include <iostream> // TODO: for now
namespace TR {
std::vector<size_t> pruned_path_labeling::multiplied_degree_value() const
{
std::vector<size_t> d;
d.reserve(adj.nr_nodes());
for(size_t i=0; i<adj.nr_nodes(); ++i)
d.push_back((adj.degree(i)+1) * (inv_adj.degree(i)+1));
return d;
}
std::vector<size_t> pruned_path_labeling::multiplied_degree_order() const
{
const auto deg_val = multiplied_degree_value();
std::vector<size_t> idx_perm;
idx_perm.reserve(adj.nr_nodes());
for(size_t i=0; i<adj.nr_nodes(); ++i)
idx_perm.push_back(i);
std::sort(idx_perm.begin(), idx_perm.end(), [&](const size_t i, const size_t j) {
return deg_val[i] > deg_val[j];
});
return idx_perm;
}
std::tuple<two_dimensional_array<size_t>, std::vector<size_t>> pruned_path_labeling::optimal_paths(const size_t nr_paths, const size_t min_path_length)
{
const std::vector<size_t> order = multiplied_degree_order();
two_dimensional_array<size_t> paths;
std::vector<size_t> dp(adj.nr_nodes(), 0);
std::vector<size_t> value = multiplied_degree_value();
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
for(auto inv_arc_it=inv_adj.begin(i); inv_arc_it!=inv_adj.end(i); ++inv_arc_it)
dp[i] = std::max(dp[i], dp[*inv_arc_it]);
dp[i] += value[i];
}
std::vector<size_t> val_sorted(adj.nr_nodes());
std::iota(val_sorted.begin(), val_sorted.end(), 0);
std::sort(val_sorted.begin(), val_sorted.end(), [&](const size_t i, const size_t j) { return value[i] > value[j]; });
std::vector<char> used(adj.nr_nodes(), false);
std::vector<size_t> path;
// back tracking
for(const size_t v : val_sorted)
{
if(paths.size() >= nr_paths)
break;
if(used[v] == true)
continue;
assert(path.size() == 0);
path.push_back(v);
// iteratively pick maximum arc from incoming ones
while(path.size() < std::pow(2,16))
{
size_t max_dp = 0;
size_t max_incoming_node = std::numeric_limits<size_t>::max();
for(auto arc_it=inv_adj.begin(path.back()); arc_it!=inv_adj.end(path.back()); ++arc_it)
{
if(dp[*arc_it] >= max_dp && used[*arc_it] == false)
{
max_dp = dp[*arc_it];
max_incoming_node = *arc_it;
}
}
if(max_incoming_node != std::numeric_limits<size_t>::max())
path.push_back(max_incoming_node);
else
break;
}
if(path.size() >= min_path_length)
{
for(const size_t w : path)
used[w] = true;
std::reverse(path.begin(), path.end());
paths.add_row(path.begin(), path.end());
}
path.clear();
}
// now add remaining nodes in order
std::vector<size_t> nodes;
for(size_t i=0; i<order.size(); ++i)
{
const size_t v = order[i];
if(!used[v])
nodes.push_back(v);
}
std::cout << "nr paths = " << paths.size() << "\n";
//for(size_t p=0; p<paths.size(); ++p)
//{
// for(size_t p_idx=0; p_idx<paths.size(p); ++p_idx)
// std::cout << paths(p,p_idx) << ", ";
// std::cout << "\n";
//}
return {paths, nodes};
}
/*
std::vector<size_t> pruned_path_labeling::optimal_path(std::vector<char>& mask) const
{
std::vector<size_t> path;
std::vector<size_t> dp(adj.nr_nodes(), 0);
std::vector<size_t> value(adj.nr_nodes());
std::ptrdiff_t max_i = -1; // first vertex of path
std::ptrdiff_t max_val = -std::numeric_limits<std::ptrdiff_t>::max();
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
for(auto inv_arc_it=inv_adj.begin(i); inv_arc_it!=inv_adj.end(i); ++inv_arc_it)
dp[i] = std::max(dp[i], dp[*inv_arc_it]);
if(mask[i])
value[i] = 0;
dp[i] += value[i];
if(max_val < dp[i])
{
max_i = i;
max_val = dp[i];
}
}
if(max_i == -1)
return {};
// back tracking
size_t v = max_i;
path.push_back(v);
while(dp[v] != value[v])
{
std::ptrdiff_t next_val = dp[v] - value[v];
for(size_t i=0; i<inv_adj.degree(v) && path.size() < std::pow(2,16); ++i) // is second condition really needed?
{
if(dp[ inv_adj(v,i) ] == next_val)
{
v = inv_adj(v,i);
path.push_back(v);
break;
}
}
}
std::reverse(path.begin(), path.end());
}
*/
void pruned_path_labeling::create_index()
{
two_dimensional_array<size_t> paths;
std::vector<size_t> nodes;
std::tie(paths, nodes) = optimal_paths(optimal_path_nr, minimum_path_length);
std::vector<char> visited(adj.nr_nodes(), false);
std::vector<size_t> visited_vertices;
std::vector<char> used(adj.nr_nodes(), false);
reach_from_path_tmp.clear();
reach_from_path_tmp.resize(adj.nr_nodes());
reach_to_path_tmp.clear();
reach_to_path_tmp.resize(adj.nr_nodes());
reach_from_nodes_tmp.clear();
reach_from_nodes_tmp.resize(adj.nr_nodes());
reach_to_nodes_tmp.clear();
reach_to_nodes_tmp.resize(adj.nr_nodes());
// compute path labelings from paths
std::queue<size_t> q;
for(size_t path_nr=0; path_nr<paths.size(); ++path_nr)
{
// BFS
for(std::ptrdiff_t i_idx=paths.size(path_nr)-1; i_idx>=0; --i_idx)
{
const size_t i = paths(path_nr,i_idx);
q.push(i);
while(!q.empty())
{
const size_t v = q.front();
q.pop();
if(visited[v])
continue;
visited[v] = true;
visited_vertices.push_back(v);
if(used[v]) // prune
continue;
if(query_tmp(i, v)) // prune
continue;
assert(path_nr <= std::numeric_limits<unsigned short int>::max());
reach_from_path_tmp[v].push_back({(unsigned short int)(path_nr), size_t(i_idx)});
for(auto arc_it=adj.begin(v); arc_it!=adj.end(v); ++arc_it)
q.push(*arc_it);
}
}
for(const size_t v : visited_vertices)
{
assert(visited[v] == true);
visited[v] = false;
}
visited_vertices.clear();
// reverse BFS
for(size_t i_idx=0; i_idx<paths.size(path_nr); ++i_idx)
{
const size_t i = paths(path_nr, i_idx);
q.push(i);
while(!q.empty())
{
const size_t v = q.front();
q.pop();
if(visited[v])
continue;
visited[v] = true;
visited_vertices.push_back(v);
if(used[v]) // prune
continue;
if(query_tmp(v, i)) // prune
continue;
assert(path_nr <= std::numeric_limits<unsigned short int>::max());
reach_to_path_tmp[v].push_back({(unsigned short int)(path_nr), i_idx});
for(auto arc_it=inv_adj.begin(v); arc_it!=inv_adj.end(v); ++arc_it)
q.push(*arc_it);
}
assert(used[paths(path_nr,i_idx)] == false);
used[paths(path_nr,i_idx)] = true;
}
for(const size_t v : visited_vertices)
{
assert(visited[v] == true);
visited[v] = false;
}
visited_vertices.clear();
//std::cout << "path nr = " << path_nr << "\n";
}
// path labeling for nodes
size_t node_nr = 0;
for(const size_t node : nodes)
{
// BFS
q.push(node);
while(!q.empty())
{
const size_t v = q.front();
q.pop();
if(visited[v])
continue;
visited[v] = true;
visited_vertices.push_back(v);
if(used[v]) // prune
continue;
if(query_tmp(node, v)) // prune
continue;
reach_from_nodes_tmp[v].push_back(node_nr);
for(auto arc_it=adj.begin(v); arc_it!=adj.end(v); ++arc_it)
q.push(*arc_it);
}
for(const size_t v : visited_vertices)
{
assert(visited[v] == true);
visited[v] = false;
}
visited_vertices.clear();
// reverse BFS
q.push(node);
while(!q.empty())
{
const size_t v = q.front();
q.pop();
if(visited[v])
continue;
visited[v] = true;
visited_vertices.push_back(v);
if(used[v]) // prune
continue;
if(query_tmp(v, node)) // prune
continue;
reach_to_nodes_tmp[v].push_back(node_nr);
for(auto arc_it=inv_adj.begin(v); arc_it!=inv_adj.end(v); ++arc_it)
q.push(*arc_it);
}
assert(used[node] == false);
used[node] = true;
for(const size_t v : visited_vertices)
{
assert(visited[v] == true);
visited[v] = false;
}
visited_vertices.clear();
++node_nr;
}
/*
std::vector<char> used(adj.nr_nodes(), false);
const auto order = multiplied_degree_order();
std::vector<size_t> visit_order(adj.nr_nodes());
size_t paths_nr = 0;
std::vector<size_t> path;
// make faster by storing unused vertices in queue
for(size_t i=0; i<adj.nr_nodes(); ++i)
{
if(paths_used < optimal_path_nr)
{
++paths_used;
path = optimal_path(used);
if(path.size() < minimum_path_length)
{
paths_used = optimal_path_nr;
path.clear();
for(size_t i=0; i<order.size(); ++i)
if(!used[order[i]])
{
path = {order[i]};
break;
}
}
if(path.size() == 0)
continue;
}
else // get unused vertex of maximal order
{
for(size_t i=0; i<order.size(); ++i)
if(!used[order[i]])
{
path = {order[i]};
break;
}
}
std::queue<size_t> q;
// BFS
size_t visited_num = 0;
for(size_t i_idx=0; i_idx<path.size(); ++i_idx)
{
const size_t i = path[i_idx];
q.push(i);
while(!q.empty())
{
const size_t v = q.front();
q.pop();
if(visited[v])
continue;
visited[v] = true;
visit_order[visited_num++] = v;
if(used[v]) // prune
continue;
if(query_tmp(i, v)) // prune
continue;
if(path.size() > 1)
reach_from_path_tmp[v].push_back(std::make_pair(path_nr, i_idx]));
else
reach_from_node_tmp[v].push_back(path_nr);
for(auto arc_it=adj.begin(v); arc_it!=adj.end(v); ++arc_it)
q.push(*arc_it);
}
}
for(size_t j=0; j<visited_num; ++j)
visited[visited_vertex[j]] = false;
// reverse BFS
visited_num = 0;
for(size_t i_idx=0; j<path.size(); ++j)
{
const size_t i = path[i_idx];
q.push(i);
while(!q.empty())
{
const size_t v = q.front();
q.pop();
if(visited[v])
continue;
visited[v] = true;
visited_vertex[visited_num++] = v;
if(used[v]) // prune
continue;
if(query_tmp(v, i)) // prune
continue;
if(path.size() > 1)
reach_to_path[v].push_back(std::make_pair(path_nr, i_idx]));
else
reach_to_node_tmp[v].push_back(path_nr);
for(auto arc_it=inv_adj.begin(v); arc_it!=inv_adj.end(v); ++arc_it)
q.push(*arc_it);
}
used[path[i_idx]] = true;
}
++path_nr;
}
*/
convert_reachability_structs();
}
/*
bool pruned_path_labeling::query(const size_t s, const size_t t) const
{
assert(s < adj.nr_nodes());
assert(t < adj.nr_nodes());
assert(s != t);
if(s > t)
return false;
size_t si = 0;
size_t ti = 0;
// path reachability
while(si < reach_to_path.size(s) && ti < reach_from_path.size(t))
{
const size_t sp = reach_to_path(s,si).path_nr;
const size_t sv = reach_to_path(s,si).path_node_nr;
const size_t tp = reach_from_path(t,ti).path_nr;
const size_t tv = reach_from_path(t,ti).path_node_nr;
if(sp == tp && sv <= tv)
return true;
if(sp <= tp)
si++;
else
ti++;
}
// node reachability
si = 0;
ti = 0;
while(si < reach_to_nodes.size(s) && ti < reach_from_nodes.size(t))
{
const size_t sp = reach_to_nodes(s,si);
const size_t tp = reach_from_nodes(t,ti);
if(sp == tp)
return true;
if(sp <= tp)
si++;
else
ti++;
}
return false;
}
*/
bool pruned_path_labeling::query_tmp(const size_t s, const size_t t) const
{
assert(s < adj.nr_nodes());
assert(t < adj.nr_nodes());
//assert(s != t);
if(s == t)
return false;
// TODO: check if s>t in the topological order!
//if(s > t)
// return false;
size_t si = 0;
size_t ti = 0;
// path reachability
while(si < reach_to_path_tmp[s].size() && ti < reach_from_path_tmp[t].size())
{
const size_t sp = reach_to_path_tmp[s][si].path_nr;
const size_t sv = reach_to_path_tmp[s][si].path_node_nr;
const size_t tp = reach_from_path_tmp[t][ti].path_nr;
const size_t tv = reach_from_path_tmp[t][ti].path_node_nr;
if(sp == tp && sv <= tv)
return true;
if(sp <= tp)
si++;
else
ti++;
}
// node reachability
si = 0;
ti = 0;
while(si < reach_to_nodes_tmp[s].size() && ti < reach_from_nodes_tmp[t].size())
{
const size_t sp = reach_to_nodes_tmp[s][si];
const size_t tp = reach_from_nodes_tmp[t][ti];
if(sp == tp)
return true;
if(sp <= tp)
si++;
else
ti++;
}
return false;
}
void pruned_path_labeling::convert_reachability_structs()
{
assert(reach_from_path.size() == 0 && reach_from_nodes.size() == 0);
reach_from_path = two_dimensional_array<reach_index>(reach_from_path_tmp);
reach_to_path = two_dimensional_array<reach_index>(reach_to_path_tmp);
reach_from_nodes = two_dimensional_array<size_t>(reach_from_nodes_tmp);
reach_to_nodes = two_dimensional_array<size_t>(reach_to_nodes_tmp);
// TODO: clear memory
//std::swap(reach_from_path_tmp, {});
//std::swap(reach_to_path_tmp, {});
//std::swap(reach_from_nodes_tmp, {});
//std::swap(reach_to_nodes_tmp, {});
}
bool pruned_path_labeling::query(const size_t s, const size_t t) const
{
assert(s < adj.nr_nodes());
assert(t < adj.nr_nodes());
assert(s != t);
// TODO: check if s>t in the topological order!
if(s > t)
return false;
size_t si = 0;
size_t ti = 0;
// path reachability
while(si < reach_to_path.size(s) && ti < reach_from_path.size(t))
{
const size_t sp = reach_to_path(s,si).path_nr;
const size_t sv = reach_to_path(s,si).path_node_nr;
const size_t tp = reach_from_path(t,ti).path_nr;
const size_t tv = reach_from_path(t,ti).path_node_nr;
if(sp == tp && sv <= tv)
return true;
if(sp <= tp)
si++;
else
ti++;
}
// node reachability
si = 0;
ti = 0;
while(si < reach_to_nodes.size(s) && ti < reach_from_nodes.size(t))
{
const size_t sp = reach_to_nodes(s,si);
const size_t tp = reach_from_nodes(t,ti);
if(sp == tp)
return true;
if(sp <= tp)
si++;
else
ti++;
}
return false;
}
}
<file_sep>#include "test.h"
#include "bloom_filter_plus.h"
using namespace TR;
void test_bloom_filter_plus(const size_t nr_nodes, const size_t out_degree)
{
const auto edges = construct_random_dag(nr_nodes, out_degree);
bloom_filter_plus R(edges.begin(), edges.end());
for(const auto e : edges)
{
test(R.query(e[0], e[1]) == reach::reachable, "false negative in reachability of random graph");
test(R.query(e[1], e[0]) == reach::unreachable, "false positive in reachability of random graph");
}
const auto test_edges = construct_random_dag(nr_nodes, out_degree);
const adjacency_list adj(edges.begin(), edges.end());
for(const auto e : test_edges)
{
const bool reach_gt = reachable(adj, e[0], e[1]);
const reach reach_pred = R.query(e[0], e[1]);
test(reach_pred != reach::undefined, "bloom filter plus must always return defined reachability answer");
if(reach_pred == reach::reachable)
test(reach_gt == true, "random edge reachability: reachability error.");
if(reach_pred == reach::unreachable)
test(reach_gt == false, "random edge reachability: reachability error.");
}
}
int main(int argc, char** argv)
{
std::vector<std::array<size_t,2>> edges = {
{0,1},
{1,2},
{2,3}
};
TR::bloom_filter_plus r(edges.begin(), edges.end());
test(r.query(0,1) == reach::reachable, "edge 0->1 reachability not detected");
test(r.query(0,2) == reach::reachable, "edge 0->2 reachability not detected");
test(r.query(0,3) == reach::reachable, "edge 0->3 reachability not detected");
test(r.query(1,2) == reach::reachable, "edge 1->2 reachability not detected");
test(r.query(1,3) == reach::reachable, "edge 1->3 reachability not detected");
test(r.query(2,3) == reach::reachable, "edge 2->3 reachability not detected");
test(r.query(1,0) == reach::unreachable, "edge 1->0 reachability not detected");
test(r.query(2,0) == reach::unreachable, "edge 2->0 reachability not detected");
test(r.query(3,0) == reach::unreachable, "edge 3->0 reachability not detected");
test(r.query(2,1) == reach::unreachable, "edge 2->1 reachability not detected");
test(r.query(3,1) == reach::unreachable, "edge 3->1 reachability not detected");
test(r.query(3,2) == reach::unreachable, "edge 3->2 reachability not detected");
test_bloom_filter_plus(10, 2);
test_bloom_filter_plus(100, 2);
test_bloom_filter_plus(1000, 2);
test_bloom_filter_plus(10000, 2);
test_bloom_filter_plus(100000, 2);
test_bloom_filter_plus(1000000, 2);
test_bloom_filter_plus(10, 200);
test_bloom_filter_plus(100, 200);
test_bloom_filter_plus(1000, 200);
test_bloom_filter_plus(10000, 200);
test_bloom_filter_plus(100000, 200);
test_bloom_filter_plus(1000000, 200);
}
<file_sep>#include "interval_label.h"
#include <stack>
#include <algorithm>
#include <cassert>
#include <iostream> // TODO: remove
namespace TR {
interval_label::interval_label(const adjacency_list& adj, const adjacency_list& inv_adj)
: g(rd())
{
compute_discovery_and_finish_time(adj, inv_adj);
}
void interval_label::compute_discovery_and_finish_time(const adjacency_list& adj, const adjacency_list& inv_adj)
{
assert(adj.is_dag());
assert(inv_adj.is_dag());
assert(adj.nr_nodes() == inv_adj.nr_nodes());
times.clear();
times.resize(adj.nr_nodes());
std::vector<size_t> roots;
for(size_t i=0; i<adj.nr_nodes(); ++i)
if(inv_adj.degree(i) == 0)
roots.push_back(i);
for(size_t interval_nr=0; interval_nr<nr_interval_labels; ++interval_nr)
{
std::shuffle(roots.begin(), roots.end(), g);
compute_discovery_and_finish_time(adj, inv_adj, roots, interval_nr);
}
}
void interval_label::compute_discovery_and_finish_time(const adjacency_list& adj, const adjacency_list& inv_adj, const std::vector<size_t>& roots, const size_t interval_nr)
{
assert(interval_nr < nr_interval_labels);
std::vector<char> visited(adj.nr_nodes(), false);
assert(adj.nr_nodes() == inv_adj.nr_nodes());
size_t current_reach = 1;
size_t current_grail = 1;
struct dfs_elem {
size_t node : 63;
size_t push_nr : 1;
};
std::stack<dfs_elem> s;
std::vector<size_t> random_adjacency_list;
for(const size_t r : roots)
{
s.push({r,0});
while(!s.empty())
{
const size_t i = s.top().node;
const size_t push_nr = s.top().push_nr;
s.pop();
//std::cout << "visiting " << i << "," << push_nr << "\n";
if(push_nr == 0)
{
if(visited[i])
continue;
visited[i] = true;
times[i].discovery[interval_nr] = current_reach++;
s.push({i,1});
random_adjacency_list.clear();
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++arc_it)
{
if(!visited[*arc_it])
{
random_adjacency_list.push_back(*arc_it);
}
}
std::shuffle(random_adjacency_list.begin(), random_adjacency_list.end(), g);
for(const size_t j : random_adjacency_list)
{
//std::cout << "pushing " << j << "\n";
s.push({j,0});
}
}
else
{
assert(times[i].L_lower[interval_nr] == 0);
assert(times[i].L_upper[interval_nr] == 0);
size_t min_children_L_lower = std::numeric_limits<size_t>::max();
for(auto arc_it=adj.begin(i); arc_it!=adj.end(i); ++arc_it)
{
assert(visited[*arc_it] == true);
assert(times[*arc_it].L_lower[interval_nr] < std::numeric_limits<size_t>::max());
assert(times[*arc_it].L_lower[interval_nr] != 0);
min_children_L_lower = std::min(times[*arc_it].L_lower[interval_nr], min_children_L_lower);
}
times[i].L_lower[interval_nr] = std::min(current_grail, min_children_L_lower);
assert(times[i].L_lower[interval_nr] != 0);
times[i].finish[interval_nr] = current_reach++;
times[i].L_upper[interval_nr] = current_grail++;
//std::cout << i << ": [" << discovery_time[i][interval_nr] << "," << finish_time[i][interval_nr] << "]\n";
}
}
}
assert(std::count(visited.begin(), visited.end(), true) == adj.nr_nodes());
}
reach interval_label::query(const size_t i, const size_t j) const
{
assert(i < times.size());
assert(j < times.size());
//std::cout << "nr interval labels = " << nr_interval_labels << "\n";
//std::cout << "query " << i << "->" << j << "\n";
for(size_t interval_nr=0; interval_nr<nr_interval_labels; ++interval_nr)
{
//std::cout << "[" << discovery_time[i][interval_nr] << "," << finish_time[i][interval_nr] << "], ";
}
//std::cout << "\n";
for(size_t interval_nr=0; interval_nr<nr_interval_labels; ++interval_nr)
{
//std::cout << "[" << discovery_time[j][interval_nr] << "," << finish_time[j][interval_nr] << "], ";
}
//std::cout << "\n";
for(size_t interval_nr=0; interval_nr<nr_interval_labels; ++interval_nr)
{
if(!(times[i].L_lower[interval_nr] <= times[j].L_lower[interval_nr] && times[i].L_upper[interval_nr] >= times[j].L_upper[interval_nr]))
return reach::unreachable;
}
for(size_t interval_nr=0; interval_nr<nr_interval_labels; ++interval_nr)
{
assert(times[i].discovery[interval_nr] != std::numeric_limits<size_t>::max());
assert(times[j].discovery[interval_nr] != std::numeric_limits<size_t>::max());
assert(times[i].finish[interval_nr] != std::numeric_limits<size_t>::max());
assert(times[j].finish[interval_nr] != std::numeric_limits<size_t>::max());
if((times[i].discovery[interval_nr] <= times[j].discovery[interval_nr] && times[i].finish[interval_nr] >= times[j].finish[interval_nr]))
return reach::reachable;
}
return reach::undefined;
}
}
<file_sep>#pragma once
#include "pruned_path_labeling.h"
#include <vector>
#include <array>
namespace TR {
std::vector<std::array<size_t,2>> transitive_reduction(adjacency_list& adj);
template<typename ITERATOR>
std::vector<std::array<size_t,2>> transitive_reduction(ITERATOR arc_begin, ITERATOR arc_end)
{
adjacency_list adj(arc_begin, arc_end);
return transitive_reduction(adj);
}
}
<file_sep>#pragma once
#include "query.h"
#include "adjacency_list.h"
#include <bitset>
#include <vector>
#include <tuple>
#include <random>
namespace TR {
class bloom_filter_label {
public:
bloom_filter_label(const adjacency_list& adj, const adjacency_list& inv_adj);
template<typename ITERATOR>
bloom_filter_label(ITERATOR arc_begin, ITERATOR arc_end);
reach query(const size_t i, const size_t j) const;
private:
void create_index(const adjacency_list& adj, const adjacency_list& inv_adj);
// return (i) vector with partition nr for each vertex and (ii) vector with partition representative for each partition nr
std::tuple<std::vector<size_t>, std::vector<size_t>> vertex_partition(const adjacency_list& adj, const adjacency_list& inv_adj, const size_t nr_partitions) const;
constexpr static size_t bloom_filter_width = 1024;
using bloom_hash = std::bitset<bloom_filter_width>;
std::vector<bloom_hash> L_in;
std::vector<bloom_hash> L_out;
static bloom_hash init_node_hash_value(const size_t nr_nodes);
static std::vector<bloom_hash> compute_hashes(const adjacency_list& adj, const adjacency_list& inv_adj);
};
template<typename ITERATOR>
bloom_filter_label::bloom_filter_label(ITERATOR arc_begin, ITERATOR arc_end)
{
adjacency_list adj(arc_begin, arc_end);
adjacency_list inv_adj = adj.inverse_adjacency_list();
create_index(adj, inv_adj);
}
}
<file_sep>#include "test.h"
#include "transitivity_reduction.h"
#include <set>
#include <chrono>
#include <iostream>
using namespace TR;
void test_random_dag_connectivity(const size_t nr_nodes, const size_t out_degree)
{
const auto edges = construct_random_dag(nr_nodes, out_degree);
const auto begin_time = std::chrono::steady_clock::now();
const auto reduced_edges = transitive_reduction(edges.begin(), edges.end());
const auto end_time = std::chrono::steady_clock::now();
std::cout << "Time for transitivity reduction = " << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - begin_time).count() << "ms" << std::endl;
std::cout << "#original edges = " << edges.size() << ", #reduced edges = " << reduced_edges.size() << ", fraction of edges left = " << 100.0*double(reduced_edges.size())/double(edges.size()) << "%\n";
return;
std::set<std::array<size_t,2>> reduced_edge_set;
for(const auto e : reduced_edges)
reduced_edge_set.insert(e);
adjacency_list reduced_adj(reduced_edges.begin(), reduced_edges.end());
for(const auto e : edges)
{
test(reachable(reduced_adj, e[0], e[1]) == true, "every original edge must be reachable in reduced graph.");
}
}
int main(int argc, char** argv)
{
std::vector<std::array<size_t,2>> edges = {
{0,1},
{1,2},
{2,3},
{0,2},
{0,3},
{1,3}
};
const auto reduced_edges = transitive_reduction(edges.begin(), edges.end());
test(reduced_edges.size() == 3, "transitivity reduction not returning correct number of edges.");
test_random_dag_connectivity(10,2);
test_random_dag_connectivity(100,2);
test_random_dag_connectivity(1000,2);
test_random_dag_connectivity(10000,2);
test_random_dag_connectivity(100000,2);
test_random_dag_connectivity(1000000,2);
test_random_dag_connectivity(10,200);
test_random_dag_connectivity(100,200);
test_random_dag_connectivity(1000,200);
test_random_dag_connectivity(10000,200);
test_random_dag_connectivity(100000,200);
test_random_dag_connectivity(1000000,200);
}
<file_sep>#include "adjacency_list.h"
#include <stack>
#include <algorithm>
#include <array>
namespace TR {
adjacency_list adjacency_list::inverse_adjacency_list() const
{
std::vector<size_t> inverse_arc_count(nr_nodes(),0);
for(const size_t head : arcs)
++inverse_arc_count[head];
std::vector<size_t> inverse_node_offsets;
inverse_node_offsets.reserve(nr_nodes()+1);
inverse_node_offsets.push_back(0);
for(const size_t i : inverse_arc_count)
inverse_node_offsets.push_back(inverse_node_offsets.back() + i);
std::fill(inverse_arc_count.begin(), inverse_arc_count.end(), 0);
std::vector<size_t> inverse_arcs(arcs.size());
for(size_t i=0; i<nr_nodes(); ++i)
for(size_t j_ctr=node_offsets[i]; j_ctr<node_offsets[i+1]; ++j_ctr)
{
const size_t j = arcs[j_ctr];
inverse_arcs[inverse_node_offsets[j] + inverse_arc_count[j]++] = i;
}
std::vector<std::array<size_t,2>> tmp;
adjacency_list inverse(tmp.begin(), tmp.end());
std::swap(inverse.arcs, inverse_arcs);
std::swap(inverse.node_offsets, inverse_node_offsets);
return inverse;
}
size_t adjacency_list::operator()(const size_t i, const size_t idx) const
{
assert(i < nr_nodes());
assert(idx < degree(i));
return arcs[node_offsets[i] + idx];
}
std::vector<size_t> adjacency_list::topological_sorting() const
{
assert(is_dag());
struct topo_node {
size_t v : 63;
size_t push_no : 1;
};
std::vector<char> visited(nr_nodes(), false);
std::stack<topo_node> s;
std::vector<size_t> order;
order.reserve(nr_nodes());
for(size_t i=0; i<nr_nodes(); ++i)
{
if(visited[i] == false)
{
s.push({i,0});
while(!s.empty())
{
const size_t i = s.top().v;
const bool push_no = s.top().push_no;
s.pop();
if(push_no == 0)
{
if(visited[i] == true)
continue;
s.push({i,1});
visited[i] = true;
for(auto arc_it=begin(i); arc_it!=end(i); ++arc_it)
if(visited[*arc_it] == false)
s.push({*arc_it,0});
}
else
{
order.push_back(i);
}
}
}
}
std::reverse(order.begin(), order.end());
assert(order.size() == nr_nodes());
return order;
}
void adjacency_list::sort_arcs_topologically()
{
const auto topo = topological_sorting();
assert(topo.size() == nr_nodes());
std::vector<size_t> inv_topo(topo.size());
for(size_t i=0; i<topo.size(); ++i)
{
assert(topo[i] < nr_nodes());
inv_topo[topo[i]] = i;
}
for(size_t i=0; i<nr_nodes(); ++i)
{
std::sort(arcs.begin() + node_offsets[i], arcs.begin() + node_offsets[i+1],
[&](const size_t j, const size_t k) { return inv_topo[j] < inv_topo[k]; });
}
}
bool adjacency_list::is_dag() const
{
std::vector<size_t> in_degree(nr_nodes(), 0);
for(size_t i=0; i<nr_nodes(); ++i)
for(auto arc_it=begin(i); arc_it!=end(i); ++arc_it)
in_degree[*arc_it]++;
std::stack<size_t> s; // queue with nodes with in-degree zero
for(size_t i=0; i<nr_nodes(); ++i)
if(in_degree[i] == 0)
s.push(i);
size_t visited_nodes = 0;
while(!s.empty())
{
const size_t i = s.top();
s.pop();
visited_nodes++;
for(auto arc_it=begin(i); arc_it!=end(i); ++arc_it)
{
in_degree[*arc_it]--;
if(in_degree[*arc_it] == 0)
s.push(*arc_it);
}
}
return visited_nodes == nr_nodes();
}
}
<file_sep>#include "bloom_filter_plus.h"
namespace TR {
bloom_filter_plus::bloom_filter_plus(const adjacency_list& _adj, const adjacency_list& _inv_adj)
: adj(_adj),
inv_adj(_inv_adj),
b(adj, inv_adj),
i(adj, inv_adj),
visited(adj.nr_nodes(), false)
{}
// function not thread-safe due to usage of visited
reach bloom_filter_plus::query(const size_t v, const size_t w) const
{
assert(visited[v] == false);
const reach ri = i.query(v, w);
if(ri != reach::undefined)
return ri;
const reach rb = b.query(v, w);
if(rb != reach::undefined)
return rb;
visited[v] = true;
//if(adj.degree(v) <= inv_adj.degree(w))
{
for(auto arc_it=adj.begin(v); arc_it!=adj.end(v); ++arc_it)
if(visited[*arc_it] == false && query(*arc_it, w) == reach::reachable)
{
visited[v] = false;
return reach::reachable;
}
}
//else
//{
// for(auto arc_it=inv_adj.begin(w); arc_it!=inv_adj.end(w); ++arc_it)
// if(query(v, *arc_it) == true)
// {
// visited[v] = false;
// return true;
// }
//}
visited[v] = false;
return reach::unreachable;
}
}
<file_sep>#pragma once
#include "query.h"
#include "adjacency_list.h"
#include <array>
#include <vector>
#include <random>
namespace TR {
class interval_label {
constexpr static size_t nr_interval_labels = 32;
public:
template<typename ITERATOR>
interval_label(ITERATOR arc_begin, ITERATOR arc_end);
interval_label(const adjacency_list& adj, const adjacency_list& inv_adj);
reach query(const size_t s, const size_t t) const;
private:
void compute_discovery_and_finish_time(const adjacency_list& adj, const adjacency_list& inv_adj);
void compute_discovery_and_finish_time(const adjacency_list& adj, const adjacency_list& inv_adj, const std::vector<size_t>& roots, const size_t interval_nr);
struct time_elem {
// for reachability queries
std::array<size_t, nr_interval_labels> discovery;
std::array<size_t, nr_interval_labels> finish;
// GRAIL for unreachability queries
std::array<size_t, nr_interval_labels> L_lower;
std::array<size_t, nr_interval_labels> L_upper;
};
std::vector<time_elem> times;
//std::vector<std::array<size_t,nr_interval_labels>> discovery_time;
//std::vector<std::array<size_t,nr_interval_labels>> finish_time;
std::random_device rd;
std::mt19937 g;
};
template<typename ITERATOR>
interval_label::interval_label(ITERATOR arc_begin, ITERATOR arc_end)
: g(rd())
{
adjacency_list adj(arc_begin, arc_end);
adjacency_list inv_adj = adj.inverse_adjacency_list();
compute_discovery_and_finish_time(adj, inv_adj);
}
}
<file_sep>#pragma once
#include <vector>
#include <numeric>
#include <cassert>
namespace TR {
template<typename T>
class two_dimensional_array {
public:
two_dimensional_array(const std::vector<std::vector<T>> a);
two_dimensional_array() {}
T& operator()(const size_t i, const size_t j);
const T& operator()(const size_t i, const size_t j) const;
size_t size() const;
size_t size(const size_t i) const;
void add_row();
void push_back(const T& elem);
template<typename ITERATOR>
void add_row(ITERATOR begin, ITERATOR end);
auto begin(const size_t i) const { assert(i < size()); return data.begin() + offsets[i]; }
auto end(const size_t i) const { assert(i < size()); return data.begin() + offsets[i+1]; }
private:
std::vector<size_t> offsets = {0};
std::vector<T> data;
};
template<typename T>
two_dimensional_array<T>::two_dimensional_array(const std::vector<std::vector<T>> a)
{
offsets.reserve(a.size()+1);
const size_t data_size = std::accumulate(a.begin(), a.end(), 0, [&](const size_t o, const auto vec) { return o + vec.size(); });
data.reserve(data_size);
for(const auto& vec : a)
{
add_row();
for(const T& elem : vec)
push_back(elem);
}
}
template<typename T>
T& two_dimensional_array<T>::operator()(const size_t i, const size_t j)
{
assert(i < size());
assert(j < size(i));
return data[offsets[i] + j];
}
template<typename T>
const T& two_dimensional_array<T>::operator()(const size_t i, const size_t j) const
{
assert(i < size());
assert(j < size(i));
return data[offsets[i] + j];
}
template<typename T>
size_t two_dimensional_array<T>::size() const
{
return offsets.size()-1;
}
template<typename T>
size_t two_dimensional_array<T>::size(const size_t i) const
{
assert(i < size());
return offsets[i+1] - offsets[i];
}
template<typename T>
void two_dimensional_array<T>::add_row()
{
offsets.push_back(offsets.back());
}
template<typename T>
void two_dimensional_array<T>::push_back(const T& elem)
{
assert(offsets.size() > 1);
++offsets.back();
data.push_back(elem);
}
template<typename T>
template<typename ITERATOR>
void two_dimensional_array<T>::add_row(ITERATOR begin, ITERATOR end)
{
add_row();
for(auto it=begin; it!=end; ++it)
push_back(*it);
}
}
<file_sep>#include "test.h"
#include "adjacency_list.h"
using namespace TR;
void test_dag(const std::vector<std::array<size_t,2>> edges, const bool result)
{
adjacency_list adj(edges.begin(), edges.end());
if(result == true)
test(adj.is_dag(), "graph is not a DAG.");
else
test(!adj.is_dag(), "graph is a DAG.");
}
int main(int argc, char** argv)
{
test_dag(construct_random_dag(10,2), true);
test_dag(construct_random_dag(100,2), true);
test_dag(construct_random_dag(1000,2), true);
test_dag(construct_random_dag(10000,2), true);
test_dag(construct_random_dag(100000,2), true);
test_dag(construct_random_dag(10,20), true);
test_dag(construct_random_dag(100,20), true);
test_dag(construct_random_dag(1000,20), true);
test_dag(construct_random_dag(10000,20), true);
test_dag(construct_random_dag(100000,20), true);
std::vector<std::array<size_t,2>> edges = {
{0,1},
{1,2},
{2,0}
};
test_dag(edges, false);
}
<file_sep>add_executable(test_pruned_path_labeling test_pruned_path_labeling.cpp)
target_link_libraries(test_pruned_path_labeling pruned_path_labeling)
add_executable(test_interval_label test_interval_label.cpp)
target_link_libraries(test_interval_label interval_label)
add_executable(test_bloom_filter_label test_bloom_filter_label.cpp)
target_link_libraries(test_bloom_filter_label bloom_filter_label)
add_executable(test_transitivity_reduction test_transitivity_reduction.cpp)
target_link_libraries(test_transitivity_reduction transitivity_reduction)
add_executable(test_dag test_dag.cpp)
target_link_libraries(test_dag adjacency_list)
add_executable(test_topological_sorting test_topological_sorting.cpp)
target_link_libraries(test_topological_sorting adjacency_list)
add_executable(test_bloom_filter_plus test_bloom_filter_plus.cpp)
target_link_libraries(test_bloom_filter_plus bloom_filter_plus adjacency_list)
|
a65f0f0556483b207040ddf074902169b2ac3e05
|
[
"Markdown",
"C++",
"CMake"
] | 25 |
Markdown
|
pawelswoboda/dag-reachability
|
6185ecef9c7a557c1a740496238a0ab364e091db
|
781b0524f762cde22aaba9ffa9dc90f7dcf9f928
|
refs/heads/master
|
<repo_name>mangotango123/hello-world<file_sep>/README.md
# hello-world
test
pirmas blynas nanana
|
cd04b00b9e6a2317ac9eee09bdd587b19da455ab
|
[
"Markdown"
] | 1 |
Markdown
|
mangotango123/hello-world
|
7f01c17c0bf45c5f1110f0e08c2d73f74ef55d1b
|
343cf55dda5f8ecf461df8247c349c97e5cc15b3
|
refs/heads/master
|
<repo_name>guilherme/testing-rails-streams<file_sep>/config/unicorn.config.rb
listen 3000, tcp_nopush: false
worker_processes 3
before_fork do |server, worker|
# Disconnect since the database connection will not carry over
if defined? ActiveRecord::Base
ActiveRecord::Base.connection.disconnect!
end
end
after_fork do |server, worker|
# Start up the database connection again in the worker
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
end
end
<file_sep>/app/controllers/test_controller.rb
class TestController < ApplicationController
def index
@user = User.where('1 = 1')
@user2 = User.where('1 = 1')
@user3 = User.where('1 = 1')
render stream: true
end
end
<file_sep>/README.rdoc
== Running
```
bundle exec rake db:create db:seed # (only in the first time)
bundle exec unicorn_rails --config-file config/unicorn.config.rb
```
== Testing
change app/controllers/test_controller.rb to put or remove the render :stream => true, and see the difference in Chrome DevTools Network tab.
|
d36fa7e3021144627a82445b3d00edcee8ca194d
|
[
"RDoc",
"Ruby"
] | 3 |
RDoc
|
guilherme/testing-rails-streams
|
9e0cdae9c3ae653db7e075abac6ee8caecefc7ed
|
62438be302a6ecce554c27a101e23455754e6890
|
refs/heads/master
|
<repo_name>markste-in/hypersphere_optimizer<file_sep>/hypersphere_n.py
from rs_optimize import *
from test_functions import *
import multiprocessing
import HelperFunctions
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
cpu_count = multiprocessing.cpu_count()
dim = 2
candidateSize = 5
print('starting rays with', cpu_count, 'CPUs')
ray.init(num_cpus=cpu_count, local_mode=False, include_webui=True)
issue = Issue('rosenbrock', dim=dim)
_, all_points = optimize(issue, local_stepSize=.001, max_episodes=300, N=candidateSize)
print(all_points)
ax = plt.axes(projection='3d')
ax = HelperFunctions.plot3d(Rosenbrock_function,ax3d=ax)
x,y,z = zip(*all_points)
ax.plot3D(x, y, z, 'black', linewidth=5)
plt.show()
<file_sep>/rs_optimize.py
import numpy as np
import ray
import pickle
import HelperFunctions
search_range = [-3, 3]
def points_on_sphere(dim=3, N=10):
return np.array(ray.get([point_on_sphere.remote(dim) for i in range(N)]))
@ray.remote
def point_on_sphere(dim=3):
dim = int(dim)
xyz = np.random.normal(0, 1, dim)
inv_l = np.array(1. / np.sqrt(np.sum(np.square(xyz))))
return inv_l * xyz
def points_in_cloud(dim=3, N=10):
return np.array([np.random.random(int(dim)) for i in range(N)])
@HelperFunctions.t_decorator
def optimize(issue, local_stepSize=1., max_episodes=100, N=5, filename=None):
all_points=[]
f = issue.f
Dim = issue.dim
N_init = N
file = filename if filename is not None else "optimizer_weights.p"
try:
SP = pickle.load(open(file, "rb"))
print('loaded weights from file')
except (OSError, IOError) as e:
print('no file was found... generating new weights')
SP = np.random.uniform(search_range[0], search_range[1], Dim)
best_value = ray.get(f.remote(SP))
print('starting here:', SP[:5])
print('value:', best_value, "N: ", N)
failed_to_improve = 0
all_points.append(list(np.ravel(SP)) + [best_value])
for i in range(max_episodes):
hyperSp = points_on_sphere(dim=Dim, N=N)
global_stepSize = np.random.choice(np.linspace(local_stepSize, 10. * local_stepSize, 10))
local_candidates = np.clip(SP + local_stepSize * hyperSp, search_range[0], search_range[1])
global_candidates = np.clip(SP + global_stepSize * hyperSp, search_range[0], search_range[1])
local_eval_cand = ray.get([f.remote(can) for can in local_candidates])
global_eval_cand = ray.get([f.remote(dyn) for dyn in global_candidates])
min_val_local = np.min(local_eval_cand)
min_val_global = np.min(global_eval_cand)
local_global_success = np.argmin([min_val_local, min_val_global])
delta = best_value - np.min([min_val_local, min_val_global])
if (np.min([min_val_local, min_val_global]) < best_value):
if min_val_local < min_val_global:
SP = local_candidates[np.argmin(local_eval_cand)]
else:
SP = global_candidates[np.argmin(global_eval_cand)]
# if (delta < 1e-5):
# failed_to_improve += 1
# print('.', end='')
# else:
failed_to_improve = 0
local_stepSize = global_stepSize
N = (N // 2) if N > 2 else 2
best_value = np.min([min_val_local, min_val_global])
print('\n', i, '[', failed_to_improve, ']', 'improved!->', best_value, 'delta:', delta, 'with',
'global step' if local_global_success else 'local step', '### SZ:', local_stepSize, global_stepSize,
' ### avg hs:', np.average(hyperSp), 'avg SP:', np.average(np.abs(SP)), "N: ", N)
print("saving new weights...")
pickle.dump(SP, open(file, "wb"))
all_points.append(list(np.ravel(SP)) + [best_value])
else:
print('x', end='')
failed_to_improve += 1
if (failed_to_improve > 5 and failed_to_improve % 5 == 0):
local_stepSize /= 2.
N += 3
print('\n', i, '[', failed_to_improve, ']',
'failed to improve for more than 5 steps -> reducing step size to', local_stepSize, 'and N to', N)
print('\n', i, '[', failed_to_improve, ']', '->', best_value, 'delta:', delta, 'with',
'global step' if local_global_success else 'local step', 'SZ:', local_stepSize, global_stepSize,
"N: ", N)
if (failed_to_improve >= 100 and failed_to_improve % 100 == 0):
local_stepSize = np.random.random()
N = N_init
print('\n', i, '[', failed_to_improve, ']',
'failed to improve for more than 100 steps -> resetting step size to', local_stepSize, 'and N to',
N)
print('\n', i, '[', failed_to_improve, ']', '->', best_value, 'delta:', delta, 'with',
'global step' if local_global_success else 'local step', 'SZ:', local_stepSize, global_stepSize,
"N: ", N)
return SP, all_points
<file_sep>/HelperFunctions.py
from timeit import default_timer as timer
import timeit
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from matplotlib import cm
import ray
def t_decorator(func):
def func_wrapper(*args, **kwargs):
start = timer()
result = func(*args, **kwargs)
end = timer()
print(func.__name__, 'took', end - start, 's')
return result
return func_wrapper
class CodeTimer:
def __init__(self, name=None):
self.name = " '" + name + "'" if name else ''
def __enter__(self):
self.start = timeit.default_timer()
def __exit__(self, exc_type, exc_value, traceback):
self.took = (timeit.default_timer() - self.start) * 1000.0
print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')
def plot_surface(f):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3, 3, 0.05)
X, Y = np.meshgrid(x, y)
XY = [list(a) for a in zip(np.ravel(X), np.ravel(Y))]
zs = np.array([f(i) for i in XY ])
# zs[zs > 50] = np.nan
Z = zs.reshape(X.shape)
# surf = ax.plot_surface(X, Y, Z, cmap=cm.jet, vmin=0, vmax=500)
surf = ax.plot_surface(X, Y, Z, cmap=cm.jet)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
# fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
#Code below partially by https://github.com/pablormier/yabox/ :)
# Default configuration
contourParams = dict(
zdir='z',
alpha=0.5,
zorder=1,
antialiased=True,
cmap=cm.PuRd_r
)
surfaceParams = dict(
rstride=1,
cstride=1,
linewidth=0.1,
edgecolors='k',
alpha=0.5,
antialiased=True,
cmap=cm.PuRd_r
)
bounds = [-1,1]
def plot3d(f,points=100, contour_levels=20, ax3d=None, figsize=(12, 8),
view_init=None, surface_kwds=None, contour_kwds=None):
contour_settings = dict(contourParams)
surface_settings = dict(surfaceParams)
if contour_kwds is not None:
contour_settings.update(contour_kwds)
if surface_kwds is not None:
surface_settings.update(surface_kwds)
xbounds, ybounds = bounds[0], bounds[1]
x = y = np.arange(-3, 3, 0.05)
X, Y = np.meshgrid(x, y)
XY = [list(a) for a in zip(np.ravel(X), np.ravel(Y))]
zs = np.array(ray.get([f.remote(i) for i in XY ]))
Z = zs.reshape(X.shape)
if ax3d is None:
fig = plt.figure(figsize=figsize)
ax = Axes3D(fig)
if view_init is not None:
ax.view_init(*view_init)
else:
ax = ax3d
# Make the background transparent
ax.patch.set_alpha(0.0)
# Make each axis pane transparent as well
ax.w_xaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
ax.w_yaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
ax.w_zaxis.set_pane_color((0.0, 0.0, 0.0, 0.0))
surf = ax.plot_surface(X, Y, Z, **surface_settings)
contour_settings['offset'] = np.min(Z)
cont = ax.contourf(X, Y, Z, contour_levels, **contour_settings)
if ax3d is None:
plt.show()
return ax
<file_sep>/README.md
[rosenbrock]: pics/rosenbrock.png
[sphere]: pics/sphere2.png
# Hypersphere Optimizer on ray
Optimizer that works with a hypersphere on the objective function. The evaluation of the objective function is parallelized with ray.
Inspired by the paper [Adaptive step size random search](https://ieeexplore.ieee.org/document/1098903) by <NAME>
Simply execute
```python
python hypersphere_n.py
```
to run the optimizer on a simple problem like the "Sphere function" or the "Rastrigin function" (you may wanna adjust the dimensions).
#### Rosenbrock Function
![rosenbrock function][rosenbrock]
#### Sphere Function
![sphere function][sphere]
Plot function by [Yabox](https://github.com/pablormier/yabox)
Also kinda works on the OpenAI gym environments like BipedalWalker-v2
```python
python worker.py
```
<file_sep>/test_functions.py
import numpy as np
#import HelperFunctions
import ray
class Issue():
def __init__(self, fname, dim):
self.f = None
if (fname == 'rastrigin'):
self.f = Rastrigin_function
elif (fname == 'sphere'):
self.f = Sphere_function
elif (fname == 'rosenbrock'):
self.f = Rosenbrock_function
else:
self.f = fname
self.dim = int(dim)
@ray.remote
def Rastrigin_function(X):
a = np.square(np.array(X))
b = -10 * np.cos(2 * np.pi * np.array(X))
sum = np.sum(a + b)
ret = (10 * 2 + sum)
return ret
@ray.remote
def Sphere_function(X):
ret = np.sum(np.square(X))
return ret
@ray.remote
def Rosenbrock_function(X):
fun = list()
for i in range(len(X) - 1):
fun.append(100 * np.square(X[i + 1] - np.square(X[i])) + np.square(1 - X[i]))
ret = np.sum(fun)
return ret
<file_sep>/worker.py
import gym
import ray
import rs_optimize
import numpy as np
import test_functions
import multiprocessing
cpu_count = multiprocessing.cpu_count()
env = gym.make('BipedalWalker-v2')
# env.seed(0)
# np.random.seed(0)
obs_space = env.observation_space.shape[0]
action_space = env.action_space.shape[0]
# action_space = env.action_space.n
obs = env.reset()
class Model:
def __init__(self):
self.weights = np.zeros(shape=(obs_space, action_space))
def action(self, obs):
return np.matmul(obs, self.weights)
model = Model()
def soft_max(X):
return np.exp(X) / np.sum(np.exp(X))
def pick_action(obs, weights):
model.weights = np.array(weights).reshape(obs_space, action_space)
a = model.action(obs.reshape(1, -1))
# a = soft_max(a[0])
# a = np.argmax(a)
return a[0]
def run_environment(env, weights, steps=500, render=False, average=1):
best_reward = [single_env_run(env, weights, steps=steps, render=render) for _ in range(average)]
return np.average(best_reward)
def single_env_run(env, weights, steps=500, render=False):
step = 0
reward_sum = 0
obs = env.reset()
# action_space = env.action_space.n
while step < steps:
if render:
env.render()
action = pick_action(obs, weights)
obs, reward, done, _ = env.step(action)
reward_sum += reward
step += 1
if done:
break
return reward_sum
steps = 500
max_attempts = 1e3
@ray.remote
def f(weights):
reward_sum = -1 * run_environment(env, weights, steps, render=False, average=3)
return reward_sum
issue = test_functions.Issue(f, obs_space * action_space)
print('starting rays with', cpu_count, 'CPUs')
ray.init(num_cpus=cpu_count, local_mode=False, include_webui=True)
file = "bipedalwalker_weights.p"
bw,_ = rs_optimize.optimize(issue, local_stepSize=0.1, max_episodes=10000, N=2, filename=file)
run_environment(env, bw, steps=steps, render=True, average=1)
|
21bb0f813bb60327d5b95e1f7b96c78d9c3d5673
|
[
"Markdown",
"Python"
] | 6 |
Markdown
|
markste-in/hypersphere_optimizer
|
99d8cd85060491d96cfd7e561c9b0bc82a4b0731
|
7c22472d500480295e9db0f7809d603f51fbcec7
|
refs/heads/master
|
<repo_name>rishi12438/cs2107<file_sep>/test1.sh
for i in {a..z}{a..z}{a..z}{a..z}{a..z};do
# do something with $line here
openssl enc -aes-128-ecb -d -nosalt -base64 -pass <PASSWORD>:$line -in flag.txt.enc -out output1.txt
if grep -q flag{ output1.txt; then
echo "done"
break
fi
done
|
5c9c0a962ec24f6b7449c093895306c308082a3d
|
[
"Shell"
] | 1 |
Shell
|
rishi12438/cs2107
|
abaf6f4eb3b87da5ae16ed79e53e4e46f96680b6
|
5df2b182a5ac2b6158f924b5667b80c419d4f435
|
refs/heads/main
|
<repo_name>burakunlu/react-sorting-comparator<file_sep>/README.md
# React Sorting Algorithm Comparator
This app is developed to visualize and compare time efficiency of sorting algorithms.
Inspired by <NAME>'s Sorting Visualizer project.

## How to run
Simply clone the repo and open "index.html" file with your browser.
## Development
Requires node and npm installed.
Install npm packages by using:
```
npm i
```
Then start the project in dev mode:
```
npm run-script dev
```
## Deployment
...
|
883cba1996e30f75cea7fe01d9ec0ee705b2b86f
|
[
"Markdown"
] | 1 |
Markdown
|
burakunlu/react-sorting-comparator
|
3e62a34efdef595ec27f04614830025b33582aa9
|
ab043808d8110ba5943fc1827be02d0d32584523
|
refs/heads/master
|
<file_sep>"use strict";
var StreetSmartRoadProbLayer = function (settings) {
var theThis, layer, keyedList, minIndex, features;
this.RefreshFromList = function () { return refreshFromList(); }
this.SetMinIndex = function (minIndex) { return setMinIndex(minIndex); }
this.GetMinIndex = function () { return minIndex; }
function getBlockStyle(block) {
//var lineWidth = 12;
var lineWidth = 6;
var lineColor = g_settings.getColorForOccupancy01(block.realTimeProbability);
return [
{ line: true, line_width: lineWidth + 2, line_color: "#88f", zindex: 1, line_dash: [20, 10] },
{ line: true, line_width: lineWidth, line_color: lineColor, line_opacity: 70, zindex: 2 }
];
}
function setMinIndex(minIndexSet) {
minIndexSet = tf.js.GetIntNumberInRange(minIndexSet, 0, g_settings.occupancyColors.length - 1, minIndex);
if (minIndexSet != minIndex) {
minIndex = minIndexSet;
refreshLayer();
}
}
function refreshLayer() {
layer.RemoveAllFeatures();
for (var i = minIndex ; i < features.length ; ++i) {
layer.AddMapFeature(features[i], true);
}
layer.AddWithheldFeatures();
}
function refreshFromList() {
if (!!layer) {
var list = keyedList.GetKeyedItemList();
var coords = [];
var nMultiLines = g_occupancyColors.length;
var multiLineCoords = new Array(nMultiLines);
features = [];
for (var i in list) {
var item = list[i], block = item.GetData();
var geometry = block.geometry;
var colorIndex = g_settings.getColorIndexForOccupancy01(block.realTimeProbability);
if (colorIndex !== undefined) {
if (multiLineCoords[colorIndex] == undefined) {
multiLineCoords[colorIndex] = [];
}
multiLineCoords[colorIndex].push(geometry.coordinates);
}
}
for (var i in multiLineCoords) {
var thisCoords = multiLineCoords[i];
var index = parseInt(i, 10);
if (thisCoords !== undefined) {
var block = { realTimeProbability: index / 10 };
var mapFeature = new tf.map.Feature({
type: "multilinestring", coordinates: thisCoords, style: getBlockStyle(block)
}
);
mapFeature.block = block;
features.push(mapFeature);
}
}
refreshLayer();
}
}
function initialize() {
minIndex = 0;
settings = tf.js.GetValidObjectFrom(settings);
if (tf.js.GetIsInstanceOf(settings.layer, tf.map.FeatureLayer) &&
tf.js.GetIsInstanceOf(settings.keyedList, tf.js.KeyedList)) {
layer = settings.layer;
keyedList = settings.keyedList;
}
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
starter.services.factory('StreetSmartService', ['$http', 'toastr', function ($http, toastr) {
//console.log('StreetSmart service instantiated');
var refreshDispatcher = new tf.events.EventNotifier({ eventName: "refresh" });
var roadProbKeyedList = new tf.js.KeyedList({
name: "roadProbKeyedList",
getKeyFromItemData: function (itemData) { return tf.js.GetIsValidObject(itemData) ? itemData.id : null; },
needsUpdateItemData: function (updateObj) {
return true;
//return updateObj.itemData.realTimeProbability != updateObj.itemDataSet.realTimeProbability;
}
});
function preProcessServiceData(data) {
var parsedData = [];
if (tf.js.GetIsValidObject(data)) {
for (var i in data) {
var block = data[i];
var node1Coords = [block.node1.lng, block.node1.lat];
var node2Coords = [block.node2.lng, block.node2.lat];
block.geometry = { type: "linestring", coordinates: [node1Coords, node2Coords] };
block.realTimeProbability = Math.random();
parsedData.push(block);
}
}
return parsedData;
}
var refreshRoadProb = function (coords) {
if (!!(coords = tf.js.GetMapCoordsFrom(coords))) {
$http({
method: 'GET', url: g_settings.streetSmartRoadGraphProbRestURL,
params: { "userLat": '' + coords[1], "userLng": '' + coords[0], "showRealTime": "true" }
}).then(function successCallback(response) {
if (tf.js.GetIsValidObject(response) && tf.js.GetIsValidObject(response.data) && tf.js.GetIsArray(response.data.blocks)) {
roadProbKeyedList.UpdateFromNewData(preProcessServiceData(response.data.blocks));
refreshDispatcher.Notify();
}
}, function errorCallback(response) { });
}
}
function deliverParking(nodes, callBack) {
var title = g_settings.searchForParkingTitle;
if (!!nodes) {
toastr.info("Found search path", title, { timeOut: 3000 });
}
else {
toastr.error("Search path not found", title, { timeOut: 3000 });
}
callBack(nodes);
}
var searchParking = function (coords, callBack) {
if (!!(callBack = tf.js.GetFunctionOrNull(callBack))) {
if (!!(coords = tf.js.GetMapCoordsFrom(coords))) {
$http({
method: 'GET', url: g_settings.streetSmartSearchParkingRestURL,
params: { "userLat": '' + coords[1], "userLng": '' + coords[0] }
}).then(function successCallback(response) {
if (tf.js.GetIsValidObject(response) && tf.js.GetIsValidObject(response.data) && tf.js.GetIsArray(response.data.nodes)) {
deliverParking(response.data.nodes, callBack);
}
else {
deliverParking(undefined, callBack);
}
}, function errorCallback(response) { deliverParking(undefined, callBack); });
}
}
}
return {
getRoadProbKeyedList: function () { return roadProbKeyedList; },
refreshRoadProb: refreshRoadProb,
addRefreshListener: function (callBack) { return refreshDispatcher.Add(callBack); },
searchParking: searchParking
};
}]);
<file_sep>"use strict";
var ITPACore = {
useDebugGeolocation: false,
AccessToken: "",
private_deviceUUID: undefined,
currentUser: {},
isIOS: undefined,
hasCredentialsSaved: false,
delCredentialsCB: undefined,
DeleteSavedCredentials: function () {
if (ITPACore.hasCredentialsSaved) {
if (ITPACore.delCredentialsCB != undefined) {
ITPACore.delCredentialsCB();
}
}
},
directionsRouteFeature: undefined,
minDistanceInMetersToBeFarFromDirections: 50,
isFilteringIncForDistance: true,
isFilteringMsgForDistance: true,
SetIsFilteringMsgForDistance: function (boolSet) { ITPACore.isFilteringMsgForDistance = !!boolSet; },
GetIsFilteringMsgForDistance: function () { return ITPACore.isFilteringMsgForDistance; },
SetIsFilteringIncForDistance: function (boolSet) { ITPACore.isFilteringIncForDistance = !!boolSet; },
GetIsFilteringIncForDistance: function () { return ITPACore.isFilteringIncForDistance; },
GetNewITPAServer: function () {
//return 'http://192.168.0.37:8080';
//return 'http://172.16.58.3';
//return 'http://itpa-stage3.cs.fiu.edu';
return 'http://utma-api.cs.fiu.edu';
},
GetNewAuthService: function () { return ITPACore.GetNewITPAServer() + '/login'; },
CVTDate: function (theDate) { return theDate + '.0'; },
GetSearchServiceUrl: function () {
var url;
var urlStart = "http://acorn.cs.fiu.edu/cgi-bin/arquery.cgi?category=itpall&vid=itpa&numfind=20&tfaction=shortdisplayflash";
var center, res;
if (ITPACore.featureLayers != undefined) {
var map = ITPACore.featureLayers.GetMap();
center = map.GetCenter();
res = map.GetResolution();
}
if (center == undefined) {
center = ITPACore.mapHomeCenter;
res = tf.units.GetResolutionByLevel(mapInitialLevel);
}
url = urlStart + "&Long=" + center[0] + "&Lat=" + center[1];
if (ITPACore.featureLayers != undefined) {
var queryStr = ITPACore.featureLayers.GetQueryStr();
if (tf.js.GetIsNonEmptyString(queryStr)) {
var encodedQueryStr = queryStr;
encodedQueryStr = encodedQueryStr.replace(' ', '+');
url += "&arcriteria=1&anyfield=" + encodedQueryStr;
}
}
url += "&filetype=.json";
return url;
},
GetStreetSmartServiceUrl: function () {
var url = 'http://streetsmartdemo.cloudapp.net/roadGraphProb?';
var lat = tf.consts.defaultLatitude, lng = tf.consts.defaultLongitude;
url += 'userLat=' + lat + '&userLng=' + lng + '&showRealTime=true';
return url;
},
itpaObjectName: "itpaObject",
mapHomeCenter: [- 80.37158562505189, 25.755917973237928],
mapHomeCenterOld: [-80.3762, 25.764],
mapBBCCenter: [-80.140366, 25.910629],
mapBBCCenterOld: [-80.14427913856048, 25.91346867681252],
mapInitialLevel: 14,
mapExtent: [-80.497512, 25.634097, -80.047760, 25.972819],
mapMinLevel: 10,
mapMaxLevel: 17,
pkRecommendationsDecalMap: undefined,
GetMapSettings: function () {
return {
container: "mapContainer",
canRotate: false,
center: ITPACore.mapHomeCenter,
level: ITPACore.mapInitialLevel,
mapType: "map",
viewSettings: {
enableRotation: false,
minLevel: ITPACore.mapMinLevel,
maxLevel: ITPACore.mapMaxLevel
},
showMapCenter: false,
goDBOnDoubleClick: false,
noNativePopups: true,
noNativeControls: true,
noScaleLine: true,
panels: undefined
};
},
geolocationWatchSettings: {
timeout: 8000,
enableHighAccuracy: false,
maximumAge: Infinity
},
occupancyColors: [
{ index: 0, text: "1%", color: "#640f0f" }, { index: 1, text: "10%", color: "#8c0f0f" }, { index: 2, text: "20%", color: "#af1616" },
{ index: 3, text: "30%", color: "#ff3c1e" }, { index: 4, text: "40%", color: "#f06a1e" }, { index: 5, text: "50%", color: "#f5b91e" },
{ index: 6, text: "60%", color: "#f8e71c" }, { index: 7, text: "70%", color: "#b4d200" }, { index: 8, text: "80%", color: "#82ba00" },
{ index: 9, text: "90%", color: "#4a8e00" }, { index: 10, text: "99%", color: "#217a00" },
],
occupancyUnknownColor: "#bfbfbf",
stopBkColor: '#ffe57f',
GetColorIndexForOccupancy01: function (oc01) {
var colorIndex = undefined;
if (oc01 !== undefined) {
var nColors = ITPACore.occupancyColors.length - 1;
oc01 = tf.js.NumberClip(tf.js.GetFloatNumber(oc01, 1), 0, 1);
colorIndex = Math.floor(oc01 * nColors);
}
return colorIndex;
},
GetPercentStrFrom01: function (occ01) { return Math.round(100 * occ01) + '%'; },
GetColorForOccupancy01: function (oc01) {
var colorIndex = ITPACore.GetColorIndexForOccupancy01(oc01);
return colorIndex == undefined ? ITPACore.occupancyUnknownColor : ITPACore.occupancyColors[colorIndex].color;
},
busFeatureName: "bus", msgFeatureName: "msg", incFeatureName: "inc", garFeatureName: "gar", occFeatureName: "occ",
stopsFeatureName: "stp", linesFeatureName: "lns", searchFeatureName: "sch", etaFeatureName: "eta",
directionsFeatureName: "dir", ssgFeatureName: "ssg", pkrecFeatureName: "pkr",
serviceErrorRetryMillis: 60000,
layerNames: undefined,
layerZIndices: undefined,
keyNames: undefined,
needsUpdateItemData: undefined,
featureStyles: undefined,
featureButtonIcons: undefined,
featureButtonIconsArray: undefined,
featureRefreshStyleOnUpdate: undefined,
externalFeatureRefreshStyleOnUpdate: undefined,
featureFilterAddItems: undefined,
featurePreProcessServiceData: undefined,
featureLayerMinMaxLevels: undefined,
AreMapCoordsInsideExtent: function (coords) {
var mapExtent = ITPACore.mapExtent;
return coords[0] >= mapExtent[0] && coords[0] <= mapExtent[2] && coords[1] >= mapExtent[1] && coords[1] <= mapExtent[3];
},
IsMapPointFeatureInsideExtent: function (itemData) {
var isInside = false;
try {
var geometry = !!itemData ? itemData.geometry : null;
if (!!geometry) { isInside = ITPACore.AreMapCoordsInsideExtent(geometry.coordinates); }
}
catch (e) { isInside = false; }
return isInside;
},
GetAllFeatureNames: function () {
return [ITPACore.busFeatureName, ITPACore.msgFeatureName, ITPACore.incFeatureName, ITPACore.garFeatureName, ITPACore.ssgFeatureName,
ITPACore.occFeatureName, ITPACore.stopsFeatureName, ITPACore.linesFeatureName, ITPACore.searchFeatureName, ITPACore.directionsFeatureName, ITPACore.etaFeatureName,
ITPACore.pkrecFeatureName
]
},
GetFeaturesWithMapLayersNames: function () {
return [ITPACore.busFeatureName, ITPACore.msgFeatureName, ITPACore.incFeatureName, ITPACore.garFeatureName, ITPACore.ssgFeatureName,
ITPACore.occFeatureName, ITPACore.stopsFeatureName, ITPACore.linesFeatureName, ITPACore.searchFeatureName,
ITPACore.directionsFeatureName]
},
getFeatureListFromData: function (data) {
if (tf.js.GetIsValidObject(data) && tf.js.GetIsArray(data.features)) { data = data.features; }
else { data = undefined; }
return data;
},
getMonthDay: function (itpaDateStamp) {
var dt = tf.js.GetDateFromTimeStamp(itpaDateStamp);
var day = dt.getDate();
var mon = dt.getMonth();
return (mon + 1) + '/' + day;
},
getAmPmHourWithSecs: function (itpaDateStamp) {
var str = itpaDateStamp.substring(11, 11 + 8);
var hourStr = str.substring(0, 2);
var hour = parseInt(hourStr, 10);
var minStr = str.substring(3, 5);
var secStr = str.substring(6, 8);
var ispm = hour > 12;
var ampm = ispm ? ' pm' : ' am';
hourStr = ispm ? hour - 12 : hour;
return hourStr + ':' + minStr + ':' + secStr + ampm;
},
getAmPmHour: function (itpaDateStamp) {
var str = itpaDateStamp.substring(11, 11 + 5);
var hourStr = str.substring(0, 2);
var hour = parseInt(hourStr, 10);
var minStr = str.substring(3, 5);
var ispm = hour > 12;
var ampm = ispm ? ' pm' : ' am';
hourStr = ispm ? hour - 12 : hour;
return hourStr + ':' + minStr + ampm;
},
addFeatureItemFunctions: undefined,
GetAddFeatureItemFunction: function (featureName) {
if (ITPACore.addFeatureItemFunctions == undefined) {
ITPACore.addFeatureItemFunctions = {};
ITPACore.addFeatureItemFunctions[ITPACore.busFeatureName] = function (item) {
var p = item.GetData().properties;
item.featureName = ITPACore.busFeatureName;
item.lineItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.linesFeatureName, p.line_id);
item.prevLineItem = item.lineItem;
};
ITPACore.addFeatureItemFunctions[ITPACore.stopsFeatureName] = function (item) {
item.featureName = ITPACore.stopsFeatureName;
item.nLines = 0;
item.lines = {};
};
ITPACore.addFeatureItemFunctions[ITPACore.msgFeatureName] = function (item) {
item.featureName = ITPACore.msgFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.incFeatureName] = function (item) {
item.featureName = ITPACore.incFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.garFeatureName] = function (item) {
item.featureName = ITPACore.garFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.occFeatureName] = function (item) {
item.featureName = ITPACore.occFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.pkrecFeatureName] = function (item) {
item.featureName = ITPACore.pkrecFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.ssgFeatureName] = function (item) {
item.featureName = ITPACore.ssgFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.linesFeatureName] = function (item) {
item.featureName = ITPACore.linesFeatureName;
item.nBuses = 0;
item.busList = {};
item.busKeyList = {};
};
ITPACore.addFeatureItemFunctions[ITPACore.searchFeatureName] = function (item) {
item.featureName = ITPACore.searchFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.directionsFeatureName] = function (item) {
item.featureName = ITPACore.directionsFeatureName;
};
ITPACore.addFeatureItemFunctions[ITPACore.etaFeatureName] = function (item) {
item.featureName = ITPACore.etaFeatureName;
};
}
return ITPACore.addFeatureItemFunctions[featureName];
},
DirNameAbrevs: { 'eastbound': 'EB', 'westbound': 'WB', 'northbound': 'NB', 'southbound': 'SB', 'clockwise': 'CW', 'counterclockwise': 'CC', 'loop': 'LP' },
AbbreviateDirection: function (dirName) {
var dirNameUse = tf.js.GetNonEmptyString(dirName, "").toLowerCase();
var abrev = ITPACore.DirNameAbrevs[dirNameUse];
return abrev ? abrev : '??';
},
delFeatureItemFunctions: undefined,
GetDelFeatureItemFunction: function (featureName) {
if (ITPACore.delFeatureItemFunctions == undefined) {
ITPACore.delFeatureItemFunctions = {};
ITPACore.delFeatureItemFunctions[ITPACore.busFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.stopsFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.msgFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.incFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.garFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.occFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.pkrecFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.ssgFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.linesFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.searchFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.directionsFeatureName] = function (item) {
};
ITPACore.delFeatureItemFunctions[ITPACore.etaFeatureName] = function (item) {
};
}
return ITPACore.delFeatureItemFunctions[featureName];
},
GetETABriefMessage: function (etaList) {
var nextStr;
if (etaList != undefined) {
var count = etaList.count;
var isOne = count == 1;
var name = etaList.etaDestItemFeature == ITPACore.stopsFeatureName ? (isOne ? "bus" : "buses") : (isOne ? "stop" : "stops");
nextStr = count + ' ' + name;
}
else { nextStr = "---"; }
return nextStr;
},
GetHeadingIcon: function (heading) {
var headingIcon = '<i class="itpa-up-arrow-icon iconInCardText"';
heading = tf.js.GetFloatNumber(heading);
var styles = tf.GetStyles();
var transformStr = styles.GetSupportedTransformProperty();
var rotateStr = styles.GetRotateByDegreeTransformStr(heading);
headingIcon += ' style="' + transformStr + ':' + rotateStr + ';width:1.2rem;"';
return headingIcon + '></i>';
},
updateFeatureItemFunctions: undefined,
utmaSWId: 15000,
MakeNumberFrom: function (numberCandidate, maxNumber) {
var result = undefined;
try { result = parseInt(numberCandidate, 10); }
catch (e) { result = undefined; }
if (isNaN(result)) {
var len = numberCandidate.length, mult = 1;
result = 0;
for (var i = len - 1; i >= 0; --i, mult *= 26) {
result += numberCandidate.charCodeAt(i) * mult;
}
}
return result % maxNumber;
},
GetUpdateFeatureItemFunction: function (featureName) {
if (ITPACore.updateFeatureItemFunctions == undefined) {
ITPACore.updateFeatureItemFunctions = {};
ITPACore.updateFeatureItemFunctions[ITPACore.busFeatureName] = function (item) {
//{"datetime":"2016-05-24 03:04:57.0","heading":"0","line_id":"12","public_transport_vehicle_id":"4011155","speed":"0.0"}}
//item.featureName = ITPACore.busFeatureName;
var p = item.GetData().properties;
item.lineItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.linesFeatureName, p.line_id);
var lineP = item.lineItem ? item.lineItem.GetData().properties : undefined;
item.lineId = p.line_id;
item.fleet = p.fleet.toUpperCase();
if (lineP) {
if (item.fleet == 'FIU') {
var lowerName = lineP.name.toLowerCase();
item.lineStr = (lowerName.indexOf('cats') >= 0) ? 'CATS' : 'GPE';
}
else {
item.lineStr = lineP.fleet_id.slice(-4);
}
item.lineColor = lineP.color;
}
else {
item.lineColor = "#fff";
item.lineStr = "?";
}
var etaCount = item.etaList ? item.etaList.etas.length : 0;
var dateTimeMsg = ITPACore.getAmPmHourWithSecs(p.datetime);
item.heading = tf.js.GetFloatNumber(p.heading);
item.fleet_id = p.name;
item.title = p.name;
var cardTitle = p.name + ' - ' + etaCount;
item.etaCount = etaCount;
item.hasETAs = !!etaCount;
var speed = p.speed !== undefined ? p.speed.toFixed(0) : 0;
item.msg = p.direction + '<br>' + (speed != 0 ? + speed + 'mph' : 'idle');
item.cardTitle = cardTitle;
item.cardMsg = dateTimeMsg;
item.order = p.order;
};
ITPACore.updateFeatureItemFunctions[ITPACore.stopsFeatureName] = function (item) {
//{"identifier":"SW 107 AV@# 917 (NTW TIRE)","platform_id":"525"}
//item.featureName = ITPACore.stopsFeatureName;
var p = item.GetData().properties;
item.title = p.identifier;
item.msg = ITPACore.GetETABriefMessage(item.etaList);
item.cardTitle = item.title;
item.cardMsg = item.msg;
};
ITPACore.updateFeatureItemFunctions[ITPACore.msgFeatureName] = function (item) {
//item.featureName = ITPACore.msgFeatureName;
var p = item.GetData().properties;
item.title = !!p.message ? p.message.toUpperCase() : "Unidentified message";
item.msg = p.message_board_location;
item.longTitle = item.title;
//item.timeStamp = ITPACore.getMonthDay(p.update_time) + ' ' + ITPACore.getAmPmHour(p.update_time);
var len = item.title.length;
var maxlenTitle = 16;
var maxlenMsg = 18;
if (len > maxlenTitle && len > item.msg.length) {
item.title = item.title.substring(0, maxlenTitle) + '...';
}
item.cardTitle = item.title;
item.cardMsg = item.msg;
if (item.cardMsg.length > maxlenMsg) {
item.cardMsg = item.cardMsg.substring(0, maxlenMsg) + '...';
}
//item.order = p.message_board_id;
item.order = item.title;
};
ITPACore.updateFeatureItemFunctions[ITPACore.incFeatureName] = function (item) {
//item.featureName = ITPACore.incFeatureName;
var p = item.GetData().properties;
item.msg = 'ongoing';
if (!!p.external_incident_type) {
item.title = p.external_incident_type;
/*if (!!p.dispatch_time) {
if (!!p.arrival_time) { item.msg = 'arrival @ ' + ITPACore.getAmPmHour(p.arrival_time); }
else { item.msg = 'dispatch @ ' + ITPACore.getAmPmHour(p.dispatch_time); }
}*/
}
else { item.title = "Unidentified Incident"; }
item.cardTitle = item.title;
item.cardMsg = item.msg;
if (tf.js.GetIsNonEmptyString(p.remarks)) {
//item.msg = p.remarks + '<br/>' + item.msg;
//item.msg = p.remarks;
item.msg = item.cardMsg = p.remarks;
}
else { item.msg = ""; }
item.order = item.title;
//item.order = p.event_id;
};
ITPACore.updateFeatureItemFunctions[ITPACore.garFeatureName] = function (item) {
//item.featureName = ITPACore.garFeatureName;
var p = item.GetData().properties;
var hasOccupancy = false;
if (item.occupancyItem == undefined) { item.occupancyItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.occFeatureName, item.GetKey()); }
item.title = p.identifier;
var op;
if (!!item.occupancyItem) {
op = item.occupancyItem.GetData().properties;
if (op.available_percentage_str != undefined) {
var ocp = op.available_01;
var ocpColor = ITPACore.GetColorForOccupancy01(ocp);
item.msgPlain = op.available_percentage_str + ' Available';
item.msg = '<span class="pkAvail-span" style="background-color:' + ocpColor + '">' + op.available_percentage_str + ' Available' + '</span><br/>';
item.occupancyColor = ocpColor;
hasOccupancy = true;
}
}
if (!hasOccupancy) {
item.msg = p.capacity + ' spaces';
item.occupancyColor = ITPACore.occupancyUnknownColor;
item.msgPlain = item.msg;
}
/*
item.occupancyColor = ITPACore.GetColorForOccupancy01(1);
item.msg = p.capacity + ' spaces';
*/
item.cardTitle = item.title;
item.cardMsg = item.msgPlain;
item.order = p.parking_site_id;
if (hasOccupancy) {
for (var i in op.items) {
var opItem = op.items[i]
var ocpColor = ITPACore.GetColorForOccupancy01(opItem.available_01);
var thisDecalStr = '<span class="pkAvail-span" style="background-color:' + ocpColor + '">' + opItem.available_percentage_str + ' ' + opItem.decalGroup + '</span> ';
item.msg += thisDecalStr;
}
}
if (item.pkRecommendations != undefined) {
var pkRec = item.pkRecommendations;
var recDecals = !!pkRec ? pkRec.decals : undefined;
var hasRecommendations = !!recDecals;
if (hasRecommendations) {
var decalMap = ITPACore.pkRecommendationsDecalMap;
if (decalMap != undefined) {
var allHTML = "<br/>Recommended parking areas:<br/>";
var foundOneRecommendation = false;
for (var i in recDecals) {
var r = recDecals[i];
var decal = decalMap[r.id + ''];
if (!!decal) {
var area = r.area;
var recStr = decal.name + ': ';
if (!!area) {
recStr += 'Level ' + area.level.level + ' - ' + area.label;
foundOneRecommendation = true;
}
else {
//recStr += 'none';
continue;
}
var thisHTML = '<span class="pkRec-span">' + recStr + '</span> ';
allHTML += thisHTML;
}
}
if (foundOneRecommendation) {
item.msg += allHTML;
}
}
}
}
};
ITPACore.updateFeatureItemFunctions[ITPACore.occFeatureName] = function (item) {
//item.featureName = ITPACore.occFeatureName;
if (item.garageItem == undefined) { item.garageItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.garFeatureName, item.GetKey()); }
if (!!item.garageItem) { ITPACore.updateFeatureItemFunctions[ITPACore.garFeatureName](item.garageItem); }
item.cardTitle = item.title;
item.cardMsg = item.msg;
//item.order = p.parking_site_id;
};
ITPACore.updateFeatureItemFunctions[ITPACore.pkrecFeatureName] = function (item) {
console.log('updateFeatureItemFunctions for pk rec');
};
ITPACore.updateFeatureItemFunctions[ITPACore.ssgFeatureName] = function (item) {
item.cardTitle = "";
item.cardMsg = "";
};
ITPACore.updateFeatureItemFunctions[ITPACore.linesFeatureName] = function (item) {
//{"identifier":"GPE_PALMETTO_MMC_BBC","color":"#b78400","line_number":"1","platform_ids":[8,7,9],"line_id":"16"}}
//item.featureName = ITPACore.linesFeatureName;
/*if (item.nBuses == undefined) {
item.nBuses = 0;
item.busList = {};
item.busKeyList = {};
}*/
var d = item.GetData();
var p = d.properties;
var title = p.fleet_id.substring(p.fleet_id.length - 4) + ' ' + p.identifier;
item.order = d.order;
item.lineColor = p.color;
item.title = title;
//item.title = item.order + '';
p.direction = '';
var nDirections = p.direction_names.length;
for (var i = 0; i < nDirections; ++i) {
if (i > 0) { p.direction += ' | '; }
p.direction += ITPACore.AbbreviateDirection(p.direction_names[i]);
}
item.msg = p.direction.toUpperCase();
item.cardTitle = item.title;
item.cardMsg = item.msg;
};
ITPACore.updateFeatureItemFunctions[ITPACore.searchFeatureName] = function (item) {
//item.featureName = ITPACore.searchFeatureName;
var d = item.GetData();
var p = d.properties;
item.order = d.order;
item.title = p.Display_Label;
item.msg = p.Display_Summary_Short_Text;
item.link = undefined;
if (tf.js.GetIsNonEmptyString(p.detailquery)) {
//p.detailquery = "http://cnn.com";
item.link = ITPACore.CreateVisitWebSiteLink(p.detailquery, undefined, true);
//item.link = ITPACore.CreateVisitWebSiteLink(p.detailquery, "console.log('here');", true);
}
item.cardTitle = item.title;
item.cardMsg = item.msg;
};
ITPACore.updateFeatureItemFunctions[ITPACore.directionsFeatureName] = function (item) {
var d = item.GetData();
var p = d.properties;
//lengthMeters, timeInSeconds
//p.lengthMeters;
//p.timeInSeconds;
item.order = d.order;
var displayLen = ITPACore.GetDisplayLength(p.lengthMeters);
var displayTime = ITPACore.GetDisplayTime(p.timeInSeconds);
var strMore = "";
if (!!displayLen || !!displayTime) {
strMore = "(";
if (!!displayLen) { strMore += displayLen; }
if (!!displayLen && !!displayTime) { strMore += ' '; }
if (!!displayTime) { strMore += displayTime; }
strMore += ")";
}
var title = (d.order + 1) + '-' + p.instruction + strMore;
item.title = title;
item.msg = p.streetName;
item.cardTitle = title;
item.cardMsg = item.msg;
item.isBusDirection = d.isBusDirection;
};
ITPACore.updateFeatureItemFunctions[ITPACore.etaFeatureName] = function (item) {
};
}
return ITPACore.updateFeatureItemFunctions[featureName];
},
GetDisplayLength: function (lengthInMeters) {
var str = "";
if (lengthInMeters > 0) {
var lengthInFeet = lengthInMeters * 3.28084;
if (lengthInFeet > 1000) {
var feetInMile = 5280, miles = lengthInFeet / feetInMile;
str = miles.toFixed(1) + 'mi';
}
else {
str = lengthInFeet.toFixed(0) + 'ft';
}
}
return str;
},
GetDisplayTime: function (timeInSeconds) {
var str = "";
if (timeInSeconds > 0) {
var minutes = timeInSeconds / 60;
if (minutes >= 1) {
var hours = minutes / 60;
if (hours >= 1) { str = hours.toFixed(1) + 'h'; }
else { str = minutes.toFixed(0) + 'm'; }
}
else { str = timeInSeconds + 's'; }
}
return str;
},
GetIsDismissedMessage: function (message) {
if (ITPACore.dismissMessages == undefined) { ITPACore.LoadDismissMessages(); }
return tf.js.GetIsNonEmptyString(message) ? ITPACore.dismissMessages.indexOf(message.toLowerCase()) >= 0 : false;
},
GetFeaturePreProcessServiceData: function (featureName) {
if (ITPACore.featurePreProcessServiceData == undefined) {
ITPACore.featurePreProcessServiceData = {};
ITPACore.featurePreProcessServiceData[ITPACore.directionsFeatureName] = function (data) {
// this function is not actually called, processing is done in directionscontrol.js
var data = ITPACore.getFeatureListFromData(data);
return data;
//return ITPACore.getFeatureListFromData(data);
};
ITPACore.featurePreProcessServiceData[ITPACore.busFeatureName] = function (data) {
ITPACore.useBusFullUpdate = ITPACore.needBusFullUpdate;
ITPACore.needBusFullUpdate = false;
data = ITPACore.getFeatureListFromData(data);
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.msgFeatureName] = function (data) {
var data = ITPACore.getFeatureListFromData(data);
if (!!data) {
var filteredData = [];
for (var i in data) {
var d = data[i], p = d.properties;
var message = p.message;
if (ITPACore.GetIsDismissedMessage(message)) {
//console.log('dismissed message: ' + message);
}
else {
p.isFarFromDirections = ITPACore.GetIsFilteringMsgForDistance() ? ITPACore.GetIsFarFromDirections(d.geometry.coordinates) : false;
filteredData.push(d);
}
}
data = filteredData;
}
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.incFeatureName] = function (data) {
var data = ITPACore.getFeatureListFromData(data);
if (!!data) {
for (var i in data) {
var d = data[i];
d.properties.isFarFromDirections = ITPACore.GetIsFilteringIncForDistance() ? ITPACore.GetIsFarFromDirections(d.geometry.coordinates) : false;
}
}
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.garFeatureName] = function (data) {
var data = ITPACore.getFeatureListFromData(data);
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.occFeatureName] = function (data) {
var newData = [], newDataById = {};
var garList = !!ITPACore.featureLayers ? ITPACore.featureLayers.GetKeyedList(ITPACore.garFeatureName) : undefined;
if (!!garList) {
var garItems = garList.GetKeyedItemList();
for (var i in garItems) {
var garItem = garItems[i], gard = garItem.GetData(), garg = gard.geometry, garp = gard.properties;
var occItem = {
properties: {
garageItem: garItem,
parking_site_id: garp.parking_site_id,
identifier: garp.identifier,
available_01: undefined,
available_percentage_str: undefined,
available: 0,
total: 0,
items: []
},
geometry: {
type: 'point',
coordinates: garp.centroid
}
}
newDataById['' + occItem.properties.parking_site_id] = occItem;
newData.push(occItem);
}
}
var garItemsToUpdate = {}, ngarItemsToUpdate = 0;
data = data ? data.data : undefined;
for (var i in data) {
var d = data[i], id = d.site_id, idk = '' + id;
var occData = newDataById[idk];
if (!!occData) {
var occp = occData.properties;
occp.total += d.total;
occp.available += d.available;
occp.available_01 = occp.total > 0 ? occp.available / occp.total : 0;
//occp.available_01 = Math.random();
occp.available_percentage_str = ITPACore.GetPercentStrFrom01(occp.available_01);
var group_available_01 = d.total > 0 ? d.available / d.total : 0;
occp.items.push({ decalGroup: d.decalgroup, total: d.total, available: d.available, available_01: group_available_01, available_percentage_str: ITPACore.GetPercentStrFrom01(group_available_01) });
var garKey = '' + occp.parking_site_id;
if (garItemsToUpdate[garKey] == undefined) {
garItemsToUpdate[garKey] = occp.garageItem;
++ngarItemsToUpdate;
}
}
}
if (ngarItemsToUpdate > 0) {
setTimeout(function () {
for (var i in garItemsToUpdate) {
garItemsToUpdate[i].NotifyUpdated();
}
}, 200);
}
return newData;
};
ITPACore.featurePreProcessServiceData[ITPACore.pkrecFeatureName] = function (data) {
var newData = [], newDataById = {};
data = data ? data.data : undefined;
var garList = !!ITPACore.featureLayers ? ITPACore.featureLayers.GetKeyedList(ITPACore.garFeatureName) : undefined;
if (!!garList) {
var garItems = garList.GetKeyedItemList();
for (var i in garItems) { garItems[i].pkRecommendations = undefined; }
if (tf.js.GetIsNonEmptyArray(data)) {
for (var i in data) {
var d = data[i];
var site = d.site;
var siteId = site.id;
var decal = d.decal;
var decalId = decal.id;
var area = d.area;
var key = siteId + '';
var decalKey = decalId + '';
var existingItem = newDataById[key];
if (existingItem == undefined) {
var garItem = garList.GetItem(siteId);
if (!!garItem) {
newDataById[key] = existingItem = {
garItem: garItem,
key: key,
siteId: siteId,
decals: {}
};
}
//else { console.log('recommendation for unknown parking site id: ' + siteId); }
}
if (!!existingItem) {
existingItem.decals[decalKey] = {
key: decalKey,
id: decalId,
area: area
};
}
}
for (var i in newDataById) {
var nd = newDataById[i];
nd.garItem.pkRecommendations = nd;
newData.push(nd);
}
}
}
return newData;
};
ITPACore.featurePreProcessServiceData[ITPACore.ssgFeatureName] = function (data) {
if (!!data) {
if (tf.js.GetIsNonEmptyArray(data.blocks)) {
var newData = [];
var occupancyColors = ITPACore.occupancyColors;
var nMultiLines = occupancyColors.length, nColors = nMultiLines - 1;
var multiLineCoords = new Array(nMultiLines);
data = data.blocks;
for (var i in data) {
var block = data[i];
var colorIndex = tf.js.NumberClip(tf.js.GetFloatNumber(block.realTimeProbability, 1), 0, 1);
var node1Coords = [block.node1.lng, block.node1.lat];
var node2Coords = [block.node2.lng, block.node2.lat];
colorIndex = Math.floor(colorIndex * nColors);
if (multiLineCoords[colorIndex] == undefined) { multiLineCoords[colorIndex] = []; }
multiLineCoords[colorIndex].push([node1Coords, node2Coords]);
}
for (var i = 0; i < nMultiLines; ++i) {
var thisCoords = multiLineCoords[i];
if (thisCoords !== undefined) {
var properties = {
realTimeProbability: i / 10, color_index: i, text: occupancyColors[i].text,
color: occupancyColors[i].color, occupancyColors: occupancyColors
};
var geometry = { type: "multilinestring", coordinates: thisCoords };
var itemData = { properties: properties, geometry: geometry, type: "Feature" };
newData.push(itemData);
}
}
data = newData;
}
else { data = undefined; }
}
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.stopsFeatureName] = function (data) {
var data = ITPACore.getFeatureListFromData(data);
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.linesFeatureName] = function (data) {
var data = tf.js.GetIsArray(data) ? data : undefined;
if (!!data) {
for (var i in data) {
var d = data[i];
if (d.fleet == 'utma') { d.direction_names[0] = 'Loop'; }
}
data.sort(function (a, b) {
var pa = a.properties, pb = b.properties;
var fa = pa.fleet, fb = pb.fleet;
var fleet_names = ['utma', 'fiu'];
for (var i in fleet_names) {
var fn = fleet_names[i];
var fav = fa == fn ? '' : fa;
var fbv = fb == fn ? '' : fb;
if (fav < fbv) { return -1; } else if (fav > fbv) { return 1; }
}
var fia = parseInt(pa.id, 10);
var fib = parseInt(pb.id, 10);
return fia < fib ? -1 : 1;
});
var index = 0;
for (var i in data) {
data[i].order = index++;
}
}
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.searchFeatureName] = function (data) {
var data = ITPACore.getFeatureListFromData(data);
var order = 0;
for (var i in data) { data[i].order = order++; }
//console.log('pre processing search data');
return data;
};
ITPACore.featurePreProcessServiceData[ITPACore.etaFeatureName] = function (data) {
//var data = tf.js.GetIsArray(data) ? data : undefined;
var data = tf.js.GetIsValidObject(data) && tf.js.GetIsArray(data.data) ? data.data : undefined;
return data;
};
}
return ITPACore.featurePreProcessServiceData[featureName];
},
UpdateKeyedItemsForDistanceToRouteFeature: function (kl, doNotFilter) {
if (!!kl) {
var keyedItems = kl.GetKeyedItemList();
for (var i in keyedItems) {
var item = keyedItems[i];
var data = item.GetData(), p = data.properties;
var wasFar = p.isFarFromDirections;
var isFar = !!doNotFilter ? false : ITPACore.GetIsFarFromDirections(data.geometry.coordinates);
p.isFarFromDirections = isFar;
if (isFar != wasFar) {
var mapFeature = ITPACore.featureLayers.GetMapFeatureFromItem(item);
//console.log('changing map feature to: ' + (isFar ? 'FAR' : 'NEAR'));
if (mapFeature) {
mapFeature.RefreshStyle();
}
else {
//console.log('missing map feature');
}
}
}
}
},
GetIsFarFromDirections: function (pointCoords) {
var isFar = false;
if (!!ITPACore.directionsRouteFeature) {
var routeFeatures = !tf.js.GetIsArray(ITPACore.directionsRouteFeature) ? [ITPACore.directionsRouteFeature] : ITPACore.directionsRouteFeature;
var nRouteFeatures = routeFeatures.length;
var isNear = false;
for (var i = 0; i < nRouteFeatures && !isNear; ++i) {
var routeFeature = routeFeatures[i];
var closestPoint = routeFeature.GetClosestPoint(pointCoords);
var distance = tf.units.GetDistanceInMetersBetweenMapCoords(closestPoint, pointCoords);
isNear = distance < ITPACore.minDistanceInMetersToBeFarFromDirections;
}
isFar = !isNear;
}
return isFar;
},
GetFeatureFilterAddItems: function (featureName) {
if (ITPACore.featureFilterAddItems == undefined) {
ITPACore.featureFilterAddItems = {};
ITPACore.featureFilterAddItems[ITPACore.busFeatureName] = function (itemData) {
/*var lastUpdated = tf.js.GetDateFromTimeStamp(itemData.properties.datetime);
var updatedInterval = Date.now() - lastUpdated;
var daysForStale = 2;
var millisForDay = 24 * 60 * 60 * 1000;
//var isNotStale = updatedInterval < daysForStale * millisForDay;
var isNotStale = true;
//var isInsideExtent = ITPACore.IsMapPointFeatureInsideExtent(itemData);
var isInsideExtent = true;
var add = isNotStale && isInsideExtent;
if (!isNotStale) {
//console.log('stale bus discarded');
}
//if (!add) { console.log('BUS outside');}
return add;*/
var p = itemData.properties;
p.prevHeadingInt = p.headingInt = Math.round(p.heading);
p.prevHasETAs = p.hasETAs = false;
p.headingRad = p.headingInt * Math.PI / 180.0;
//if (item.prevHeadingInt == undefined) { item.prevHeadingInt = item.headingInt; }
//item.headingRad = item.headingInt * Math.PI / 180.0
return true;
};
ITPACore.featureFilterAddItems[ITPACore.msgFeatureName] = function (itemData) {
//var add = ITPACore.IsMapPointFeatureInsideExtent(itemData);
//return add;
return true;
};
ITPACore.featureFilterAddItems[ITPACore.incFeatureName] = function (itemData) {
//var add = ITPACore.IsMapPointFeatureInsideExtent(itemData);
//return add;
return true;
};
ITPACore.featureFilterAddItems[ITPACore.garFeatureName] = function (itemData) {
return true;
};
ITPACore.featureFilterAddItems[ITPACore.occFeatureName] = function (itemData) {
/*if (ITPACore.mmcParkingSiteIDs.indexOf(parseInt(itemData.properties.parking_site_id, 10)) >= 0) {
return true;
}
return false;*/
return true;
};
ITPACore.featureFilterAddItems[ITPACore.pkrecFeatureName] = function (itemData) {
return true;
};
ITPACore.featureFilterAddItems[ITPACore.ssgFeatureName] = function (itemData) {
return true;
};
ITPACore.featureFilterAddItems[ITPACore.stopsFeatureName] = function (itemData) {
var add = true;
return add;
};
ITPACore.featureFilterAddItems[ITPACore.linesFeatureName] = function (itemData) {
//{"identifier":"GPE_PALMETTO_MMC_BBC","color":"#b78400","line_number":"1","platform_ids":[8,7,9],"line_id":"16"}}
var add = true;
return add;
};
ITPACore.featureFilterAddItems[ITPACore.searchFeatureName] = function (itemData) {
//var add = ITPACore.IsMapPointFeatureInsideExtent(itemData);
//if (!add) { console.log('SEARCH outside'); }
//return true;
//return add;
return true;
};
ITPACore.featureFilterAddItems[ITPACore.directionsFeatureName] = function (itemData) {
return true;
};
ITPACore.featureFilterAddItems[ITPACore.etaFeatureName] = function (itemData) {
/*var add;
if (itemData.busItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.busFeatureName, itemData.public_transport_vehicle_id)) {
if (itemData.stopItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.stopsFeatureName, itemData.platform_id)) {
itemData.datetime = tf.js.GetDateFromTimeStamp(itemData.eta);
add = true;
}
}
return add;*/
return true;
};
}
return ITPACore.featureFilterAddItems[featureName];
},
minLevelBeforeUCFeature: 14,
GetFeatureLayerMinMaxLevels: function (featureName) {
if (ITPACore.featureLayerMinMaxLevels == undefined) {
ITPACore.featureLayerMinMaxLevels = {};
ITPACore.featureLayerMinMaxLevels[ITPACore.garFeatureName] = { minLevel: ITPACore.minLevelBeforeUCFeature, maxLevel: tf.consts.maxLevel };
ITPACore.featureLayerMinMaxLevels[ITPACore.occFeatureName] = { minLevel: 16, maxLevel: tf.consts.maxLevel };
ITPACore.featureLayerMinMaxLevels[ITPACore.ssgFeatureName] = { minLevel: ITPACore.minLevelBeforeUCFeature, maxLevel: tf.consts.maxLevel };
}
return ITPACore.featureLayerMinMaxLevels[featureName];
},
GetFeatureRefreshStyleOnUpdate: function (featureName) {
if (ITPACore.featureRefreshStyleOnUpdate == undefined) {
ITPACore.featureRefreshStyleOnUpdate = {};
ITPACore.featureRefreshStyleOnUpdate[ITPACore.busFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.msgFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.incFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.garFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.occFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.pkrecFeatureName] = false;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.stopsFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.linesFeatureName] = true;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.searchFeatureName] = false;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.directionsFeatureName] = false;
ITPACore.featureRefreshStyleOnUpdate[ITPACore.etaFeatureName] = false;
}
return ITPACore.featureRefreshStyleOnUpdate[featureName];
},
GetExternalFeatureRefreshStyleOnUpdate: function (featureName) {
if (ITPACore.externalFeatureRefreshStyleOnUpdate == undefined) {
ITPACore.externalFeatureRefreshStyleOnUpdate = {};
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.busFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.msgFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.incFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.garFeatureName] = ITPACore.occFeatureName;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.occFeatureName] = ITPACore.garFeatureName;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.pkrecFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.ssgFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.stopsFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.linesFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.searchFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.directionsFeatureName] = undefined;
ITPACore.externalFeatureRefreshStyleOnUpdate[ITPACore.etaFeatureName] = undefined;
}
return ITPACore.externalFeatureRefreshStyleOnUpdate[featureName];
},
GetGeoCodeFeatureStyleSpecs: function (withHover) {
var scale = withHover ? 0.3 : 0.24, zindex = withHover ? 8 : 4;
if (withHover) {
var style = ITPACore.doGetPreloadedIconStyleSpecs(ITPACore.mapGeoCodeImagePreloaded, scale, [0.5, 1], zindex);
var circleStyle = { circle: true, circle_radius: 6, shape_points: 4, fill: true, fill_color: "#eecc29", zindex: zindex + 1, line: true, line_color: "#213873", line_width: 2 };
return [style, circleStyle];
}
return ITPACore.doGetPreloadedIconStyleSpecs(ITPACore.mapGeoCodeImagePreloaded, scale, [0.5, 1], zindex);
},
GetBBCFeatureStyle: function () {
return [
{ shape: true, shape_radius: 16, shape_points: 5, fill: true, fill_color: "#fff", fill_opacity: 1, zindex: 1 },
{ icon: true, icon_url: "./img/bbcmapicon.svg", snapToPixel: false, icon_anchor: [0.5, 0.5], scale: 1.8, zindex: 2 }
]
},
GetUCFeatureStyle: function () {
return [
{ shape: true, shape_radius: 16, shape_points: 5, fill: true, fill_color: "#fff", fill_opacity: 1, zindex: 1 },
{ icon: true, icon_url: "./img/ucmapicon.svg", snapToPixel: false, icon_anchor: [0.5, 0.5], scale: 1.8, zindex: 2 }
]
},
GetUserLocationFeatureStyle: function () {
return [
/*{ circle: true, circle_radius: 20, fill: true, fill_color: "#fff", fill_opacity: 1, zindex: 1 }*/,
{ icon: true, icon_url: "./img/user position.svg", snapToPixel: false, scale: 1.5, zindex: 2 }
]
},
mapBusGOImagePreloaded: undefined,
mapBusROImagePreloaded: undefined,
mapBusBOImagePreloaded: undefined,
mapDirectionImagePreloaded: undefined,
mapIncImagePreloaded: undefined,
mapIncSelImagePreloaded: undefined,
mapMsgImagePreloaded: undefined,
mapStopImagePreloaded: undefined,
mapSearchImagePreloaded: undefined,
mapGeoCodeImagePreloaded: undefined,
mapDirectionsImagePreloaded: undefined,
PreloadImages: function (callBack, scope) {
if (ITPACore.mapMsgImagePreloaded == undefined) {
ITPACore.mapMsgImagePreloaded = null;
new tf.dom.ImgsPreLoader({
imgSrcs: [
"./img/busGreenOsm.png",
"./img/busRedOsm.png",
"./img/busBlueOsm.png",
"./img/directionsm.png",
"./img/inc.png",
"./img/msgbd on.png",
"./img/stop.png",
"./img/mapPinBlue.png",
"./img/mapPinBlueLight.png",
"./img/incSel.png",
"./img/directionDir.png"
],
onAllLoaded: function (ipl) {
var imgs = ipl.GetImgs();
var index = 0;
ITPACore.mapBusGOImagePreloaded = imgs[index++];
ITPACore.mapBusROImagePreloaded = imgs[index++];
ITPACore.mapBusBOImagePreloaded = imgs[index++];
ITPACore.mapDirectionImagePreloaded = imgs[index++];
ITPACore.mapIncImagePreloaded = imgs[index++];
ITPACore.mapMsgImagePreloaded = imgs[index++];
ITPACore.mapStopImagePreloaded = imgs[index++];
ITPACore.mapSearchImagePreloaded = imgs[index++];
ITPACore.mapGeoCodeImagePreloaded = imgs[index++];
ITPACore.mapIncSelImagePreloaded = imgs[index++];
ITPACore.mapDirectionsImagePreloaded = imgs[index++];
if (!!(callBack = tf.js.GetFunctionOrNull(callBack))) { callBack.apply(scope); }
}
});
}
},
doGetPreloadedIconStyleSpecs: function (preloadedIcon, iconScale, iconAnchor, iconZIndex, iconOpacity) {
var style = {
icon: true, icon_img: preloadedIcon.GetImg(), icon_size: preloadedIcon.GetDimensions(), icon_anchor: iconAnchor,
scale: iconScale, zindex: iconZIndex,
opacity: iconOpacity != undefined ? iconOpacity : 1
};
return style;
},
doGetPreloadedIconStyle: function (preloadedIcon, iconScale, iconAnchor, iconZIndex, iconOpacity) {
//iconScale = iconScale == 1 ? 1.4 :
var style = ITPACore.doGetPreloadedIconStyleSpecs(preloadedIcon, iconScale, iconAnchor, iconZIndex, iconOpacity);
return new tf.map.FeatureStyle(style);
},
doGetIconStyle: function (iconUrl, iconScale, iconAnchor, iconZIndex) {
var style = [
{ icon: true, icon_url: iconUrl, icon_anchor: iconAnchor, scale: iconScale, zindex: iconZIndex, snaptopixel: false }
];
return new tf.map.FeatureStyle(style);
},
busStyleCache: {},
busFeatureStyle: undefined, busFeatureHoverStyle: undefined,
doGetBusStyle: function (item, withHover) {
var scale = withHover ? 0.9 : 0.75;
var scaleD = scale * 0.85;
var zindex = withHover ? 3 : 1;
var p = item.GetData().properties;
var hasETAs = p.hasETAs;
var cacheKey = "";
if (withHover) { cacheKey += 'h-'; } else { cacheKey += 's-'; }
if (hasETAs) { cacheKey += 'y-'; } else { cacheKey += 'n-'; }
cacheKey += '' + p.headingInt;
var cachedStyle = ITPACore.busStyleCache[cacheKey];
if (!cachedStyle) {
//console.log('bs for: ' + cacheKey);
var imgOutline;
if (hasETAs) { zindex++; imgOutline = ITPACore.mapBusBOImagePreloaded; }
else { imgOutline = ITPACore.mapBusROImagePreloaded; }
var style = ITPACore.doGetPreloadedIconStyleSpecs(imgOutline, scale, [0.5, 0.45], zindex);
var dirStyle = ITPACore.doGetPreloadedIconStyleSpecs(ITPACore.mapDirectionImagePreloaded, scaleD, [0.5, 0.5], zindex + 1);
dirStyle.rotation_rad = p.headingRad;
dirStyle.rotate_with_map = true;
ITPACore.busStyleCache[cacheKey] = cachedStyle = new tf.map.FeatureStyle([style, dirStyle]);
} //else { console.log('skipping bs creation'); }
return cachedStyle;
},
dimOpacity: 0.15,
msgFeatureStyle: undefined, msgFeatureHoverStyle: undefined, msgFeatureDimStyle: undefined,
doGetMsgStyle: function (withHover, isDim) {
var scale = withHover ? 0.3 : (isDim ? 0.18 : 0.24), zindex = withHover ? 3 : 1;
var opacity = isDim ? ITPACore.dimOpacity : 1;
if (withHover) {
var style = ITPACore.doGetPreloadedIconStyleSpecs(ITPACore.mapMsgImagePreloaded, scale, [0, 1], zindex, opacity);
var circleStyle = {
circle: true, circle_radius: 6, shape_points: 4, fill: true, fill_color: "#ffc900", zindex: zindex + 1, line: true,
line_color: "#000", line_width: 2
};
return new tf.map.FeatureStyle([style, circleStyle]);
}
return ITPACore.doGetPreloadedIconStyle(ITPACore.mapMsgImagePreloaded, scale, [0, 1], zindex, opacity);
},
incFeatureStyle: undefined, incFeatureHoverStyle: undefined, incFeatureDimStyle: undefined,
doGetIncStyle: function (withHover, isDim) {
var scale = withHover ? 0.4 : (isDim ? 0.24 : 0.3), zindex = withHover ? 3 : 1;
var opacity = isDim ? ITPACore.dimOpacity : 1;
return ITPACore.doGetPreloadedIconStyle(withHover ? ITPACore.mapIncSelImagePreloaded : ITPACore.mapIncImagePreloaded, scale, [0.5, 0.5], zindex, opacity);
},
stopsFeatureStyle: undefined, stopsFeatureHoverStyle: undefined,
doGetStopsStyle: function (withHover) {
var scale = withHover ? 1.4 : 1.1, zindex = withHover ? 3 : 1;
return ITPACore.doGetPreloadedIconStyle(ITPACore.mapStopImagePreloaded, scale, [0.5, 0.5], zindex);
},
searchFeatureStyle: undefined, searchFeatureHoverStyle: undefined,
doGetSearchStyle: function (withHover) {
var scale = withHover ? 0.3 : 0.24, zindex = withHover ? 3 : 1;
if (withHover) {
var style = ITPACore.doGetPreloadedIconStyleSpecs(ITPACore.mapSearchImagePreloaded, scale, [0.5, 1], zindex);
var circleStyle = { circle: true, circle_radius: 6, shape_points: 4, fill: true, fill_color: "#eecc29", zindex: zindex + 1, line: true, line_color: "#213873", line_width: 2 };
return new tf.map.FeatureStyle([style, circleStyle]);
}
return ITPACore.doGetPreloadedIconStyle(ITPACore.mapSearchImagePreloaded, scale, [0.5, 1], zindex);
},
directionsFeatureStyle: undefined, directionsFeatureHoverStyle: undefined,
doGetDirectionsStyle: function (item, withHover) {
var scale = withHover ? 1 : 0.8, zindex = withHover ? 10 : 9;
var circleStyle = { circle: true, circle_radius: 16, fill: true, fill_opacity: 30, fill_color: "#fff", zindex: zindex - 1, line: true, line_color: "#213873", line_width: 1, line_opacity: 50 };
var style = ITPACore.doGetPreloadedIconStyleSpecs(ITPACore.mapDirectionsImagePreloaded, scale, [0.5, 0.5], zindex);
var angle = item.GetData().properties.postTurnDirection * Math.PI / 180;
style.rotation_rad = angle;
style.rotate_with_map = true;
return new tf.map.FeatureStyle([circleStyle, style]);
},
GetFeatureStyle: function (featureName) {
if (ITPACore.featureStyles == undefined) {
ITPACore.featureStyles = {};
ITPACore.featureStyles[ITPACore.busFeatureName] = function getBusStyle(mapFeature, item, isHover) {
ITPACore.busFeatureStyle = ITPACore.doGetBusStyle(item, false);
ITPACore.busFeatureHoverStyle = ITPACore.doGetBusStyle(item, true);
return isHover ? ITPACore.busFeatureHoverStyle : ITPACore.busFeatureStyle;
};
ITPACore.featureStyles[ITPACore.msgFeatureName] = function getMsgStyle(mapFeature, item, isHover) {
return isHover ? ITPACore.doGetMsgStyle(true, false) :
(item.GetData().properties.isFarFromDirections ? ITPACore.doGetMsgStyle(false, true) : ITPACore.doGetMsgStyle(false, false));
}
ITPACore.featureStyles[ITPACore.incFeatureName] = function getStyle(mapFeature, item, isHover) {
return isHover ? ITPACore.doGetIncStyle(true, false) :
(item.GetData().properties.isFarFromDirections ? ITPACore.doGetIncStyle(false, true) : ITPACore.doGetIncStyle(false, false));
};
ITPACore.featureStyles[ITPACore.stopsFeatureName] = function getStyle(mapFeature, item, isHover) {
if (ITPACore.stopsFeatureStyle == undefined) {
ITPACore.stopsFeatureStyle = ITPACore.doGetStopsStyle(false);
ITPACore.stopsFeatureHoverStyle = ITPACore.doGetStopsStyle(true);
}
return isHover ? ITPACore.stopsFeatureHoverStyle : ITPACore.stopsFeatureStyle;
};
ITPACore.featureStyles[ITPACore.garFeatureName] = function getStyle(mapFeature, item, isHover) {
var fillColor;
var key = item.GetKey();
var occItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.occFeatureName, item.GetKey());
var hasOccupancy = false;
if (occItem) {
var occData = occItem.GetData(), occp = occData.properties;
if (!!occp.available_percentage_str) {
hasOccupancy = true;
fillColor = ITPACore.GetColorForOccupancy01(occp.available_01);
}
}
if (!hasOccupancy) { fillColor = ITPACore.occupancyUnknownColor; }
var lineOpacity = isHover ? 70 : 50, lineWidth = isHover ? 3 : 1, zIndex = isHover ? 3 : 1;
return { line: true, line_color: "#00f", line_opacity: lineOpacity, line_width: lineWidth, fill: true, fill_color: fillColor, zindex: zIndex };
};
ITPACore.featureStyles[ITPACore.ssgFeatureName] = function getStyle(mapFeature, item, isHover) {
var p = !!item ? item.GetData().properties : undefined;
var line_color = !!p ? p.color : vacancyUnknownColor;
var around_line_color = isHover ? "#000" : "#88a";
var lineWidth = isHover ? 10 : 6;
return [
{ line: true, line_width: lineWidth + 4, line_color: around_line_color, zindex: 1, line_opacity: 70, line_dash: [20, 10] },
{ line: true, line_width: lineWidth, line_color: line_color, line_opacity: 100, zindex: 2, line_dash: [20, 10] }
];
};
ITPACore.featureStyles[ITPACore.occFeatureName] = function getStyle(mapFeature, item, isHover) {
var occData = item.GetData(), occp = occData.properties, font = "1rem arial", fillColor = "#fff", lineColor = "#000", lineWidth = 2;
var garItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.garFeatureName, item.GetKey());
var label = garItem ? garItem.GetData().properties.identifier.toLowerCase() : "";
var lineWidth = isHover ? 2 : 1;
var zindex = isHover ? 6 : 1;
var marker_color = "#fff";
if (occp.available_percentage_str != undefined) {
label += ' ' + occp.available_percentage_str;
marker_color = "#ffd";
zindex = isHover ? 7 : 2;
}
isHover = true;
var markerOpacity = isHover ? 100 : 80;
var baseStyle = {
marker_horpos: "center", marker_verpos: "center",
marker: true, label: label, font_height: isHover ? 18 : 15, zindex: zindex, marker_color: marker_color, font_color: isHover ? "#008" : "#008",
line_width: lineWidth, line_color: "#ffffff", marker_opacity: markerOpacity, border_opacity: 60, border_color: "#000"
};
return baseStyle;
};
ITPACore.featureStyles[ITPACore.linesFeatureName] = function getStyle(mapFeature, item, isHover) {
var lineWidth = 3, zindex = isHover ? 5 : 1;
var lineWidthTick = lineWidth * 2 + 1;
var lineItemColor = item.GetData().properties.color;
var style = { line: true, line_color: lineItemColor, line_width: lineWidth, zindex: zindex };
if (isHover) { style.line_dash = [20, 20]; style.line_color = "#fff"; };
return isHover ? [{ line: true, line_color: "#000", line_width: lineWidthTick + 2, zindex: 3 },
{ line: true, line_color: lineItemColor, line_width: lineWidthTick, zindex: 4 }, style] : style;
}
ITPACore.featureStyles[ITPACore.searchFeatureName] = function getStyle(mapFeature, item, isHover) {
if (ITPACore.searchFeatureStyle == undefined) {
ITPACore.searchFeatureStyle = ITPACore.doGetSearchStyle(false);
ITPACore.searchFeatureHoverStyle = ITPACore.doGetSearchStyle(true);
}
return isHover ? ITPACore.searchFeatureHoverStyle : ITPACore.searchFeatureStyle;
};
ITPACore.featureStyles[ITPACore.directionsFeatureName] = function getStyle(mapFeature, item, isHover) {
return ITPACore.doGetDirectionsStyle(item, isHover);
};
}
return ITPACore.featureStyles[featureName];
},
RefreshMapFeatureStyle: function (item, mapFeature) {
if (item.featureName == ITPACore.busFeatureName) {
var d = item.GetData(), p = d.properties;
p.hasETAs = item.etaCount > 0;
p.headingInt = Math.round(p.heading);
if (p.prevHadETAs != p.hasETAs || p.prevHeadingInt != p.headingInt) {
p.headingRad = p.headingInt * Math.PI / 180.0;
p.prevHadETAs = p.hasETAs;
p.prevHeadingInt = p.headingInt;
mapFeature.RefreshStyle();
} //else { console.log('skipping bus map feature refresh'); }
}
else {
mapFeature.RefreshStyle();
}
},
needBusFullUpdate: false,
useBusFullUpdate: false,
GetNeedsUpdateItemData: function (featureName) {
if (ITPACore.needsUpdateItemData == undefined) {
ITPACore.needsUpdateItemData = {};
ITPACore.needsUpdateItemData[ITPACore.busFeatureName] = function (updateObj) {
if (ITPACore.useBusFullUpdate) { return true; }
//return true;
var coordsOld = updateObj.itemData.geometry.coordinates;
var coordsNew = updateObj.itemDataSet.geometry.coordinates;
var pOld = updateObj.itemData.properties;
var pNew = updateObj.itemDataSet.properties;
pOld.order = pNew.order;
return coordsOld[0] != coordsNew[0] ||
coordsOld[1] != coordsNew[1] ||
pOld.name != pNew.name ||
pOld.line_id != pNew.line_id ||
pOld.datetime != pNew.datetime ||
pOld.heading != pNew.heading ||
pOld.number_of_occupants != pNew.number_of_occupants;
};
ITPACore.needsUpdateItemData[ITPACore.msgFeatureName] = function (updateObj) {
var coordsOld = updateObj.itemData.geometry.coordinates;
var coordsNew = updateObj.itemDataSet.geometry.coordinates;
if (coordsOld[0] != coordsNew[0] || coordsOld[1] != coordsNew[1]) { return true; }
var props = updateObj.itemData.properties;
var newProps = updateObj.itemDataSet.properties;
if (newProps.isFarFromDirections != props.isFarFromDirections) { return true; }
return props.message != newProps.message;
};
ITPACore.needsUpdateItemData[ITPACore.incFeatureName] = function (updateObj) {
/*var coordsOld = updateObj.itemData.geometry.coordinates;
var coordsNew = updateObj.itemDataSet.geometry.coordinates;
if (coordsOld[0] != coordsNew[0] || coordsOld[1] != coordsNew[1]) { return true; }
return updateObj.itemData.properties.last_updated != updateObj.itemDataSet.properties.last_updated;*/
var props = updateObj.itemData.properties;
var newProps = updateObj.itemDataSet.properties;
if (newProps.isFarFromDirections != props.isFarFromDirections) { return true; }
var geomCoords = updateObj.itemData.geometry.coordinates;
var newGeomCoords = updateObj.itemDataSet.geometry.coordinates;
if (newGeomCoords[0] != geomCoords[0] || newGeomCoords[1] != geomCoords[1]) { return true; }
return props.external_incident_type != newProps.external_incident_type ||
props.dispatch_time != newProps.dispatch_time ||
props.arrival_time != newProps.arrival_time;
},
ITPACore.needsUpdateItemData[ITPACore.garFeatureName] = function (updateObj) {
var p = updateObj.itemData.properties;
var newP = updateObj.itemDataSet.properties;
if (p.is_active != newP.is_active || p.identifier != newP.identifier || p.total_level != newP.total_level || p.capacity != newP.capacity ||
p.parking_site_type_id != newP.parking_site_type_id) {
return true;
}
var g = updateObj.itemData.geometry;
var newG = updateObj.itemDataSet.geometry;
if ((g.coordinates == undefined && newG.coordinates != undefined) || (g.coordinates != undefined && newG.coordinates == undefined)) {
return true;
}
if (g.coordinates != undefined && newG.coordinates != undefined) {
var l = g.coordinates.length;
var nl = newG.coordinates.length;
if (l != nl) { return true; }
if (l == nl && l == 1) {
var c = g.coordinates[0], nc = newG.coordinates[0];
if (c != undefined && nc != undefined) {
l = c.length;
nl = nc.length;
if (l != nl) { return true; }
for (var i = 0; i < l; ++i) {
var cc = c[i];
var ncc = nc[i];
if (cc != undefined && ncc != undefined) {
if (cc.length == 2 && ncc.length == 2) {
if (cc[0] != ncc[0] || cc[1] != ncc[1]) { return true; }
} else { break; }
} else { break; }
}
}
}
}
return false;
}
ITPACore.needsUpdateItemData[ITPACore.occFeatureName] = function (updateObj) {
/*if (updateObj.itemData.properties.occupancy_percentage != updateObj.itemDataSet.properties.occupancy_percentage) { return true; }
var geomCoords = updateObj.itemData.geometry.coordinates;
var newGeomCoords = updateObj.itemDataSet.geometry.coordinates;
if (newGeomCoords[0] != geomCoords[0] || newGeomCoords[1] != geomCoords[1]) { return true; }
return false;*/
return true;
}
ITPACore.needsUpdateItemData[ITPACore.ssgFeatureName] = function (updateObj) {
return true;
}
ITPACore.needsUpdateItemData[ITPACore.stopsFeatureName] = function (updateObj) { return true; }
ITPACore.needsUpdateItemData[ITPACore.linesFeatureName] = function (updateObj) { return true; }
ITPACore.needsUpdateItemData[ITPACore.searchFeatureName] = function (updateObj) { return true; }
ITPACore.needsUpdateItemData[ITPACore.etaFeatureName] = function (updateObj) {
return updateObj.itemData.eta != updateObj.itemDataSet.eta;
}
}
return ITPACore.needsUpdateItemData[featureName];
},
GetKeyName: function (featureName) {
if (ITPACore.keyNames == undefined) {
ITPACore.keyNames = {};
//ITPACore.keyNames[ITPACore.busFeatureName] = "public_transport_vehicle_id";
ITPACore.keyNames[ITPACore.busFeatureName] = "key";
//ITPACore.keyNames[ITPACore.msgFeatureName] = "message_board_id";
ITPACore.keyNames[ITPACore.msgFeatureName] = "id";
//ITPACore.keyNames[ITPACore.incFeatureName] = "event_id";
ITPACore.keyNames[ITPACore.incFeatureName] = "id";
//ITPACore.keyNames[ITPACore.garFeatureName] = "parking_site_id";
ITPACore.keyNames[ITPACore.garFeatureName] = "id";
ITPACore.keyNames[ITPACore.occFeatureName] = "parking_site_id";
ITPACore.keyNames[ITPACore.pkrecFeatureName] = "key";
ITPACore.keyNames[ITPACore.ssgFeatureName] = "color_index";
//ITPACore.keyNames[ITPACore.stopsFeatureName] = "platform_id";
ITPACore.keyNames[ITPACore.stopsFeatureName] = "key";
//ITPACore.keyNames[ITPACore.linesFeatureName] = "line_id";
ITPACore.keyNames[ITPACore.linesFeatureName] = "key";
ITPACore.keyNames[ITPACore.searchFeatureName] = "Display_Link_Detail";
ITPACore.keyNames[ITPACore.directionsFeatureName] = "key";
ITPACore.keyNames[ITPACore.etaFeatureName] = undefined;
}
return ITPACore.keyNames[featureName];
},
GetLayerZIndex: function (featureName) {
if (ITPACore.layerZIndices == undefined) {
var index = 0;
ITPACore.layerZIndices = {};
ITPACore.layerZIndices[ITPACore.garFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.ssgFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.linesFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.busFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.occFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.stopsFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.searchFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.directionsFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.msgFeatureName] = index++;
ITPACore.layerZIndices[ITPACore.incFeatureName] = index++;
}
return ITPACore.layerZIndices[featureName];
},
GetLayerName: function (featureName) {
if (ITPACore.layerNames == undefined) {
ITPACore.layerNames = {};
ITPACore.layerNames[ITPACore.busFeatureName] = "Buses";
ITPACore.layerNames[ITPACore.msgFeatureName] = "Messages";
ITPACore.layerNames[ITPACore.incFeatureName] = "Incidents";
ITPACore.layerNames[ITPACore.garFeatureName] = "Parking";
ITPACore.layerNames[ITPACore.ssgFeatureName] = "StreetSmart";
ITPACore.layerNames[ITPACore.occFeatureName] = "Occupancy";
ITPACore.layerNames[ITPACore.stopsFeatureName] = "Bus Stops";
ITPACore.layerNames[ITPACore.linesFeatureName] = "Bus Lines";
ITPACore.layerNames[ITPACore.searchFeatureName] = "Search Results";
}
return ITPACore.layerNames[featureName];
},
featureLayers: undefined,
CreateFeatureLayers: function (settings, then) {
ITPACore.PreloadImages(function () {
if (ITPACore.featureLayers == undefined && tf.js.GetIsValidObject(settings) && tf.js.GetIsMap(settings.map)) {
ITPACore.featureLayers = new ITPACore.FeatureLayers(settings);
}
then();
});
},
mapFeatureToaster: undefined,
CreateMapFeatureToaster: function (map) {
if (ITPACore.mapFeatureToaster == undefined && tf.js.GetIsMap(map)) {
ITPACore.mapFeatureToaster = new ITPACore.MapFeatureToaster({ map: map });
}
},
mapETAToaster: undefined,
CreateMapETAToaster: function (map) {
if (ITPACore.mapETAToaster == undefined && tf.js.GetIsMap(map)) {
ITPACore.mapETAToaster = new ITPACore.MapETAToaster({ map: map });
}
},
linesAndStopsAreLinked: false,
LinkLinesAndStops: function () {
//console.log("TRYING TO LINK STOPS AND LINES");
if (ITPACore.featureLayers !== undefined) {
var stopsLayer = ITPACore.featureLayers.GetFeatureLayer(ITPACore.stopsFeatureName);
var linesLayer = ITPACore.featureLayers.GetFeatureLayer(ITPACore.linesFeatureName);
if (!!stopsLayer && !!linesLayer) {
var stopsKeyedList = stopsLayer.GetKeyedList();
var linesKeyedList = linesLayer.GetKeyedList();
if (!!stopsKeyedList && !!linesKeyedList) {
var stopsCount = stopsKeyedList.GetItemCount();
var linesCount = linesKeyedList.GetItemCount();
//console.log(linesKeyedList.GetName());
if (stopsCount > 0 && linesCount > 0) {
//console.log("LINKING STOPS " + stopsCount + " AND LINES " + linesCount);
ITPACore.linesAndStopsAreLinked = true;
var lineItems = linesKeyedList.GetKeyedItemList();
var stopItems = stopsKeyedList.GetKeyedItemList();
var lineCount = 0;
for (var i in stopItems) {
var item = stopItems[i];
item.nLines = 0;
item.lines = {};
}
for (var i in lineItems) {
var lineItem = lineItems[i], lineData = lineItem.GetData(), lineDataP = lineData.properties, platformIds = lineDataP.platform_ids, line_id = lineDataP.line_id;
var lineFleet = lineDataP.fleet;
var lineFleedPrefix = lineFleet + '|';
lineItem.lineIndex = lineCount++;
var lineKey = lineItem.GetKey();
//uncomment to debug by line_id
//if (line_id == 26) { line_id = 26; }
var nplats = !!platformIds ? platformIds.length : 0;
for (var j = 0; j < nplats; ++j) {
var platId = platformIds[j];
var platKey = lineFleedPrefix + platId;
var platItem = stopsKeyedList.GetItem(platKey);
if (!!platItem) {
if (platItem.lines[lineKey] == undefined) {
platItem.lines[lineKey] = { lineItem: lineItem, index: j };
++platItem.nLines;
}
else {
if (platItem.lines[lineKey].index == 0 && j == nplats - 1) {
//console.log('LINKING STOPS AND LINES: platform ' + platId + ' is LOOP begin/end for ' + lineKey);
platItem.isLoop = true;
} else { console.log('LINKING STOPS AND LINES: platform ' + platId + ' added twice to line ' + lineKey); }
}
} else { console.log('LINKING STOPS AND LINES: line ' + i + ' is missing platform [' + j + '] = id = ' + platId); }
}
}
//console.log("STOPS AND LINES LINKED");
}
}
}
}
},
ObjectToParams: function (obj) {
var p = {};
for (var key in obj) {
p[key] = encodeURIComponent(obj[key]);
}
return p;
},
CreateVisitWebSiteLink: function (url, thenStr, notIonic) {
var linkStr = "";
if (tf.js.GetIsNonEmptyString(url)) {
var onClickStr = "\"window.open('" + url + "', '_system', 'location=yes'); ";
if (tf.js.GetIsNonEmptyString(thenStr)) { onClickStr += thenStr; }
onClickStr += " return false;\"";
var linkStyle = "text-decoration:none;padding:0px;";
var buttonClass = !!notIonic ? tf.GetStyles().buttonShapedLinkClass : "button button-balanced button-block";
if (!!notIonic) {
linkStyle += "background-color:#33cd5f;padding:4px;padding-left:6px;padding-right:6px;";
}
//var link = "<a class='" + buttonClass + "' href='" + url + "' onclick=" + onClickStr + " style=\"" + linkStyle + "\">";
var link = "<a class='" + buttonClass + "' href='#' onclick=" + onClickStr + " style=\"" + linkStyle + "\">";
linkStr = link + "Visit Website<a/>";
}
return linkStr;
},
global_map_object: undefined,
SetLocalStorageItem: function (itemName, item) {
if (tf.js.GetIsNonEmptyString(itemName) && tf.js.GetIsValidObject(item)) {
try {
var itemStr = JSON.stringify(item);
window.localStorage.setItem(itemName, itemStr);
}
catch (e) { }
}
},
GetLocalStorageItem: function (itemName) {
var item;
if (tf.js.GetIsNonEmptyString(itemName)) {
try {
item = window.localStorage.getItem(itemName);
if (tf.js.GetIsNonEmptyString(item)) {
item = JSON.parse(item);
}
}
catch (e) { item = undefined; }
}
return item;
},
DelLocalStorageItem: function (itemName) {
if (tf.js.GetIsNonEmptyString(itemName)) {
try { window.localStorage.removeItem(itemName); } catch (e) { }
}
},
CreateMapControlButtonHolder: function (map, applyStyles) {
var styles = tf.GetStyles();
var div = new tf.dom.Div({ cssClass: styles.GetUnPaddedDivClassNames(false, false) });
styles.AddDefaultShadowStyle(div);
div.GetHTMLElement().style.pointerEvents = 'none';
return { holder: new tf.map.HTMLControl({ map: map, content: div, isVisible: true, cssStyle: applyStyles }), div: div };
},
CreateMapButton: function (iconName, callBack, div, visibleBool, backgroundColor, buttonClassName) {
var button = document.createElement('button');
var displayStyle = visibleBool != undefined ? (tf.js.GetIsNonEmptyString(visibleBool) ? visibleBool : (!!visibleBool ? "block" : "none")) : "block";
button.className = buttonClassName != undefined ? buttonClassName : "button button-icon button-clear";
button.style.display = displayStyle;
button.style.marginBottom = "4px";
button.style.padding = "2px";
button.style.pointerEvents = "all";
if (backgroundColor != undefined) { button.style.backgroundColor = backgroundColor; }
var icon = document.createElement('icon');
icon.className = "button button-icon " + iconName;
icon.style.padding = "0px";
button.addEventListener('click', callBack);
button.appendChild(icon);
if (!!div) { div.AddContent(button); }
return button;
},
CreateMapButton2: function (iconName, callBack, div, visibleBool, backgroundColor, buttonClassName) {
var button = document.createElement('button');
var displayStyle = visibleBool != undefined ? (tf.js.GetIsNonEmptyString(visibleBool) ? visibleBool : (!!visibleBool ? "block" : "none")) : "block";
button.className = buttonClassName != undefined ? buttonClassName : "button button-icon button-clear";
button.style.display = displayStyle;
button.style.marginBottom = "4px";
button.style.padding = "2px";
button.style.pointerEvents = "all";
if (backgroundColor != undefined) { button.style.backgroundColor = backgroundColor; }
var icon = document.createElement('icon');
icon.className = "button button-icon " + iconName;
icon.style.padding = "0px";
button.addEventListener('click', callBack);
button.appendChild(icon);
if (!!div) { div.AddContent(button); }
return button;
},
GetDeviceActivityData: function (geoLocationPos) {
var data = {}
//console.log('ITPACore.GetDeviceActivityData');
if (tf.js.GetIsValidObject(geoLocationPos)) {
var coords = geoLocationPos.coords;
if (!!coords) {
var metersPerSecondToMilesPerHour = 2.23694;
try {
data = {
token: ITPACore.AccessToken,
lon: coords.longitude,
lat: coords.latitude,
coordinate_on: tf.js.GetTimeStampFromDate(new Date(geoLocationPos.timestamp))
};
if (coords.altitude != undefined && coords.altitude != null) {
data.altitude = coords.altitude;
}
if (coords.speed !== undefined && coords.speed !== null) {
data.speed_mph = coords.speed * metersPerSecondToMilesPerHour;
}
if (typeof coords.heading !== 'undefined' && isFinite(coords.heading) && !isNaN(coords.heading)) {
data.heading_degree = Math.floor(coords.heading);
}
}
catch (Exception) {
data = {};
}
}
}
data.uuid = ITPACore.GetDeviceUUID();
return data;
},
MakeAuthForm: function () {
return {
email: ITPACore.currentUser.email,
password: <PASSWORD>
};
},
SetDeviceUUID: function (uuid) {
ITPACore.private_deviceUUID = tf.js.GetIsNonEmptyString(uuid) ? uuid : undefined;
},
GetDeviceUUID: function () {
return ITPACore.private_deviceUUID != undefined ? ITPACore.private_deviceUUID : "";
},
GeoCodeAddress: function (addressStr, then) {
if (tf.js.GetFunctionOrNull(then)) { new tf.services.Geocoder({ address: addressStr, callBack: then }); }
},
dismissMessagesStorageName: "dismissMsgs",
dismissMessages: undefined,
LoadDismissMessages: function () {
ITPACore.dismissMessages = ITPACore.GetLocalStorageItem(ITPACore.dismissMessagesStorageName);
if (!ITPACore.dismissMessages) {
ITPACore.dismissMessages = [];
}
},
SetDismissMessages: function (item) {
if (!tf.js.GetIsArray(item)) { item = []; }
ITPACore.dismissMessages = item;
ITPACore.SetLocalStorageItem(ITPACore.dismissMessagesStorageName, item);
},
trackReportCount: 5
};
function g_globalOnVisitedWebSite(then) { if (tf.js.GetFunctionOrNull(then)) { then(); } }
<file_sep>"use strict";
ITPACore.ETA = function (settings) {
var theThis, busKeyedList, stopsKeyedList, linesKeyedList, busLayer, preProcessServiceData, featureName;
this.GetFeatureName = function () { return featureName; }
this.UpdateFromNewData = function (data) { return updateFromNewData(data); }
/*
{
"identifier": "17 ST@MERIDIAN AV",
"eta": "2016-06-28 09:31:50.0",
"platform_id": "363",
"public_transport_vehicle_id": "1787"
},
*/
function updateFromNewData(data) {
if (data = preProcessServiceData(data)) {
var buses = {}/*, stops = {}*/;
for (var i in data) {
var itemData = data[i];
var busId = itemData.public_transport_vehicle_id;
var busItem = busKeyedList.GetItem(busId);
if (!!busItem) {
var etaLineId = itemData.route_key;//itemData.line_id;
var busDataProps = busItem.GetData().properties;
var busLine = busDataProps.line_id;
if (busLine == etaLineId) {
var stopId = itemData.platform_id;
var stopItem = stopsKeyedList.GetItem(stopId);
var eta = itemData.eta;
if (!!stopItem) {
var etaLine = linesKeyedList.GetItem(etaLineId);
if (!!etaLine) {
//var lineKey = etaLine.GetKey();
//var stopLine = stopItem.lines[lineKey];
var stopLine = stopItem.lines[etaLineId];
if (!!stopLine) {
var etaItem = {
lineId: etaLineId,
busItem: busItem,
busItemId: busId,
stopItem: stopItem,
stopItemId: stopId,
eta: eta,
dateTime: tf.js.GetDateFromTimeStamp(eta)
};
if (buses[busId] == undefined) {
buses[busId] = { count: 1, etas: [], etaDestItem: busItem, etaDestItemId: busId, etaDestItemFeature: ITPACore.busFeatureName };
}
else { ++buses[busId].count; }
buses[busId].etas.push(etaItem);
} //else { console.log('eta for line ' + etaLineId + ' uses stop out of line: ' + stopId + ' with bus id: ' + busId); }
} //else { console.log('eta for unknown line ' + etaLineId + ' plat id: ' + stopId); }
} //else { console.log('bus: ' + busId + ' with eta to unknown stop: ' + stopId); }
} //else { console.log('eta for wrong bus line, busId: ' + busId + ' plat id: ' + stopId + ' bus line: ' + busLine + ' eta line: ' + etaLineId); }
} //else { console.log('eta for unknown bus id: ' + busId); }
}
var allBusItems = busKeyedList.GetKeyedItemList(), allBusKeys = busKeyedList.GetKeyList();
for (var i in allBusItems) {
var busItem = allBusItems[i];
//var busId = busItem.GetData().properties.public_transport_vehicle_id;
busItem.etaList = buses[allBusKeys[i]];
}
busLayer.OnItemsUpdated({ items: allBusItems, keys: allBusKeys });
}
}
function initialize() {
settings = tf.js.GetValidObjectFrom(settings);
featureName = ITPACore.etaFeatureName;
var featureLayers = ITPACore.featureLayers;
busLayer = featureLayers.GetFeatureLayer(ITPACore.busFeatureName);
busKeyedList = featureLayers.GetKeyedList(ITPACore.busFeatureName);
stopsKeyedList = featureLayers.GetKeyedList(ITPACore.stopsFeatureName);
linesKeyedList = featureLayers.GetKeyedList(ITPACore.linesFeatureName);
preProcessServiceData = ITPACore.GetFeaturePreProcessServiceData(featureName);
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
<file_sep>"use strict";
ITPACore.MapETAToaster = function (settings) {
var theThis, tfStyles, etaToastList, layer, toastedItem;
var eventDispatcher;
var allEventName = "all";
var lastETAClicked;
this.OnFirst = function() { return onFirst(); }
this.OnNextPrev = function (isNext) { return onNextPrev(isNext); }
this.GetLastETAClicked = function () { return lastETAClicked; }
this.Toast = function (toastedItem) { return toast(toastedItem); }
this.Clear = function () { return clear(); }
this.AddListener = function (callBack) { return eventDispatcher.AddListener(allEventName, callBack); }
function onFirst() { if (lastETAClicked != undefined) { setLastETAClicked(etaToastList[0]); } }
function onNextPrev(isNext) {
if (lastETAClicked != undefined) {
var index = lastETAClicked.index, len = etaToastList.length;
if (isNext) { if (++index >= len) { index = 0; } }
else { if (--index < 0) { index = len - 1; } }
setLastETAClicked(etaToastList[index]);
}
}
function unHoverLastETAClicked() {
if (lastETAClicked != undefined) {
var st = lastETAClicked.stopMapFeature;
if (!!st) { lastETAClicked.stopMapFeature.SetIsAlwaysInHover(false); }
//else { console.log('lastETAClicked has invalid mapFeature'); }
}
}
function hoverLastETAClicked() {
if (lastETAClicked != undefined) {
var stopMapFeature = lastETAClicked.stopMapFeature;
if (!!stopMapFeature) { stopMapFeature.SetIsAlwaysInHover(true); }
}
}
function setLastETAClicked(eta) {
unHoverLastETAClicked();
lastETAClicked = eta;
hoverLastETAClicked();
notifyLastEtaClicked();
}
function notifyLastEtaClicked() { notify({ eta: lastETAClicked }); }
function onETAClicked(notification) {
var mapFeature = notification.mapFeature;
var stopItem = !!mapFeature ? mapFeature.stopItem : undefined;
if (!!stopItem) {
var stopETAFeatures = stopItem.stopETAFeatures;
if (!!stopETAFeatures && stopETAFeatures.index < etaToastList.length) {
setLastETAClicked(etaToastList[stopETAFeatures.index]);
}
}
}
function notify(data) { eventDispatcher.Notify(allEventName, data); }
function toast(toastedItemSet) {
var etaListSet;
if (!!(toastedItem = toastedItemSet)) {
etaListSet = toastedItem.etaList;
}
toastETAList(etaListSet);
}
function toastETAList(etaList) {
var lastStopItemSaved = !!lastETAClicked ? lastETAClicked.stopItem : undefined;
clear();
if (etaList != undefined) {
layer = ITPACore.featureLayers.GetFeatureLayer(ITPACore.stopsFeatureName).GetLayer();
//console.log('eta toast show');
//var localEtas = etaList.etas.slice(0);
var localEtas = etaList.etas;
etaToastList = [];
var index = 0;
for (var i in localEtas) {
var etaItem = localEtas[i];
var stopItem = etaItem.stopItem;
var stopETAFeatures = stopItem.stopETAFeatures;
var stopMapFeature;
if (stopETAFeatures == undefined) {
stopItem.stopETAFeatures = stopETAFeatures = { stopItem: stopItem };
}
else {
stopMapFeature = stopETAFeatures.stopMapFeature;
}
stopETAFeatures.index = index;
stopETAFeatures.etaItem = etaItem;
if (!!stopMapFeature) {
stopMapFeature.RefreshStyle();
}
else {
var d = stopItem.GetData(), g = d.geometry;
g.style = getGetStopStyle(stopItem, false);
g.hoverStyle = getGetStopStyle(stopItem, true);
stopETAFeatures.stopMapFeature = stopMapFeature = new tf.map.Feature(g);
stopETAFeatures.stopMapFeature.stopItem = stopItem;
tf.js.SetObjProperty(stopItem, ITPACore.itpaObjectName, stopMapFeature);
tf.js.SetObjProperty(stopMapFeature, ITPACore.itpaObjectName, stopItem);
stopMapFeature.SetOnClickListener(onETAClicked);
}
layer.AddMapFeature(stopMapFeature, true);
etaToastList.push(stopItem.stopETAFeatures);
if (lastStopItemSaved == stopItem) {
lastETAClicked = etaToastList[index];
}
++index;
}
layer.AddWithheldFeatures();
if (lastETAClicked == undefined && index > 0) { lastETAClicked = etaToastList[0]; }
hoverLastETAClicked();
}
}
function clear() {
if (!!layer) { layer.RemoveAllFeatures(); }
unHoverLastETAClicked();
lastETAClicked = undefined;
etaToastList = [];
}
function getETAStyle(stopItem, isHover) {
var etaStr;
if (stopItem != undefined) {
etaStr = ITPACore.getAmPmHour(stopItem.stopETAFeatures.etaItem.eta);
}
else {
etaStr = "??:??";
}
//var etaStr = ITPACore.getAmPmHour(etaItem.eta);
return {
marker: true, label: etaStr, font_height: isHover ? 18 : 15, zindex: isHover ? 6 : 1, marker_color: isHover ? "#ffa" : ITPACore.stopBkColor, font_color: isHover ? "#008" : "#008",
line_width: isHover ? 2 : 1, line_color: "#ffffff", marker_opacity: isHover ? 100 : 85, border_opacity: 60, border_color: "#000"
};
}
function getGetStopStyle(stopItem, isHover) { return function (mapFeature) { return getETAStyle(stopItem, isHover); } }
function initialize() {
eventDispatcher = new tf.events.MultiEventNotifier({ eventNames: [allEventName] });
settings = tf.js.GetValidObjectFrom(settings);
etaToastList = [];
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
<file_sep>"use strict;"
starter.controllers.controller('HomeCtrl', ['$scope', '$state', '$ionicModal', '$ionicPopup', 'toastr',
'GeoLocate', 'ITPAUser', '$http',
function ($scope, $state, $ionicModal, $ionicPopup, toastr, GeoLocate, ITPAUser, $http) {
//toastr.options.preventDuplicates = true;
$scope.hasCredentials = ITPACore.hasCredentialsSaved;
var uber;
var mapCenter;
var showingLines = false, fullyInited = false, showingAllLines = true;
var homeNotification, homeInit, homeOngoing, list, map, itpaFeatureLayers, lineBusMapControl, directionsControl, msgControl, incControl;
var barHeight = 44, allBarHeights = barHeight * 3;
var searchTextControl;
$scope.mapTemplateHeight = "calc(100% - " + allBarHeights + "px)";
//$scope.mapTemplateHeight = "300px";
var listHeight = 60;
//var listHeight = 80;
//var listHeight = 110;
//var listHeight = 120;
//var listHeight = 160;
function calcMapListHeights() {
if (ITPACore.isIOS) {
var mapTopDiv = document.getElementById("mapTopDiv");
tf.dom.ReplaceCSSClass(mapTopDiv, "mapTop", "mapTop-ios");
barHeight = 64;
//mapTopDiv.style.top = "64px";
}
$scope.listContainerHeight = listHeight + "px";
$scope.mapContainerHeight = "calc(100% - " + $scope.listContainerHeight + " - " + barHeight + "px)";
}
calcMapListHeights();
//$scope.text = { searchText: '1 east flagler st miami fl' };
$scope.text = { searchText: '' };
function setLineExtent(lineItem) {
if (!!lineItem) {
var mapFeature = itpaFeatureLayers.GetMapFeatureFromItem(lineItem);
var extent = mapFeature.GetGeom().GetExtent();
if (extent[0] < extent[2]) {
extent = tf.js.ScaleMapExtent(extent, 1.6);
map.SetVisibleExtent(extent);
}
}
}
$scope.onClickCard = function (card) {
var item = card.item;
var mapFeature = itpaFeatureLayers.GetMapFeatureFromItem(item);
if (!!mapFeature) {
var pointCoords;
if (mapFeature.GetIsPoint()) {
pointCoords = mapFeature.GetPointCoords();
if (pointCoords[0] == 0) {
pointCoords = [tf.consts.defaultLongitude, tf.consts.defaultLatitude];
}
}
else {
if (item.featureName == ITPACore.garFeatureName) {
var occItem = ITPACore.featureLayers.GetKeyedItem(ITPACore.occFeatureName, item.GetKey());
if (occItem) {
pointCoords = itpaFeatureLayers.GetMapFeatureFromItem(occItem).GetPointCoords();
}
}
}
if (pointCoords) {
map.AnimatedSetCenterIfDestVisible(pointCoords);
itpaFeatureLayers.SelectAndToast(mapFeature, pointCoords);
}
else {
setLineExtent(item);
itpaFeatureLayers.Select(mapFeature, map.GetCenter());
}
}
if (item.featureName == ITPACore.linesFeatureName) {
setCurrentLineFromItem(item);
}
}
function setCurrentLineFromItem(item) {
var lineId;
switch (item.featureName) {
case ITPACore.linesFeatureName:
//lineId = item.GetData().properties.line_id;
lineId = item.GetKey();
linesItem = item;
break;
case ITPACore.busFeatureName:
lineId = item.GetData().properties.line_id;
linesItem = itpaFeatureLayers.GetKeyedItem(ITPACore.linesFeatureName, lineId);
break;
}
if (lineId != undefined) {
//if (itpaFeatureLayers.GetCurrentLine() != lineId) {
var toastedItem = ITPACore.mapFeatureToaster.GetToastedItem();
if (!!toastedItem && toastedItem.featureName == ITPACore.busFeatureName) {
if (toastedItem.GetData().properties.line_id != lineId) {
ITPACore.mapFeatureToaster.CloseToast();
}
}
itpaFeatureLayers.SetCurrentLine(lineId);
lineBusMapControl.Update();
if (linesItem != undefined && showingLines) {
setTimeout(function () { list.scrollToItem(linesItem); }, 100);
}
}
}
function showMyLocationToast() {
var lastLocation = homeOngoing.GetLastLocation();
if (!!lastLocation) { toastr.info("lat " + lastLocation[1].toFixed(3) + ' lon ' + lastLocation[0].toFixed(3), "My Location", { timeOut: 4000 }); }
else { toastr.info(undefined, "My Location is unknown", { timeOut: 3000 }); }
}
function setSearchResultExtent() {
var kl = itpaFeatureLayers.GetKeyedList(ITPACore.searchFeatureName);
var ki = kl.GetKeyedItemList();
var gf = itpaFeatureLayers.GetGeoCodeFeature();
var extent, count = 0;
if (!!gf) {
var pc = gf.GetPointCoords();
extent = [pc[0], pc[1], pc[0], pc[1]];
++count;
}
for (var i in ki) {
var i = ki[i], d = i.GetData(), g = d.geometry, c = g.coordinates;
if (extent == undefined) { extent = [c[0], c[1], c[0], c[1]]; }
else { extent = tf.js.UpdateMapExtent(extent, c); }
++count;
}
if (count > 0) {
if (count == 1) { setMapToStreetLevel(); }
else {
extent = tf.js.ScaleMapExtent(extent, 1.6);
if (extent[0] < extent[2]) {
map.SetVisibleExtent(extent);
if (map.GetLevel() > ITPACore.mapMaxLevel) {
map.AnimatedSetLevel(ITPACore.mapMaxLevel);
//map.AnimatedSetLevel(10);
}
}
}
}
}
//event handlers
function onFeatureRefreshed(featureName) {
if (featureName == ITPACore.searchFeatureName) {
var nResults = getNSearchResults();
toastr.info(nResults + " items", "Search Results", { timeOut: 3000 });
if (!itpaFeatureLayers.IsLayerShowing(ITPACore.searchFeatureName)) {
//itpaFeatureLayers.ShowLayer(ITPACore.searchFeatureName, true);
homeOngoing.ClickOnMapButton(ITPACore.searchFeatureName);
}
setSearchResultExtent();
}
else if (featureName == ITPACore.linesFeatureName || featureName == ITPACore.stopsFeatureName) {
if (!!directionsControl) { directionsControl.SetLinesStopsNeedUpdate(); }
}
else if (featureName == ITPACore.pkrecFeatureName) {
console.log('home rec refresh');
}
}
function onETARefresh() { if (!!lineBusMapControl) { lineBusMapControl.Update(); } }
function onLineNameClicked() {
showingLines = true;
var featureName = showingLines ? ITPACore.linesFeatureName : ITPACore.busFeatureName;
list.showCards(featureName);
setLineExtent(itpaFeatureLayers.GetCurrentLineItem());
if (showingLines) {
setTimeout(function () { list.scrollToItem(itpaFeatureLayers.GetCurrentLineItem()); }, 300);
}
}
function moveToPointItem(pointItem) {
if (!!pointItem) {
var geom = pointItem.GetData().geometry;
if (geom.type.toLowerCase() == "point") {
map.SetCenter(geom.coordinates);
}
}
}
function animateToPointItem(pointItem) {
if (!!pointItem) {
var geom = pointItem.GetData().geometry;
if (geom.type.toLowerCase() == "point") {
map.AnimatedSetCenterIfDestVisible(geom.coordinates);
}
}
}
function onBusNameClicked() {
var toastedItem = ITPACore.mapFeatureToaster.GetToastedItem();
if (!!toastedItem && toastedItem.featureName == ITPACore.busFeatureName) {
animateToPointItem(toastedItem);
ITPACore.mapETAToaster.OnFirst();
if (!showingLines) { list.scrollToItem(toastedItem); }
}
}
function onNextPrevStopClicked(notification) {
ITPACore.mapETAToaster.OnNextPrev(notification.isNext);
onStopNameClicked();
}
function onStopNameClicked() {
var stopItem;
var eta = ITPACore.mapETAToaster.GetLastETAClicked();
if (!!eta) { animateToPointItem(eta.stopItem); }
}
function onLineDirectionClicked() {
var curLine = itpaFeatureLayers.GetCurrentLineItem();
if (!!curLine) {
/*
var curLineP = curLine.GetData().properties;
var direction = curLineP.direction, lineId = curLineP.line_id, lineNumber = curLineP.line_number;
var lineList = itpaFeatureLayers.GetKeyedList(ITPACore.linesFeatureName);
var lineItems = lineList.GetKeyedItemList();
for (var i in lineItems) {
var line = lineItems[i], lineP = line.GetData().properties;
if (lineP.line_id != lineId && lineP.line_number == lineNumber) {
setCurrentLineFromItem(line);
break;
}
}
*/
setLineExtent(itpaFeatureLayers.GetCurrentLineItem());
}
}
function onShowAllLinesCLicked() {
//toastr.info(undefined, 'all lines clicked');
ITPACore.mapFeatureToaster.CloseToast();
showingAllLines = !showingAllLines;
itpaFeatureLayers.ShowAllLines(showingAllLines);
if (showingAllLines) {
setMapToOverview();
}
else {
setLineExtent(itpaFeatureLayers.GetCurrentLineItem());
}
}
function getShowingAllLines() { return showingAllLines; }
function onMapButtonClicked(featureName) {
if (fullyInited) {
var showingMsg, showFeatureName = true, showLineBusControl = false, showDirectionsControl = false, showMapCenter = false;
var layersShowHide, addDirectionsLayer = true, showIncControl, showMsgControl;
switch (featureName) {
case ITPACore.busFeatureName:
showingMsg = "Transit";
layersShowHide = [ITPACore.linesFeatureName, ITPACore.stopsFeatureName, ITPACore.busFeatureName];
showLineBusControl = true;
showingLines = false;
setMapToOverview();
break;
case ITPACore.garFeatureName:
showingMsg = "Parking";
layersShowHide = [ITPACore.occFeatureName, ITPACore.garFeatureName/*, ITPACore.ssgFeatureName*/];
panHome();
break;
case ITPACore.incFeatureName:
showingMsg = "Incidents";
layersShowHide = [ITPACore.incFeatureName];
showIncControl = true;
setMapToOverview();
break;
case ITPACore.msgFeatureName:
showingMsg = "Messages";
layersShowHide = [ITPACore.msgFeatureName];
showMsgControl = true;
setMapToOverview();
break;
case ITPACore.searchFeatureName:
showingMsg = "Search Results";
layersShowHide = [ITPACore.searchFeatureName];
if (!getNSearchResults()) { var gf = itpaFeatureLayers.GetGeoCodeFeature(); if (!gf) { onSearch(); } }
break;
case ITPACore.directionsFeatureName:
showingMsg = "Directions";
layersShowHide = [];
addDirectionsLayer = true;
showDirectionsControl = true;
showMapCenter = true;
break;
}
if (!!layersShowHide) {
if (addDirectionsLayer) { layersShowHide.push(ITPACore.directionsFeatureName); }
itpaFeatureLayers.ShowHideFeatureLayers(layersShowHide);
}
if (!!mapCenter) { mapCenter.style.display = showMapCenter ? "block" : "none"; }
directionsControl.Show(showDirectionsControl);
lineBusMapControl.Show(!!showLineBusControl);
msgControl.Show(showMsgControl);
incControl.Show(showIncControl);
if (showFeatureName) { list.showCards(featureName); }
homeOngoing.CheckButtonsEnabled();
if (!!showingMsg) { toastr.success(undefined, "Showing " + showingMsg, { timeOut: 3000 }); }
}
}
//search
function getNSearchResults() { return itpaFeatureLayers.GetItemCount(ITPACore.searchFeatureName); }
function onSearch() {
if (!!itpaFeatureLayers) {
var searchText = $scope.text.searchText;
itpaFeatureLayers.SetQueryStr(searchText);
itpaFeatureLayers.GeoCode(searchText, function (notification) { if (notification.status) { toastr.info(undefined, "Found 1 address"); setSearchResultExtent(); } });
toastr.info(undefined, "Searching...", { timeOut: 1000 });
homeOngoing.RefreshSearch();
}
}
$scope.onSearch = function () { onSearch(); }
//about
var aboutModal;
$ionicModal.fromTemplateUrl('templates/modal/about.html', { scope: $scope }).then(function (modal) { aboutModal = modal; });
$scope.onAbout = function () { aboutModal.show(); }
$scope.closeAbout = function () { aboutModal.hide(); }
//ellipsis - TerraFly link
var ellipsisModal;
$scope.ellipsisSettings = {
fromURL: undefined,
toURL: undefined,
currentURL: undefined,
centerURL: undefined
};
$ionicModal.fromTemplateUrl('templates/modal/ellipsis.html', { scope: $scope }).then(function (modal) { ellipsisModal = modal; });
$scope.closeEllipsis = function () { ellipsisModal.hide(); }
$scope.onEllipsis = function () {
var fromFeature = !!directionsControl ? directionsControl.GetFromFeature() : undefined;
var toFeature = !!directionsControl ? directionsControl.GetToFeature() : undefined;
var lastLocation = !!homeOngoing ? homeOngoing.GetLastLocation() : undefined;
$scope.ellipsisSettings.fromURL = createEllipsisURL(!!fromFeature ? fromFeature.GetPointCoords() : undefined);
$scope.ellipsisSettings.toURL = createEllipsisURL(!!toFeature ? toFeature.GetPointCoords() : undefined);
$scope.ellipsisSettings.currentURL = createEllipsisURL(!!lastLocation ? lastLocation : undefined);
$scope.ellipsisSettings.centerURL = createEllipsisURL(!!map ? map.GetCenter() : undefined);
ellipsisModal.show();
}
function createEllipsisURL(coords) {
return !!coords ? "http://vn4.cs.fiu.edu/cgi-bin/gnis.cgi?Lat=" + coords[1] + "&Long=" + coords[0] + "&vid=itpaapp&tfaction=arqueryitpamore" : undefined;
}
$scope.onEllipsisGo = function (goURL) {
$scope.closeEllipsis();
if (goURL) { window.open(goURL, '_system', 'location=yes'); }
return false;
}
//msg dismiss
$scope.dismissMsgArray;
var msgDismissModal;
$ionicModal.fromTemplateUrl('templates/modal/msgdismiss.html', { scope: $scope }).then(function (modal) { msgDismissModal = modal; });
function onDismissMsg(message) {
dismissMsgArray = {};
var len = ITPACore.dismissMessages.length, key = '0';
if (!ITPACore.GetIsDismissedMessage(message)) {
dismissMsgArray[key] = { key: '0', message: message.toLowerCase() };
}
for (var i = 0 ; i < len ; ++i) {
var m = ITPACore.dismissMessages[i];
var key = '' + (i + 1);
dismissMsgArray[key] = { key: key, message: m };
}
$scope.dismissMsgArray = dismissMsgArray;
msgDismissModal.show();
}
$scope.deleteMsgDismiss = function(message) { delete $scope.dismissMsgArray[message.key]; }
$scope.closeMsgDismiss = function (confirmed) {
msgDismissModal.hide();
if (confirmed) {
var newMsgs = [];
for (var i in $scope.dismissMsgArray) { newMsgs.push($scope.dismissMsgArray[i].message); }
ITPACore.SetDismissMessages(newMsgs);
homeOngoing.UpdateNow(ITPACore.msgFeatureName);
}
}
//button handlers
function panHome() { if (!!map) { map.SetCenter(ITPACore.mapHomeCenter); map.SetLevel(ITPACore.mapInitialLevel); } }
function panBBC() { if (!!map) { map.SetCenter(ITPACore.mapBBCCenter); map.SetLevel(ITPACore.mapInitialLevel); } }
function setMapToOverview() { if (!!map) { map.SetVisibleExtent(ITPACore.mapExtent); } }
function setMapToStreetLevel() {
if (!!map) {
var targetCoords;
var lastMapButtonClicked = homeOngoing.GetLastMapButtonClicked();
if (lastMapButtonClicked == ITPACore.busFeatureName) {
var eta = ITPACore.mapETAToaster.GetLastETAClicked();
if (!!eta) {
var etaFeature = itpaFeatureLayers.GetMapFeatureFromItem(eta.stopItem);
if (!!etaFeature) { targetCoords = etaFeature.GetPointCoords(); }
}
}
if (targetCoords == undefined) {
var toastedItem = ITPACore.mapFeatureToaster.GetToastedItem();
if (!!toastedItem) {
moveToPointItem(toastedItem);
}
else if (itpaFeatureLayers.IsLayerShowing(ITPACore.searchFeatureName)) {
var gf = itpaFeatureLayers.GetGeoCodeFeature();
if (!!gf) { targetCoords = gf.GetPointCoords(); }
}
else if (homeOngoing.GetLastMapButtonClicked() == ITPACore.directionsFeatureName) {
var fromOrTo = directionsControl.GetFromOrToFeature();
if (!!fromOrTo) { targetCoords = fromOrTo.GetPointCoords(); }
}
}
if (targetCoords != undefined) {
map.SetCenter(targetCoords);
}
map.SetLevel(ITPACore.mapMaxLevel - 1);
}
}
function onStreetLevel() { toastr.info(undefined, "Street Level", { timeOut: 3000 }); setMapToStreetLevel(); }
function onOverview() { toastr.info(undefined, "Overview", { timeOut: 3000 }); setMapToOverview(); }
function onHome(event) { toastr.info(undefined, "UniversityCity", { timeOut: 3000 }); panHome(); }
function onBBC(event) { toastr.info(undefined, "FIU BBC Campus", { timeOut: 3000 }); panBBC(); }
function onLocation() {
showMyLocationToast(); var lastLocation = homeOngoing.GetLastLocation(); if (!!lastLocation && !!map) {
map.SetCenter(lastLocation);
}
}
function getDirectionTargetCoords() {
var targetCoords;
var lastMapButtonClicked = homeOngoing.GetLastMapButtonClicked();
if (lastMapButtonClicked == ITPACore.busFeatureName) {
var eta = ITPACore.mapETAToaster.GetLastETAClicked();
if (!!eta) {
var etaFeature = itpaFeatureLayers.GetMapFeatureFromItem(eta.stopItem);
if (!!etaFeature) { targetCoords = etaFeature.GetPointCoords(); }
}
}
if (targetCoords == undefined) {
var toastedMapFeature = ITPACore.mapFeatureToaster.GetToastedMapFeature();
if (!!toastedMapFeature && toastedMapFeature.GetIsPoint()) {
targetCoords = toastedMapFeature.GetPointCoords();
}
}
if (targetCoords == undefined) {
if (lastMapButtonClicked == ITPACore.searchFeatureName) {
var gf = itpaFeatureLayers.GetGeoCodeFeature();
if (!!gf) { targetCoords = gf.GetPointCoords(); }
}
}
if (targetCoords == undefined) { targetCoords = map.GetCenter(); }
return targetCoords;
}
function onUpdateDirections(notification) {
ITPACore.directionsRouteFeature = notification.sender.GetRouteFeature();
msgControl.Update();
incControl.Update();
}
//uber
var uberModal;
$ionicModal.fromTemplateUrl('templates/modal/uber.html', { scope: $scope }).then(function (modal) { uberModal = modal; });
$scope.closeUber = function () { uberModal.hide(); }
$scope.uberPriceArray = [];
$scope.isRefreshingUber;
$scope.uberListIsEmpty;
$scope.selectUberPrice = function (priceItem) {
if (priceItem.isAvailable) {
toastr.info('Requesting Uber Ride...', undefined, { timeOut: 3000 });
var url = uber.MakeSetPickupUrl(uberFromCoords, "From-Location", uberToCoords, "To-Location", priceItem.product_id);
window.open(url, '_system', 'location=yes');
$scope.closeUber();
}
else {
toastr.clear();
toastr.error('Uber Ride not available for trip endpoints', undefined, { timeOut: 3000 });
}
}
var uberProductsRefreshed, uberTimesRefreshed, uberPriceRefreshed;
var uberProducts, uberTimes, uberPrices;
function checkUberRefreshEnded() {
if (uberProductsRefreshed && uberTimesRefreshed && uberPriceRefreshed) {
var data = uberProducts;
$scope.isRefreshingUber = false;
var len = data.length;
if (!($scope.uberListIsEmpty = (len == 0))) {
var now = new Date();
for (var i = 0 ; i < len ; ++i) {
var d = data[i];
d.sharedStr = d.shared ? 'Shared' : 'Not shared';
d.sharedBkColor = d.shared ? "rgb(0,255,0)" : "rgb(255,0,0)";
d.availableBkColor = "rgb(255,0,0)";
d.endTime = "Unavailable";
d.etaTime = "";
d.isAvailable = false;
for (var j = 0 ; j < uberPrices.length ; ++j) {
var thisPrice = uberPrices[j];
if (thisPrice.product_id == d.product_id) {
if (thisPrice.duration != undefined) {
var endTime = new Date();
endTime.setSeconds(now.getSeconds() + thisPrice.duration);
//d.endTime = "Trip end " + tf.js.GetAMPMHourWithMinutes(endTime);
d.endTime = "Available";
d.availableBkColor = "rgb(0,255,0)";
d.isAvailable = true;
}
d.estimate = thisPrice.estimate;
break;
}
}
if (d.isAvailable) {
for (var j = 0 ; j < uberTimes.length ; ++j) {
var thisTime = uberTimes[j];
if (thisTime.product_id == d.product_id) {
var etaTime = new Date();
etaTime.setSeconds(now.getSeconds() + thisTime.estimate);
d.etaTime = ' (' + tf.js.GetAMPMHourWithMinutes(etaTime) + ')';
break;
}
}
}
}
}
$scope.uberPriceArray = data;
}
}
var uberFromCoords, uberToCoords;
$scope.refreshUber = function () {
if (!$scope.isRefreshingUber) {
var fromFeature = !!directionsControl ? directionsControl.GetFromFeature() : undefined;
var toFeature = !!directionsControl ? directionsControl.GetToFeature() : undefined;
$scope.isRefreshingUber = true;
$scope.uberListIsEmpty = false;
$scope.uberPriceArray = [];
uberProducts = uberTimes = uberPrices = [];
uberProductsRefreshed = uberTimesRefreshed = uberPriceRefreshed = true;
uberFromCoords = uberToCoords = undefined;
if (!!fromFeature && !!toFeature) {
uberProductsRefreshed = uberTimesRefreshed = uberPriceRefreshed = false;
var fromCoords = fromFeature.GetPointCoords();
var toCoords = toFeature.GetPointCoords();
uber.GetProducts(function (data) {
uberProducts = !!data && tf.js.GetIsArray(data.products) ? data.products : [];
uberProductsRefreshed = true;
checkUberRefreshEnded();
}, fromCoords);
uber.GetTimeEstimate(function (data) {
uberTimes = !!data && tf.js.GetIsArray(data.times) ? data.times : [];
uberTimesRefreshed = true;
checkUberRefreshEnded();
}, fromCoords);
uber.GetPriceEstimate(function (data) {
uberPrices = !!data && tf.js.GetIsArray(data.prices) ? data.prices : [];
uberPriceRefreshed = true;
checkUberRefreshEnded();
}, fromCoords, toCoords, 1);
}
uberFromCoords = fromCoords.slice(0);
uberToCoords = toCoords.slice(0);
checkUberRefreshEnded();
}
}
function onUber(notification) {
$scope.refreshUber();
uberModal.show();
}
function onPrevNextDirection(notification) {
var inc = notification.inc;
var dirkl = itpaFeatureLayers.GetKeyedList(ITPACore.directionsFeatureName);
var nextIndex, count = dirkl.GetItemCount();
if (inc == 0) { nextIndex = 0; }
else if (inc == -2) { nextIndex = count - 1; }
else {
var toastedItem = ITPACore.mapFeatureToaster.GetToastedItem();
if (!!toastedItem && toastedItem.featureName != ITPACore.directionsFeatureName) { toastedItem = undefined; }
if (!!toastedItem) {
var curIndex = toastedItem.GetData().order;
nextIndex = curIndex + inc;
}
else { nextIndex = inc < 0 ? count - 1 : 0; }
}
if (nextIndex < 0) { return; } else if (nextIndex >= count) { return; }
if (nextIndex >= 0 && nextIndex < count) {
var nextItem = dirkl.GetItem(nextIndex + 1);
if (!!nextItem) {
var nextFeature = itpaFeatureLayers.GetMapFeatureFromItem(nextItem);
if (!!nextFeature) {
itpaFeatureLayers.SelectAndToast(nextFeature);
animateToPointItem(nextItem);
setTimeout(function () { list.scrollToItem(nextItem); }, 50);
}
}
}
}
//init
function afterLinesAndStopsAreLoaded() {
homeOngoing.StartLocationTrack();
var lineKeyedList = itpaFeatureLayers.GetKeyedList(ITPACore.linesFeatureName);
var lineKeyedItemList = lineKeyedList.GetKeyedItemList();
var firstLine;
for (var i in lineKeyedItemList) {
var thisLine = lineKeyedItemList[i];
if (firstLine == undefined) { firstLine = thisLine; break;}
}
if (firstLine) { itpaFeatureLayers.SetCurrentLine(firstLine.GetData().properties.line_id); }
directionsControl = new ITPACore.DirectionsControl({
stops: itpaFeatureLayers.GetKeyedList(ITPACore.stopsFeatureName),
routes: itpaFeatureLayers.GetKeyedList(ITPACore.linesFeatureName),
map: map, toastr: toastr, onPrevNext: onPrevNextDirection,
getTargetCoords: getDirectionTargetCoords,
onUber: onUber,
$http: $http,
onUpdate: onUpdateDirections
});
lineBusMapControl = new ITPACore.LineBusMapControl({
map: map, onLineNameClicked: onLineNameClicked, onLineDirectionClicked: onLineDirectionClicked, onShowAllLinesCLicked: onShowAllLinesCLicked, getShowAllLines: getShowingAllLines,
onBusNameClicked: onBusNameClicked, onStopNameClicked: onStopNameClicked, onNextPrevStopClicked: onNextPrevStopClicked
});
msgControl = new ITPACore.MsgControl({ map: map, $ionicPopup: $ionicPopup, onDismiss: onDismissMsg });
incControl = new ITPACore.IncControl({ map: map });
fullyInited = true;
homeOngoing.ClickOnMapButton(ITPACore.directionsFeatureName);
}
function doInit() {
homeOngoing.OnMapLoaded(map, afterLinesAndStopsAreLoaded);
}
function onListAndMapRegistered() {
if (!!map && !!list) {
ITPACore.CreateFeatureLayers({
onUCClick: onHome,
onBBCClick: onBBC,
onUserLocationClick: onLocation,
map: map, baseZIndex: 20,
onAdd: function (featureName, items) { list.addCards(items); },
onDel: function (featureName, items) {
list.delCards(items);
if (featureName == ITPACore.busFeatureName) { lineBusMapControl.Update(); }
},
onSelect: function (notification) {
var item = itpaFeatureLayers.GetItemFromMapFeature(notification.selected);
var timeOutTime = 100;
if (item.featureName == ITPACore.busFeatureName) {
setCurrentLineFromItem(item);
if (showingLines) {
showingLines = false;
list.showCards(ITPACore.busFeatureName);
timeOutTime = 300;
}
}
else if (item.featureName == ITPACore.linesFeatureName) {
setCurrentLineFromItem(item);
if (!showingLines) {
showingLines = true;
list.showCards(ITPACore.linesFeatureName);
timeOutTime = 300;
}
}
else if (item.featureName == ITPACore.occFeatureName) {
item = item.GetData().properties.garageItem;
}
if (!!item) { setTimeout(function () { list.scrollToItem(item); }, timeOutTime); }
}
}, function() {
itpaFeatureLayers = ITPACore.featureLayers;
setTimeout(doInit, 500);
});
}
}
$scope.onSearchKbdGo = function () {
cordova.plugins.Keyboard.close();
onSearch();
}
$scope.onRegisterMap = function (theMap) {
map = theMap.map;
uber = new tf.services.Uber({ serverToken: 'SW4uAK8DDcnW8N99JAa1N2ufif14rylTUR64nt0F', clientId: '3f8josraMAKXEdjxDq3rMF_ihCePSJvA', useDeepLink: false });
map.SetFractionalZoomInteraction(true);
var resetNotifications = false;
//var resetNotifications = true;
homeNotification = new ITPACore.HomeNotification({ $ionicPopup: $ionicPopup, reset: resetNotifications });
homeOngoing = new ITPACore.HomeOngoing({
$http: $http,
homeNotification: homeNotification,
geoLocate: GeoLocate, onFeatureRefresh: onFeatureRefreshed,
onMapButtonClicked: onMapButtonClicked, onETARefresh: onETARefresh, toastr: toastr
});
homeInit = new ITPACore.HomeInit({ map: map, onHome: onHome, onBBC: onBBC, onOverview: onOverview, onLocation: onLocation, onStreetLevel: onStreetLevel });
mapCenter = document.getElementById("mapCenter");
onListAndMapRegistered();
map.OnResize();
}
$scope.onRegisterList = function (theList) { list = theList; onListAndMapRegistered(); }
$scope.gotoUCWebSite = function() {
//button does go to web site functionality, this function called in case future further processing is required
}
$scope.onRemoveLoginCredentials = function () {
ITPACore.DeleteSavedCredentials();
$scope.hasCredentials = ITPACore.hasCredentialsSaved;
}
}]);
<file_sep>"use strict";
var g_notificationPopup;
function onVisitedWebSite() { if (g_notificationPopup) { g_notificationPopup.close(); } }
ITPACore.HomeNotification = function (settings) {
var theThis, notificationItemName, $ionicPopup, pendingNotifications;
this.ResetNotifications = function () { return delNotificationItem; }
this.OnNotificationsReceived = function (data) { return onNotificationsReceived(data); };
function getNotificationItem() {
var item = ITPACore.GetLocalStorageItem(notificationItemName);
if (!item) { item = {}; }
return item;
}
function delNotificationItem() { return ITPACore.DelLocalStorageItem(notificationItemName); }
function setNotificationItem(notificationItem) { return ITPACore.SetLocalStorageItem(notificationItemName, notificationItem); }
function getNotificationKey(notificationId) {
return (tf.js.GetIsInt(notificationId) && notificationId > 0) ? '#' + notificationId : undefined;
}
function recordNotificationRead(notificationId) {
var notificationKey = getNotificationKey(notificationId);
if (notificationKey != undefined) {
var notificationItem = getNotificationItem();
if (notificationItem[notificationKey] == undefined) {
notificationItem[notificationKey] = notificationId;
setNotificationItem(notificationItem);
}
}
}
function advanceToNext() { if (pendingNotifications.length > 0) { setTimeout(showPendingNotification, 250); } }
function showPendingNotification() {
if (pendingNotifications.length > 0) {
var n = pendingNotifications[0];
pendingNotifications.splice(0, 1);
recordNotificationRead(n.notification_id);
var summary = n.summary;
var template;
if (n.icon) {
summary = "<img src='" + n.icon + "' style='float:left;padding:5px;max-width:35%;'/>" + summary;
}
if (n.url) {
var link = ITPACore.CreateVisitWebSiteLink(n.url, "onVisitedWebSite();")
summary = summary + link;
}
if ($ionicPopup) {
var alertPopup = $ionicPopup.alert({
title: n.title,
template: summary,
});
g_notificationPopup = alertPopup;
alertPopup.then(function (res) { advanceToNext(); });
}
else {
advanceToNext();
}
}
}
function onNotificationsReceived(data) {
if (!pendingNotifications.length) {
pendingNotifications = [];
//data = data ? data.data : undefined;
if (tf.js.GetIsNonEmptyArray(data)) {
var notificationItem = getNotificationItem();
for (var i in data) {
var n = data[i];
var notificationKey = getNotificationKey(n.notification_id);
if (notificationKey != undefined && notificationItem[notificationKey] == undefined) { pendingNotifications.push(n); }
}
}
if (pendingNotifications.length > 0) { showPendingNotification(); }
}
};
function initialize() {
pendingNotifications = [];
notificationItemName = ITPACore.currentUser.email + "-notification2";
if (tf.js.GetIsValidObject(settings)) {
$ionicPopup = settings.$ionicPopup;
if (!!settings.reset) { delNotificationItem(); }
}
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
<file_sep>"use strict";
ITPACore.IncControl = function (settings) {
var theThis, map, itpaFeatureLayers, keyedList, isShowing, mapControl, filterButton, getFilterFnc, setFilterFnc;
this.Show = function (showBool) { return show(showBool); }
this.GetIsShowing = function () { return isShowing; }
this.Update = function () { return update(); }
function show(showBool) {
if (isShowing != (showBool = !!showBool)) {
isShowing = showBool;
if (mapControl) {
mapControl.SetVisible(isShowing);
checkFilterButtonVisibility();
}
}
}
function checkFilterButtonVisibility() {
if (!!filterButton) { filterButton.style.display = ITPACore.directionsRouteFeature != undefined ? "inline-block" : "none"; }
}
function update() {
ITPACore.UpdateKeyedItemsForDistanceToRouteFeature(keyedList, !getFilterFnc());
checkFilterButtonVisibility();
}
function createButton(className, color, backgroundColor, fontWeight, display, eventListener) {
var button = document.createElement('button');
button.className = className;
if (color != undefined) { button.style.color = color; }
if (backgroundColor != undefined) { button.style.backgroundColor = backgroundColor; }
button.style.pointerEvents = "all";
if (fontWeight != undefined) { button.style.fontWeight = fontWeight; }
button.style.display = display;
button.addEventListener('click', eventListener);
return button;
}
function updateFilterButton() { if (!!filterButton) { filterButton.innerHTML = getFilterFnc() ? "All" : "Near"; } }
function onFilterToggle() { setFilterFnc(!getFilterFnc()); updateFilterButton(); update(); }
function createMapControl() {
var mapControlStyles = { position: "absolute", right: "8px", bottom: "8px", zIndex: 3000, pointerEvents: 'none' };
var mapControlHolder = ITPACore.CreateMapControlButtonHolder(map, mapControlStyles);
var divMapControl = mapControlHolder.div;
filterButton = createButton("button button-balanced lineMapDetail button-less-height button-width-like-less-height", undefined, undefined, undefined, "inline-block",
onFilterToggle);
updateFilterButton();
divMapControl.AddContent(filterButton)
mapControl = mapControlHolder.holder;
isShowing = true;
show(false);
}
function initialize() {
itpaFeatureLayers = ITPACore.featureLayers;
if (tf.js.GetIsValidObject(settings)) {
if (map = tf.js.GetMapFrom(settings.map)) {
getFilterFnc = ITPACore.GetIsFilteringIncForDistance;
setFilterFnc = ITPACore.SetIsFilteringIncForDistance;
keyedList = itpaFeatureLayers.GetKeyedList(ITPACore.incFeatureName);
createMapControl();
}
}
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
<file_sep>"use strict";
ITPACore.FeatureLayer = function (settings) {
var theThis, featureLayers, map, layer, keyedList, pixelRatio, animatePoints, mapFeature, featureName, keyName,
getFeatureStyle, refreshStyleOnUpdate, refreshExternalFeatureOnUpdate, preProcessServiceData, featureAddItemFunction, featureUpdateItemFunction,
featureDelItemFunction, toaster;
var constantStyle, constantHoverStyle, filterAddCB, addedItems;
this.GetLayer = function () { return layer; }
this.OnItemsUpdated = function (notification) { return onUpdated(notification); }
this.ShowItemsOnMap = function (itemKeys) { return showItemsOnMap(itemKeys); }
this.Clear = function () { return clear(); }
this.GetKeyedList = function () { return keyedList; }
this.GetItemCount = function () { return !!keyedList ? keyedList.GetItemCount() : 0; }
this.GetKeyedItem = function (key) { return keyedList.GetItem(key); }
this.GetMapFeature = function (key) {
var item = theThis.GetKeyedItem(key); return !!item ? tf.js.GetObjProperty(item, ITPACore.itpaObjectName) : undefined;
}
this.GetParentLayers = function () { return featureLayers; }
this.IsLayerVisible = function () { return isLayerVisible(); }
this.ToggleLayerVisible = function () { return toggleLayerVisible(); }
this.SetLayerVisible = function (showOrHideBool) { return setLayerVisible(showOrHideBool); }
function isLayerVisible() { return layer.GetIsVisible(); }
function setLayerVisible(showOrHideBool) {
showOrHideBool = !!showOrHideBool;
layer.SetVisible(showOrHideBool);
var toastedItem = !showOrHideBool ? toaster.GetToastedItem() : undefined;
for (var i in addedItems) {
var item = addedItems[i]; item.isVisible = showOrHideBool ? item.isAddedToLayer : false;
if (item == toastedItem) { toaster.CloseToast(); }
}
return showOrHideBool;
}
function toggleLayerVisible() { return setLayerVisible(!isLayerVisible()); }
this.CreatePointAnimator = function (animationDuration, pointProviders, circleRadius, lineColor) {
return new tf.map.PointsStyleAnimator({
maps: [map], pointProviders: pointProviders,
duration: animationDuration, getStyle: function (elapsed01) {
var radius = Math.round((circleRadius + Math.pow(elapsed01, 1 / 2) * circleRadius) * pixelRatio) + 2;
var opacity = 1 - Math.pow(elapsed01, 3);
var line_width = Math.round(3 - elapsed01);
var flashStyle = {
circle: true,
circle_radius: radius,
snapToPixel: false,
line: true,
line_width: line_width,
line_color: lineColor,
line_opacity: Math.round(opacity * 100)
};
return flashStyle;
}
});
}
this.UpdateFromNewData = function (data) {
if (data != undefined) {
if ((data = preProcessServiceData(data)) != undefined) {
if (!!keyedList) {
keyedList.UpdateFromNewData(data);
}
}
}
}
this.GetLayer = function () { return layer; }
this.GetKeyedList = function () { return keyedList; }
this.GetMap = function () { return map; }
function checkRefreshExternalFeature(item) {
if (!!refreshExternalFeatureOnUpdate) {
var otherFeature = featureLayers.GetMapFeature(refreshExternalFeatureOnUpdate, item.GetKey());
if (otherFeature) { otherFeature.RefreshStyle(); }
}
}
function doGetStyle(mapFeature, item, isHover) { return function (mapFeature) { return getFeatureStyle(mapFeature, item, isHover); } }
function logLayer(verb) {
if (false) {//featureName == ITPACore.busFeatureName || featureName == ITPACore.linesFeatureName) {
//console.log(featureName + ' after ' + verb + ' has: ' + keyedList.GetItemCount());
}
}
function checkFeatureAddFunction(item) { if (!!featureAddItemFunction) { featureAddItemFunction(item); } }
function checkFeatureUpdateFunction(item) { if (!!featureUpdateItemFunction) { featureUpdateItemFunction(item); } }
function checkFeatureDelFunction(item) { if (!!featureDelItemFunction) { featureDelItemFunction(item); } }
function clear() {
for (var i in addedItems) { show(addedItems[i], false, true, true); }
layer.RemoveAllFeatures();
}
function showItemsOnMap(itemKeys) {
if (!itemKeys) {
itemKeys = keyedList.GetKeyList();
}
for (var i in itemKeys) {
var itemKey = itemKeys[i];
var item = keyedList.GetItem(itemKey);
if (!!item) {
show(item, true, true, false);
}
}
layer.AddWithheldFeatures();
}
function show(item, showOrHide, withHoldAddDel, doNotDel) {
if (!!item && item.mapLayer == layer) {
if ((showOrHide = !!showOrHide) != item.isAddedToLayer) {
var itemKey = item.GetKey();
var mapFeature = tf.js.GetObjProperty(item, ITPACore.itpaObjectName);
if (showOrHide) {
layer.AddMapFeature(mapFeature, withHoldAddDel);
if (!!addedItems[itemKey]) {
//console.log('featureLayer: adding item already visible ' + featureName);
}
addedItems[itemKey] = item;
}
else {
if (!doNotDel) { layer.DelMapFeature(mapFeature, withHoldAddDel); }
if (addedItems[itemKey] == undefined) {
//console.log('featureLayer: deleting item already invisible ' + featureName);
}
delete addedItems[itemKey];
}
}
if (item.isAddedToLayer = showOrHide) {
item.isVisible = layer.GetIsVisible();
}
else { item.isVisible = false; }
}
}
function onAdded(notification) {
for (var i in notification.items) {
var item = notification.items[i], itemData = item.GetData();
var geometry = itemData.geometry;
if (!!constantStyle) {
geometry.style = constantStyle;
geometry.hoverStyle = constantHoverStyle;
}
else { geometry.style = doGetStyle(mapFeature, item, false); geometry.hoverStyle = doGetStyle(mapFeature, item, true); }
if (featureName != ITPACore.stopsFeatureName) {
var mapFeature = new tf.map.Feature(geometry);
tf.js.SetObjProperty(item, ITPACore.itpaObjectName, mapFeature);
tf.js.SetObjProperty(mapFeature, ITPACore.itpaObjectName, item);
}
item.mapLayer = layer;
item.isAddedToLayer = false;
item.isVisible = false;
var doAddToLayer = (!!filterAddCB) ? filterAddCB(item) : true;
if (doAddToLayer) { show(item, true, true, false); }
checkFeatureAddFunction(item);
checkFeatureUpdateFunction(item);
checkRefreshExternalFeature(item);
//console.log('adding feature ' + featureName + ' with ' + geometry.coordinates.length + ' points');
}
layer.AddWithheldFeatures();
featureLayers.OnAdd(featureName, notification.items);
//logLayer('add');
}
function onDeleted(notification) {
var toastedItem = toaster.GetToastedItem(), needsToastDel;
for (var i in notification.items) {
var item = notification.items[i];
if (item.isAddedToLayer) { show(item, false, true, false); }
checkFeatureDelFunction(item);
if (item == toastedItem) {
if (needsToastDel) {
//console.log('double toast del for item: ' + item.featureName + ' ' + item.GetKey());
}
needsToastDel = true;
}
}
layer.DelWithheldFeatures();
if (needsToastDel) { toaster.CloseToast(); }
//setTimeout(function() {featureLayers.OnDel(featureName, notification.items)}, 100);
featureLayers.OnDel(featureName, notification.items);
//logLayer('del');
}
function onUpdated(notification) {
var pointProviders = [];
var toastedItem = toaster.GetToastedItem(), needsToastUpdate;
for (var i in notification.items) {
var item = notification.items[i], itemData = item.GetData();
var geometry = itemData.geometry;
var mapFeature = tf.js.GetObjProperty(item, ITPACore.itpaObjectName);
if (mapFeature) {
if (refreshStyleOnUpdate) { ITPACore.RefreshMapFeatureStyle(item, mapFeature); }
if (mapFeature.GetIsPoint()) {
var nowCoords = mapFeature.GetPointCoords();
if (nowCoords[0] != geometry.coordinates[0] || nowCoords[1] != geometry.coordinates[1]) {
mapFeature.SetPointCoords(geometry.coordinates);
if (featureName == ITPACore.busFeatureName) {
var curBus = ITPACore.featureLayers.GetKeyedItem(ITPACore.busFeatureName, item.GetKey());
if (curBus.isVisible) {
pointProviders.push(geometry.coordinates);
}
}
}
}
else {
mapFeature.SetGeom(new tf.map.FeatureGeom(geometry));
}
}
checkFeatureUpdateFunction(item);
checkRefreshExternalFeature(item);
if (item == toastedItem) {
if (needsToastUpdate) {
//console.log('double toast update for item: ' + item.featureName + ' ' + item.GetKey());
}
needsToastUpdate = true;
}
}
if (needsToastUpdate) { toaster.OnUpdateToastedItem(); }
if (pointProviders.length > 0) {
if (!!animatePoints) { animatePoints(pointProviders, pixelRatio); }
else {
theThis.CreatePointAnimator(1000, pointProviders, 12, "#c00");
}
}
//logLayer('upd');
featureLayers.OnUpdate(featureName, notification.items);
}
/*function refreshFeature() {
if (!!mapFeature) { layer.DelMapFeature(mapFeature); mapFeature = null; }
var items = keyedList.GetKeyedItemList();
var coords = [];
for (var i in items) {
var item = items[i], data = item.GetData(), geom = data.geometry;
coords.push(geom.coordinates);
}
if (coords.length > 0) {
//console.log('adding feature ' + featureName + ' with ' + coords.length + ' points');
mapFeature = new tf.map.Feature({ type: "multipoint", coordinates: coords, style: settings.getStyle });
layer.AddMapFeature(mapFeature);
}
}*/
function initialize() {
settings = tf.js.GetValidObjectFrom(settings);
if (tf.js.GetIsInstanceOf(settings.map, tf.map.Map) && tf.js.GetIsInstanceOf(settings.featureLayers, ITPACore.FeatureLayers)) {
addedItems = {};
featureLayers = settings.featureLayers;
toaster = ITPACore.mapFeatureToaster;
featureName = settings.featureName;
filterAddCB = tf.js.GetFunctionOrNull(settings.filterAdd);
preProcessServiceData = ITPACore.GetFeaturePreProcessServiceData(featureName);
pixelRatio = tf.browser.GetDevicePixelRatio();
animatePoints = tf.js.GetFunctionOrNull(settings.animatePoints);
map = settings.map;
var addLayerSettings = {
name: ITPACore.GetLayerName(featureName), isVisible: false, isHidden: true, useClusters: false,
zIndex: ITPACore.GetLayerZIndex(featureName) + tf.js.GetIntNumberInRange(settings.baseZIndex, 0, 99999, 0),
minMaxLevels: ITPACore.GetFeatureLayerMinMaxLevels(featureName)
};
/*if (featureName == ITPACore.stopsFeatureName) {
addLayerSettings.useClusters = true;
addLayerSettings.clusterFeatureDistance = 30;
//addLayerSettings.clusterStyle = { circle: true, circle_radius: 8, fill: true, fill_color: "#f00" };
addLayerSettings.clusterStyle = { icon: true, icon_url: "./img/station-clustered.svg", snapToPixel: false, icon_anchor: [0.5, 0.5], scale: 1.2, zindex: 2 }
}*/
layer = map.AddFeatureLayer(addLayerSettings);
keyName = ITPACore.GetKeyName(featureName);
getFeatureStyle = ITPACore.GetFeatureStyle(featureName);
if (!!settings.useConstantStyle) {
constantStyle = doGetStyle(undefined, undefined, false)();
constantHoverStyle = doGetStyle(undefined, undefined, true)();
//console.log('featureLayer: using constant style ' + featureName);
}
refreshStyleOnUpdate = ITPACore.GetFeatureRefreshStyleOnUpdate(featureName);
refreshExternalFeatureOnUpdate = ITPACore.GetExternalFeatureRefreshStyleOnUpdate(featureName);
featureAddItemFunction = ITPACore.GetAddFeatureItemFunction(featureName);
featureDelItemFunction = ITPACore.GetDelFeatureItemFunction(featureName);
featureUpdateItemFunction = ITPACore.GetUpdateFeatureItemFunction(featureName);
keyedList = new tf.js.KeyedList({
name: featureName,
getKeyFromItemData: function (itemData) {
return tf.js.GetIsValidObject(itemData) ? itemData.properties[keyName] : null;
},
needsUpdateItemData: ITPACore.GetNeedsUpdateItemData(featureName),
filterAddItem: ITPACore.GetFeatureFilterAddItems(featureName)
});
keyedList.AddListener(tf.consts.keyedListDeletedItemsEvent, onDeleted);
keyedList.AddListener(tf.consts.keyedListAddedItemsEvent, onAdded);
keyedList.AddListener(tf.consts.keyedListUpdatedItemsEvent, onUpdated);
//keyedList.NotifyItemsAdded(onAdded);
}
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
}
ITPACore.FeatureLayers = function (settings) {
var theThis, featureLayers, map, mapFeatureToaster, directionsLayer, overviewLayer, topLayer, searchLayer;
var geoCodeFeature, UCFeature, BBCFeature, userLocationFeature, onAddCB, onUpdateCB, onDelCB, lastSelected;
var onSelectCB, onUCClickCB, onBBCClickCB, onUserLocationClickCB, currentLineId, queryStr, currentLine, currentLineMapFeature, showingAllLines;
this.ShowHideFeatureLayers = function (showThese) {
for (var i in featureLayers) {
var fl = featureLayers[i];
var isVisible = (!!showThese) ? ((showThese.indexOf(i) != -1) ? true : false) : false;
fl.SetLayerVisible(isVisible);
}
}
this.GetGeoCodeFeature = function () { return geoCodeFeature; }
this.GeoCode = function (addressStr, then) { return geoCode(addressStr, then); }
this.GetQueryStr = function () { return queryStr; }
this.SetQueryStr = function (newQueryStr) { queryStr = newQueryStr; }
this.GetMap = function() { return map; }
this.ShowAllLines = function (showBool) { return showAllLines(showBool); }
this.GetShowAllLines = function () { return showingAllLines; }
this.SetCurrentLine = function (currentLineId) {
return setCurrentLine(currentLineId);
};
this.GetCurrentLine = function () { return currentLineId; }
this.GetCurrentLineItem = function () {
var featureLayer = theThis.GetFeatureLayer(ITPACore.linesFeatureName);
return (!!featureLayer) ? featureLayer.GetKeyedItem(currentLineId) : undefined;
}
this.SetUserLocation = function (pointCoords) { return setUserLocation(pointCoords); }
this.OnAdd = function (featureName, items) {
switch (featureName) {
case ITPACore.busFeatureName:
for (var i in items) {
var item = items[i];
var lineItem = item.lineItem;//ITPACore.featureLayers.GetKeyedItem(ITPACore.linesFeatureName, item.GetData().properties.line_id);
if (lineItem) { addBusToLine(lineItem, item); }
}
break;
default:
break;
}
if (onAddCB) { onAddCB(featureName, items); }
}
this.OnUpdate = function (featureName, items) {
var needsBusLayerRefresh;
switch (featureName) {
case ITPACore.busFeatureName:
for (var i in items) {
var item = items[i];
var lineItem = item.lineItem;//ITPACore.featureLayers.GetKeyedItem(ITPACore.linesFeatureName, item.GetData().properties.line_id);
var prevLineItem = item.prevLineItem;
if (prevLineItem != lineItem) {
var lineFrom = !!prevLineItem ? prevLineItem.GetData().properties.line_id : "none";
var lineTo = !!lineItem ? lineItem.GetData().properties.line_id : "none";
//console.log("bus: " + item.GetKey() + " changed lines from " + lineFrom + " to " + lineTo + " at " + item.GetData().properties.datetime);
if (!!prevLineItem) { delBusFromLine(prevLineItem, item); item.prevLineItem = lineItem; }
if (lineItem) { addBusToLine(lineItem, item); }
if (!needsBusLayerRefresh) {
if (currentLine) {
needsBusLayerRefresh = lineItem == currentLine || prevLineItem == currentLine;
}
}
}
}
if (needsBusLayerRefresh) {
//console.log("bus line change prompted bus layer refresh");
var busLayer = theThis.GetFeatureLayer(ITPACore.busFeatureName);
busLayer.Clear();
busLayer.ShowItemsOnMap(currentLine.busKeyList);
updateToastedItem();
}
break;
default:
break;
}
if (onUpdateCB) { onUpdateCB(featureName, items); }
}
this.OnDel = function (featureName, items) {
switch (featureName) {
case ITPACore.busFeatureName:
for (var i in items) {
var item = items[i];
var lineItem = item.lineItem;//ITPACore.featureLayers.GetKeyedItem(ITPACore.linesFeatureName, item.GetData().properties.line_id);
if (lineItem) { delBusFromLine(lineItem, item); }
}
break;
default:
break;
}
if (onDelCB) { onDelCB(featureName, items); }
}
this.GetLastSelected = function () { return lastSelected; }
this.UnSelectLast = function () { return unselectLast(); }
this.Select = function (mapFeature, bypassNotification) { return select(mapFeature, bypassNotification); }
this.Toast = function (mapFeature, pointCoords) { return toast(mapFeature, pointCoords); }
this.SelectAndToast = function (mapFeature, pointCoords) { return selectAndToast(mapFeature, pointCoords); }
this.GetTopLayer = function () { return topLayer; }
this.GetOverviewLayer = function () { return overviewLayer; }
this.GetFeatureLayer = function (featureName) { return featureLayers[featureName]; }
this.GetKeyedList = function (featureName) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return (!!featureLayer) ? featureLayer.GetKeyedList() : false;
}
this.GetItemCount = function (featureName) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return (!!featureLayer) ? featureLayer.GetItemCount() : 0;
}
this.GetKeyedItem = function (featureName, key) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return (!!featureLayer) ? featureLayer.GetKeyedItem(key) : undefined;
}
this.GetMapFeature = function (featureName, key) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return (!!featureLayer) ? featureLayer.GetMapFeature(key) : undefined;
}
this.GetItemFromMapFeature = function (mapFeature) {
return tf.js.GetObjProperty(mapFeature, ITPACore.itpaObjectName);
}
this.GetMapFeatureFromItem = function (item) {
return tf.js.GetObjProperty(item, ITPACore.itpaObjectName);
}
this.GetItemFeatureName = function (item) {
return item.featureName;
/*var featureName;
if (tf.js.GetIsInstanceOf(item, tf.js.KeyedItem)) {
featureName = item.GetList().GetName();
}
return featureName;*/
}
this.GetMapFeatureFeatureName = function (mapFeature) {
return theThis.GetItemFeatureName(theThis.GetItemFromMapFeature(mapFeature));
}
this.ToggleLayer = function (featureName) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return (!!featureLayer) ? featureLayer.ToggleLayerVisible() : false;
}
this.ShowLayer = function (featureName, showOrHideBool) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return !!featureLayer ? featureLayer.SetLayerVisible(showOrHideBool) : false;
}
this.IsLayerShowing = function (featureName) {
var featureLayer = theThis.GetFeatureLayer(featureName);
return !!featureLayer ? featureLayer.IsLayerVisible() : false;
}
this.UpdateFromNewData = function (featureName, data) {
var featureLayer = theThis.GetFeatureLayer(featureName);
if (!!featureLayer) { featureLayer.UpdateFromNewData(data); }
}
function unselectLast() {
if (!!lastSelected) {
if (lastSelected != currentLineMapFeature) { lastSelected.SetIsAlwaysInHover(false); }
lastSelected = undefined;
}
}
function select(mapFeature, bypassNotification) {
var lastSaved = lastSelected;
unselectLast();
if (!!mapFeature) {
(lastSelected = mapFeature).SetIsAlwaysInHover(true);
}
if (!bypassNotification) {
if (!!onSelectCB) { onSelectCB({ sender: theThis, last: lastSaved, selected: lastSelected }); }
}
}
function IsBusInLine(lineItem, busItem) { return lineItem.busList[busItem.GetKey()] != undefined; }
function addBusToLine(lineItem, busItem) {
if (!IsBusInLine(lineItem, busItem)) {
var key = busItem.GetKey();
lineItem.busList[key] = busItem;
lineItem.busKeyList[key] = key;
++lineItem.nBuses;
ITPACore.GetUpdateFeatureItemFunction(ITPACore.linesFeatureName)(lineItem);
}
}
function delBusFromLine(lineItem, busItem) {
if (IsBusInLine(lineItem, busItem)) {
var key = busItem.GetKey();
delete lineItem.busList[key];
delete lineItem.busKeyList[key];
--lineItem.nBuses;
ITPACore.GetUpdateFeatureItemFunction(ITPACore.linesFeatureName)(lineItem);
}
}
function toast(mapFeature, pointCoords) { mapFeatureToaster.ShowToast(mapFeature, pointCoords); }
function selectAndToast(mapFeature, pointCoords) { toast(mapFeature, pointCoords); select(mapFeature, false); }
function onFeatureClick(notification) {
var mapFeature = notification.mapFeature;
var item = theThis.GetItemFromMapFeature(mapFeature);
if (!!item) {
if (item.featureName != ITPACore.stopsFeatureName) {
//if (item.featureName == ITPACore.busFeatureName) { console.log(item.GetData().properties.heading); }
if (item.featureName == ITPACore.linesFeatureName) { select(mapFeature, false); }
else { selectAndToast(mapFeature, notification.eventCoords); }
}
}
else if (mapFeature == UCFeature) { if (!!onUCClickCB) { onUCClickCB(); } }
else if (mapFeature == BBCFeature) { if (!!onBBCClickCB) { onBBCClickCB(); } }
else if (mapFeature == userLocationFeature) { if (!!onUserLocationClickCB) { onUserLocationClickCB(); } }
}
function setUserLocation(pointCoords) {
if (tf.js.GetIsArrayWithMinLength(pointCoords, 2)) {
if (userLocationFeature == undefined) {
userLocationFeature = new tf.map.Feature({
type: "point", coordinates: pointCoords, style: ITPACore.GetUserLocationFeatureStyle()
});
topLayer.AddMapFeature(userLocationFeature);
}
else {
userLocationFeature.SetPointCoords(pointCoords);
}
}
else {
topLayer.DelMapFeature(userLocationFeature);
userLocationFeature = undefined;
}
}
function isBusItem(item) { return item.featureName == ITPACore.busFeatureName; }
function isStopItem(item) { return item.featureName == ITPACore.stopsFeatureHoverStyle; }
function isLineItem(item) { return item.featureName == ITPACore.linesFeatureName; }
function filterCurrentLineBuses(item) {
if (!showingAllLines) {
if (!!item) {
var data = item.GetData();
return data.properties.line_id == currentLineId;
}
return false;
}
return true;
}
function updateToastedItem() {
var toastedItem = mapFeatureToaster.GetToastedItem();
if (toastedItem) {
if (!toastedItem.isVisible) { mapFeatureToaster.CloseToast(); }
else { mapFeatureToaster.OnUpdateToastedItem(); }
}
}
function showAllLines(showBool) {
if (showingAllLines != (showBool = !!showBool)) {
showingAllLines = showBool;
setCurrentLine(currentLineId, true);
/*var linesLayer = theThis.GetFeatureLayer(ITPACore.linesFeatureName);
if (showingAllLines = showBool) {
linesLayer.ShowItemsOnMap();
}
else {
linesLayer.Clear();
if (currentLineId != undefined) { linesLayer.ShowItemsOnMap([currentLineId]); }
}
updateToastedItem();*/
}
}
function setCurrentLineOnHover(setBool) { if (currentLineMapFeature) { currentLineMapFeature.SetIsAlwaysInHover(setBool); } }
function setCurrentLine(currentLineIdSet, forceBool) {
//if (tf.js.GetIsNonEmptyString(currentLineIdSet)) { currentLineIdSet = parseInt(currentLineIdSet); }
if ((currentLineId != currentLineIdSet) || !!forceBool) {
var linesLayer = theThis.GetFeatureLayer(ITPACore.linesFeatureName);
//var stopsLayer = theThis.GetFeatureLayer(ITPACore.stopsFeatureName);
var busLayer = theThis.GetFeatureLayer(ITPACore.busFeatureName);
var line = linesLayer.GetKeyedItem(currentLineIdSet);
setCurrentLineOnHover(false);
if (!showingAllLines) {
linesLayer.Clear();
//stopsLayer.Clear();
busLayer.Clear();
if (!!line) {
linesLayer.ShowItemsOnMap([currentLineIdSet]);
}
//stopsLayer.ShowItemsOnMap(line.GetData().properties.platform_ids);
busLayer.ShowItemsOnMap(line.busKeyList);
}
else {
busLayer.ShowItemsOnMap();
linesLayer.ShowItemsOnMap();
}
if (!!line) {
currentLineId = currentLineIdSet;
currentLine = line;
currentLineMapFeature = theThis.GetMapFeatureFromItem(currentLine);
setCurrentLineOnHover(true);
}
else {
currentLineId = undefined;
currentLine = undefined;
currentLineMapFeature = undefined;
}
updateToastedItem();
}
}
/*function onZoomClose(notification) {
var centerCoords = !!notification.mapFeature ? notification.mapFeature.GetPointCoords() : notification.eventCoords;
map.SetCenter(centerCoords);
map.SetLevel(ITPACore.mapMaxLevel - 1);
}*/
function geoCode(addressStr, then) {
if (!!geoCodeFeature) { searchLayer.DelMapFeature(geoCodeFeature); geoCodeFeature = undefined; }
if (tf.js.GetIsNonEmptyString(addressStr)) {
ITPACore.GeoCodeAddress(addressStr, function (data) {
var result = false;
if (!!data) {
if (tf.js.GetIsArrayWithMinLength(data.pointCoords, 2) && ITPACore.AreMapCoordsInsideExtent(data.pointCoords)) {
var style = ITPACore.GetGeoCodeFeatureStyleSpecs(false);
var textStyle = {
marker: true, label: addressStr, font_height: 15, zindex: 10, marker_color: "#ffa",
font_color: "#008",
line_width: 1, line_color: "#ffffff", marker_opacity: 85, border_opacity: 60, border_color: "#000"
};
var hoverStyle = ITPACore.GetGeoCodeFeatureStyleSpecs(true);
hoverStyle.push(textStyle);
var geom = { type: 'point', style: style, hoverStyle: hoverStyle, coordinates: data.pointCoords }
searchLayer.AddMapFeature(geoCodeFeature = new tf.map.Feature(geom));
geoCodeFeature.SetOnClickListener(function () { geoCodeFeature.SetIsAlwaysInHover(!geoCodeFeature.GetIsAlwaysInHover()); });
result = true;
}
}
if (tf.js.GetFunctionOrNull(then)) {
then({ sender: theThis, status: result });
}
});
}
}
function initialize() {
settings = tf.js.GetValidObjectFrom(settings);
showingAllLines = true;
if (tf.js.GetIsInstanceOf(settings.map, tf.map.Map)) {
onAddCB = tf.js.GetFunctionOrNull(settings.onAdd);
onUpdateCB = tf.js.GetFunctionOrNull(settings.onUpdate);
onDelCB = tf.js.GetFunctionOrNull(settings.onDel);
onSelectCB = tf.js.GetFunctionOrNull(settings.onSelect);
onUCClickCB = tf.js.GetFunctionOrNull(settings.onUCClick);
onBBCClickCB = tf.js.GetFunctionOrNull(settings.onBBCClick);
onUserLocationClickCB = tf.js.GetFunctionOrNull(settings.onUserLocationClick);
var featureNames = ITPACore.GetFeaturesWithMapLayersNames();
featureLayers = {};
ITPACore.CreateMapFeatureToaster(map = settings.map);
mapFeatureToaster = ITPACore.mapFeatureToaster;
//map.AddListener(tf.consts.mapDblClickEvent, onZoomClose);
//map.AddListener(tf.consts.mapFeatureDblClickEvent, onZoomClose);
map.AddListener(tf.consts.mapFeatureClickEvent, onFeatureClick);
var baseZIndex = tf.js.GetIntNumberInRange(settings.baseZIndex, 0, 99999, 0);
for (var i in featureNames) {
var featureName = featureNames[i];
var useConstantStyle = undefined;
var filterAdd = undefined;
switch (featureName) {
//case ITPACore.msgFeatureName:
//case ITPACore.incFeatureName:
//case ITPACore.busFeatureName:
case ITPACore.stopsFeatureName:
case ITPACore.searchFeatureName:
useConstantStyle = true;
break;
default:
break;
}
switch (featureName) {
case ITPACore.linesFeatureName:
break;
case ITPACore.busFeatureName:
filterAdd = filterCurrentLineBuses;
break;
case ITPACore.stopsFeatureName:
filterAdd = function () { return false; }
break;
default:
break;
}
featureLayers[featureName] = new ITPACore.FeatureLayer({
map: map, featureName: featureName, featureLayers: theThis,
baseZIndex: baseZIndex,
useConstantStyle: useConstantStyle,
filterAdd: filterAdd
});
}
var zIndexAboveFeatureLayers = baseZIndex + 5;
var directionsLayerSettings = {
name: "Directions", isVisible: false, isHidden: true, useClusters: false,
zIndex: zIndexAboveFeatureLayers++
};
var overviewLayerSettings = {
name: "Overview", isVisible: true, isHidden: true, useClusters: false,
zIndex: zIndexAboveFeatureLayers++,
minMaxLevels: { maxLevel: ITPACore.minLevelBeforeUCFeature, minLevel: tf.consts.minLevel }
};
var topLayerSettings = {
name: "Top", isVisible: true, isHidden: true, useClusters: false,
zIndex: zIndexAboveFeatureLayers++
};
searchLayer = theThis.GetFeatureLayer(ITPACore.searchFeatureName).GetLayer();
UCFeature = new tf.map.Feature({ type: "point", coordinates: ITPACore.mapHomeCenter, style: ITPACore.GetUCFeatureStyle() });
BBCFeature = new tf.map.Feature({ type: "point", coordinates: ITPACore.mapBBCCenter, style: ITPACore.GetBBCFeatureStyle() });
directionsLayer = map.AddFeatureLayer(directionsLayerSettings);
overviewLayer = map.AddFeatureLayer(overviewLayerSettings);
overviewLayer.AddMapFeature(UCFeature);
overviewLayer.AddMapFeature(BBCFeature);
topLayer = map.AddFeatureLayer(topLayerSettings);
}
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
<file_sep>"use strict";
starter.services.factory('GeoLocate', ['$ionicPlatform', '$cordovaGeolocation', 'toastr', function ($ionicPlatform, $cordovaGeolocation, toastr) {
//console.log('GeoLocate service instantiated');
var maximumAge = 800;
//var maximumAge = Infinity;
var timeout = 15000, watchNextTimeout = 1000, toggleAccuracyMinErrors = 2;
var count = 0, errorCount = 0, consecutiveErrorCount = 0, toggledAccuracyCount = 0;
var lastLocation, lastError;
var geolocationWatchSettings = { maximumAge: maximumAge, timeout: timeout, enableHighAccuracy: true, };
//var useToaster = ITPACore.useDebugGeolocation;
//var toasterMax = 1;
//var toasterCounter = toasterMax;
//var exceptionError = 'exception during getCurrentPosition success handler';
function watchNext() {
setTimeout(startWatch, watchNextTimeout);
}
function startWatch() {
//if (useToaster) { if (++toasterCounter >= toasterMax) { toasterCounter = 0; } if (toasterCounter == 0) { toastr.info("geolocation call", { timeOut: 200 }); } }
$cordovaGeolocation
.getCurrentPosition(geolocationWatchSettings)
.then(function (position) {
try {
lastLocation = position;
//if (useToaster && toasterCounter == 0) { toastr.info("lon " + lastLocation.coords.longitude.toFixed(5) + ' lat ' + lastLocation.coords.latitude.toFixed(5), undefined, { timeOut: 500 }); }
lastError = undefined;
++count;
consecutiveErrorCount = 0;
if (!geolocationWatchSettings.enableHighAccuracy) {
geolocationWatchSettings.enableHighAccuracy = true;
++toggledAccuracyCount;
}
}
catch (e) {
//console.log(exceptionError);
}
watchNext();
}, function (err) {
try {
//if (useToaster) { toastr.info("ERROR: " + err.message, { timeOut: 1000 }); }
lastLocation = undefined;
lastError = err;
++errorCount;
if (geolocationWatchSettings.enableHighAccuracy) {
if (++consecutiveErrorCount >= toggleAccuracyMinErrors) {
geolocationWatchSettings.enableHighAccuracy = false;
consecutiveErrorCount = 0;
++toggledAccuracyCount;
}
}
}
catch (e) {
//console.log(exceptionError);
}
watchNext();
});
}
$ionicPlatform.ready(function () { startWatch(); });
return {
getLastLocation: function () {
return lastLocation;
},
getInfo: function () {
return {
count: count,
errorCount: errorCount,
lastLocation: lastLocation,
enableHighAccuracy: geolocationWatchSettings.enableHighAccuracy,
toggledAccuracyCount: toggledAccuracyCount,
lastError: lastError
};
}
};
}]);
<file_sep>"use strict;"
starter.controllers.controller('MapViewCtrl', ['$scope', 'toastr',
function ($scope, toastr) {
var map = ITPACore.global_map_object;
var resizeCount = 0;
var resizeInterval;
if (map == undefined) {
ITPACore.global_map_object = map = new tf.map.Map(ITPACore.GetMapSettings());
$scope.onRegisterMap({ map: map });
//resizeMap();
//setTimeout(function () { resizeMap(); setInterval(resizeMap, 5000); }, 1000);
setTimeout(function () {
resizeMap();
resizeInterval = setInterval(resizeMap, 5000);
}, 1000);
}
function resizeMap() {
map.OnResize();
resizeCount++;
if (resizeCount > 4) {
if (resizeInterval) {
clearInterval(resizeInterval);
resizeInterval = undefined;
}
}
}
}]);
<file_sep>"use strict";
var starter = angular.module('starter', ['ionic', 'ngCordova', 'ngResource', 'toastr', 'starter.controllers', 'starter.services']);
starter.controllers = angular.module('starter.controllers', ['toastr']);
starter.services = angular.module('starter.services', ['ngResource']);
starter.run(function ($ionicPlatform) {
$ionicPlatform.ready(function ($cordovaDevice) {
if (cordova.platformId === 'ios' && window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
//cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
var device = ionic.Platform.device();
ITPACore.SetDeviceUUID(device.uuid);
//console.log(device.uuid);
if (window.StatusBar) { StatusBar.styleDefault(); }
//if (window.cordova) { ITPACore.SetCordovaDevice($cordovaDevice); }
ITPACore.isIOS = !!ionic.Platform.isIOS();
document.addEventListener('backbutton', (event) => {
event.preventDefault();
console.log('back button');
}, false);
try {
//var debugParkingDetectorPlugIn = true;
//var debugParkingDetectorPlugIn = false;
/*if (initParkingDetectorPlugin != undefined) {
initParkingDetectorPlugin(debugParkingDetectorPlugIn, 2, "http://streetsmartdemo.cloudapp.net/newParkingActivity");
}*/
}
catch(e){}
});
});
starter.config(['$stateProvider', '$urlRouterProvider', '$compileProvider',
function ($stateProvider, $urlRouterProvider, $compileProvider) {
$compileProvider.debugInfoEnabled(true);
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
.state('app', {
name: "app",
url: '',
abstract: true,
templateUrl: 'templates/home.html',
controller: 'HomeCtrl',
})
.state('app.home', {
url: '/',
views: {
"mapViewContent": {
templateUrl: 'templates/views/mapview.html',
controller: 'MapViewCtrl'
},
"listViewContent": {
templateUrl: 'templates/views/listview.html',
controller: 'ListViewCtrl'
}
}
});
$urlRouterProvider.otherwise('/login');
}]);
starter.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
<file_sep>"use strict";
starter.controllers.controller('ListViewCtrl', ['$scope', function ($scope) {
var listScrollLefts = [0, 0];
var cardArrays = {};
var cardArrayFeatureNames = [ITPACore.busFeatureName, ITPACore.incFeatureName, ITPACore.msgFeatureName,
ITPACore.garFeatureName, ITPACore.linesFeatureName, ITPACore.searchFeatureName, ITPACore.directionsFeatureName];
for (var i in cardArrayFeatureNames) { cardArrays[cardArrayFeatureNames[i]] = []; }
var placeholderFeatureName = 'placeholder', placeholderItemKey = '1';
var placeholderItem = {
cardTitle: 'Retrieving information from server...',
cardMsg: ' ',
isVisible: true
};
var placeholderCard = {
featureKey: placeholderFeatureName,
featureName: placeholderFeatureName,
item: placeholderItem,
itemKey: placeholderItemKey
};
var placeholderCardArray = [placeholderCard];
$scope.isPlaceholderCard = function (card) {
return card.featureName == placeholderFeatureName;
}
$scope.isBusCard = function (card) { return card.featureName == ITPACore.busFeatureName; }
$scope.isIncidentCard = function (card) { return card.featureName == ITPACore.incFeatureName; }
$scope.isMessageCard = function (card) { return card.featureName == ITPACore.msgFeatureName; }
$scope.isGarageCard = function (card) { return card.featureName == ITPACore.garFeatureName; }
$scope.isStopCard = function (card) { return card.featureName == ITPACore.stopsFeatureName; }
$scope.isLineCard = function (card) { return card.featureName == ITPACore.linesFeatureName; }
$scope.isSearchCard = function (card) { return card.featureName == ITPACore.searchFeatureName; }
$scope.isDirectionsCard = function (card) {
return card.featureName == ITPACore.directionsFeatureName && !card.item.isBusDirection;
};
$scope.isBusDirectionsCard = function (card) {
return card.featureName == ITPACore.directionsFeatureName && card.item.isBusDirection;
};
$scope.cardArrayUse = placeholderCardArray;
//$scope.cardArrayUse = [];
function createCardForItem(item) {
var featureName = item.featureName;
if (cardArrays[featureName]) {
var itemKey = item.GetKey();
return {
featureKey: featureName + '|' + itemKey,
featureName: featureName,
//title: featureName + ' #' + itemKey,
item: item,
itemKey: itemKey/*,
itemOrder: itemKey*/
};
}
return undefined;
}
function addCards(items) {
var cardArray = getCardArrayForItems(items);
if (cardArray) {
var cardsToAdd = [];
for (var i in items) {
var item = items[i], card = createCardForItem(items[i]);
if (!!card) { cardsToAdd.push(card); }
}
if (cardsToAdd.length) { cardArray.push.apply(cardArray, cardsToAdd); }
}
}
function filterItems(fromCardArray, items) {
return fromCardArray.filter(function (card) {
for (var i in items) { if (items[i] == card.item) { return false; } }
return true;
});
}
function getCardArrayForItem(item) { return !!item ? cardArrays[item.featureName] : undefined; }
function getCardArrayForItems(items) { for (var i in items) { return getCardArrayForItem(items[i]); } return undefined; }
function delCards(items) {
var cardArray = getCardArrayForItems(items);
if (cardArray) { cardArray = filterItems(cardArray, items); }
}
function getCardHTMLElement(card) { return document.getElementById(card.featureKey); }
function getAllListHTMLElement() { return document.getElementById("itpaList"); }
function getAllCardsListHTMLElement() { return document.getElementById("itpaAllListContent"); }
function getListHTMLElement(item) { return getAllListHTMLElement(); }
function scrollToItemOnCardArray(item, cardArray) {
var found;
for (var i in cardArray) {
var card = cardArray[i];
if (card.item == item) {
//console.log('trying to scroll to item ' + card.itemKey);
var cardElem = getCardHTMLElement(card);
if (!!cardElem) {
var listElem = getListHTMLElement(item);
if (!!listElem) {
//console.log('scrolling to item ' + card.itemKey);
var off = cardElem.offsetLeft;
//if (off > itpaList.scrollLeft && off > 40) { off -= 20; }
listElem.scrollLeft = off;
}
}
found = true;
break;
}
}
if (!found) {
console.log('failed to scroll to item ' + item.GetKey());
}
}
function scrollToItem(item) {
var cardArray = getCardArrayForItem(item);
if (cardArray) { scrollToItemOnCardArray(item, cardArray); }
}
function showCards(featureName) {
$scope.cardArrayUse = cardArrays[featureName] != undefined ? cardArrays[featureName] : [];
}
$scope.filterAllList = function(value, index, array) {
return value.item.isVisible || value.item.featureName == ITPACore.linesFeatureName;
}
$scope.orderList = function (cardItem) {
/*if (cardItem.item.featureName == ITPACore.busFeatureName) {
var item = cardItem.item;
return item.order;
}
return undefined;*/
return cardItem.item.order;
}
function setPlaceHolder(title, msg) {
placeholderItem.cardTitle = title;
placeholderItem.cardMsg = msg;
}
$scope.onRegisterList({ addCards: addCards, delCards: delCards, scrollToItem: scrollToItem, showCards: showCards, setPlaceHolder: setPlaceHolder });
}]);
<file_sep>"use strict";
starter.services.factory('ITPAUser', ['$http', function ($http) {
var loginURL = ITPACore.GetNewAuthService();
function access(user, then, error) {
var url = loginURL + '?' + tf.js.ObjectToURLParams(user);
var req = { method: 'GET', url: url, data: user, headers: { 'Content-Type': 'application/json' } };
$http(req).
success(function (data, status, headers, config) {
if (tf.js.GetFunctionOrNull(then)) {
then(data, status, headers, config);
}
}).
error(function (data, status, headers, config) {
if (tf.js.GetFunctionOrNull(error)) {
error(data, status, headers, config);
}
});
return 0;
};
return {
access: access
};
}]);
<file_sep>"use strict";
ITPACore.HomeOngoing = function (settings) {
var theThis, isTracking, geoLocate, lastGeoLocation, lastLocation, itpaFeatureLayers;
var map, mapButtons, onFeatureRefreshCB, ETAs, onMapButtonClickedCB;
var garBtn, busBtn, incBtn, msgBtn, searchBtn, dirBtn, buttons, buttonFeatureNames, onETARefreshCB;
var bkColorOn, bkColorOff;
var trackIndex, trackTimeOut, lastMapButtonClicked;
var featurePeriodicRefresh;
var toastr;
var loadedLines, loadedStops;
var needBusFullUpdate;
var polyCode;
var homeNotification;
var $http;
this.UpdateNow = function (featureName) {
if (isSocketWorking()) {
var dataSetName = socketDataSetByFeatureName[featureName];
if (dataSetName) { socket.emit(get_last_data_set, dataSetName); }
}
}
this.ClickOnMapButton = function (featureName) { return onMapButtonClicked(featureName); }
this.GetLastMapButtonClicked = function () { return lastMapButtonClicked; }
this.RefreshSearch = function () {
if ($http) {
var url = ITPACore.GetSearchServiceUrl();
$http({
method: 'GET',
//headers: headers,
//params: {},
url: url
}).then(function successCallback(response) {
var data = (tf.js.GetIsValidObject(response) && tf.js.GetIsValidObject(response.data)) ? response.data : undefined;
onRefreshedData({ featureName: ITPACore.searchFeatureName, data: data });
}, function errorCallback(response) {
console.log('failed search call to: ' + url);
});
}
};
this.OnMapLoaded = function (theMap, thenCallBack) { if (map = tf.js.GetMapFrom(theMap)) { itpaFeatureLayers = ITPACore.featureLayers; createMapButtons(); initialRefresh(thenCallBack); } };
this.CheckButtonsEnabled = function () { return checkButtonsEnabled(); };
this.GetLastLocation = function () { return lastLocation; };
this.GetIsTracking = function () { return isTracking; };
this.StartLocationTrack = function () {
if (!isTracking) { itpaFeatureLayers = ITPACore.featureLayers; if (isTracking = (!!geoLocate && !!itpaFeatureLayers)) { doTrack(); } }
};
function doTrack() {
lastGeoLocation = geoLocate.getLastLocation();
if (lastGeoLocation) {
var coords = lastGeoLocation.coords;
var newLocation = [coords.longitude, coords.latitude];
if (lastLocation === undefined || lastLocation[0] !== newLocation[0] || lastLocation[1] !== newLocation[1]) {
itpaFeatureLayers.SetUserLocation(lastLocation = newLocation);
}
if (trackIndex === 1) { logActivity(); }
if (++trackIndex >= ITPACore.trackReportCount) { trackIndex = 1; }
}
if (isTracking) { setTimeout(doTrack, trackTimeOut); }
};
var socket;
var itpa_track_device_type = 'itpa_track_device';
var lastButtonSubscriptions;
var subscribe_data_change = 'subscribe_data_change';
var unsubscribe_data_change = 'unsubscribe_data_change';
var notify_data_change = 'notify_data_change';
var itpa_buses_current = 'itpa_buses_current?features';
var itpa_bus_routes = 'itpa_bus_routes';
var itpa_bus_stops = 'itpa_bus_stops?features';
var itpa_bus_etas = 'itpa_bus_etas';
var fl511_messages_type = 'fl511_messages_current?features';
var flhsmv_incidents_type = 'flhsmv_incidents_current?features';
var itpa_parking_sites_type = 'itpa_parking_sites?features';
var itpa_parking_decals = 'itpa_parking_decals';
var itpa_parking_availability = 'itpa_parking_availability';
var itpa_parking_recommendations = 'itpa_parking_recommendations';
var itpa_notifications_active = 'itpa_notifications_active';
var get_last_data_set = 'get_last_data_set';
function isSocketWorking() { return socket && socket.connected && isAuthenticated; };
function logActivity() {
if (isSocketWorking()) {
socket.emit(itpa_track_device_type, ITPACore.GetDeviceActivityData(lastGeoLocation));
}
};
function addRemoveSubscriptions(buttonType, isAdd) {
if (isSocketWorking() && buttonType) {
var subscriptions = [];
switch (buttonType) {
case ITPACore.busFeatureName:
subscriptions = [
{ name: itpa_bus_routes/*, preventEmitBack: loadedLines*/ },
{ name: itpa_bus_stops/*, preventEmitBack: loadedStops*/ },
{ name: itpa_buses_current },
{ name: itpa_bus_etas }
];
break;
case ITPACore.garFeatureName:
subscriptions = [
{ name: itpa_parking_decals },
{ name: itpa_parking_sites_type },
{ name: itpa_parking_availability },
{ name: itpa_parking_recommendations }
];
break;
case ITPACore.msgFeatureName: subscriptions = [{ name: fl511_messages_type }]; break;
case ITPACore.incFeatureName: subscriptions = [{ name: flhsmv_incidents_type }]; break;
}
if (subscriptions.length) {
var verb = isAdd ? subscribe_data_change : unsubscribe_data_change;
for (var i in subscriptions) {
var subs = subscriptions[i];
socket.emit(verb, subs.name, subs.preventEmitBack);
}
}
}
};
function updateSubscriptions(newButtonSubscriptions) {
if (lastButtonSubscriptions != newButtonSubscriptions) {
addRemoveSubscriptions(lastButtonSubscriptions, false);
addRemoveSubscriptions(lastButtonSubscriptions = newButtonSubscriptions, true);
}
};
var isAuthenticated;
function initSocket() {
if (!socket) {
socket = io.connect(ITPACore.GetNewITPAServer(), { path: "/socketio/socketio/socket.io"/*, transports: ['websocket']*/ });
socket.on('disconnect', function () {
isAuthenticated = false;
});
socket.on('connect', function () {
isAuthenticated = false;
//console.log('CONNECTED TO SOCKET IO');
socket.emit('authentication', {
token: ITPACore.AccessToken
});
});
socket.on('authenticated', function (authResult) {
//console.log('authenticated: ' + JSON.stringify(authResult));
isAuthenticated = true;
lastButtonSubscriptions = undefined;
updateSubscriptions(lastMapButtonClicked);
socket.emit(subscribe_data_change, itpa_notifications_active, false);
if (authResult.trackSeconds !== undefined) {
ITPACore.trackReportCount = authResult.trackSeconds;
}
});
socket.on(notify_data_change, function (data_set_name, data_set) {
//console.log("GOT DATA CHANGE " + data_set_name);
try {
var featureName = featureNameBySocketDataSet[data_set_name];
//data_set = JSON.parse(data_set);
if (data_set) {
var data;
switch (data_set_name) {
// cases below will not update features
case itpa_notifications_active:
//console.log("GOT DATA CHANGE " + data_set_name);
if (homeNotification) {
data = data_set.data;
if (data) {
for (var i in data) {
var d = data[i];
d.notification_id = d.id;
if (d.start_on) {
d.start_on = d.start_on.replace('T', ' ');
d.start_on = ITPACore.CVTDate(d.start_on);
}
if (d.expire_on) {
d.expire_on = d.expire_on.replace('T', ' ');
d.expire_on = ITPACore.CVTDate(d.expire_on);
}
}
data.sort(function (a, b) { return a.notification_id - b.notification_id; });
homeNotification.OnNotificationsReceived(data);
}
}
break;
case itpa_parking_decals:
data = data_set.data;
var decalMap = {};
for (var i in data) {
var d = data[i];
if (typeof (d.id) == "number" && tf.js.GetIsNonEmptyString(d.name) && tf.js.GetIsNonEmptyString(d.description)) {
decalMap['' + d.id] = d;
}
}
ITPACore.pkRecommendationsDecalMap = decalMap;
break;
// cases below will update features
case itpa_parking_recommendations:
data = data_set.data;
break;
case itpa_parking_availability:
data = data_set.data;
break;
case itpa_bus_etas:
data = data_set.data;
for (var i in data) {
var d = data[i];
var fleet = d.fleet;
var fleetKeyPrefix = fleet + '|';
d.eta = d.eta.replace('T', ' ');
d.eta = ITPACore.CVTDate(d.eta);
if (d.last_updated) {
d.last_updated = d.last_updated.replace('T', ' ');
d.last_updated = ITPACore.CVTDate(d.last_updated);
}
d.public_transport_vehicle_id = fleetKeyPrefix + d.bus_id;
d.platform_id = fleetKeyPrefix + d.stop_id;
d.route_key = fleetKeyPrefix + d.route_id;
}
break;
case itpa_bus_routes:
var newData = [];
data = data_set.data;
for (var i in data) {
var oldD = data[i], oldP = oldD;
var newD = {
properties: tf.js.ShallowMerge(oldP)
}, newP = newD.properties;
newP.key = oldP.fleet + '|' + oldP.id;
newP.fleet_id = newP.line_id = oldP.id;
newP.identifier = oldP.name;
newP.platform_ids = oldP.compressed_stop_ids.split(',');
newD.largeGeometry = newD.geometry = polyCode.ToGeoJSONMultiLineStringNoFlip(oldD.compressed_multi_linestring, 6);
newD.nPointsLargeGeometry = newD.nPointsGeometry = tf.js.CountMLSPoints(newD.geometry);
newD.nPointsSmallToLarge = 1;
newData.push(newD);
}
data_set = newData;
break;
case itpa_bus_stops:
data = data_set.features;
for (var i in data) {
var d = data[i], p = d.properties;
p.key = p.fleet + '|' + p.id;
p.platform_id = p.id;
p.fleet_id = p.id;
p.identifier = p.name;
}
break;
case itpa_buses_current:
data = data_set.features;
for (var i in data) {
var d = data[i], p = d.properties;
p.key = p.fleet + '|' + p.id;
p.public_transport_vehicle_id = p.id;
p.coordinate_updated = p.coordinate_updated.replace('T', ' ');
p.datetime = ITPACore.CVTDate(p.coordinate_updated);
p.number_of_occupants = Math.floor(p.occupancy_percentage * 1000);
p.speed = p.speed_mph;
p.heading = p.heading_degree;
p.line_id = p.fleet + '|' + p.route_id;
if (p.fleet == 'utma') {
p.fleet_order = 0;
}
else if (p.fleet == 'fiu') {
p.fleet_order = 1;
}
else {
p.fleet_order = 2;
}
}
/*
var extraRecord = tf.js.ShallowMerge(data[0]);
var erP = extraRecord.properties;
erP.fleet = 'utma';
erP.name = 'SW-6';
erP.route_id = '1';
erP.line_id = erP.fleet + '|' + erP.route_id;
erP.fleet_order = 0;
data.push(extraRecord);
*/
if (data && data.length) {
data.sort(function (a, b) {
var ap = a.properties;
var bp = b.properties;
if (ap.fleet_order < bp.fleet_order) { return -1; }
if (ap.fleet_order > bp.fleet_order) { return 1; }
if (ap.route_id < bp.route_id) { return -1; }
if (ap.route_id > bp.route_id) { return 1; }
if (ap.id < bp.id) { return -1; }
if (ap.id > bp.id) { return 1; }
return 0;
});
var len = data.length;
for (var i = 0; i < len; ++i) {
data[i].properties.order = i + 1;
}
}
break;
case fl511_messages_type:
data = data_set.features;
for (var i in data) {
var d = data[i], p = d.properties;
p.message_board_id = p.id;
p.message_on = p.message_on.replace('T', ' ');
p.last_updated = p.last_updated.replace('T', ' ');
p.message_on = ITPACore.CVTDate(p.message_on);
p.record_updated = ITPACore.CVTDate(p.last_updated);
p.message_board_location = p.location;
}
break;
case flhsmv_incidents_type:
data = data_set.features;
for (var i in data) {
var d = data[i], p = d.properties;
p.event_id = p.id;
p.date = p.date.replace('T', ' ');
p.dispatch_time = ITPACore.CVTDate(p.date);
p.incident_id = p.external_id;
p.external_incident_type = p.type;
}
break;
case itpa_parking_sites_type:
data = data_set.features;
for (var i in data) {
var d = data[i], p = d.properties;
p.parking_site_id = p.id;
p.parking_site_type_name = p.type_name;
p.parking_site_type_id = p.type_id;
p.total_level = p.number_of_levels;
p.centroid = !p.lon || !p.lat ? undefined : [p.lon, p.lat];
}
break;
}
}
if (featureName) { onRefreshedData({ featureName: featureName, data: data_set }); }
} catch (e) {
console.log('EXCEPTION: ' + e.message);
}
});
}
};
function onMapButtonClicked(featureName) {
if (lastMapButtonClicked != featureName) {
updateSubscriptions(featureName);
lastMapButtonClicked = featureName;
if (onMapButtonClickedCB) { onMapButtonClickedCB(featureName); }
}
}
function getOnMapButtonClicked(featureName) { return function() { return onMapButtonClicked(featureName); } }
function createMapButtons() {
if (!!map) {
var mapButtonStyles = { position: "absolute", left: "6px", top: "12px", pointerEvents: 'none' };
var result = ITPACore.CreateMapControlButtonHolder(map, mapButtonStyles);
var div = result.div;
mapButtons = result.holder;
div.GetHTMLElement().parentNode.style.zIndex = 2;
var show = true;
var bkColor = bkColorOff;
dirBtn = ITPACore.CreateMapButton2("itpa-mapdir-button", getOnMapButtonClicked(ITPACore.directionsFeatureName), div, show, bkColor, "button button-clear mapButtonLeft");
busBtn = ITPACore.CreateMapButton2("itpa-mapbus-button", getOnMapButtonClicked(ITPACore.busFeatureName), div, show, bkColor, "button button-clear mapButtonLeft");
garBtn = ITPACore.CreateMapButton2("itpa-mapgar-button", getOnMapButtonClicked(ITPACore.garFeatureName), div, show, bkColor, "button button-clear mapButtonLeft");
incBtn = ITPACore.CreateMapButton2("itpa-mapinc-button", getOnMapButtonClicked(ITPACore.incFeatureName), div, show, bkColor, "button button-clear mapButtonLeft");
msgBtn = ITPACore.CreateMapButton2("itpa-mapmsg-button", getOnMapButtonClicked(ITPACore.msgFeatureName), div, show, bkColor, "button button-clear mapButtonLeft");
searchBtn = ITPACore.CreateMapButton2("itpa-mapsearch-button", getOnMapButtonClicked(ITPACore.searchFeatureName), div, show, bkColor, "button button-clear mapButtonLeft");
buttons = {};
buttons[ITPACore.garFeatureName] = garBtn;
buttons[ITPACore.busFeatureName] = busBtn;
buttons[ITPACore.incFeatureName] = incBtn;
buttons[ITPACore.msgFeatureName] = msgBtn;
buttons[ITPACore.searchFeatureName] = searchBtn;
buttons[ITPACore.directionsFeatureName] = dirBtn;
buttonFeatureNames = [ITPACore.garFeatureName, ITPACore.busFeatureName, ITPACore.incFeatureName,
ITPACore.msgFeatureName, ITPACore.searchFeatureName, ITPACore.directionsFeatureName];
}
}
function checkButtonEnabled(featureName) {
if (!!buttons) {
var button = buttons[featureName];
if (!!button) {
var isOn;
if (featureName != ITPACore.directionsFeatureName) {
isOn = itpaFeatureLayers.IsLayerShowing(featureName);
}
else {
isOn = lastMapButtonClicked == featureName;
}
button.style.backgroundColor = isOn ? bkColorOn : bkColorOff;
}
}
}
function checkButtonsEnabled() {
if (!!buttonFeatureNames) { for (var i in buttonFeatureNames) { checkButtonEnabled(buttonFeatureNames[i]); } }
}
function onRefreshedData(notification) {
var featureName = notification.featureName;
var data = notification.data;
if (!data) { data = []; }
if (featureName == ITPACore.pkrecFeatureName) {
var garList = !!ITPACore.featureLayers ? ITPACore.featureLayers.GetKeyedList(ITPACore.garFeatureName) : undefined;
if (!!garList) {
var data = !!notification ? ITPACore.featurePreProcessServiceData[ITPACore.pkrecFeatureName](notification.data) : [];
garList.NotifyItemsUpdated();
}
}
else if (featureName == ITPACore.etaFeatureName) {
ETAs.UpdateFromNewData(data);
if (onETARefreshCB) { onETARefreshCB(); }
}
else {
itpaFeatureLayers.UpdateFromNewData(featureName, data);
if (featureName == ITPACore.linesFeatureName) {
loadedLines = true;
ITPACore.linesAndStopsAreLinked = false;
needBusFullUpdate = true;
}
else if (featureName == ITPACore.stopsFeatureName) {
loadedStops = true;
ITPACore.linesAndStopsAreLinked = false;
}
if (!ITPACore.linesAndStopsAreLinked) { if (loadedLines && loadedStops) { ITPACore.LinkLinesAndStops(); } }
if (onFeatureRefreshCB) { onFeatureRefreshCB(featureName); }
}
};
function initialRefresh(thenCallBack) {
ETAs = new ITPACore.ETA({});
if (tf.js.GetFunctionOrNull(thenCallBack)) { thenCallBack(); }
}
var socketDataSetByFeatureName, featureNameBySocketDataSet;
function initialize() {
socketDataSetByFeatureName = {};
socketDataSetByFeatureName[ITPACore.pkrecFeatureName] = itpa_parking_recommendations;
socketDataSetByFeatureName[ITPACore.occFeatureName] = itpa_parking_availability;
socketDataSetByFeatureName[ITPACore.etaFeatureName] = itpa_bus_etas;
socketDataSetByFeatureName[ITPACore.stopsFeatureName] = itpa_bus_stops;
socketDataSetByFeatureName[ITPACore.linesFeatureName] = itpa_bus_routes;
socketDataSetByFeatureName[ITPACore.busFeatureName] = itpa_buses_current;
socketDataSetByFeatureName[ITPACore.msgFeatureName] = fl511_messages_type;
socketDataSetByFeatureName[ITPACore.incFeatureName] = flhsmv_incidents_type;
socketDataSetByFeatureName[ITPACore.garFeatureName] = itpa_parking_sites_type;
featureNameBySocketDataSet = {};
for (var i in socketDataSetByFeatureName) {
featureNameBySocketDataSet[socketDataSetByFeatureName[i]] = i;
}
polyCode = new tf.map.PolyCode();
loadedLines = loadedStops = false;
needBusFullUpdate = false;
trackIndex = 1;
trackTimeOut = 1000;
bkColorOff = "rgba(255, 255, 255, 0.6)";
bkColorOn = "rgba(255, 255, 255, 1)";
if (tf.js.GetIsValidObject(settings)) {
geoLocate = settings.geoLocate;
onFeatureRefreshCB = tf.js.GetFunctionOrNull(settings.onFeatureRefresh);
onETARefreshCB = tf.js.GetFunctionOrNull(settings.onETARefresh);
onMapButtonClickedCB = tf.js.GetFunctionOrNull(settings.onMapButtonClicked);
homeNotification = settings.homeNotification;
toastr = settings.toastr;
$http = settings.$http;
featurePeriodicRefresh = {};
initSocket();
}
}
(function actualConstructor(theThisSet) { theThis = theThisSet; initialize(); })(this);
};
|
00bde7e7ca00871bae98e51eabc4b82d92c4d456
|
[
"JavaScript"
] | 14 |
JavaScript
|
HPDRC/ITPA-App
|
661408be377f999736aa9edecab32bcd276c135e
|
f7e6a78b4247ca79b9261da10d6581be69542856
|
refs/heads/master
|
<file_sep> # -*- coding: utf-8 -*-
def is_mulltiple(n, m):
"""1. Write a short Python function, is multiple(n, m), that takes two integer
values and returns True if n is a multiple of m, that is, n = mi for some
integer i, and False otherwise
>>> is_mulltiple(8,4)
True
>>> is_mulltiple(8,5)
False
>>> is_mulltiple(8,2)
True
"""
try:
result = True if n % m == 0 else False
except ZeroDivisionError:
result = False
finally:
return result
# Below should have the unit test
def is_even(k):
"""2. Write a short Python function, is even(k), that takes an integer value and
returns True if k is even, and False otherwise. However, your function
cannot use the multiplication, modulo, or division operators.
>>> is_even(8)
True
>>> is_even(3)
False
>>> is_even(5)
False
"""
return True if (-1)**k == 1 else False
# There should be a blank in the printed tuple pair, otherwise the doctest won't pass
def minmax(data):
"""3. Write a short Python function, minmax(data), that takes a sequence of
one or more numbers, and returns the smallest and largest numbers, in the
form of a tuple of length two. Do not use the built-in functions min or
max in implementing your solution
>>> minmax([3,4,5,6,7])
(3, 7)
>>> minmax([7,6,5,4,3])
(3, 7)
>>> minmax([5,4,6,8,7])
(4, 8)
>>> minmax([2,4,9,0,7])
(0, 9)
"""
minNum, maxNum = data[0], data[0]
for num in data:
if minNum > num:
minNum = num
if maxNum < num:
maxNum = num
return minNum, maxNum #Auto packing here
def sumSquare(n):
"""1.4 Write a short Python function that takes a positive integer n and returns
the sum of the squares of all the positive integers smaller than n.
>>> sumSquare(3)
5
>>> sumSquare(4)
14
>>> sumSquare(6)
55
"""
total = 0
for i in range(n):
total += i * i;
return total
def sumSquare2(n):
"""1.5 Give a single command that computes the sum from Exercise R-1.4,
relying on Python’s comprehension syntax and the built-in sum function.
>>> sumSquare2(3)
5
>>> sumSquare2(4)
14
>>> sumSquare2(6)
55
"""
return sum([i*i for i in range(n)])
def oddSumSquare(n):
"""1.7 Write a short Python function that takes a positive integer n and returns
the sum of the squares of all the odd positive integers smaller than n.
>>> oddSumSquare(3)
1
>>> oddSumSquare(5)
10
>>> oddSumSquare(9)
84
>>> oddSumSquare(11)
165
"""
return sum(i*i for i in range(n) if i%2 != 0)
"""1.8 Python allows negative integers to be used as indices into a sequence,
such as a string. If string s has length n, and expression s[k] is used for index −n ≤ k < 0, what is the equivalent index j ≥ 0 such that s[j] references
the same element?
Answer: j = len(s) + n
"""
"""1.9 What parameters should be sent to the range constructor, to produce a
range with values 50, 60, 70, 80?
Answer: range(50, 90, 10)"""
"""1.10 What parameters should be sent to the range constructor, to produce a
range with values 8, 6, 4, 2, 0, −2, −4, −6, −8?
Answer: range(8, -10, -2)
"""
"""Demonstrate how to use Python’s list comprehension syntax to produce
the list [1, 2, 4, 8, 16, 32, 64, 128, 256].
Answer: [2*i for i in range(9)]
"""
def choice(data):
"""1.11 Python’s random module includes a function choice(data) that returns
a random element from a non-empty sequence. The random module includes a more
basic function randrange, with parameterization similar to the built-in range
function, that return a random choice from the given range. Using only the
randrange function, implement your own version of the choice function
"""
import random
return data[random.randrange(len(data))]
def reverse(data):
"""Write a pseudo-code description of a function that reverses a list of n
integers, so that the numbers are listed in the opposite order than they
>>> example = [2,3,4,5,6,7]
>>> reverse(example)
>>> example
[7, 6, 5, 4, 3, 2]
>>> reverse(example)
>>> example
[2, 3, 4, 5, 6, 7]
>>> example = [2,3,4,5,6,7,8]
>>> reverse(example)
>>> example
[8, 7, 6, 5, 4, 3, 2]
>>> reverse(example)
>>> example
[2, 3, 4, 5, 6, 7, 8]
"""
for i in range(len(data)//2):
data[i], data[len(data)-i-1] = data[len(data)-i-1], data[i]
def oddPair(data):
"""Write a short Python function that takes a sequence of integer values and
determines if there is a distinct pair of numbers in the sequence whose
product is odd.
>>> oddPair([3,4,5,6,7])
True
>>> oddPair([2,4,6,6,8])
False
>>> oddPair([2,5,4,5,6])
False
>>> oddPair([4,5,5,6,6,7,7])
True
"""
firstOne = False
for i in data:
if i%2 != 0:
if firstOne and first != i:
return True
else:
firstOne = True
first =i
return False
# Performance Isssue, there should be a better way to do this, instead of using
# the built-in sort function
def distinctSequence(data):
""" 1.15 Write a Python function that takes a sequence of numbers and determines
if all the numbers are different from each other (that is, they are distinct).
>>> distinctSequence([3,2,4,1,6])
True
>>> distinctSequence([3,2,4,1,6,9,12,3,4])
False
>>> distinctSequence([3,2,4,1,6,8,9,0,23,45])
True
>>> distinctSequence([3,2,4,1,3])
False
"""
# Notice that this will change the parameter data.
# You can use the sorted() function instead.
data.sort()
for i in range(len(data)-1):
if data[i] == data[i+1]:
return False
return True
"""Had we implemented the scale function (page 25) as follows, does it work
properly?
def scale(data, factor):
for val in data:
val = factor
Explain why or why not.
Answer: This won't work, it will not change the parameter data.
In every iteration, the val is a (shadow) copy of the element in data, so the
change on val dose nothing to the data's element.
"""
"""1.18 Demonstrate how to use Python’s list comprehension syntax to produce
the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].
Answer: [i * (i+1) for i in range(9)] """
"""1.19 Demonstrate how to use Python’s list comprehension syntax to produce
the list [ a , b , c , ..., z ], but without having to type all 26 such
characters literally
Answer: [chr(i) for i in range(97, 123)]"""
def shuffle(data):
""" 1.20 Python’s random module includes a function shuffle(data) that accepts a
list of elements and randomly reorders the elements so that each possible
order occurs with equal probability. The random module includes a more basic
function randint(a, b) that returns a uniformly random integer from a to b
(including both endpoints). Using only the randint function, implement your
own version of the shuffle function."""
import random
for i in range(len(data)-1, 0, -1):
position = random.randint(0, i) # The i is inclusive here
data[position], data[i] = data[i], data[position]
def readLines():
""" 1.21 Write a Python program that repeatedly reads lines from standard input
until an EOFError is raised, and then outputs those lines in reverse order
(a user can indicate end of input by typing ctrl-D). Saved it in the file """
filename = input("Enter the file to be created:")
fp = open(filename, "w", encoding='utf-8')
while True:
try:
line = input("Enter a line:(Use the Ctrl-D to exit): \n")
fp.write(line+'\n')
except EOFError as e:
print("Exist the program")
break
fp.close()
if __name__ == '__main__':
import doctest
doctest.testmod()
<file_sep># -*- coding: utf-8 -*-
# Chapter 2 Object Oriented Programming
"""R-2.4 Write a Python class, Flower, that has three instance variables of type
str, int, and float, that respectively represent the name of the flower, its
number of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your class should
include methods for setting the value of each type, and retrieving the value
of each type."""
class Flower:
def __init__(self, name, petals, price):
self._name = name
self._petals = petals
self._price = price
def get_flower_name(self):
return self._name
def get_flower_petals(self):
return self._petals
def get_flower_price(self):
return self._price
def set_flower_name(self, name):
self._name = name
def set_flower_petals(self, petals):
self._petals = petals
def set_flower_price(self, price):
self._price = price
# The basic CreditCard Class
class CreditCard:
def __init__(self, customer, bank, acnt, limit):
self._customer = customer
self._bank = bank
self._account = acnt
self._limit = limit
self._balance = 0
def get_customer(self):
return self._customer
def get_bank(self):
return self._bank
def get_account(self):
return self._account
def get_limit(self):
return self._limit
def get_balance(self):
return self._balance
def charge(self, price):
if price + self._balance > self._limit:
return False
else:
self._balance += price
return True
def make_payment(self, amount):
self._balance -= amount
"""R-2.5 Use the techniques of Section 1.7 to revise the charge and make payment
methods of the CreditCard class to ensure that the caller sends a number
as a parameter
In Python3:
if not isinstance(parameter, (int,float)):
raise ValueError
In Python2, you may need to add the (long) type into the list
The classical Python ,metality, though, is that it's easier to ask forgiveness
than permission.
try:
self._balance -= parameter:
except TypeError:
# do something else
"""
"""R-2.7 The CreditCard class of Section 2.3 initializes the balance of a new
account to zero. Modify that class so that a new account can be given a
nonzero balance using an optional fifth parameter to the constructor. The
four-parameter constructor syntax should continue to produce an account
with zero balance.
In the class definition:
def __init__(self, customer, bank, acnt, limit, balance=0):
self._balance = balance
"""
"""In Section 2.3.3, we note that our Vector class supports a syntax such as
v = u + [5, 3, 10, −2, 1], in which the sum of a vector and list returns
a new vector. However, the syntax v = [5, 3, 10, −2, 1] + u is illegal.
Explain how the Vector class definition can be revised so that this syntax
generates a new vector."""
class Vector:
def __init__(self, n, data=[]):
if data: # data is empty or not
if n != len(data):
raise ValueError
else:
self._seq = data
else:
self._seq = [0] * n
self._length = n
def __len__(self):
return self._length
def __getitem__(self, k):
return self._seq[k]
def __setitem__(self, k, val):
self._seq[k] = val
def _valid_check(self, other):
if not isinstance(other, Vector) or self._length != len(other):
raise ValueError
def _operation(self, other, operator):
result = Vector(self._length)
for i in range(self._length):
result[i] = operator(self[i], other[i])
return result
def __add__(self, other):
from operator import add
self._valid_check(other)
return self._operation(other, add)
def __sub__(self, other):
from operator import sub
self._valid_check(other)
return self._operation(other, sub)
def __mul__(self, other):
"""Dot product of the vectors"""
from operator import mul
self._valid_check(other)
return self._operation(other, mul)
def __str__(self):
return '[' + ' '.join( [str(i) for i in self._seq] ) +']'
"""In Section 2.3.3, we note that our Vector class supports a syntax such as
v = u + [5, 3, 10, −2, 1], in which the sum of a vector and list returns
a new vector. However, the syntax v = [5, 3, 10, −2, 1] + u is illegal.
Explain how the Vector class definition can be revised so that this syntax
generates a new vector.
# The [5, 2, 10, -2 ,1] will fail the _valid_check method.
Add the __radd__() function, will work this out.
def __radd__(self, other):
return self + other
"""
"""R-2.12 Implement the mul method for the Vector class of Section 2.3.3, so
that the expression v 3 returns a new vector with coordinates that are 3
times the respective coordinates of v.
def __mul__(self, n):
if isinstance(n, int):
raise ValueError
return Vector(self._length * n, self._seq * n)
"""
if __name__ == '__main__':
a = Vector(5)
b = Vector(5, [2,3,4,5,6])
c = Vector(5, [6,5,4,3,2])
print(a)
print(b)
print(a+b)
print(b+c)
print(a-b)
print(b-c)
print(a * b)
# ======================================================
"""What are some potential efficiency disadvantages of having very deep inheritance
trees, that is, a large set of classes, A, B, C, and so on, such that B extends
A, C extends B, D extends C, etc.?
My Answer: The dynamic dispatch takes more time to determine the identifier and
its associated value. Also, you need to keep a large amount of key-value pair,
which is not memory efficient.
(1). Deep inheritance results in a very tight bingding between a superclass
and its subclasses
(2). Removing or swapping out a superclass may break subclasses.
(3). Deep inheritance is too complicated, which make the code hard to read.
"""
"""
What are some potential efficiency disadvantages of having very shallow
inheritance trees, that is, a large set of classes, A, B, C, and so on, such
that all of these classes extend a single class, Z?
If A, B, C are not related in real word, then there i nothing wrong.
Inheritance should be used when the classes form a strict hierarchy, where
subclasses are their parent classes in every sense of the word.
In that way, keep a shallow inheritance trees may cause code redundance.
And also hard to maintained.
"""
<file_sep># DataStructure-Algorithm-in-Python
Self-Practice, Learning and Googling.
DataStructure and algorithm in Python, assignments and solutions(part)
<file_sep>def dotProduct(a, b):
"""Write a short Python program that takes two arrays a and b of length n
storing int values, and returns the dot product of a and b. That is, it returns
an array c of length n such that c[i] = a[i] · b[i], for i = 0,...,n− 1.
>>> dotProduct([1,2,3], [2,3,4])
[2, 6, 12]
>>> dotProduct([3,2,3], [5,6,8])
[15, 12, 24]
>>> dotProduct([1,2,3], [2,1,3])
[2, 2, 9]
"""
# Assumption: The length of the array are the same
return [a[i]*b[i] for i in range(len(a))]
def indexOutOfBound(data):
"""1.23 Give an example of a Python code fragment that attempts to write an
element to a list based on an index that may be out of bounds. If that index
is out of bounds, the program should catch the exception that results, and
print the following error message:
“Don’t try buffer overflow attacks in Python!”"""
import random
while True:
try:
index = random.randrange(0, len(data)+1) # The last number is exlusive
print(data[index])
except IndexError as e:
print("Don't try buffer overflow attacks in Python!")
break
def vowelsCount(data):
"""1.24 Write a short Python function that counts the number of vowels in a given
character string.
>>> vowelsCount("you are kidding")
6
>>> vowelsCount("you are")
4
>>> vowelsCount("good")
2
>>> vowelsCount("GOOD")
2
"""
count = 0
for i in data:
if i in "aeiouAEIOU":
count += 1
return count
def removePunctuation(data):
"""25 Write a short Python function that takes a string s, representing a
sentence, and returns a copy of the string with all punctuation removed.
For example, if given the string "Let s try, Mike.", this function would
return "Lets try Mike"
>>> removePunctuation("You should be here, then we can go together.")
'You should be here then we can go together'
>>> removePunctuation("You, And, I? Good!")
'You And I Good'
"""
import string
return ''.join([i for i in data if i not in string.punctuation])
# For more efficient solution: visit http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python
def arithmeticHelper(a, b, c, operators):
for i in operators:
try:
if(i(a, b) == c):
return True
except ZeroDivisionError:
pass
return False
def arithmeticTest(a, b, c):
""" 1.26 Write a short program that takes as input three integers, a, b, and c, from
the console and determines if they can be used in a correct arithmetic
formula (in the given order), like “a+ b = c,” “a = b− c,” or “a∗ b = c.”
>>> arithmeticTest(3,4,7)
True
>>> arithmeticTest(5, 6, 30)
True
>>> arithmeticTest(5, 6, 31)
False
>>> arithmeticTest(10, 4, 6)
True
>>> arithmeticTest(8, 4, 2)
True
>>> arithmeticTest(11, 33, 3)
True
>>> arithmeticTest(1, 3, 2)
True
>>> arithmeticTest(1, 0, 2)
False
"""
from operator import add, sub, mul, truediv
operators = [add, sub, mul, truediv]
return arithmeticHelper(a,b,c,operators) or \
arithmeticHelper(a,c,b, operators) or \
arithmeticHelper(b,a,c, operators) or \
arithmeticHelper(b,c,a, operators) or \
arithmeticHelper(c,a,b, operators) or \
arithmeticHelper(c,b,a, operators)
# Sklip the 1.27 and 1.28
if __name__ == '__main__':
import doctest
doctest.testmod()
<file_sep># -*- coding: utf-8 -*-
# The Project Part
def stringCombination():
"""1.29 Write a Python program that outputs all possible strings formed by
using the characters c , a , t , d , o , and g exactly once."""
data = 'catdog'
for i in range(len(data)):
print(allCombination(data, i))
def allCombination(data, i):
if len(data) == 1:
return data
else:
return data[i] + allCombination(data[:i]+data[i+1:], 1)
def dividedByTwo(n):
""" 1.30 Write a Python program that can take a positive integer greater than 2 as
input and write out the number of times one must repeatedly divide this
number by 2 before getting a value less than 2.
>>> dividedByTwo(8)
3
>>> dividedByTwo(9)
3
>>> dividedByTwo(16)
4
>>> dividedByTwo(32)
5
>>> dividedByTwo(30)
4
"""
import math
return int(math.log(n, 2))
def divideTwo(n):
""" Using recursion to solve the problem.
>>> divideTwo(8)
3
>>> divideTwo(7)
2
>>> divideTwo(2)
1
>>> divideTwo(10)
3
>>> divideTwo(16)
4
>>> divideTwo(32)
5
"""
if n < 2:
return 0
else:
return 1 + divideTwo(n/2)
"""Write a Python program that can “make change.” Your program should
take two numbers as input, one that is a monetary amount charged and the
other that is a monetary amount given. It should then return the number
of each kind of bill and coin to give back as change for the difference
between the amount given and the amount charged. The values assigned
to the bills and coins can be based on the monetary system of any current
or former government. Try to design your program so that it returns as
few bills and coins as possible."""
if __name__ == '__main__':
import doctest
doctest.testmod()
|
26019481fec2455121a0f1d9c220629251abf1fd
|
[
"Markdown",
"Python"
] | 5 |
Markdown
|
Root-shady/DataStructure-Algorithm-in-Python
|
feac8b1e6f058aee7c1c72469094ccc13776e2a7
|
821a1a212f039f0bb47247532d4b7969457c6e20
|
refs/heads/master
|
<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
#ifndef GEOMETRYLIB_GLOBAL_H
#define GEOMETRYLIB_GLOBAL_H
#ifdef GEOMETRYLIB_LIB
# define GEOMETRYLIB_EXPORT __declspec(dllexport)
#else
# define GEOMETRYLIB_EXPORT __declspec(dllimport)
#endif
#endif // GEOMETRYLIB_GLOBAL_H
<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
/**
* @file : GeoLine.cpp
* @brief :
* @author : liuk
* @date : 2016/11/19 11:32:56
* @version : 1.0.0.0
* @contact : <EMAIL>
*
*/
#include "GeoLine.h"
GeoLine::GeoLine()
{
}
GeoLine::~GeoLine()
{
}
<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
/**
* @file : geometrylib.cpp
* @brief :
* @author : liuk
* @date : 2016/08/28 11:22
* @version : 1.0.0.0
* @contact : <EMAIL>
*
*/
#include "geometrylib.h"
GEOMETRYLIB_EXPORT bool gFuzzyCompare(double dX1, double dX2)
{
return fabs(dX1 - dX2) <= 0.00000001F * (min(fabs(dX1), fabs((dX2))));
}
<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
/**
* @file : GeoPoint.h
* @brief : 几何图形点的类型申明
* @author : liuk
* @date : 2016/08/28 12:14
* @version : 1.0.0.0
* @contact : <EMAIL>
*
*/
#ifndef _GEOPOINT_H
#define _GEOPOINT_H
#include <math.h>
/*!
* @class : CGeoPoint
* @brief : 几何图形中的点,有X轴与Y轴坐标共同描述
* @author : liuk
* @date : 2016/08/28 12:26
*/
class CGeoPoint
{
public:
/**
* @fn : CGeoPoint
* @brief : 点的默认构造函数,其X、坐标均设置为0.0
* @access : public
*/
CGeoPoint();
/**
* @fn : CGeoPoint
* @brief : 拷贝构造函数
* @access : public
* @param : const CGeoPoint & point 构造传值
*/
CGeoPoint(const CGeoPoint &point);
/**
* @fn : CGeoPoint
* @brief : 构造函数
* @access : public
* @param : double xpos x轴坐标
* @param : double ypos y轴坐标
*/
CGeoPoint(double xpos, double ypos);
/**
* @fn : ~CGeoPoint
* @brief : 析构
* @access : public
*/
~CGeoPoint();
/**
* @fn : ManhattanLength
* @brief : 返回横纵坐标的绝对值得和,就是传统上的从原点开始的矢量的“曼哈顿长度”。
* 这个传统的出现是因为这样的距离适用于在矩形方格上旅行的履行者们,就像曼哈顿的街道一样。
* @access : public
* @return : double 点的曼哈顿长度
*/
inline double ManhattanLength() const;
/**
* @fn : rx
* @brief : 返回x坐标的引用,可通过对返回值修改而直接改动当前坐标点
* @access : public
* @return : double& x轴的坐标引用
*/
inline double& rx();
/**
* @fn : ry
* @brief : 返回y坐标的引用,可通过对返回值修改而直接改动当前坐标点
* @access : public
* @return : double& y轴的坐标引用
*/
double& ry();
/**
* @fn : SetX
* @brief : 设置X轴坐标
* @access : public
* @param : double dX 新的X坐标
* @return : void
*/
inline void SetX(double dX);
/**
* @fn : SetY
* @brief : 设置Y轴坐标
* @access : public
* @param : double dY 新的Y轴坐标
* @return : void
*/
inline void SetY(double dY);
/**
* @fn : GetX
* @brief : 获取当前点X坐标
* @access : public
* @return : 当前点X坐标
*/
inline double GetX() const;
/**
* @fn : GetY
* @brief : 获取当前点Y坐标
* @access : public
* @return : 当前点Y坐标
*/
inline double GetY() const;
/**
* @fn : operator*
* @brief : 点的乘法运算,将其横纵坐标同时变为指定倍数
* @access : public
* @param : double factor 要改变的倍数
* @return : CGeoPoint 运算后的点坐标
*/
inline CGeoPoint operator*(double factor) const;
/**
* @fn : operator*=
* @brief : 自乘运算
* @access : public
* @param : double factor 要扩大的倍数
* @return : 当前点的引用
*/
inline CGeoPoint& operator*=(double factor);
/**
* @fn : operator+
* @brief : 计算两个点的和,将其横纵坐标分别相加
* @access : public
* @param : const CGeoPoint & point
* @return : CGeoPoint
*/
inline CGeoPoint operator+(const CGeoPoint &point) const;
inline CGeoPoint& operator+=(const CGeoPoint &point);
inline CGeoPoint operator-(const CGeoPoint &point) const;
inline CGeoPoint& operator-=(const CGeoPoint &point);
inline CGeoPoint operator/(double divisor) const;
inline CGeoPoint& operator/=(double divisor);
/**
* @fn : dotProduct
* @brief : 计算两个点的点积
* @access : public static
* @param : const CGeoPoint & p1
* @param : const CGeoPoint & p2
* @return : double
*/
static inline double dotProduct(const CGeoPoint &p1, const CGeoPoint &p2)
{
return p1.m_dX * p2.m_dX + p1.m_dY * p2.m_dY;
}
private:
double m_dX;
double m_dY;
};
inline double CGeoPoint::ManhattanLength() const
{
return fabs(m_dY) + fabs(m_dX);
}
inline double & CGeoPoint::rx()
{
return m_dX;
}
inline double & CGeoPoint::ry()
{
return m_dY;
}
inline void CGeoPoint::SetX(double dX)
{
m_dX = dX;
}
inline void CGeoPoint::SetY(double dY)
{
m_dY = dY;
}
inline double CGeoPoint::GetX() const
{
return m_dX;
}
inline double CGeoPoint::GetY() const
{
return m_dY;
}
inline CGeoPoint CGeoPoint::operator*(double factor) const
{
return CGeoPoint(m_dX * factor, m_dY * factor);
}
inline CGeoPoint & CGeoPoint::operator*=(double factor)
{
*this = *this * factor;
return *this;
}
inline CGeoPoint CGeoPoint::operator+(const CGeoPoint & point) const
{
return CGeoPoint(m_dX + point.GetX(), m_dY + point.GetY());
}
inline CGeoPoint& CGeoPoint::operator+=(const CGeoPoint &point)
{
*this = *this + point;
return *this;
}
inline CGeoPoint CGeoPoint::operator-(const CGeoPoint & point) const
{
return CGeoPoint(m_dX - point.GetX(), m_dY - point.GetY());
}
inline CGeoPoint & CGeoPoint::operator-=(const CGeoPoint & point)
{
*this = *this - point;
return *this;
}
inline CGeoPoint CGeoPoint::operator/(double divisor) const
{
return CGeoPoint(m_dX / divisor, m_dY / divisor);
}
inline CGeoPoint & CGeoPoint::operator/=(double divisor)
{
*this = *this / divisor;
return *this;
}
#endif<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
/**
* @file : geometrylib.h
* @brief :
* @author : liuka
* @date : 2016/08/28 11:22
* @version : 1.0.0.0
* @copyright: <EMAIL>
*
*/
#ifndef GEOMETRYLIB_H
#define GEOMETRYLIB_H
#include "math.h"
#include "geometrylib_global.h"
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
#ifndef PI
#define PI 3.1415926535897932384626433832795
#endif
/**
* @fn : gFuzzyCompare
* @brief : 比较两个浮点数是否相等,
* 因为在浮点数计算中容易出现精度损失,
* 故使用这种失精的算法来排除精度损失的干扰
* @access : public
* @param : double dX1 待比较的参数之一
* @param : double dX2 待比较的参数之一
* @return : 两数是否相等,相等返回true,否则返回false
*/
GEOMETRYLIB_EXPORT bool gFuzzyCompare(double dX1, double dX2);
#endif // GEOMETRYLIB_H
<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
/**
* @file : GeoLine.h
* @brief :
* @author : liuk
* @date : 2016/11/19 11:29:54
* @version : 1.0.0.0
* @contact : <EMAIL>
*
*/
#ifndef GEOLINE_H
#define GEOLINE_H
#include "GeoPoint.h"
/*!
* @class : GeoLine
* @brief : 线
* @author : liuk
* @date : 2016/11/19 11:30
*/
class GeoLine
{
public:
GeoLine();
~GeoLine();
public:
CGeoPoint GetP1() const;
CGeoPoint GetP2() const;
double GetX1() const;
double GetY1() const;
double GetX2() const;
double GetY2() const;
private:
CGeoPoint m_ptP1;
CGeoPoint m_ptP2;
};
#endif // GEOLINE_H<file_sep>/**********************************************************************
* @特别声明
* 本段代码由liuk创建,所有通过正常途径获取此文件的开发人员
* 均可任意修改、增加及删除文件内容,但请保留此声明。
* 如有疑问请联系作者。
* @特别声明结束
********************************************************************/
/**
* @file : GeoPoint.cpp
* @brief :
* @author : liuk
* @date : 2016/08/28 12:14
* @version : 1.0.0.0
* @contact : <EMAIL>
*
*/
#include "GeoPoint.h"
CGeoPoint::CGeoPoint()
: m_dX(0.0F),m_dY(0.0F)
{
}
CGeoPoint::CGeoPoint(const CGeoPoint &point)
{
*this = point;
}
CGeoPoint::CGeoPoint(double xpos, double ypos)
: m_dX(xpos), m_dY(ypos)
{
}
CGeoPoint::~CGeoPoint()
{
}
|
4e301021281d331c6884e7ba8e99d39990877d09
|
[
"C++",
"C"
] | 7 |
C++
|
liuk-cn-cd/GeometryLib
|
6624378539133cb94e627638f3e9e6208dd1c046
|
0f0b543809a24e5b26cbc86ba28d0ad0435518d8
|
refs/heads/master
|
<file_sep>var config = {
port:7777,
plugins:{
cache:{plugin:require('../plugins/restack_cache'),settings:{
}},
data:{plugin:require('../plugins/restack_data'),settings:{
}},
authentication:{plugin:require('../plugins/restack_auth'),settings:{
}},
session:{plugin:require('../plugins/restack_session'),settings:{
}}
},
middleware:{
authentication:require('../middleware/authentication'),
cache:require('../middleware/cache'),
data:require('../middleware/data'),
headers:require('../middleware/response'),
router:require('../middleware/router'),
session:require('../middleware/session')
}
}
module.exports = config;<file_sep>var data_helper = {
internals:{
},
connected:false,
initialize:function(params, done)
{
//done('Not implemented');
done();
},
getType:function(type, done){
done('Not implemented');
},
find:function(type, criteria, done)
{
done('Not implemented');
},
findIn:function(type, columnName, matchValues, done)
{
done('Not implemented');
},
findOne:function(type, criteria, done)
{
done('Not implemented');
},
getById:function(type, id, done)
{
done('Not implemented');
},
getAll:function(type, done)
{
done('Not implemented');
},
create:function(type, obj, done) {
done('Not implemented');
},
update_criteria:function(type, criteria, obj, done) {
done('Not implemented');
},
update:function(id, type, obj, done) {
done('Not implemented');
},
destroy:function(type, id, done) {
done('Not implemented');
}
}
module.exports = data_helper;<file_sep>/*
* Packages the operation response
*/
var response = function (err, req, res, next) {
console.log('response called');
var status = 'OK';
var data = null;
var message = null;
if (req['operation'] != null && req['operation']['payload'] != null)
data = req['operation']['payload'];
if (err)
{
message = err.toString();
}
else
{
if (req['operation'] != null && req['operation']['message'] != null)
message = req['operation']['message'];
}
res.setHeader("X-Powered-By","restackJS");
res.setHeader("Access-Control-Allow-Origin",req.headers['host']);
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
res.setHeader("Access-Control-Allow-Methods", "GET,PUT,DELETE,POST");
res.send({'status':status, 'message':message, 'data':data}) ;
}
module.exports = response;<file_sep>var config = {
port:7777,
plugins:{
cache:{settings:{
}},
data:{settings:{
}},
authentication:{settings:{
}},
session:{settings:{
}}
},
middleware:{
},
application_schema:require('./restack_test_schema')
}
module.exports = config;<file_sep>var request = require('request');
var assert = require("assert");
describe('server-test', function(){
it('testCreateAccount', function(callback){
assert.fail('test not implemented');
callback();
});
it('testLogin', function(callback){
assert.fail('test not implemented');
callback();
});
it('testCreateData', function(callback){
assert.fail('test not implemented');
callback();
});
it('testGetData', function(callback){
assert.fail('test not implemented');
callback();
});
it('testFindData', function(callback){
assert.fail('test not implemented');
callback();
});
it('testUpdateData', function(callback){
assert.fail('test not implemented');
callback();
});
it('testDeleteData', function(callback){
assert.fail();
callback();
});
it('testCreateGuest', function(callback){
assert.fail('test not implemented');
callback();
});
it('testGuestInsufficientPriviledges', function(callback){
assert.fail('test not implemented');
callback();
});
it('testGetPermissions', function(callback){
assert.fail('test not implemented');
callback();
});
});
<file_sep>var router =
{createAccount:function (req,res,next) {
console.log('createAccount called');
req.urlChecked = true;
//code here updates request with operation object
next();
},confirmAccount:function (req,res,next) {
console.log('confirmAccount called');
req.urlChecked = true;
//code here updates request with operation object
next();
},login:function (req,res,next) {
console.log('login called');
req.urlChecked = true;
//code here updates request with operation object
next();
},availableAccounts:function (req,res,next) {
console.log('availableAccounts called');
req.urlChecked = true;
//code here updates request with operation object
next();
},getPermissions:function (req,res,next) {
console.log('availableAccounts called');
req.urlChecked = true;
//code here updates request with operation object
next();
},getModel:function (req,res,next) {
console.log('getModel called');
req.urlChecked = true;
//code here updates request with operation object
next();
},find:function (req,res,next) {
console.log('find called');
req.urlChecked = true;
//code here updates request with operation object
next();
},getAll:function (req,res,next) {
console.log('getAll called');
req.urlChecked = true;
//code here updates request with operation object
next();
},getItemById:function (req,res,next) {
console.log('getItemById called');
req.urlChecked = true;
//code here updates request with operation object
next();
},createItem:function (req,res,next) {
console.log('createItem called');
req.urlChecked = true;
//code here updates request with operation object
next();
},updateItem:function (req,res,next) {
console.log('updateItem called');
req.urlChecked = true;
//code here updates request with operation object
next();
},deleteItem:function (req,res,next) {
console.log('deleteItem called');
req.urlChecked = true;
//code here updates request with operation object
next();
},check:function (req,res,next) {
console.log('check called');
if (!req.urlChecked)
next('Path not valid');
else
next();
}
}
module.exports = router;
|
16ffb45d70d13d14e0cd186a871ae0a970c1f713
|
[
"JavaScript"
] | 6 |
JavaScript
|
ianpetzer/restack
|
cf388ff03ee5c57862993021ba4bc8af814bfb97
|
a82e79e579423725353c01be9dc3f7ee4995ef5e
|
refs/heads/master
|
<repo_name>gurunate/sorting-app<file_sep>/server.js
'use strict';
const express = require('express');
const expressHandlebars = require('express-handlebars');
const config = require('rc')('app');
const env = process.env.NODE_ENV || 'development';
const server = express();
server.use(express.static(__dirname + '/public'));
// Register handlebars template engine
server.engine('hbs', expressHandlebars({
defaultLayout: 'default',
extname: 'hbs'
}));
server.set('view engine', 'hbs');
server.get('/', (req, res) => {
res.render('home', {
title: config[env].title
});
});
// Start server
server.listen(config[env].port, (err) => {
if (err) {
throw err;
} else {
console.log(`Server running at http://localhost:${config[env].port}`);
}
});
<file_sep>/views/partials/footer.hbs
<footer>
© 2017
</footer>
<file_sep>/README.md
# sorting-app
A sorting hat Node app.
## Setup
```bash
$ npm install
```
## Start
```bash
$ npm start
```
# Dependences
* [Node](https://nodejs.org/)
* http://3.bp.blogspot.com/-5bomIo2ycKo/UKUbsKF36sI/AAAAAAAAAJg/Jf7INtC4TEA/s1600/the_sorting_hat__by_rose_ann_mary_k-d3108ym.jpg
<file_sep>/views/partials/header.hbs
<header>
<nav>
Header coming...
</nav>
</header>
|
0fdf91bec6aac56aad4264be9618e6ea358c5020
|
[
"Handlebars",
"Markdown",
"JavaScript"
] | 4 |
Handlebars
|
gurunate/sorting-app
|
78ce665fba1a22ca2b769748c718154e56d24686
|
e49e45f8c399bbd7587062eae6813a9dbf3b5770
|
refs/heads/master
|
<repo_name>hoppertunity/SimpleFragment<file_sep>/classes/OL_DepotRoutingHelper.cls
/**
* File Name : OL_DepotRoutingHelper.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 04/09/2014 <NAME> TNT-542 find collection depot
*/
public with sharing class OL_DepotRoutingHelper {
public static String errorMsg;
public static Id routingTableId;
public static Id depotRoutingId;
public static String cutOffTime;
public static Account findCollectionDepot(String collPostcode, String collDistrict, String collTown, Id lobId, Datetime collTime)
{
// reset variables
routingTableId = null;
depotRoutingId = null;
cutOffTime = null;
errorMsg = '';
errorMsg += String.isBlank(collPostcode) ? '- missing collection postcode<br/>' : '';
errorMsg += String.isBlank(collTown) ? '- missing collection town<br/>' : '';
errorMsg += lobId == null ? '- missing line of business<br/>' : '';
errorMsg += collTime == null ? '- missing collection time<br/>' : '';
if(String.isNotBlank(errorMsg))
{
errorMsg = 'Could not calculate depot:<br/>' + errorMsg;
return null;
}
else
{
errorMsg = null;
}
Routing_Table__c rt = findRoutingTableEntry(collPostcode, collDistrict, collTown);
if(rt == null)
{
errorMsg = 'No Routing Table entry found.';
return null;
}
Day__c d = findDay(rt.Depot__r.Depot_Calendar__c,collTime);
if(d == null)
{
errorMsg = 'No Calendar/Day entry found.';
return null;
}
if(d.Day_Type__c.startsWith(ConstantUtil.PLVAL_DAY_DAYTYPE_NONWORKING))
{
errorMsg = 'Selected collection date is a non working day.';
return null;
}
String roundGroup = d.Day_Type__c.startsWith(ConstantUtil.PLVAL_DAY_DAYTYPE_WORKING)
? ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_NORMAL : ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_SATURDAY;
Account collDepot = findDepot(lobId, rt.Id, roundGroup);
errorMsg = collDepot == null ? 'No depot found.' : null;
routingTableId = collDepot == null ? null : rt.Id;
return collDepot;
}
public static Routing_Table__c findRoutingTableEntry(String collPostcode, String collDistrict, String collTown)
{
if(String.isNotBlank(collPostcode) && collPostcode.length() > 3)
{
String pc = collPostcode;
pc = pc.substring(0, pc.length()-2);
for(Routing_Table__c rtab : [select id, Depot__c, Depot__r.Depot_Calendar__c from Routing_Table__c
where Part_Postcode__c = :pc
and District__c = :collDistrict
and Town__c = :collTown
order by Routing_Default__c desc]) // default first
{
return rtab;
}
}
return null;
}
public static Day__c findDay(Id calId, Datetime collTime)
{
for(Day__c d : [select Id, Day_Type__c from Day__c where Date__c = :collTime.date() and Calendar__c = :calId])
{
return d;
}
return null;
}
public static Account findDepot(Id lobId, Id rtId, String roundGroup)
{
String network = lobId == null ? null : [select Routing_Network__c from Line_of_Business__c where Id = :lobId limit 1].Routing_Network__c;
for(Depot_Routing__c dr : [select Collection_Cut_Off_Time__c, Collection_Depot__c, Collection_Depot__r.Name, Collection_Depot__r.Depot_Number__c
from Depot_Routing__c
where Routing_Table__c = :rtId and Collection_Depot__c != null
and (Line_Of_Business__c = :lobId or Line_Of_Business__c = null)
and (Round_Group__c = :roundGroup or Round_Group__c = :ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_ALL)
and Routing_Network__c =:network
order by Line_Of_Business__c asc nulls last]) // exact matches have precedence over nulls
{
depotRoutingId = dr.Id;
cutOffTime = dr.Collection_Cut_Off_Time__c;
return dr.Collection_Depot__r;
}
return null;
}
}<file_sep>/classes/uksvcsTntGetQuotePricingServiceMockImpl.cls
/**
* File Name : uksvcsTntGetQuotePricingServiceMockImpl.cls
* Description : Mock class to test Pricing service
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 11/08/2014 <NAME> Initial version, TNT-545
*/
@isTest
global class uksvcsTntGetQuotePricingServiceMockImpl implements WebServiceMock{
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
uksvcsTntGetQuotePricing.ResponseMessage_MasterType respElement = new uksvcsTntGetQuotePricing.ResponseMessage_MasterType();
respElement.qt = new uksvcsTntGetQuotePricing.QuoteResponse_MasterType();
respElement.qt.dels = new uksvcsTntGetQuotePricing.Deliveries_ContainerType();
respElement.qt.dels.del = new List<uksvcsTntGetQuotePricing.Delivery_MasterType>();
uksvcsTntGetQuotePricing.Delivery_MasterType del = new uksvcsTntGetQuotePricing.Delivery_MasterType();
del.delDt = Date.today();
del.delSvcs = new uksvcsTntGetQuotePricing.DeliveryServices_ContainerType();
del.delSvcs.delSvc = new List<uksvcsTntGetQuotePricing.DeliveryService_MasterType>();
uksvcsTntGetQuotePricing.DeliveryService_MasterType delSvc = new uksvcsTntGetQuotePricing.DeliveryService_MasterType();
delSvc.svcCd = 'SC';
delSvc.cmm = 'ServName';
delSvc.qtAmt = '50.45';
delSvc.curCd = 'GPB';
delSvc.prSvcInd = false;
delSvc.guarSvcInd = true;
delSvc.srchrgs = new uksvcsTntGetQuotePricing.Surcharges_ContainerType();
delSvc.srchrgs.srchrg = new List<uksvcsTntGetQuotePricing.Surcharge_MasterType>();
uksvcsTntGetQuotePricing.Surcharge_MasterType srch = new uksvcsTntGetQuotePricing.Surcharge_MasterType();
srch.srchrgTypCd = 'Sch Code';
srch.srchrgTypNm = 'Sch Name';
srch.chrgAmt = '5.45';
srch.curCd = 'GBP';
srch.chrgPrcnt = '1.1';
delSvc.srchrgs.srchrg.add(srch);
del.delSvcs.delSvc.add(delSvc);
respElement.qt.dels.del.add(del);
response.put('response_x', respElement);
}
}<file_sep>/classes/TimeUtilTest.cls
/**
* File Name : TimeUtilTest.cls
* Description : test time methods
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 03/07/2014 <NAME> Initial version
*
*
*/
@isTest
private class TimeUtilTest {
static Date monday = Date.newInstance(2014,6,30); // June 30th, 2014 (Monday)
static testMethod void testWorkdaysEarlyMorning()
{
TestUtil.setupBusinessHoursAndHolidays();
// cycle through the week trying out days
Integer hrs = 2;
Datetime mondayDT = Datetime.newInstance(monday.year(),monday.month(),monday.day(),hrs,0,0);
system.assertEquals(ConstantUtil.MONDAY_ABRV,TimeUtil.getDayOfWeek(mondayDT));
for(Integer i = 0; i < ConstantUtil.DAYS_IN_WEEK; i++)
{
Datetime dt = mondayDT.addDays(i);
system.assert(i != 6 ? TimeUtil.isWorkDay(dt.date()) : !TimeUtil.isWorkDay(dt.date()),
'Only Sunday should be a non working day: ' + TimeUtil.getDayOfWeek(dt));
system.assert(i == 2 ? TimeUtil.isAllday(dt.date()) : !TimeUtil.isAllday(dt.date()),
'Only Wednesday should be all day: ' + TimeUtil.getDayOfWeek(dt));
system.assert(i == 2 ? TimeUtil.isWithinWorkHours(dt) : !TimeUtil.isWithinWorkHours(dt),
'02:00h should not be within working hours except on Wednesday: ' + TimeUtil.getDayOfWeek(dt));
}
}
static testMethod void testWorkdaysMidday()
{
TestUtil.setupBusinessHoursAndHolidays();
// cycle through the week trying out days
Integer hrs = 12;
Datetime mondayDT = Datetime.newInstance(monday.year(),monday.month(),monday.day(),hrs,0,0);
system.assertEquals(ConstantUtil.MONDAY_ABRV,TimeUtil.getDayOfWeek(mondayDT));
for(Integer i = 0; i < ConstantUtil.DAYS_IN_WEEK; i++)
{
Datetime dt = mondayDT.addDays(i);
system.assert(i != 6 ? TimeUtil.isWorkDay(dt.date()) : !TimeUtil.isWorkDay(dt.date()),
'Only Sunday should be a non working day: ' + TimeUtil.getDayOfWeek(dt));
system.assert(i == 2 ? TimeUtil.isAllday(dt.date()) : !TimeUtil.isAllday(dt.date()),
'Only Wednesday should be all day: ' + TimeUtil.getDayOfWeek(dt));
system.assert(i != 6 ? TimeUtil.isWithinWorkHours(dt) : !TimeUtil.isWithinWorkHours(dt),
'12:00h should be within working hours except on Sunday: ' + TimeUtil.getDayOfWeek(dt));
}
}
static testMethod void testHolidays()
{
TestUtil.setupBusinessHoursAndHolidays();
// assert that holidays really are detected as such
for(Holiday hd : TimeUtil.holidays)
{
system.assert(TimeUtil.isHoliday(hd.ActivityDate),'TimeUtil.isHoliday() returned false for holiday: ' + hd.ActivityDate);
}
}
static testMethod void testResumeDates()
{
TestUtil.setupBusinessHoursAndHolidays();
Test.startTest();
Time t;
// DT before usual work hours
t = Time.newInstance(2,0,0,0);
system.assertEquals(Datetime.newInstance(monday,TimeUtil.bh.MondayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday,t)));
system.assertEquals(Datetime.newInstance(monday.addDays(1),TimeUtil.bh.TuesdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(1),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(2),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(2),t))); // Wed is all day
system.assertEquals(Datetime.newInstance(monday.addDays(3),TimeUtil.bh.ThursdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(3),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(4),TimeUtil.bh.FridayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(4),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(5),TimeUtil.bh.SaturdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(5),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(7),TimeUtil.bh.MondayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(6),t))); // Sun is not work day
// DT during usual work hours
t = Time.newInstance(12,0,0,0);
system.assertEquals(Datetime.newInstance(monday,t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday,t)));
system.assertEquals(Datetime.newInstance(monday.addDays(1),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(1),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(2),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(2),t))); // Wed is all day
system.assertEquals(Datetime.newInstance(monday.addDays(3),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(3),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(4),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(4),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(5),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(5),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(7),TimeUtil.bh.MondayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(6),t))); // Sun is not work day
// DT after usual work hours
t = Time.newInstance(20,0,0,0);
system.assertEquals(Datetime.newInstance(monday.addDays(1),TimeUtil.bh.TuesdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday,t)));
system.assertEquals(Datetime.newInstance(monday.addDays(2),TimeUtil.bh.WednesdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(1),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(2),t),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(2),t))); // Wed is all day
system.assertEquals(Datetime.newInstance(monday.addDays(4),TimeUtil.bh.FridayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(3),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(5),TimeUtil.bh.SaturdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(4),t)));
system.assertEquals(Datetime.newInstance(monday.addDays(7),TimeUtil.bh.MondayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(5),t))); // Sun is not work day
system.assertEquals(Datetime.newInstance(monday.addDays(7),TimeUtil.bh.MondayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(monday.addDays(6),t))); // Sun is not work day
// holidays
t = Time.newInstance(12,0,0,0);
system.assertEquals(Datetime.newInstance(Date.newInstance(2014,4,3),TimeUtil.bh.ThursdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(Date.newInstance(2014,4,2),t)));
system.assertEquals(Datetime.newInstance(Date.newInstance(2013,12,27),TimeUtil.bh.FridayStartTime), // Xmas 2013 was Wed
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(Date.newInstance(2013,12,25),t)));
t = Time.newInstance(20,0,0,0);
system.assertEquals(Datetime.newInstance(Date.newInstance(2014,4,3),TimeUtil.bh.ThursdayStartTime),
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(Date.newInstance(2014,4,1),t)));
system.assertEquals(Datetime.newInstance(Date.newInstance(2013,12,27),TimeUtil.bh.FridayStartTime), // Xmas 2013 was Wed
TimeUtil.getWorkingDayResumeDT(Datetime.newInstance(Date.newInstance(2013,12,24),t)));
Test.stopTest();
}
static testMethod void testAddWorkHours()
{
TestUtil.setupBusinessHoursAndHolidays();
Test.startTest();
Time t;
// DT before usual work hours
t = Time.newInstance(2,0,0,0);
system.assertEquals(Datetime.newInstance(monday.addDays(2),Time.newInstance(4,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday,t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(2),Time.newInstance(14,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(1),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(3),Time.newInstance(10,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(2),t),24)); // Wed is all day
system.assertEquals(Datetime.newInstance(monday.addDays(5),Time.newInstance(13,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(3),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(7),Time.newInstance(14,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(4),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(8),Time.newInstance(13,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(5),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(9),Time.newInstance(4,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(6),t),24)); // Sun is not work day
// DT during usual work hours
t = Time.newInstance(12,0,0,0);
system.assertEquals(Datetime.newInstance(monday.addDays(2),Time.newInstance(8,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday,t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(2),Time.newInstance(18,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(1),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(4),Time.newInstance(10,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(2),t),24)); // Wed is all day
system.assertEquals(Datetime.newInstance(monday.addDays(5),Time.newInstance(17,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(3),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(7),Time.newInstance(18,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(4),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(8),Time.newInstance(16,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(5),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(9),Time.newInstance(4,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(6),t),24)); // Sun is not work day
// DT after usual work hours
t = Time.newInstance(20,0,0,0);
system.assertEquals(Datetime.newInstance(monday.addDays(2),Time.newInstance(14,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday,t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(2),Time.newInstance(23,59,59,999)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(1),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(5),Time.newInstance(9,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(2),t),24)); // Wed is all day
system.assertEquals(Datetime.newInstance(monday.addDays(7),Time.newInstance(14,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(3),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(8),Time.newInstance(13,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(4),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(9),Time.newInstance(4,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(5),t),24));
system.assertEquals(Datetime.newInstance(monday.addDays(9),Time.newInstance(4,0,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(monday.addDays(6),t),24)); // Sun is not work day
// holidays
t = Time.newInstance(12,0,0,0);
system.assertEquals(Datetime.newInstance(Date.newInstance(2014,4,4),Time.newInstance(16,00,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(Date.newInstance(2014,4,1),t),24));
system.assertEquals(Datetime.newInstance(Date.newInstance(2013,12,30),Time.newInstance(14,0,0,0)), // Xmas 2013 was Wed
TimeUtil.addWorkHours(Datetime.newInstance(Date.newInstance(2013,12,25),t),24));
t = Time.newInstance(20,0,0,0);
system.assertEquals(Datetime.newInstance(Date.newInstance(2014,4,5),Time.newInstance(13,30,0,0)),
TimeUtil.addWorkHours(Datetime.newInstance(Date.newInstance(2014,4,1),t),24));
system.assertEquals(Datetime.newInstance(Date.newInstance(2013,12,30),Time.newInstance(14,0,0,0)), // Xmas 2013 was Wed
TimeUtil.addWorkHours(Datetime.newInstance(Date.newInstance(2013,12,24),t),24));
Test.stopTest();
}
public static testMethod void testHMTime()
{
Test.startTest();
TimeUtil.HMTime hmt = new TimeUtil.HMTime('12:30');
system.assertEquals('12',hmt.hour);
system.assertEquals('30',hmt.minute);
system.assertEquals(TimeUtil.hours.size()+1,hmt.getHourOptions().size());
system.assertEquals(TimeUtil.minutes.size()+1,hmt.getMinuteOptions().size());
system.assertEquals('12:30',hmt.getFormatedTime());
Test.stoptest();
}
static testMethod void testCalculateMinutesInBusinessHours()
{
//Test calss is very sensetive to bussiness hours
Test.startTest();
DateTime startDT = DateTime.newInstance(Date.newInstance(2015, 4, 17), TimeUtil.bh.FridayEndTime.addMinutes(-30));
DateTime endDT = DateTime.newInstance(Date.newInstance(2015, 4, 20), TimeUtil.bh.MondayStartTime.addMinutes(90));
Decimal mins = TimeUtil.calculateMinutesInBusinessHours(startDT, endDT);
system.assertEquals(120, mins);
mins = TimeUtil.calculateMinutesInBusinessHours(startDT, null);
system.assertEquals(0, mins);
mins = TimeUtil.calculateMinutesInBusinessHours(null, endDT);
system.assertEquals(0, mins);
endDT = DateTime.newInstance(Date.newInstance(2015, 4, 17), TimeUtil.bh.FridayEndTime.addMinutes(-10));
mins = TimeUtil.calculateMinutesInBusinessHours(startDT, endDT);
system.assertEquals(20, mins);
startDT = DateTime.newInstance(Date.newInstance(2015, 4, 17), TimeUtil.bh.FridayEndTime.addMinutes(30));
endDT = DateTime.newInstance(Date.newInstance(2015, 4, 17), TimeUtil.bh.FridayEndTime.addMinutes(120));
mins = TimeUtil.calculateMinutesInBusinessHours(startDT, endDT);
system.assertEquals(0, mins);
startDT = DateTime.newInstance(Date.newInstance(2015, 4, 17), TimeUtil.bh.FridayEndTime.addMinutes(120));
endDT = DateTime.newInstance(Date.newInstance(2015, 4, 17), TimeUtil.bh.FridayEndTime.addMinutes(-30));
mins = TimeUtil.calculateMinutesInBusinessHours(startDT, endDT);
system.assertEquals(-30, mins);
Test.stopTest();
}
}<file_sep>/classes/CS_ClaimsTriggerHandler.cls
/**
* File Name : CS_ClaimsTriggerHandler.cls
* Description : methods called from CS_Claims trigger
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 16/07/2014 <NAME> Initial version
*
*/
public with sharing class CS_ClaimsTriggerHandler {
// HANDLERS
public static void onBeforeInsertHandler(List<CS_Claims__c> triggerNew)
{
fillDataFromRelatedObjects(triggerNew);
}
public static void onAfterInsertHandler(List<CS_Claims__c> triggerNew)
{
}
public static void onAfterUpdateHandler(List<CS_Claims__c> triggerNew, Map<Id,CS_Claims__c> triggerOldMap)
{
}
public static void onBeforeUpdateHandler(List<CS_Claims__c> triggerNew, Map<Id,CS_Claims__c> triggerOldMap)
{
}
// METHODS
private static void fillDataFromRelatedObjects(List<CS_Claims__c> claims){
Set<Id> accountIds = new Set<Id>();
Set<Id> contactIds = new Set<Id>();
for(CS_Claims__c c : claims){
accountIds.add(c.Account__c);
accountIds.add(c.Depot__c);
contactIds.add(c.Contact__c);
}
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Name, AccountNumber, BillingStreet, BillingState, BillingPostalCode,
BillingCountry, BillingCity, Phone
FROM Account WHERE Id IN : accountIds]);
Map<Id, Contact> contacts = new Map<Id, Contact>([SELECT Name, Email, MailingStreet, MailingState, MailingPostalCode,
MailingCountry, MailingCity, Phone
FROM Contact WHERE Id IN : contactIds]);
//Select Address Information
Map<Id, Account_Address__c> aId_DefAddress = new Map<Id, Account_Address__c>();
for(Account_Address__c aa : [SELECT Account__c, Street_1__c, Street_2__c, City__c, Postcode__c FROM Account_Address__c WHERE Account__c IN : accountIds AND Default__c = true]){
aId_DefAddress.put(aa.Account__c, aa);
}
//fill fields in Claims
for(CS_Claims__c c : claims){
Account a = accounts.get(c.Account__c);
Account d = accounts.get(c.Depot__c);
Contact cont = contacts.get(c.Contact__c);
Account_Address__c aa = aId_DefAddress.get(c.Account__c);
c.TNT_account_no__c = a.AccountNumber;
c.Sender_company_name__c = a.Name;
if(aa != null){
c.Sender_Address_1__c = aa.Street_1__c;
c.Sender_Address_2__c = aa.Street_2__c;
c.Sender_Address_3__c = aa.City__c;
c.Sender_Postcode__c = aa.Postcode__c;
}
c.Sender_Telephone_no__c = a.Phone;
c.Depot_no__c = d.AccountNumber;
if(cont != null){
c.Sender_Contact_Name__c = cont.Name;
if(c.Sender_Email_Address__c == null || c.Sender_Email_Address__c == ''){
c.Sender_Email_Address__c = cont.Email;
}
}
}
}
}<file_sep>/classes/GBMailer_Service.cls
/**
* File Name : GBMailer_Service.cls
* Description : orginally generated by wsdl2apex
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 05/08/2014 <NAME> Initial version (TNT-549)
*
*/
public class GBMailer_Service {
public class CreateSessionResponse_element {
public String CreateSessionResult;
private String[] CreateSessionResult_type_info = new String[]{'CreateSessionResult','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'CreateSessionResult'};
}
/* ---- Not in use ----
public class Info_element {
public String szPackageName;
public String szSessionID;
public String szUserName;
public String szPassword;
public String szInfoType;
private String[] szPackageName_type_info = new String[]{'szPackageName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szSessionID_type_info = new String[]{'szSessionID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szUserName_type_info = new String[]{'szUserName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPassword_type_info = new String[]{'szPassword','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szInfoType_type_info = new String[]{'szInfoType','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'szPackageName','szSessionID','szUserName','szPassword','szInfoType'};
}
public class Find_element {
public String szPackageName;
public String szSessionID;
public String szUserName;
public String szPassword;
public GBMailer_Service.AcceleratorAddress structSearchCriteria;
public String szAddressFormat;
public String szRelatedTypes;
public String szAddressLevel;
public Integer nOffset;
public Integer nMaxReturns;
private String[] szPackageName_type_info = new String[]{'szPackageName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szSessionID_type_info = new String[]{'szSessionID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szUserName_type_info = new String[]{'szUserName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPassword_type_info = new String[]{'szPassword','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] structSearchCriteria_type_info = new String[]{'structSearchCriteria','http://webportal.gb.co.uk/GBPortal','AcceleratorAddress','1','1','false'};
private String[] szAddressFormat_type_info = new String[]{'szAddressFormat','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szRelatedTypes_type_info = new String[]{'szRelatedTypes','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szAddressLevel_type_info = new String[]{'szAddressLevel','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] nOffset_type_info = new String[]{'nOffset','http://www.w3.org/2001/XMLSchema','int','1','1','false'};
private String[] nMaxReturns_type_info = new String[]{'nMaxReturns','http://www.w3.org/2001/XMLSchema','int','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'szPackageName','szSessionID','szUserName','szPassword','structSearchCriteria','szAddressFormat','szRelatedTypes','szAddressLevel','nOffset','nMaxReturns'};
}
*/
public class AcceleratorItem {
public String Key;
public String Value;
private String[] Key_type_info = new String[]{'Key','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Value_type_info = new String[]{'Value','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'Key','Value'};
}
/* ---- Not in use ----
public class FindResponse_element {
public GBMailer_Service.AcceleratorSearchReturn FindResult;
private String[] FindResult_type_info = new String[]{'FindResult','http://webportal.gb.co.uk/GBPortal','AcceleratorSearchReturn','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'FindResult'};
}
*/
public class TerminateSessionResponse_element {
public Boolean TerminateSessionResult;
private String[] TerminateSessionResult_type_info = new String[]{'TerminateSessionResult','http://www.w3.org/2001/XMLSchema','boolean','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'TerminateSessionResult'};
}
/* ---- Not in use ----
public class TriggerEventResponse_element {
public String TriggerEventResult;
private String[] TriggerEventResult_type_info = new String[]{'TriggerEventResult','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'TriggerEventResult'};
}
*/
public class GBPortalWSSoap {
public String endpoint_x = 'https://webportal.gb.co.uk/GBPortalWS/GBPortalWS.asmx';
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal', 'GBMailer_Service'};
/* ---- Not in use ----
public String TriggerEvent(String szPackageName,String szEventID,String szSessionID,String szUserName,String szPassword,String szParameterData) {
GBMailer_Service.TriggerEvent_element request_x = new GBMailer_Service.TriggerEvent_element();
GBMailer_Service.TriggerEventResponse_element response_x;
request_x.szPackageName = szPackageName;
request_x.szEventID = szEventID;
request_x.szSessionID = szSessionID;
request_x.szUserName = szUserName;
request_x.szPassword = <PASSWORD>;
request_x.szParameterData = szParameterData;
Map<String, GBMailer_Service.TriggerEventResponse_element> response_map_x = new Map<String, GBMailer_Service.TriggerEventResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/TriggerEvent',
'http://webportal.gb.co.uk/GBPortal',
'TriggerEvent',
'http://webportal.gb.co.uk/GBPortal',
'TriggerEventResponse',
'GBMailer_Service.TriggerEventResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.TriggerEventResult;
}
public GBMailer_Service.AcceleratorSearchReturn Find(String szPackageName,String szSessionID,String szUserName,String szPassword,GBMailer_Service.AcceleratorAddress structSearchCriteria,String szAddressFormat,String szRelatedTypes,String szAddressLevel,Integer nOffset,Integer nMaxReturns) {
GBMailer_Service.Find_element request_x = new GBMailer_Service.Find_element();
GBMailer_Service.FindResponse_element response_x;
request_x.szPackageName = szPackageName;
request_x.szSessionID = szSessionID;
request_x.szUserName = szUserName;
request_x.szPassword = <PASSWORD>;
request_x.structSearchCriteria = structSearchCriteria;
request_x.szAddressFormat = szAddressFormat;
request_x.szRelatedTypes = szRelatedTypes;
request_x.szAddressLevel = szAddressLevel;
request_x.nOffset = nOffset;
request_x.nMaxReturns = nMaxReturns;
Map<String, GBMailer_Service.FindResponse_element> response_map_x = new Map<String, GBMailer_Service.FindResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/Find',
'http://webportal.gb.co.uk/GBPortal',
'Find',
'http://webportal.gb.co.uk/GBPortal',
'FindResponse',
'GBMailer_Service.FindResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.FindResult;
}*/
public GBMailer_Service.AcceleratorSearchReturn Pinpoint(String szPackageName,String szSessionID,String szUserName,String szPassword,String szPostcode,String szPremise,String szAddressFormat,String szRelatedTypes,Integer nOffset,Integer nMaxReturns) {
GBMailer_Service.Pinpoint_element request_x = new GBMailer_Service.Pinpoint_element();
GBMailer_Service.PinpointResponse_element response_x;
request_x.szPackageName = szPackageName;
request_x.szSessionID = szSessionID;
request_x.szUserName = szUserName;
request_x.szPassword = <PASSWORD>;
request_x.szPostcode = szPostcode;
request_x.szPremise = szPremise;
request_x.szAddressFormat = szAddressFormat;
request_x.szRelatedTypes = szRelatedTypes;
request_x.nOffset = nOffset;
request_x.nMaxReturns = nMaxReturns;
Map<String, GBMailer_Service.PinpointResponse_element> response_map_x = new Map<String, GBMailer_Service.PinpointResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/Pinpoint',
'http://webportal.gb.co.uk/GBPortal',
'Pinpoint',
'http://webportal.gb.co.uk/GBPortal',
'PinpointResponse',
'GBMailer_Service.PinpointResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.PinpointResult;
}
/* ---- Not in use ----
public GBMailer_Service.AcceleratorInfoReturn Info(String szPackageName,String szSessionID,String szUserName,String szPassword,String szInfoType) {
GBMailer_Service.Info_element request_x = new GBMailer_Service.Info_element();
GBMailer_Service.InfoResponse_element response_x;
request_x.szPackageName = szPackageName;
request_x.szSessionID = szSessionID;
request_x.szUserName = szUserName;
request_x.szPassword = <PASSWORD>;
request_x.szInfoType = szInfoType;
Map<String, GBMailer_Service.InfoResponse_element> response_map_x = new Map<String, GBMailer_Service.InfoResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/Info',
'http://webportal.gb.co.uk/GBPortal',
'Info',
'http://webportal.gb.co.uk/GBPortal',
'InfoResponse',
'GBMailer_Service.InfoResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.InfoResult;
}
public GBMailer_Service.AcceleratorSearchReturn getList(String szPackageName,String szSessionID,String szUserName,String szPassword,String szKey,String szTemplate,Integer nOffset,Integer nMaxReturns) {
GBMailer_Service.List_element request_x = new GBMailer_Service.List_element();
GBMailer_Service.ListResponse_element response_x;
request_x.szPackageName = szPackageName;
request_x.szSessionID = szSessionID;
request_x.szUserName = szUserName;
request_x.szPassword = <PASSWORD>;
request_x.szKey = szKey;
request_x.szTemplate = szTemplate;
request_x.nOffset = nOffset;
request_x.nMaxReturns = nMaxReturns;
Map<String, GBMailer_Service.ListResponse_element> response_map_x = new Map<String, GBMailer_Service.ListResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/List',
'http://webportal.gb.co.uk/GBPortal',
'List',
'http://webportal.gb.co.uk/GBPortal',
'ListResponse',
'GBMailer_Service.ListResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.ListResult;
}
*/
public String CreateSession() {
GBMailer_Service.CreateSession_element request_x = new GBMailer_Service.CreateSession_element();
GBMailer_Service.CreateSessionResponse_element response_x;
Map<String, GBMailer_Service.CreateSessionResponse_element> response_map_x = new Map<String, GBMailer_Service.CreateSessionResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/CreateSession',
'http://webportal.gb.co.uk/GBPortal',
'CreateSession',
'http://webportal.gb.co.uk/GBPortal',
'CreateSessionResponse',
'GBMailer_Service.CreateSessionResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.CreateSessionResult;
}
public Boolean TerminateSession(String szSessionID) {
GBMailer_Service.TerminateSession_element request_x = new GBMailer_Service.TerminateSession_element();
GBMailer_Service.TerminateSessionResponse_element response_x;
request_x.szSessionID = szSessionID;
Map<String, GBMailer_Service.TerminateSessionResponse_element> response_map_x = new Map<String, GBMailer_Service.TerminateSessionResponse_element>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'http://webportal.gb.co.uk/GBPortal/TerminateSession',
'http://webportal.gb.co.uk/GBPortal',
'TerminateSession',
'http://webportal.gb.co.uk/GBPortal',
'TerminateSessionResponse',
'GBMailer_Service.TerminateSessionResponse_element'}
);
response_x = response_map_x.get('response_x');
return response_x.TerminateSessionResult;
}
}
public class ArrayOfAcceleratorItem {
public GBMailer_Service.AcceleratorItem[] AcceleratorItem;
private String[] AcceleratorItem_type_info = new String[]{'AcceleratorItem','http://webportal.gb.co.uk/GBPortal','AcceleratorItem','0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'AcceleratorItem'};
}
public class CreateSession_element {
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{};
}
public class TerminateSession_element {
public String szSessionID;
private String[] szSessionID_type_info = new String[]{'szSessionID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'szSessionID'};
}
/* ---- Not in use ----
public class InfoResponse_element {
public GBMailer_Service.AcceleratorInfoReturn InfoResult;
private String[] InfoResult_type_info = new String[]{'InfoResult','http://webportal.gb.co.uk/GBPortal','AcceleratorInfoReturn','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'InfoResult'};
}
public class List_element {
public String szPackageName;
public String szSessionID;
public String szUserName;
public String szPassword;
public String szKey;
public String szTemplate;
public Integer nOffset;
public Integer nMaxReturns;
private String[] szPackageName_type_info = new String[]{'szPackageName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szSessionID_type_info = new String[]{'szSessionID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szUserName_type_info = new String[]{'szUserName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPassword_type_info = new String[]{'szPassword','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szKey_type_info = new String[]{'szKey','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szTemplate_type_info = new String[]{'szTemplate','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] nOffset_type_info = new String[]{'nOffset','http://www.w3.org/2001/XMLSchema','int','1','1','false'};
private String[] nMaxReturns_type_info = new String[]{'nMaxReturns','http://www.w3.org/2001/XMLSchema','int','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'szPackageName','szSessionID','szUserName','szPassword','szKey','szTemplate','nOffset','nMaxReturns'};
}*/
public class AcceleratorAddress {
public String Text;
public GBMailer_Service.ArrayOfAcceleratorItem Items;
private String[] Text_type_info = new String[]{'Text','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Items_type_info = new String[]{'Items','http://webportal.gb.co.uk/GBPortal','ArrayOfAcceleratorItem','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'Text','Items'};
}
public class ArrayOfAcceleratorAddress {
public GBMailer_Service.AcceleratorAddress[] AcceleratorAddress;
private String[] AcceleratorAddress_type_info = new String[]{'AcceleratorAddress','http://webportal.gb.co.uk/GBPortal','AcceleratorAddress','0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'AcceleratorAddress'};
}
public class PinpointResponse_element {
public GBMailer_Service.AcceleratorSearchReturn PinpointResult;
private String[] PinpointResult_type_info = new String[]{'PinpointResult','http://webportal.gb.co.uk/GBPortal','AcceleratorSearchReturn','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'PinpointResult'};
}
/* ---- Not in use ----
public class AcceleratorInfoReturn {
public String Status;
public String Remarks;
public GBMailer_Service.ArrayOfAcceleratorComponent Components;
private String[] Status_type_info = new String[]{'Status','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Remarks_type_info = new String[]{'Remarks','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Components_type_info = new String[]{'Components','http://webportal.gb.co.uk/GBPortal','ArrayOfAcceleratorComponent','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'Status','Remarks','Components'};
}*/
public class AcceleratorSearchReturn {
public String Status;
public String Remarks;
public GBMailer_Service.ArrayOfAcceleratorAddress Addresses;
private String[] Status_type_info = new String[]{'Status','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Remarks_type_info = new String[]{'Remarks','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Addresses_type_info = new String[]{'Addresses','http://webportal.gb.co.uk/GBPortal','ArrayOfAcceleratorAddress','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'Status','Remarks','Addresses'};
}
public class Pinpoint_element {
public String szPackageName;
public String szSessionID;
public String szUserName;
public String szPassword;
public String szPostcode;
public String szPremise;
public String szAddressFormat;
public String szRelatedTypes;
public Integer nOffset;
public Integer nMaxReturns;
private String[] szPackageName_type_info = new String[]{'szPackageName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szSessionID_type_info = new String[]{'szSessionID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szUserName_type_info = new String[]{'szUserName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPassword_type_info = new String[]{'szPassword','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPostcode_type_info = new String[]{'szPostcode','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPremise_type_info = new String[]{'szPremise','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szAddressFormat_type_info = new String[]{'szAddressFormat','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szRelatedTypes_type_info = new String[]{'szRelatedTypes','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] nOffset_type_info = new String[]{'nOffset','http://www.w3.org/2001/XMLSchema','int','1','1','false'};
private String[] nMaxReturns_type_info = new String[]{'nMaxReturns','http://www.w3.org/2001/XMLSchema','int','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'szPackageName','szSessionID','szUserName','szPassword','szPostcode','szPremise','szAddressFormat','szRelatedTypes','nOffset','nMaxReturns'};
}
/* ---- Not in use ----
public class ArrayOfAcceleratorComponent {
public GBMailer_Service.AcceleratorComponent[] AcceleratorComponent;
private String[] AcceleratorComponent_type_info = new String[]{'AcceleratorComponent','http://webportal.gb.co.uk/GBPortal','AcceleratorComponent','0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'AcceleratorComponent'};
}
public class AcceleratorComponent {
public String Description;
public GBMailer_Service.ArrayOfAcceleratorItem Items;
private String[] Description_type_info = new String[]{'Description','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Items_type_info = new String[]{'Items','http://webportal.gb.co.uk/GBPortal','ArrayOfAcceleratorItem','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'Description','Items'};
}
public class ListResponse_element {
public GBMailer_Service.AcceleratorSearchReturn ListResult;
private String[] ListResult_type_info = new String[]{'ListResult','http://webportal.gb.co.uk/GBPortal','AcceleratorSearchReturn','1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'ListResult'};
}
public class TriggerEvent_element {
public String szPackageName;
public String szEventID;
public String szSessionID;
public String szUserName;
public String szPassword;
public String szParameterData;
private String[] szPackageName_type_info = new String[]{'szPackageName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szEventID_type_info = new String[]{'szEventID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szSessionID_type_info = new String[]{'szSessionID','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szUserName_type_info = new String[]{'szUserName','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szPassword_type_info = new String[]{'szPassword','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] szParameterData_type_info = new String[]{'szParameterData','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://webportal.gb.co.uk/GBPortal','true','false'};
private String[] field_order_type_info = new String[]{'szPackageName','szEventID','szSessionID','szUserName','szPassword','szParameterData'};
}
*/
/*public static TestMethod void test_GBPortalWSSoap_TriggerEvent() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.TriggerEvent('TEST', 'TEST', 'TEST', 'TEST', 'TEST', 'TEST'));
Test.StopTest();
}
public static TestMethod void test_GBPortalWSSoap_Find() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.Find('TEST', 'TEST', 'TEST', 'TEST', new GBMailer_Service.AcceleratorAddress(), 'TEST', 'TEST', 'TEST', 0, 0));
Test.StopTest();
}
public static TestMethod void test_GBPortalWSSoap_Pinpoint() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.Pinpoint('TEST', 'TEST', 'TEST', 'TEST', 'TEST', 'TEST', 'TEST', 'TEST', 0, 0));
Test.StopTest();
}
public static TestMethod void test_GBPortalWSSoap_Info() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.Info('TEST', 'TEST', 'TEST', 'TEST', 'TEST'));
Test.StopTest();
}
public static TestMethod void test_GBPortalWSSoap_getList() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.getList('TEST', 'TEST', 'TEST', 'TEST', 'TEST', 'TEST', 0, 0));
Test.StopTest();
}
public static TestMethod void test_GBPortalWSSoap_CreateSession() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.CreateSession());
Test.StopTest();
}
public static TestMethod void test_GBPortalWSSoap_TerminateSession() {
GBMailer_Service.GBPortalWSSoap cont = new GBMailer_Service.GBPortalWSSoap();
Test.StartTest();
System.debug(cont.TerminateSession('TEST'));
Test.StopTest();
}*/
}<file_sep>/classes/uksvcsTntComSearchConsignment.cls
//Generated by wsdl2apex
public class uksvcsTntComSearchConsignment {
public class DetailProofOfDelivery_MasterType {
public String podSts {get; set;}
public Boolean sosInd {get; set;}
public String numItms {get; set;}
public String file {get; set;}
public String rcvrNm {get; set;}
public String rcvrCmts {get; set;}
public Boolean imgInd {get; set;}
public String manSgnInd {get; set;}
public DateTime podDtTm {get; set;}
private String[] podSts_type_info = new String[]{'podSts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sosInd_type_info = new String[]{'sosInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] numItms_type_info = new String[]{'numItms','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] file_type_info = new String[]{'file','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] rcvrNm_type_info = new String[]{'rcvrNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] rcvrCmts_type_info = new String[]{'rcvrCmts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] imgInd_type_info = new String[]{'imgInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] manSgnInd_type_info = new String[]{'manSgnInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] podDtTm_type_info = new String[]{'podDtTm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'podSts','sosInd','numItms','file','rcvrNm','rcvrCmts','imgInd','manSgnInd','podDtTm'};
}
public class DetailConsignmentStatusHistory_MasterType {
public DateTime stsDtTm {get; set;}
public String dep {get; set;}
public String rnd {get; set;}
public String sts {get; set;}
public String subSts {get; set;}
public String dscrpCmmts {get; set;}
public Boolean hasDscrp {get; set;}
private String[] stsDtTm_type_info = new String[]{'stsDtTm','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] dep_type_info = new String[]{'dep','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] rnd_type_info = new String[]{'rnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sts_type_info = new String[]{'sts','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] subSts_type_info = new String[]{'subSts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'stsDtTm','dep','rnd','sts','subSts'};
}
public class RequestMessage_MasterType {
public uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType con;
public uksvcsTntComGenericPayloadHeader.payloadHeader hdr;
private String[] con_type_info = new String[]{'con','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] hdr_type_info = new String[]{'hdr','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'con','hdr'};
}
public class ConsignmentDiscrepancy_MasterType {
public DateTime dscrpDt {get; set;}
public String rnd {get; set;}
public String dscrp {get; set;}
public String cmmts {get; set;}
private String[] dscrpDt_type_info = new String[]{'dscrpDt','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] rnd_type_info = new String[]{'rnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] dscrp_type_info = new String[]{'dscrp','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] cmmts_type_info = new String[]{'cmmts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'dscrpDt','rnd','dscrp','cmmts'};
}
public class ConsignmentDiscrepancy_ContainerType {
public uksvcsTntComSearchConsignment.ConsignmentDiscrepancy_MasterType[] dscrp {get; set;}
private String[] dscrp_type_info = new String[]{'dscrp','http://express.tnt.com/service/schema/srchcon/v2',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'dscrp'};
}
public class DetailAddress_MasterType {
public String orgNm {get; set;}
public String subPrem {get; set;}
public String premNum {get; set;}
public String premNm {get; set;}
public String strAddr1 {get; set;}
public String strAddr2 {get; set;}
public String strAddr3 {get; set;}
public String strAddr4 {get; set;}
public String dstct {get; set;}
public String twn {get; set;}
public String cnty {get; set;}
public String cntry {get; set;}
public String pstCd {get; set;}
private String[] orgNm_type_info = new String[]{'orgNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] subPrem_type_info = new String[]{'subPrem','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] premNum_type_info = new String[]{'premNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] premNm_type_info = new String[]{'premNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] strAddr1_type_info = new String[]{'strAddr1','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] strAddr2_type_info = new String[]{'strAddr2','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] strAddr3_type_info = new String[]{'strAddr3','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] strAddr4_type_info = new String[]{'strAddr4','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] dstct_type_info = new String[]{'dstct','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] twn_type_info = new String[]{'twn','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] cnty_type_info = new String[]{'cnty','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] cntry_type_info = new String[]{'cntry','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] pstCd_type_info = new String[]{'pstCd','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'orgNm','subPrem','premNum','premNm','strAddr1','strAddr2','strAddr3','strAddr4','dstct','twn','cnty','cntry','pstCd'};
}
public class ShortProofOfDelivery_MasterType {
public String podSts {get; set;}
private String[] podSts_type_info = new String[]{'podSts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'podSts'};
}
public class ConsignmentRating_MasterType {
public String trnsLiabLvl {get; set;}
public Date rtdDt {get; set;}
public String rtngDep {get; set;}
public String schRvAmt {get; set;}
public String netRvAmt {get; set;}
public Date invDt {get; set;}
private String[] trnsLiabLvl_type_info = new String[]{'trnsLiabLvl','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] rtdDt_type_info = new String[]{'rtdDt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] rtngDep_type_info = new String[]{'rtngDep','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] schRvAmt_type_info = new String[]{'schRvAmt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] netRvAmt_type_info = new String[]{'netRvAmt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] invDt_type_info = new String[]{'invDt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'trnsLiabLvl','rtdDt','rtngDep','schRvAmt','netRvAmt','invDt'};
}
public class ConsignmentResponse_MasterType {
public String unqConNum {get; set;} //Unique identifier for the consignment.
public String tntConNum {get; set;} //Consignment number generated by a TNT con note system (e.g. express shipper).
public String orgConNum {get; set;} //Unique identifier of another consignment that this consignment is linked to. -> Original
public String bkgNum {get; set;} //Unique identifier of the booking that the consignment relates to. -> Col Req Num
public String ntTyp {get; set;} //Type of documentation used for the consignment -> Type
public String svcCd {get; set;} //Description of the TNT service that was used for the consignment. -> Service
public String cmm {get; set;} //Description of the TNT commodity that the consignment relates to. -> Description
public String delInst {get; set;} //Special delivery instructions provided by the customer. -> Del Instrc
public String lobRef {get; set;} //Unique reference for the Line of Business linked to the consignment.
public String options {get; set;} //Description of the TNT sub-service that was used for the consignment. -> Sub
public String custRef {get; set;} //Customer provided reference for the consignment. -> Customer Ref
public String colDep {get; set;} //Collection depot for the consignment. -> Coll Depot
public String delDep {get; set;} //Delivery depot for the consignment. -> Del Depot
public String orgnDep {get; set;} //Originating depot for the consignment. -> Orig Depot
public Date colDt {get; set;} //Date consignment was collected. -> Coll Date
public Date delDat {get; set;} //Date consignment was delivered. -> Del Date
public DateTime dueDtTm {get; set;} //Date/time consignment is due to be delivered. -> Due Date
public String dclItms {get; set;} //Number of items the customer has declared are in the consignment. -> Dec Items
public String dclWght {get; set;} //Customer declared total weight of all items in the consignment. -> Dec Wgt
public String chkItms {get; set;} //Number of items checked in at the collection depot. -> Check Items
public String chkWght {get; set;} //Combined weight of all items in the consignment - TNT checked at collection depot.-> Check Wgt
public String colRnd {get; set;} //Collection round used for collection of the consignment. -> Coll Round
public String sqNum {get; set;} //Split of collection round consignment notes into sequences. Used for data entry. -> Seq
public Boolean pdcInd {get; set;} //Indicates that the consignment was processed by a PDC.
public String delRnd {get; set;} //Delivery round used for delivery of the consignment. -> Del Round
public String uplMeth {get; set;} //Indicates how the consignment was uploaded onto the system. -> Upload
public Boolean qryInd {get; set;} //Indicates if a query file has been logged for the consignment. -> Queries
public Boolean clInd {get; set;} //Indicates if a claim has been raised for the consignment.
public String bayNum {get; set;} //Code of the logical area in TNT where the consignment is currently allocated. -> Bay Number
public String bayNm {get; set;} //Name of the logical area in TNT where the consignment is currently allocated.
public String sndrNm {get; set;} //Name of sender
public String delToNm {get; set;} //Name of recipient.
public String delToCnt {get; set;} //Name of the person to deliver the item to. Also referred to as FAO on the consignment.
public Boolean discInd {get; set;} //Indicates that a discrepancy has been logged against the consignment.
public uksvcsTntComSearchConsignment.DetailProofOfDelivery_MasterType pod {get; set;}
public uksvcsTntComSearchConsignment.DetailAddress_MasterType addr {get; set;}
public uksvcsTntComSearchConsignment.ConsignmentStatusHistory_ContainerType conStss {get; set;}
public uksvcsTntComSearchConsignment.ConsignmentRating_MasterType rtng {get; set;}
public uksvcsTntComSearchConsignment.ConsignmentDiscrepancy_ContainerType dscrps {get; set;}
public uksvcsTntComSearchConsignment.Account_MasterType act {get; set;}
private String[] unqConNum_type_info = new String[]{'unqConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] tntConNum_type_info = new String[]{'tntConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] orgConNum_type_info = new String[]{'orgConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] bkgNum_type_info = new String[]{'bkgNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] ntTyp_type_info = new String[]{'ntTyp','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] svcCd_type_info = new String[]{'svcCd','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] cmm_type_info = new String[]{'cmm','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] delInst_type_info = new String[]{'delInst','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] lobRef_type_info = new String[]{'lobRef','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] options_type_info = new String[]{'options','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] custRef_type_info = new String[]{'custRef','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] colDep_type_info = new String[]{'colDep','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] delDep_type_info = new String[]{'delDep','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] orgnDep_type_info = new String[]{'orgnDep','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] colDt_type_info = new String[]{'colDt','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] delDat_type_info = new String[]{'delDat','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] dueDtTm_type_info = new String[]{'dueDtTm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] dclItms_type_info = new String[]{'dclItms','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] dclWght_type_info = new String[]{'dclWght','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] chkItms_type_info = new String[]{'chkItms','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] chkWght_type_info = new String[]{'chkWght','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] colRnd_type_info = new String[]{'colRnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sqNum_type_info = new String[]{'sqNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] pdcInd_type_info = new String[]{'pdcInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delRnd_type_info = new String[]{'delRnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] uplMeth_type_info = new String[]{'uplMeth','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] qryInd_type_info = new String[]{'qryInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] clInd_type_info = new String[]{'clInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] bayNum_type_info = new String[]{'bayNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] bayNm_type_info = new String[]{'bayNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sndrNm_type_info = new String[]{'sndrNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delToNm_type_info = new String[]{'delToNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delToCnt_type_info = new String[]{'delToCnt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] discInd_type_info = new String[]{'discInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] pod_type_info = new String[]{'pod','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] addr_type_info = new String[]{'addr','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] conStss_type_info = new String[]{'conStss','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] rtng_type_info = new String[]{'rtng','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] dscrps_type_info = new String[]{'dscrps','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] act_type_info = new String[]{'act','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'unqConNum','tntConNum','orgConNum','bkgNum','ntTyp','svcCd','cmm','delInst','lobRef','options','custRef','colDep','delDep','orgnDep','colDt','delDat','dueDtTm','dclItms','dclWght','chkItms','chkWght','colRnd','sqNum','pdcInd','delRnd','uplMeth','qryInd','clInd','bayNum','bayNm','sndrNm','delToNm','delToCnt','discInd','pod','addr','conStss','rtng','dscrps','act'};
public void addDiscrepCommentsToHistoryRecords(){
if(conStss != null && dscrps != null && dscrps.dscrp != null){
List<DetailConsignmentStatusHistory_MasterType> historyLines = conStss.conSts;
List<ConsignmentDiscrepancy_MasterType> dscrpLines = dscrps.dscrp;
Integer j = historyLines.size() - 1;
for(Integer i = dscrpLines.size() - 1; i >= 0; i--){
ConsignmentDiscrepancy_MasterType dscrp = dscrpLines[i];
DetailConsignmentStatusHistory_MasterType firstHist;
DetailConsignmentStatusHistory_MasterType histWithSubType;
for(Integer k = j; k >= 0; k--){
DetailConsignmentStatusHistory_MasterType stHist = historyLines[k];
if(stHist.stsDtTm <= dscrp.dscrpDt && firstHist == null){
firstHist = stHist;
j = k - 1;
}
if(stHist.stsDtTm <= dscrp.dscrpDt && !String.isEmpty(stHist.subSts) && histWithSubType == null && (dscrp.dscrpDt.getTime() - stHist.stsDtTm.getTime())/1000*60 < 5){
histWithSubType = stHist;
firstHist = stHist;
j = k - 1;
}
if(histWithSubType != null || (firstHist != null && (dscrp.dscrpDt.getTime() - stHist.stsDtTm.getTime())/1000*60 > 5)){
firstHist.dscrpCmmts = dscrp.cmmts;
firstHist.hasDscrp = true;
break;
}
}
}
}
}
}
public class Account_MasterType {
public String actNum {get; set;}
public String actNm {get; set;}
public String phNum {get; set;}
private String[] actNum_type_info = new String[]{'actNum','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] actNm_type_info = new String[]{'actNm','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] phNum_type_info = new String[]{'phNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'actNum','actNm','phNum'};
}
public class ResponseMessage_MasterType {
public uksvcsTntComSearchConsignment.ConsignmentResponse_MasterType con;
public uksvcsTntComSearchConsignment.ConsignmentResponse_ContainerType consearch;
public uksvcsTntComGenericPayloadHeader.payloadHeader hdr;
private String[] con_type_info = new String[]{'con','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] consearch_type_info = new String[]{'consearch','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] hdr_type_info = new String[]{'hdr','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'con','consearch','hdr'};
}
public class ConsignmentStatusHistory_ContainerType {
public uksvcsTntComSearchConsignment.DetailConsignmentStatusHistory_MasterType[] conSts {get; set;}
private String[] conSts_type_info = new String[]{'conSts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'conSts'};
}
public class Consignment_MasterType {
public String unqConNum {get; set;}
public String tntConNum {get; set;}
public String bkgNum {get; set;}
public String custRef {get; set;}
public String actNum {get; set;}
public String sndrNm {get; set;}
public String delToNm {get; set;}
public Date colDt {get; set;}
public Date delDt {get; set;}
public String ntTypCd {get; set;}
public String lobRef {get; set;}
public String svcCd {get; set;}
public Boolean discInd {get; set;}
public uksvcsTntComSearchConsignment.CurrentConsignmentStatus_MasterType curConSts {get; set;}
public uksvcsTntComSearchConsignment.ShortProofOfDelivery_MasterType pod {get; set;}
public uksvcsTntComSearchConsignment.ShortAddress_MasterType delAddr {get; set;}
private String[] unqConNum_type_info = new String[]{'unqConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] tntConNum_type_info = new String[]{'tntConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] bkgNum_type_info = new String[]{'bkgNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] custRef_type_info = new String[]{'custRef','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] actNum_type_info = new String[]{'actNum','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] sndrNm_type_info = new String[]{'sndrNm','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] delToNm_type_info = new String[]{'delToNm','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] colDt_type_info = new String[]{'colDt','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] delDt_type_info = new String[]{'delDt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] ntTypCd_type_info = new String[]{'ntTypCd','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] lobRef_type_info = new String[]{'lobRef','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] svcCd_type_info = new String[]{'svcCd','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] discInd_type_info = new String[]{'discInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] curConSts_type_info = new String[]{'curConSts','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] pod_type_info = new String[]{'pod','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delAddr_type_info = new String[]{'delAddr','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'unqConNum','tntConNum','bkgNum','custRef','actNum','sndrNm','delToNm','colDt','delDt','ntTypCd','lobRef','svcCd','discInd','curConSts','pod','delAddr'};
}
public class ShortConsignmentStatusHistory_MasterType {
public Boolean negStsInd {get; set;}
public Boolean negSubStsInd {get; set;}
public String sts {get; set;}
public String subSts {get; set;}
private String[] negStsInd_type_info = new String[]{'negStsInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] negSubStsInd_type_info = new String[]{'negSubStsInd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sts_type_info = new String[]{'sts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] subSts_type_info = new String[]{'subSts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'negStsInd','negSubStsInd','sts','subSts'};
}
public class ConsignmentResponse_ContainerType {
public uksvcsTntComSearchConsignment.Consignment_MasterType[] con {get; set;}
private String[] con_type_info = new String[]{'con','http://express.tnt.com/service/schema/srchcon/v2',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'con'};
}
public class CurrentConsignmentStatus_MasterType {
public DateTime stsDtTm;
public String dep;
public String rnd;
public String sts {get; set;}
public String subSts;
private String[] stsDtTm_type_info = new String[]{'stsDtTm','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] dep_type_info = new String[]{'dep','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] rnd_type_info = new String[]{'rnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sts_type_info = new String[]{'sts','http://express.tnt.com/service/schema/srchcon/v2',null,'1','1','false'};
private String[] subSts_type_info = new String[]{'subSts','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'stsDtTm','dep','rnd','sts','subSts'};
}
public class ConsignmentRequest_MasterType {
public String unqConNum {get; set;}
public String tntConNum {get; set;}
public String bkgNum {get; set;}
public String custRef {get; set;}
public String actNum {get; set;}
public String sndrNm {get; set;}
public String delToNm {get; set;}
public String colDep {get; set;}
public String delDep {get; set;}
public String colRnd {get; set;}
public String delRnd {get; set;}
public Date delDt {get; set;}
public String bayNum {get; set;}
public String orgDep {get; set;}
public String ntTyp {get; set;}
public String lobRef {get; set;}
public String svcCd {get; set;}
public String options {get; set;}
public uksvcsTntComSearchConsignment.ShortAddress_MasterType delAddr {get; set;}
public uksvcsTntComSearchConsignment.ShortConsignmentStatusHistory_MasterType stsHstry {get; set;}
private String[] unqConNum_type_info = new String[]{'unqConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] tntConNum_type_info = new String[]{'tntConNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] bkgNum_type_info = new String[]{'bkgNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] custRef_type_info = new String[]{'custRef','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] actNum_type_info = new String[]{'actNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] sndrNm_type_info = new String[]{'sndrNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delToNm_type_info = new String[]{'delToNm','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] colDep_type_info = new String[]{'colDep','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delDep_type_info = new String[]{'delDep','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] colRnd_type_info = new String[]{'colRnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delRnd_type_info = new String[]{'delRnd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delDt_type_info = new String[]{'delDt','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] bayNum_type_info = new String[]{'bayNum','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] orgDep_type_info = new String[]{'orgDep','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] ntTyp_type_info = new String[]{'ntTyp','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] lobRef_type_info = new String[]{'lobRef','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] svcCd_type_info = new String[]{'svcCd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] options_type_info = new String[]{'options','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] delAddr_type_info = new String[]{'delAddr','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] stsHstry_type_info = new String[]{'stsHstry','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'unqConNum','tntConNum','bkgNum','custRef','actNum','sndrNm','delToNm','colDep','delDep','colRnd','delRnd','delDt','bayNum','orgDep','ntTyp','lobRef','svcCd','options','delAddr','stsHstry'};
}
public class ShortAddress_MasterType {
public String pstCd {get; set;}
public String twn {get; set;}
private String[] pstCd_type_info = new String[]{'pstCd','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] twn_type_info = new String[]{'twn','http://express.tnt.com/service/schema/srchcon/v2',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v2','false','false'};
private String[] field_order_type_info = new String[]{'pstCd','twn'};
}
}<file_sep>/classes/OL_DepotRoutingHelperTest.cls
/**
* File Name : OL_DepotRoutingHelperTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 04/09/2014 <NAME>
*/
@isTest
public class OL_DepotRoutingHelperTest {
static testMethod void findNormalDepotForWorkingDay()
{
Line_Of_Business__c lob = new Line_Of_Business__c();
lob.Name = 'LOB1';
lob.Line_Of_Business_Reference__c = '10';
lob.Routing_Network__c = 'EXP';
insert lob;
Account_Address__c aa = TestUtil.createAccountAddress(null,null);
Date collDate = Date.newInstance(2014,9,1); // Monday
Account depot = TestUtil.setupDepotRouting(lob.id,aa,collDate);
Test.startTest();
system.assertEquals(depot.id,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate).id);
Test.stopTest();
}
static testMethod void findSaturdayDepotForSaturdayDay()
{
Line_Of_Business__c lob = new Line_Of_Business__c();
lob.Name = 'LOB1';
lob.Line_Of_Business_Reference__c = '10';
lob.Routing_Network__c = 'EXP';
insert lob;
Account_Address__c aa = TestUtil.createAccountAddress(null,null);
Date collDate = Date.newInstance(2014,8,30); // Saturday
Account depot = TestUtil.setupDepotRouting(lob.id,aa,collDate);
// set saturday
Day__c d = [select id, Day_Type__c from Day__c limit 1];
d.Day_Type__c = ConstantUtil.PLVAL_DAY_DAYTYPE_SATURDAY;
update d;
Depot_Routing__c dr = [select id, Round_Group__c from Depot_Routing__c limit 1];
dr.Round_Group__c = ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_SATURDAY;
update dr;
Test.startTest();
system.assertEquals(depot.id,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate).id);
Test.stopTest();
}
static testMethod void nonWorkingDay()
{
Line_Of_Business__c lob = new Line_Of_Business__c();
lob.Name = 'LOB1';
lob.Line_Of_Business_Reference__c = '10';
lob.Routing_Network__c = 'EXP';
insert lob;
Account_Address__c aa = TestUtil.createAccountAddress(null,null);
Date collDate = Date.newInstance(2014,8,31); // Sunday
Account depot = TestUtil.setupDepotRouting(lob.id,aa,collDate);
// set sunday
Day__c d = [select id, Day_Type__c from Day__c limit 1];
d.Day_Type__c = ConstantUtil.PLVAL_DAY_DAYTYPE_NONWORKING;
update d;
Depot_Routing__c dr = [select id, Round_Group__c from Depot_Routing__c limit 1];
dr.Round_Group__c = ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_ALL;
update dr;
Test.startTest();
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
Test.stopTest();
}
static testMethod void failSaturdayDepotForWorkingDay()
{
Line_Of_Business__c lob = new Line_Of_Business__c();
lob.Name = 'LOB1';
lob.Line_Of_Business_Reference__c = '10';
lob.Routing_Network__c = 'EXP';
insert lob;
Account_Address__c aa = TestUtil.createAccountAddress(null,null);
Date collDate = Date.newInstance(2014,9,1); // Monday
Account depot = TestUtil.setupDepotRouting(lob.id,aa,collDate);
Depot_Routing__c dr = [select id, Round_Group__c from Depot_Routing__c limit 1];
dr.Round_Group__c = ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_SATURDAY;
update dr;
Test.startTest();
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
Test.stopTest();
}
static testMethod void failNormalDepotForSaturdayDay()
{
Line_Of_Business__c lob = new Line_Of_Business__c();
lob.Name = 'LOB1';
lob.Line_Of_Business_Reference__c = '10';
lob.Routing_Network__c = 'EXP';
insert lob;
Account_Address__c aa = TestUtil.createAccountAddress(null,null);
Date collDate = Date.newInstance(2014,8,30); // Saturday
Account depot = TestUtil.setupDepotRouting(lob.id,aa,collDate);
// set saturday
Day__c d = [select id, Day_Type__c from Day__c limit 1];
d.Day_Type__c = ConstantUtil.PLVAL_DAY_DAYTYPE_SATURDAY;
update d;
Test.startTest();
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
Test.stopTest();
}
static testMethod void allFail()
{
Line_Of_Business__c lob = new Line_Of_Business__c();
lob.Name = 'LOB1';
lob.Line_Of_Business_Reference__c = '10';
lob.Routing_Network__c = 'EXP';
insert lob;
Account_Address__c aa = TestUtil.createAccountAddress(null,null);
Date collDate = Date.newInstance(2014,9,1); // Monday
Account depot = TestUtil.setupDepotRouting(lob.id,aa,collDate);
Test.startTest();
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(null,null,null,null,null));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
delete [select id from Depot_Routing__c];
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
delete [select id from Day__c];
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
delete [select id from Routing_Table__c];
system.assertEquals(null,OL_DepotRoutingHelper.findCollectionDepot(aa.Postcode__c,aa.District__c,aa.City__c,lob.id,collDate));
system.assertNotEquals(null,OL_DepotRoutingHelper.errorMsg);
Test.stopTest();
}
}<file_sep>/classes/BookingTriggerHandler.cls
/**
* File Name : BookingTriggerHandler.cls
* Description : methods called from Booking trigger
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 24/07/2014 <NAME> Initial version TNT-536
* 0.2 28/08/2014 <NAME> TNT-1400
* 0.3 29/08/2014 <NAME> add generateBookingId() method TNT-1414
* 0.4 12/09/2014 <NAME> update createCaseIfRejected() method TNT-1605
*
*/
public with sharing class BookingTriggerHandler {
// HANDLERS
public static void onBeforeInsertHandler(List<Booking__c> triggerNew)
{
generateBookingId(triggerNew);
maintainRecordType(triggerNew);
}
public static void onAfterInsertHandler(List<Booking__c> triggerNew)
{
updateAccountLob(triggerNew,null);
updateLastUsedOnAccountAddress(triggerNew,null);
}
public static void onAfterUpdateHandler(List<Booking__c> triggerNew, Map<Id,Booking__c> triggerOldMap)
{
createCaseIfRejected(triggerNew, triggerOldMap);
updateAccountLob(triggerNew, triggerOldMap);
updateLastUsedOnAccountAddress(triggerNew,triggerOldMap);
}
public static void onBeforeUpdateHandler(List<Booking__c> triggerNew, Map<Id,Booking__c> triggerOldMap)
{
maintainRecordType(triggerNew);
}
// METHODS
public static void createCaseIfRejected(List<Booking__c> bookings, Map<Id,Booking__c> oldMap){
List<Booking__c> books = new List<Booking__c>();
for(Booking__c b : bookings)
{
if( (b.Booking_Rejected_by_Depot__c && (b.Booking_Rejected_by_Depot__c != oldMap.get(b.Id).Booking_Rejected_by_Depot__c))
|| (b.Status__c == ConstantUtil.PLVAL_BOOKING_STATUS_REJECTED_TO_CS && (b.Status__c != oldMap.get(b.Id).Status__c)) )
{
books.add(b);
}
}
if(books.isEmpty()) return;
System.debug('Bookings Not Empty');
// find all relevant accounts
Map<Id,Account> accMap = new Map<Id,Account>();
{
Set<Id> accIds = new Set<Id>();
for(Booking__c b : books)
{
if(b.Account__c != null)
{
accIds.add(b.Account__c);
}
}
if(!accIds.isEmpty())
{
accMap = new Map<Id,Account>([select id, Auto_Case_Creation__c from Account where id in :accIds]);
}
}
// find all relevant LOBs added by DH 22/01/2016
Map<Id,Line_Of_Business__c> lobMap = new Map<Id,Line_Of_Business__c>();
{
Set<Id> lobIds = new Set<Id>();
for(Booking__c b : books)
{
if(b.Line_Of_Business__c != null)
{
lobIds.add(b.Line_Of_Business__c);
}
}
if(!lobIds.isEmpty())
{
lobMap = new Map<Id,Line_Of_Business__c>([select id, Line_Of_Business_Reference__c from Line_Of_Business__c where id in :lobIds]);
}
}
List<Case> cases = new List<Case>();
Set<String> AutoCaseLOBs = ConstantUtil.AutoRejectionCaseLOBList;
for(Booking__c b : books){
System.Debug('This bookings LOB is: ' + b.Line_of_Business__c);
if(b.Account__c == null || (accMap.get(b.Account__c).Auto_Case_Creation__c && (lobMap.containsKey(b.Line_of_Business__c) && AutoCaseLOBs.contains(lobMap.get(b.Line_of_Business__c).Line_of_Business_Reference__c))))
{
//check if rejected
/*Change made by <NAME>
Code depricated, had a discussion with Kishan he said this is not used 9 Apr 2015
if(b.Booking_Rejected_by_Depot__c && (b.Booking_Rejected_by_Depot__c != oldMap.get(b.Id).Booking_Rejected_by_Depot__c)){
//Create Case
Case c = createCase(b);
c.Subject = 'Booking ' + b.Name + ' Rejected';
c.Description = b.Reason_for_Depot_Rejection__c;
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = ConstantUtil.PLVAL_CASE_TYPE_BOOKING_ADN_QUOTES;
cases.add(c);
} */
if(b.Status__c == ConstantUtil.PLVAL_BOOKING_STATUS_REJECTED_TO_CS && (b.Status__c != oldMap.get(b.Id).Status__c)){
//Create Case
Case c = createCase(b);
c.Subject = 'Booking ' + b.Name + ' Rejected to CS';
c.Description = b.Reason_for_Depot_Rejection__c;
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_SYSTEM;
c.Type = ConstantUtil.PLVAL_CASE_TYPE_BOOKINGS;
c.Case_Types_Level_2__c = ConstantUtil.PLVAL_CASE_TYPE_LAVEL1_CS_FAILED_COLLECTION;
c.Proactive_Case__c = true;
c.Collection_Depot__c = b.Collection_Depot__c;
c.Delivery_Depot__c = b.Delivery_Depot__c;
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
//DH added 01/02/2016 for call back
c.Call_me_back__c = '1 hour';
cases.add(c);
}
}
}
if(!cases.isEmpty()){
// make sure cases pass through assignment rule
AssignmentRule AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];
//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId = AR.id;
for(Case c : cases) {
c.setOptions(dmlOpts);
}
insert cases;
}
}
private static Case createCase(Booking__c b){
Case c = new Case();
c.AccountId = b.Account__c;
c.Booking__c = b.Id;
c.ContactId = b.Order_Contact__c;
c.Status = ConstantUtil.PLVAL_CASE_STATUS_NEW;
c.Priority = ConstantUtil.PLVAL_CASE_PRIORITY_MEDIUM;
return c;
}
public static void updateAccountLob(List<Booking__c> triggerNew, Map<Id,Booking__c> triggerOldMap)
{
final String US = '_';
Boolean isInsert = triggerOldMap == null;
Set<String> bookCombo = new Set<String>(); // accountID_lineOfBusinessID
Set<id> accIds = new Set<id>();
Set<id> lobIds = new Set<id>();
for(Booking__c bo: triggerNew)
{
if(bo.Status__c == ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED && bo.Account__c != null && bo.Line_Of_Business__c != null
&& (isInsert || triggerOldMap.get(bo.id).Status__c != ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED))
{
accIds.add(bo.Account__c);
lobIds.add(bo.Line_Of_Business__c);
bookCombo.add(bo.Account__c+US+bo.Line_Of_Business__c);
}
}
if(!bookCombo.isEmpty()) {
List<Account_LOB__c> acclobs = [SELECT ID, Last_Collection_Date__c, Account__c,
Line_Of_Business__c
FROM Account_LOB__c
WHERE Account__c IN :accIds
AND Line_Of_Business__c IN :lobIds
AND (Last_Collection_Date__c < TODAY OR Last_Collection_Date__c = null)];
Integer n = acclobs.size();
for(Integer i = 0; i < n; i++)
{
Account_LOB__c al = acclobs.get(i);
if(bookCombo.contains(al.Account__c+US+al.Line_Of_Business__c))
{
al.Last_Collection_Date__c = Date.today();
}
else
{
acclobs.remove(i);
i--;
n--;
}
}
update acclobs;
}
}
public static void generateBookingId(List<Booking__c> bookings){
Boolean generateIds = false;
for(Booking__c bk : bookings) {
if(bk.Booking_Id__c == null) {
generateIds = true;
break;
}
}
if(generateIds) {
Integer startDepot = Integer.valueOf(Label.Salesforce_Start_Depot);
Integer endDepot = Integer.valueOf(Label.Salesforce_End_Depot);
list<Booking_Id_Settings__c> biss = [SELECT Prefix__c, Current_Number__c FROM Booking_Id_Settings__c WHERE Name = 'Default' FOR UPDATE];
if(biss.isEmpty()) {
biss.add(new Booking_Id_Settings__c(Name = 'Default', Prefix__c = Integer.valueOf(Label.Salesforce_Start_Depot), Current_Number__c = 0));
}
Booking_Id_Settings__c bis = biss.get(0);
Integer prefix = (Integer)bis.Prefix__c;
Integer numPointer = (Integer)bis.Current_Number__c;
for(Booking__c bk : bookings) {
if(bk.Booking_Id__c == null) {
bk.Booking_Id__c = String.valueOf((prefix*10000000) + numPointer);
//increment number and prefix
numPointer++;
if(numPointer == 10000000){
numPointer = 0;
prefix = prefix == endDepot ? startDepot : prefix + 1;
}
}
}
bis.Prefix__c = prefix;
bis.Current_Number__c = numPointer;
upsert bis;
}
for(Booking__c bk : bookings) {
if(bk.Name == null || bk.Name == '') {
bk.Name = bk.Booking_Id__c;
}
}
}
public static void updateLastUsedOnAccountAddress(List<Booking__c> triggerNew, Map<Id,Booking__c> triggerOldMap)
{
Set<Id> aaIds = new Set<Id>();
for(Booking__c book : triggerNew)
{
if(book.Coll_Account_Address__c != null
&& (triggerOldMap == null || book.Coll_Account_Address__c != triggerOldMap.get(book.id).Coll_Account_Address__c))
{
aaIds.add(book.Coll_Account_Address__c);
}
if(book.Del_Account_Address__c != null
&& (triggerOldMap == null || book.Del_Account_Address__c != triggerOldMap.get(book.id).Del_Account_Address__c))
{
aaIds.add(book.Del_Account_Address__c);
}
}
if(!aaIds.isEmpty())
{
List<Account_Address__c> aas = [select id, Last_Used__c from Account_Address__c where id in :aaIds];
for(Account_Address__c aa : aas)
{
aa.Last_Used__c = Datetime.now();
}
update aas;
}
}
private static void maintainRecordType(List<Booking__c> triggerNew) {
/*
Map<String,Schema.RecordTypeInfo> rtMapByName = Schema.SObjectType.Booking__c.RecordTypeInfosByName;
Id newBookingId = rtMapByName.get(ConstantUtil.PLVAL_BOOKING_RECORD_TYPE_NEW).RecordTypeId;
Id blockedBookingId = rtMapByName.get(ConstantUtil.PLVAL_BOOKING_RECORD_TYPE_BLOCKED).RecordTypeId;
for(Booking__c book : triggerNew) {
if((book.Status__c == ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED || book.Status__c == ConstantUtil.PLVAL_BOOKING_STATUS_CANCELLED)
&& book.RecordTypeId != blockedBookingId) {
System.debug('****I am setting this booking to a BLOCKED booking Record type****');
book.RecordTypeId = blockedBookingId;
}
else if(book.RecordTypeId != newBookingId) {
System.debug('****I am setting this booking to a NEW booking Record type****');
book.RecordTypeId = newBookingId;
}
}
*/ }
}<file_sep>/classes/uksvcsTntGetItemsForConsignment.cls
//Generated by wsdl2apex
public class uksvcsTntGetItemsForConsignment {
public class ItemTracking_MasterType {
public String locCd {get; set;}
public String locTyp {get; set;}
public String scnTyp {get; set;}
public DateTime scnDtTm {get; set;}
public String vhcl {get; set;}
public String scnTypInd {get; set;}
public String oprUsrId {get; set;}
public String redirDepNum {get; set;}
public Boolean untScnInd {get; set;}
public String cntActn {get; set;}
private String[] locCd_type_info = new String[]{'locCd','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] locTyp_type_info = new String[]{'locTyp','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] scnTyp_type_info = new String[]{'scnTyp','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] scnDtTm_type_info = new String[]{'scnDtTm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] vhcl_type_info = new String[]{'vhcl','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] scnTypInd_type_info = new String[]{'scnTypInd','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] oprUsrId_type_info = new String[]{'oprUsrId','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] redirDepNum_type_info = new String[]{'redirDepNum','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] untScnInd_type_info = new String[]{'untScnInd','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] cntActn_type_info = new String[]{'cntActn','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'locCd','locTyp','scnTyp','scnDtTm','vhcl','scnTypInd','oprUsrId','redirDepNum','untScnInd','cntActn'};
}
public class RequestMessage_MasterType {
public uksvcsTntComGenericPayloadHeader.payloadHeader hdr;
public uksvcsTntGetItemsForConsignment.ItemRequest_MasterType itm;
private String[] hdr_type_info = new String[]{'hdr','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] itm_type_info = new String[]{'itm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'hdr','itm'};
}
public class Item_MasterType {
public String itmNum {get; set;}
public String pcNum {get; set;}
public String chkWght {get; set;}
public String chkLen {get; set;}
public String chkHght {get; set;}
public String chkCbWght {get; set;}
public String lenUOM {get; set;}
public String wghtUOM {get; set;}
public String chrgWghtTyp {get; set;}
public String itmTyp {get; set;}
public Boolean imgInd {get; set;}
public DateTime lstColScnDtTm {get; set;}
public DateTime lstHubScnDtTm {get; set;}
public DateTime lstDelScnDtTm {get; set;}
public DateTime lstPodScnDtTm {get; set;}
public DateTime lstScnDtTm {get; set;}
public String lstScnDep {get; set;}
public String lstScnDepNm {get; set;}
public String chkWdth {get; set;}
public Boolean untScnInd {get; set;}
public String dimSrc {get; set;}
public String itmSrc {get; set;}
public String custItmRef {get; set;}
public Boolean isSet {get {return itmTyp == 'Set';} set;}
public Boolean isCtn {get {return itmTyp == 'Carton';} set;}
public Boolean isPlt {get {return itmTyp == 'Pallet';} set;}
public uksvcsTntGetItemsForConsignment.ItemsTracking_MasterType itmstrck {get; set;}
private String[] itmNum_type_info = new String[]{'itmNum','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] pcNum_type_info = new String[]{'pcNum','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] chkWght_type_info = new String[]{'chkWght','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] chkLen_type_info = new String[]{'chkLen','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] chkHght_type_info = new String[]{'chkHght','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] chkCbWght_type_info = new String[]{'chkCbWght','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lenUOM_type_info = new String[]{'lenUOM','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] wghtUOM_type_info = new String[]{'wghtUOM','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] chrgWghtTyp_type_info = new String[]{'chrgWghtTyp','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] itmTyp_type_info = new String[]{'itmTyp','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] imgInd_type_info = new String[]{'imgInd','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstColScnDtTm_type_info = new String[]{'lstColScnDtTm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstHubScnDtTm_type_info = new String[]{'lstHubScnDtTm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstDelScnDtTm_type_info = new String[]{'lstDelScnDtTm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstPodScnDtTm_type_info = new String[]{'lstPodScnDtTm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstScnDtTm_type_info = new String[]{'lstScnDtTm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstScnDep_type_info = new String[]{'lstScnDep','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] lstScnDepNm_type_info = new String[]{'lstScnDepNm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] chkWdth_type_info = new String[]{'chkWdth','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] untScnInd_type_info = new String[]{'untScnInd','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] dimSrc_type_info = new String[]{'dimSrc','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] itmSrc_type_info = new String[]{'itmSrc','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] custItmRef_type_info = new String[]{'custItmRef','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','1','false'};
private String[] itmstrck_type_info = new String[]{'itmstrck','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'itmNum','pcNum','chkWght','chkLen','chkHght','chkCbWght','lenUOM','wghtUOM','chrgWghtTyp','itmTyp','imgInd','lstColScnDtTm','lstHubScnDtTm','lstDelScnDtTm','lstPodScnDtTm','lstScnDtTm','lstScnDep','lstScnDepNm','chkWdth','untScnInd','dimSrc','itmSrc','custItmRef','itmstrck'};
}
public class ItemRequest_MasterType {
public String unqConNum;
private String[] unqConNum_type_info = new String[]{'unqConNum','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'unqConNum'};
}
public class ItemsResponse_MasterType {
public uksvcsTntGetItemsForConsignment.Item_MasterType[] itm;
private String[] itm_type_info = new String[]{'itm','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'itm'};
}
public class ItemsTracking_MasterType {
public uksvcsTntGetItemsForConsignment.ItemTracking_MasterType[] itmtrck {get; set;}
private String[] itmtrck_type_info = new String[]{'itmtrck','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'itmtrck'};
}
public class ResponseMessage_MasterType {
public uksvcsTntComGenericPayloadHeader.payloadHeader hdr;
public uksvcsTntGetItemsForConsignment.ItemsResponse_MasterType itms;
private String[] hdr_type_info = new String[]{'hdr','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] itms_type_info = new String[]{'itms','http://express.tnt.com/service/schema/getitmsforcon/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1','false','false'};
private String[] field_order_type_info = new String[]{'hdr','itms'};
}
}<file_sep>/classes/OL_CodeForObjectUtil.cls
/**
* File Name : OL_CodeForObjectUtil.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 09/09/2014 <NAME> Initial version, TNT-546
*/
public with sharing class OL_CodeForObjectUtil {
public static String delimitedServiceCodes {get; set;}
public static String delimitedLobCodes {get; set;}
public static Map<String, String> getLineOfBusinesMap(){
Map<String, String> res = new Map<String, String>();
delimitedLobCodes = '';
for(Line_of_Business__c lob : [SELECT Name, Line_of_Business_Reference__c FROM Line_of_Business__c]){
res.put(lob.Line_of_Business_Reference__c, lob.Name);
delimitedLobCodes += '*' + lob.Line_of_Business_Reference__c + '*';
}
return res;
}
public static Map<String, String> getServiceMap(){
Map<String, String> res = new Map<String, String>();
delimitedServiceCodes = '';
for(Service__c s : [SELECT Name, Service_Code__c FROM Service__c]){
res.put(s.Service_Code__c, s.Name);
delimitedServiceCodes += '*' + s.Service_Code__c + '*';
}
return res;
}
}<file_sep>/classes/GBMailer_ServiceMockImpl.cls
@isTest
global class GBMailer_ServiceMockImpl implements WebServiceMock{
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
Object respElement;
if(responseType == 'GBMailer_Service.CreateSessionResponse_element'){
GBMailer_Service.CreateSessionResponse_element res = new GBMailer_Service.CreateSessionResponse_element();
res.CreateSessionResult = 'TestCode';
respElement = res;
}
if(responseType == 'GBMailer_Service.PinpointResponse_element'){
GBMailer_Service.PinpointResponse_element res = new GBMailer_Service.PinpointResponse_element();
res.PinpointResult = new GBMailer_Service.AcceleratorSearchReturn();
res.PinpointResult.Addresses = new GBMailer_Service.ArrayOfAcceleratorAddress();
res.PinpointResult.Addresses.AcceleratorAddress = new List<GBMailer_Service.AcceleratorAddress>();
GBMailer_Service.AcceleratorAddress address = new GBMailer_Service.AcceleratorAddress();
address.Items = new GBMailer_Service.ArrayOfAcceleratorItem();
address.Items.AcceleratorItem = new List<GBMailer_Service.AcceleratorItem>();
GBMailer_Service.AcceleratorItem item = new GBMailer_Service.AcceleratorItem();
item.Key = GBMailer_Util.CODE_ORGANISATION;
item.Value = 'Address Name';
address.Items.AcceleratorItem.add(item);
item = new GBMailer_Service.AcceleratorItem();
item.Key = GBMailer_Util.CODE_SUBPREMISE;
item.Value = 'FLAT 1-2';
address.Items.AcceleratorItem.add(item);
item = new GBMailer_Service.AcceleratorItem();
item.Key = GBMailer_Util.CODE_BUILDINGNUMBER;
item.Value = '11';
address.Items.AcceleratorItem.add(item);
item = new GBMailer_Service.AcceleratorItem();
item.Key = GBMailer_Util.CODE_STREET;
item.Value = 'ONE ROAD';
address.Items.AcceleratorItem.add(item);
item = new GBMailer_Service.AcceleratorItem();
item.Key = GBMailer_Util.CODE_TOWN;
item.Value = 'LONDON';
address.Items.AcceleratorItem.add(item);
item = new GBMailer_Service.AcceleratorItem();
item.Key = GBMailer_Util.CODE_POSTCODE;
item.Value = 'SW15 1TW';
address.Items.AcceleratorItem.add(item);
res.PinpointResult.Addresses.AcceleratorAddress.add(address);
respElement = res;
}
if(responseType == 'GBMailer_Service.TerminateSessionResponse_element'){
GBMailer_Service.TerminateSessionResponse_element res = new GBMailer_Service.TerminateSessionResponse_element();
res.TerminateSessionResult = true;
respElement = res;
}
response.put('response_x', respElement);
}
}<file_sep>/classes/uksvcsTntComGenericPayloadHeader.cls
//Generated by wsdl2apex
public class uksvcsTntComGenericPayloadHeader {
public class search_x {
public String pgNum;
public Date dtFrom;
public Date dtTo;
private String[] pgNum_type_info = new String[]{'pgNum','http://express.tnt.com/general/schema/payloadheader/v1',null,'0','1','false'};
private String[] dtFrom_type_info = new String[]{'dtFrom','http://express.tnt.com/general/schema/payloadheader/v1',null,'0','1','false'};
private String[] dtTo_type_info = new String[]{'dtTo','http://express.tnt.com/general/schema/payloadheader/v1',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/general/schema/payloadheader/v1','false','false'};
private String[] field_order_type_info = new String[]{'pgNum','dtFrom','dtTo'};
}
public class payloadHeader {
public String cnsmrRef = 'Salesforce';
public String infoMsg;
public uksvcsTntComGenericPayloadHeader.search_x srch;
private String[] cnsmrRef_type_info = new String[]{'cnsmrRef','http://express.tnt.com/general/schema/payloadheader/v1',null,'1','1','false'};
private String[] infoMsg_type_info = new String[]{'infoMsg','http://express.tnt.com/general/schema/payloadheader/v1',null,'0','1','false'};
private String[] srch_type_info = new String[]{'srch','http://express.tnt.com/general/schema/payloadheader/v1',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/general/schema/payloadheader/v1','false','false'};
private String[] field_order_type_info = new String[]{'cnsmrRef','infoMsg','srch'};
}
}<file_sep>/classes/CaseBasedRoutingWebService.cls
global with sharing class CaseBasedRoutingWebService
{
webService static string getCaseOwnerAvayaID(String caseNumber)
{
String paddedCaseNumber;
if(caseNumber == null || caseNumber == '' || caseNumber.length() > 8)
{
system.debug('**ERROR** Case Number null, empty or > 8 chrs: ' + caseNumber);
return 'ERROR:INVALID CASE NUMBER';
}
try
{
integer caseInt = integer.valueOf(caseNumber);
if(caseInt < 0) return 'ERROR:INVALID CASE NUMBER';
paddedCaseNumber = String.valueOf(caseInt);
while (paddedCaseNumber.length() < 8)
{
paddedCaseNumber = '0' + paddedCaseNumber;
}
}
catch(Exception ex)
{
system.debug('**ERROR** Case Number not an integer: ' + caseNumber);
return 'ERROR:INVALID CASE NUMBER';
}
System.debug('*** Getting Case ***');
List<Case> selectedCase = [Select ownerID from case where isclosed = false and caseNumber =:paddedCaseNumber and owner.type = 'User' and owner.isActive = true limit 1];
if(selectedCase.size() == 0) return 'Not Found';
System.DEBUG('***Case Found***');
string avayaID = ([Select AVAYA_ID__c from user where id=:selectedCase[0].OwnerID limit 1]).AVAYA_ID__c;
return avayaID != null ? avayaID : 'Not Found';
}
}<file_sep>/classes/AccountContactTriggerHandler.cls
/**
* File Name : AccountContactTriggerHandler.cls
* Description : methods called from Account_Contact trigger
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 21/08/2014 <NAME> Initial version (TNT-1334)
*
*/
public with sharing class AccountContactTriggerHandler {
// HANDLERS
public static void onAfterInsertHandler(List<Account_Contact__c> triggerNew)
{
createParentAccountContactObj(triggerNew);
}
// METHODS
private static void createParentAccountContactObj(List<Account_Contact__c> newAC){
List<Account_Contact__c> newAccountContacts = new List<Account_Contact__c>();
Map<Id, Id> contactId_accountId = new Map<Id, Id>();
Map<Id, Id> accountId_parentId = new Map<Id, Id>();
for(Account_Contact__c ac : newAC){
contactId_accountId.put(ac.Contact__c, ac.Account__c);
}
for(Account a : [SELECT ParentId FROM Account WHERE Id IN : contactId_accountId.values()]){
if(a.ParentId != null){
accountId_parentId.put(a.Id, a.ParentId);
}
}
if(!accountId_parentId.isEmpty()){
Map<String, Account_Contact__c> existedAccountContacts = new Map<String, Account_Contact__c>();
for(Account_Contact__c ac : [SELECT Account__c, Contact__c FROM Account_Contact__c
WHERE Contact__c IN : contactId_accountId.keyset() AND Account__c IN : accountId_parentId.values()]){
String key = (String)ac.Account__c + (String)ac.Contact__c;
existedAccountContacts.put(key, ac);
}
for(Account_Contact__c ac : newAC){
if(accountId_parentId.containsKey(ac.Account__c)){
String key = (String)accountId_parentId.get(ac.Account__c) + (String)ac.Contact__c;
if(!existedAccountContacts.containsKey(key)){
Account_Contact__c newRec = new Account_Contact__c();
newRec.Account__c = accountId_parentId.get(ac.Account__c);
newRec.Contact__c = ac.Contact__c;
newAccountContacts.add(newRec);
}
}
}
if(!newAccountContacts.isEmpty()){
insert newAccountContacts;
}
}
}
}<file_sep>/classes/OL_SearchConsignmentControllerTest.cls
/**
* File Name : OL_SearchConsignmentControllerTest.cls
* Description : Test class for OL_SearchConsignmentController.cls
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 09/09/2014 <NAME> Initial version, TNT-546
*/
@isTest
private class OL_SearchConsignmentControllerTest {
static testMethod void testData() {
Account d = TestUtil.createAccountDepot();
d.Depot_Number__c = '123';
insert d;
Service__c svc = new Service__c(Name='Test Svc', Service_Code__c='01');
insert svc;
Option_Settings__c os = new Option_Settings__c(Name='01', SF_Description__c='Test Opt');
insert os;
Note_Type_Settings__c nts = new Note_Type_Settings__c(Name='01', SF_Description__c='Test Nt Type');
insert nts;
Con_Status_Settings__c css = new Con_Status_Settings__c(Name='01', SF_Description__c='Test Con Stattus');
insert css;
Con_Sub_Status_Settings__c csss = new Con_Sub_Status_Settings__c(Name='01', SF_Description__c='Test Con Sub Status');
insert csss;
Line_of_Business__c lob = new Line_of_Business__c(Name='Test Lob', Line_of_Business_Reference__c='01');
insert lob;
OL_SearchConsignmentController cntr = new OL_SearchConsignmentController();
system.assertEquals(1, cntr.getConSubStatusItems().size());
system.assertEquals(1, cntr.getConStatusItems().size());
system.assertEquals(1, cntr.getNoteTypeItems().size());
system.assertEquals(1, cntr.getOptionItems().size());
system.assertEquals(1, cntr.getServiceItems().size());
system.assertEquals(1, cntr.getDepotItems().size());
system.assertEquals(1, cntr.getLobItems().size());
system.assertEquals(1, cntr.lobMap.size());
system.assertEquals(1, cntr.serviceMap.size());
}
static testMethod void testService() {
OL_SearchConsignmentController cntr = new OL_SearchConsignmentController();
cntr.consReq.stsHstry.negStsInd = false;
cntr.consReq.stsHstry.negSubStsInd = true;
Test.startTest();
Test.setMock(WebServiceMock.class, new uksvcsTntComSearchConsignmentServiceMock());
cntr.consReq.tntConNum = '12345678';
cntr.searchAdvanced();
cntr.next();
system.assertEquals(2, cntr.pageNumber);
cntr.prew();
system.assertEquals(1, cntr.pageNumber);
Test.stopTest();
system.assertEquals('111', cntr.cons.con[0].unqConNum);
}
static testMethod void test_checkSearchData() {
OL_SearchConsignmentController cntr = new OL_SearchConsignmentController();
system.assert(!cntr.checkSearchData());
cntr.consReq.tntConNum = '12345678';
system.assert(cntr.checkSearchData());
cntr.consReq.tntConNum = null;
cntr.isAdvanced = true;
cntr.quote.Collection_Date__c = Date.today() - 8;
system.assert(!cntr.checkSearchData());
cntr.quoteTo.Collection_Date__c = Date.today() - 10;
system.assert(!cntr.checkSearchData());
cntr.quoteTo.Collection_Date__c = null;
system.assert(!cntr.checkSearchData());
cntr.quoteTo.Collection_Date__c = Date.today() - 4;
cntr.consReq.colRnd = '2';
system.assert(!cntr.checkSearchData());
cntr.consReq.colDep = '123';
system.assert(cntr.checkSearchData());
cntr.consReq.delRnd = '2';
system.assert(!cntr.checkSearchData());
cntr.consReq.delDep = '123';
system.assert(cntr.checkSearchData());
}
static testMethod void testInitSaerch() {
OL_SearchConsignmentController cntr = new OL_SearchConsignmentController();
ApexPages.currentPage().getParameters().put('bNum', '123456');
Test.startTest();
Test.setMock(WebServiceMock.class, new uksvcsTntComSearchConsignmentServiceMock());
cntr.initSearch();
Test.stopTest();
system.assertEquals('111', cntr.cons.con[0].unqConNum);
}
//***** tests for Detail part
static testMethod void test_searchConsignment() {
OL_SearchConsignmentController cnt = new OL_SearchConsignmentController();
cnt.consignmentId = '1234';
Test.startTest();
Test.setMock(WebServiceMock.class, new uksvcsTntComGetConsDetlsServiceMock());
cnt.searchConsignment();
Test.stopTest();
system.assertNotEquals(null, cnt.consignment);
}
static testMethod void test_searchConsignmentItems() {
OL_SearchConsignmentController cnt = new OL_SearchConsignmentController();
cnt.consignment = new uksvcsTntComSearchConsignment.ConsignmentResponse_MasterType();
cnt.consignment.unqConNum = '1234';
Test.startTest();
Test.setMock(WebServiceMock.class, new uksvcsTntGetItemsForConsignmentSvcMock());
cnt.searchConsignmentItems();
Test.stopTest();
system.assertNotEquals(null, cnt.consignmentItems);
}
static testMethod void cover_other(){
Account a = TestUtil.createAccountDepot();
a.Depot_Number__c = '111';
insert a;
Service__c svc = new Service__c(Name='Test Svc', Service_Code__c='01');
insert svc;
Line_of_Business__c lob = new Line_of_Business__c(Name='Test Lob', Line_of_Business_Reference__c='01');
insert lob;
OL_SearchConsignmentController cnt = new OL_SearchConsignmentController();
cnt.setSelectedItemRaw();
uksvcsTntComGenericPayloadHeader.search_x s = new uksvcsTntComGenericPayloadHeader.search_x();
system.assertEquals('*111*', cnt.depotKeys);
}
static testMethod void test_CaseCreation(){
Account a = TestUtil.createAccountClient();
a.Account_Number__c = '111';
insert a;
Account depot = TestUtil.createAccountDepot();
depot.Depot_Number__c = '010';
insert depot;
OL_SearchConsignmentController cnt = new OL_SearchConsignmentController();
cnt.consignment = new uksvcsTntComSearchConsignment.ConsignmentResponse_MasterType();
cnt.consignment.tntConNum = '123';
cnt.consignment.unqConNum = '321';
cnt.consignment.orgnDep = depot.Depot_Number__c;
cnt.consignment.act = new uksvcsTntComSearchConsignment.Account_MasterType();
cnt.consignment.act.actNum = '111';
cnt.fillDepots();
cnt.runCreateAndSaveCase();
Case c = [SELECT AccountId, Type, Status, Delivery_Depot__c FROM Case LIMIT 1];
system.assertEquals(a.Id, c.AccountId);
system.assertEquals(ConstantUtil.PLVAL_CASE_STATUS_CLOSED, c.Status);
system.assertEquals(ConstantUtil.PLVAL_CASE_TYPE_RECORD_TRACK, c.Type);//MODIFIED by DH 24/09/15
system.assertEquals(depot.Id, c.Delivery_Depot__c);
cnt.runCreateAndOpenCase();
system.assertEquals(null, cnt.caseToOpen);
cnt.createAndOpenCase();
c = [SELECT AccountId, Type, Status, Delivery_Depot__c FROM Case where Id = :cnt.caseToOpen.Id];
system.assertEquals(a.Id, c.AccountId);
system.assertEquals(ConstantUtil.PLVAL_CASE_STATUS_WORKING_ON, c.Status);
system.assertEquals(ConstantUtil.PLVAL_CASE_TYPE_TRACK, c.Type);
system.assertEquals(depot.Id, c.Delivery_Depot__c);
}
}<file_sep>/classes/TimeUtil.cls
/**
* File Name : TimeUtil.cls
* Description : Class for working with business hours etc
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 03/07/2014 <NAME> Initial version
*
*
*/
public with sharing class TimeUtil {
public static final String DATETIMEPICKER_FORMAT = 'dd/MM/yyyy HH:mm';
public static BusinessHours bh = [select Id, Name,
MondayStartTime, MondayEndTime,
TuesdayStartTime, TuesdayEndTime,
WednesdayStartTime, WednesdayEndTime,
ThursdayStartTime, ThursdayEndTime,
FridayStartTime, FridayEndTime,
SaturdayStartTime, SaturdayEndTime,
SundayStartTime, SundayEndTime,
IsDefault,
IsActive,
TimeZoneSidKey
from BusinessHours
where IsDefault = true and IsActive = true limit 1];
public static List<Holiday> holidays = [select Name,
ActivityDate,
IsRecurrence,
RecurrenceType,
RecurrenceMonthOfYear,
RecurrenceDayOfWeekMask,
RecurrenceDayOfMonth,
RecurrenceInstance,
IsAllDay
from Holiday h];
// get next work day with preserved time component
public static Datetime getNextWorkingDay(Datetime dt)
{
Datetime nextDay = getNextWorkingDayStartDT(dt.date());
return Datetime.newInstance(nextDay.date(),dt.time());
}
// get next work day with start time for that day
public static Datetime getNextWorkingDayStartDT(Date d)
{
d = d.addDays(1);
while(!isWorkingDay(d))
{
d = d.addDays(1);
}
return Datetime.newInstance(d,getDayStartTime(d));
}
// get next datetime when work can resume - if dateime is within working hours then will return dt
public static Datetime getWorkingDayResumeDT(Datetime dt)
{
Datetime startWorkDT;
if(isWorkingDay(dt.date())) // now check if the time falls into work hours
{
startWorkDT = dt;
if(!isAllDay(startWorkDT.date()))
{
if(startWorkDT.time() < getDayStartTime(startWorkDT.date())) // if too early, move to start time
{
startWorkDT = Datetime.newInstance(startWorkDT.date(),getDayStartTime(startWorkDT.date()));
}
else
{
if(startWorkDT.time() > getDayEndTime(startWorkDT.date())) // if too late, move to other day start time
{
startWorkDT = getNextWorkingDayStartDT(startWorkDT.date());
}
}
}
}
else
{
startWorkDT = getNextWorkingDayStartDT(dt.date()); // if you had to move to next day rewind to start hours
}
return startWorkDT;
}
// format hh:mm
public static Time parseTime(String ts)
{
Time t ;
if(String.isNotBlank(ts) && ts.contains(':'))
{
String[] ls = ts.split(':');
//if(ls.size() == 2 && String.isNumeric(ls.get(0)) && String.isNumeric(ls.get(1)))
if(ls.size() == 2)
{
t = Time.newInstance(Integer.valueOf(ls.get(0)),Integer.valueOf(ls.get(1)),0,0);
}
}
return t;
}
public static Datetime addWorkHours(Datetime dt, Integer addHours)
{
system.debug(dt + ' + ' + addHours);
// make sure begining is workday
Datetime startWorkDT = getWorkingDayResumeDT(dt);
// now that we have start datetime, we need end datetime
Datetime endWorkDT = startWorkDT;
for(Integer i = addHours; i > 0; i--)
{
Time currentEndTime = isAllDay(endWorkDT.date()) ? Time.newInstance(23,59,59,999) : getDayEndTime(endWorkDT.date());
Datetime endWorkOldDT = endWorkDT; // in case we pass midnight
endWorkDT = endWorkDT.addHours(1);
system.debug(currentEndTime);
system.debug(endWorkDT);
// if you surpassed end time for that day or if we passed midnight, split the hour between this and next day
if(endWorkDT.time() > currentEndTime || !endWorkOldDT.isSameDay(endWorkDT))
{
Datetime nextWorkingDT = getNextWorkingDayStartDT(endWorkOldDT.date());
// find the difference between the workday end time and the endWorkDT time
Long diff = endWorkDT.getTime() - Datetime.newInstance(endWorkOldDT.date(),currentEndTime).getTime();
endWorkDT = Datetime.newInstance(nextWorkingDT.getTime() + diff);
}
// handle special case if final result is at midnigt (23:59+) on allDay - don't carry over to next day, but keep in same day
// more consistent with how other if statement sets time
if(i == 1 && !endWorkOldDT.isSameDay(endWorkOldDT.addHours(1))
&& endWorkOldDT.addHours(1).time() == Time.newInstance(0,0,0,0) && currentEndTime == Time.newInstance(23,59,59,999))
{
endWorkDT = Datetime.newInstance(endWorkOldDT.date(),currentEndTime);
}
}
return endWorkDT;
}
public static Boolean isWithinWorkHours(Datetime dt)
{
Time startTime = getDayStartTime(dt.date());
Time endTime = getDayEndTime(dt.date());
Time t = dt.time();
return isWorkDay(startTime,endTime) && !isHoliday(dt.date()) && (isAllDay(startTime,endTime) || (t >= startTime && t <= endTime));
}
public static Boolean isWorkingDay(Date d)
{
return !isHoliday(d) && isWorkDay(d);
}
public static Boolean isWorkDay(Date d)
{
Time startTime = getDayStartTime(d);
Time endTime = getDayEndTime(d);
return isWorkDay(startTime, endTime);
}
public static Boolean isWorkDay(Time startTime, Time endTime)
{
return startTime != null && endTime != null;
}
public static Boolean isAllDay(Date d)
{
Time startTime = getDayStartTime(d);
Time endTime = getDayEndTime(d);
return isAllDay(startTime, endTime);
}
public static Boolean isAllDay(Time startTime, Time endTime)
{
return startTime == endTime && endTime == Time.newInstance(0,0,0,0); // if something is 24h, it will be 00:00-00:00
}
public static Boolean isHoliday(Date d)
{
Boolean isHoliday = false; // if at least on holiday is a match, it will return true
for(Holiday hd : holidays) // expecting all holidays to be all day with yearly intervals if recurring
{
// TODO put int constants
if(hd.IsRecurrence)
{
if(d.month() == ConstantUtil.MONTHS_S2I.get(hd.RecurrenceMonthOfYear))
{
if(hd.RecurrenceType == 'RecursYearly')
{
isHoliday |= d.day() == hd.RecurrenceDayOfMonth;
}
if(hd.RecurrenceType == 'RecursYearlyNth')
{
final Integer INT7 = ConstantUtil.DAYS_IN_WEEK;
// resolve bitmask - expecting only one day per week
Integer dayOfWeek = 1;
while(Math.pow(2,dayOfWeek-1) < hd.RecurrenceDayOfWeekMask)
{
dayOfWeek++;
}
dayOfWeek = dayOfWeek == 1 ? INT7 : dayOfWeek-1; // they use Sunday as first day, and I use Monday
if(getDayOfWeek(d) == ConstantUtil.WEEKDAYS_ABRV_I2S.get(dayOfWeek))
{
Integer numOfWeeks = hd.RecurrenceInstance == ConstantUtil.HOLIDAY_RECINSTANCE_FIRST ? 1 :
(hd.RecurrenceInstance == ConstantUtil.HOLIDAY_RECINSTANCE_SECOND ? 2 :
(hd.RecurrenceInstance == ConstantUtil.HOLIDAY_RECINSTANCE_THIRD ? 3 :
(hd.RecurrenceInstance == ConstantUtil.HOLIDAY_RECINSTANCE_FOURTH ? 4 : 0)));
if(numOfWeeks != 0)
{
isHoliday |= d.day() >= (numOfWeeks-1)*INT7 + 1 && d.day() <= numOfWeeks*INT7;
}
else // handle last in month - has to occur within last 7 days of month
{
isHoliday |= d.day() >= Date.daysInMonth(d.year(),d.month())- INT7 + 1
&& d.day() <= Date.daysInMonth(d.year(),d.month());
}
}
}
}
}
else
{
isHoliday |= d.isSameDay(hd.ActivityDate);
}
}
return isHoliday;
}
public static Time getDayStartTime(Date d)
{
String weekday = getDayOfWeek(d);
return weekday == ConstantUtil.MONDAY_ABRV ? bh.MondayStartTime :
(weekday == ConstantUtil.TUESDAY_ABRV ? bh.TuesdayStartTime :
(weekday == ConstantUtil.WEDNESDAY_ABRV ? bh.WednesdayStartTime :
(weekday == ConstantUtil.THURSDAY_ABRV ? bh.ThursdayStartTime :
(weekday == ConstantUtil.FRIDAY_ABRV ? bh.FridayStartTime :
(weekday == ConstantUtil.SATURDAY_ABRV ? bh.SaturdayStartTime :
(weekday == ConstantUtil.SUNDAY_ABRV ? bh.SundayStartTime : null))))));
}
public static Time getDayEndTime(Date d)
{
String weekday = getDayOfWeek(d);
return weekday == ConstantUtil.MONDAY_ABRV ? bh.MondayEndTime :
(weekday == ConstantUtil.TUESDAY_ABRV ? bh.TuesdayEndTime :
(weekday == ConstantUtil.WEDNESDAY_ABRV ? bh.WednesdayEndTime :
(weekday == ConstantUtil.THURSDAY_ABRV ? bh.ThursdayEndTime :
(weekday == ConstantUtil.FRIDAY_ABRV ? bh.FridayEndTime :
(weekday == ConstantUtil.SATURDAY_ABRV ? bh.SaturdayEndTime :
(weekday == ConstantUtil.SUNDAY_ABRV ? bh.SundayEndTime : null))))));
}
// return first three letters of the weekday name
public static String getDayOfWeek(Date d)
{
return getDayOfWeek(Datetime.newInstance(d,Time.newInstance(2,0,0,0)));
}
public static String getDayOfWeek(Datetime dt)
{
return dt.format('E');
}
public static final List<String> hours =
new List<String>{'00','01','02','03','04','05','06','07','08','09','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23'};
public static final List<String> minutes = new List<String>{'00','15','30','45'};
//method calculates amount of minutes in business hours for time span
public static Decimal calculateMinutesInBusinessHours(DateTime startDT, DateTime endDT){
Decimal res = 0;
if(startDT != null && endDT != null){
res = BusinessHours.diff(bh.id, startDT, endDT) / 60000.00;
}
return res;
}
// class used for storing time and minutes
public class HMTime
{
public String hour {get; set;}
public String minute {get; set;}
public String separator = ':';
public HMTime(String val)
{
if(String.isNotBlank(val) && val.length() == 5 && val.contains(separator))
{
String[] t = val.split(separator);
hour = t.get(0);
minute = t.get(1);
}
}
public List<Selectoption> getHourOptions()
{
List<Selectoption> sos = new List<Selectoption>();
sos.add(new selectoption('','--'));
for(String h : hours)
{
sos.add(new selectoption(h,h));
}
return sos;
}
public List<Selectoption> getMinuteOptions()
{
List<Selectoption> sos = new List<Selectoption>();
sos.add(new selectoption('','--'));
for(String m : minutes)
{
sos.add(new selectoption(m,m));
}
return sos;
}
public String getFormatedTime()
{
return String.isNotBlank(hour) && String.isNotBlank(minute) ? (hour + separator + minute) : '';
}
}
}<file_sep>/classes/CS_Claims_Form_Controller.cls
/*********************************************************************************************************************************************************
This controller is used for building the claims form visual force page. (TNT Claims UK)
**********************************************************************************************************************************************************
**********************************************************************************************************************************************************
This Apex class is build for the Apex page and it was build by Makepositive - Mohammed - +44 (0)20 7960 4197
**********************************************************************************************************************************************************/
public without sharing class CS_Claims_Form_Controller {
public CS_Claims__c claim {get; set;}
public Boolean Editable {get; set;}
public Id id {get; set;}
public String fax1 {
get{
return CS_TNT_Claims__c.getInstance().Fax_1__c;
}
}
public String fax2 {
get{
return CS_TNT_Claims__c.getInstance().Fax_2__c;
}
}
public String Tele {
get{
return CS_TNT_Claims__c.getInstance().Telephone__c;
}
}
public String emailId {
get{
return CS_TNT_Claims__c.getInstance().Email_Id__c;
}
}
public String address {
get{
return CS_TNT_Claims__c.getInstance().Claims_postal_address__c;
}
}
public String header {
get{
return CS_TNT_Claims__c.getInstance().Header__c;
}
}
public String Sender_section_title{
get{
return CS_TNT_Claims__c.getInstance().Sender_section_title__c;
}
}
public String Recipient_section_title{
get{
return CS_TNT_Claims__c.getInstance().Recipient_Section_title__c;
}
}
public String Claims_type_fieldset_label{
get{
return CS_TNT_Claims__c.getInstance().Claims_type_fieldset_label__c;
}
}
public String Claims_type_details_section_title{
get{
return CS_TNT_Claims__c.getInstance().Claims_type_details_section_title__c;
}
}
public String Claims_type_details_section_content{
get{
return CS_TNT_Claims__c.getInstance().Claims_type_details_section_content__c;
}
}
public String Claims_damaged_section_title{
get{
return CS_TNT_Claims__c.getInstance().Claims_damaged_section_title__c;
}
}
public String damaged_items_inspection_label{
get{
return CS_TNT_Claims__c.getInstance().damaged_items_inspection_label__c;
}
}
public String payment_method_label{
get{
return CS_TNT_Claims__c.getInstance().Method_of_payment_fieldset_label__c;
}
}
public String Declaration_section_title{
get{
return CS_TNT_Claims__c.getInstance().Declaration_section_title__c;
}
}
public String Cost_value_of_consignment_label{
get{
return CS_TNT_Claims__c.getInstance().Cost_value_of_consignment_label__c;
}
}
public String Cost_value_of_items_label{
get{
return CS_TNT_Claims__c.getInstance().Cost_value_of_items_label__c;
}
}
public String check_list_opt_1{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_1__c;
}
}
public String check_list_opt_2{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_2__c;
}
}
public String check_list_opt_3{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_3__c;
}
}
public String check_list_opt_4{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_4__c;
}
}
public String replacement_consignement_no_label{
get{
return CS_TNT_Claims__c.getInstance().Replacement_consignment_no_Label__c;
}
}
public CS_Claims_Form_Controller(ApexPages.StandardController controller){
try{
Decimal VisitCounter;
claim = new CS_Claims__c();
Editable= false;
id = ApexPages.currentPage().getParameters().get('cid');
claim = getClaims(id);
VisitCounter = claim.Form_Visit_Counter__c;
if(VisitCounter == null){
VisitCounter = 0;
}
claim.Form_Visit_Counter__c = VisitCounter + 1;
if(!ApexPages.hasMessages()){
if(claim.Claims_Stage__c != 'Returned' && claim.Claims_Stage__c != 'Closed' ){
claim.Claims_Stage__c = 'In Progress';
Editable = true;
}else if(claim.Claims_Stage__c == 'Closed'){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Your claim form has been expired as it has been more than 21 days from the date of issue. Please contact TNT Customer care for more details.'));
Editable= false;
}
}
}catch(Exception ex){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Access Denied. Please contact TNT customer care for further assistance.'));
}
}
public PageReference updateCounter(){
if(id != null){
update claim;
}
return null;
}
public PageReference quickSave(){
claim.Claims_Stage__c = 'In Progress';
update claim;
if(!ApexPages.hasMessages()){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Your form has been saved, to complete it later please click on the same link from your mail.'));
}
return null;
}
public Pagereference sendLink(){
Id id = ApexPages.CurrentPage().getParameters().get('id');
claim = getClaims(id);
if(claim.Claims_Stage__c != 'Returned' && claim.Claims_Stage__c != 'Closed' ){
claim.Claims_Stage__c = 'Sent to Customer';
update claim;
}
Schema.DescribeSObjectResult r = CS_Claims__c.sObjectType.getDescribe();
String keyPrefix = r.getKeyPrefix();
PageReference pg = new PageReference('/' + keyPrefix + '/o');
pg.setRedirect(true);
return pg;
}
public PageReference save_m(){
Boolean valid = true;
Boolean sendEmail = false;
if(claim.Declarant_Full_Name_of__c == null){
valid = false;
claim.Declarant_Full_Name_of__c.addError('Please complete the Full name of the Declerant.');
}else if(claim.Declarant_Date__c == null){
valid = false;
claim.Declarant_Date__c.addError('Date is a required field.');
}else if(claim.Lost__c == true && claim.Damaged__c == true){
valid = false;
claim.Lost__c.addError('only one option can be selected either "Lost" or "Damaged".');
claim.Damaged__c.addError('only one option can be selected either "Lost" or "Damaged".');
}else if (claim.cheque__c == true && claim.Credit_your_TNT_account__c == true ){
valid = false;
claim.cheque__c.addError('only one option can be selected "Cheque" or "Credit your TNT account".');
claim.Credit_your_TNT_account__c.addError('only one option can be selected "Cheque" or "Credit your TNT account".');
}
if(valid){
claim.Claims_Stage__c = 'Returned';
Map<String, Schema.RecordTypeInfo> ClaimsTypes = CS_Claims__c.SObjectType.getDescribe().getRecordTypeInfosByName();
claim.RecordTypeId = ClaimsTypes.get('CS Sent to Customer').getRecordTypeId();
try{
upsert claim;
sendEmail = true;
}catch(exception e){
sendEmail = false;
}
Editable = false;
}
PageReference pg = Page.CS_Claim_Form_View_Page;
pg.getParameters().put('cid',(String) claim.Id);
if(sendEmail){
pg.setRedirect(true);
return pg;
}else{
return null;
}
}
public PageReference sendEmail(){
// send email to the Claims Lotus system once the record is returned from the customer
try{
CS_Claims__c cl = getClaims(claim.Id);
system.debug('==>CLAIMS '+ cl);
if(cl.ClaimReturnMailSent__c == false){
system.debug('===inIFCondition=== '+ cl.ClaimReturnMailSent__c);
Pagereference pdf = Page.CS_Claim_Form_PDF;
pdf.getParameters().put('cid',(String)cl.id);
pdf.setRedirect(true);
Blob body = pdf.getContent();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSaveAsActivity(false);
String[] toAddresses = new String[1];
system.debug('=====cl.Lotus_Notes_Claims_Email_ID__c=====' +cl.Lotus_Notes_Claims_Email_ID__c);
toAddresses[0] = cl.Lotus_Notes_Claims_Email_ID__c; //& Uncommment this line in production
/*
* To test this in Sandbox comment above two lines and add the below given line and uncoment below three line as well
* String[] toAddresses = new String[3];
*/
//String[] toAddresses = new String[3];
//toAddresses[0] = '<EMAIL>'; //& Comment this line in production
//toAddresses[1] = '<EMAIL>';
//toAddresses[2]='<EMAIL>';
mail.setToAddresses(toAddresses);
mail.setHtmlBody('<p>Attached is Claim ' + cl.Name + ' returned by '+ cl.Sender_Contact_Name__c +'</p><p> Reference No: '+ cl.Reference_no__c+'</p>');
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(cl.Reference_no__c +'.pdf');
efa.setBody(body);
mail.setFileAttachments(new Messaging.Emailfileattachment[] {efa});
mail.setSubject('TNT Claim Return. Claim Reference no: '+ cl.Reference_no__c +' Consignment no: '+ cl.Consignment_no__c +' Depot code: ' + cl.Depot_no__c);
mail.setReplyTo(cl.Sender_Email_Address__c);
mail.setSenderDisplayName(cl.Sender_Email_Address__c);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
cl.ClaimReturnMailSent__c = true;
update cl;
}
}catch(Exception e){
system.debug('==>emialTrigger' + e);
}
return null;
}
public CS_Claims__c getClaims(Id id){
CS_Claims__c cl = new CS_Claims__c();
try{
cl = [SELECT
Name,
Copy_of_relevant_commercial_invoice__c,
Copy_of_repair_estimate__c,
Sender_Address_1__c,
Recipient_Address_1__c,
Sender_Address_2__c,
Recipient_Address_2__c,
Sender_Address_3__c,
Recipient_Address_3__c,
All_requested_information__c,
cheque__c,
Claims_Stage__c,
Sender_company_name__c,
Consignment_no__c,
Sender_Contact_Name__c,
Recipient_Contact_Name__c,
Cost_of_consignment_exclcuding_VAT__c,
Cost_of_items_exclcuding_VAT__c,
Credit_your_TNT_account__c,
Sender_Email_Address__c,
Damaged__c,
Declarant_Date__c,
Date_of_dispatch__c,
Depot_no__c,
Detail_description_of_items__c,
Declarant_Full_Name_of__c,
damaged_packing_inspection__c,
Lost__c,
photographs_of_the_items__c,
Sender_Postcode__c,
Recipient_Postcode__c,
Reference_no__c,
Salvage_value__c,
Sender_Telephone_no__c,
Recipient_Telephone_no__c,
TNT_account_no__c,
Weight_of_items__c,
Repair_cost__c,
Replacement_Consignment_No__c,
Form_Visit_Counter__c,
Lotus_Notes_Claims_Email_ID__c,
ClaimReturnMailSent__c
FROM CS_Claims__c
WHERE
id=: id
];
}catch(Exception e){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'If this error persists please contact TNT Customer care for further help. ERROR:' + e.getMessage()));
}
return cl;
}
}<file_sep>/classes/OL_AccountOnStopSubmit.cls
/**
* File Name : OL_AccountOnStopSubmit.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 05/08/2014 <NAME> Initial version (TNT-1293)
*
*/
public without sharing class OL_AccountOnStopSubmit {
public Boolean hasError {get; set;}
Account a;
public OL_AccountOnStopSubmit(Apexpages.standardController stdCtrl)
{
Account a = (Account) stdCtrl.getRecord();
}
public void submitAccount()
{
Id aId = Apexpages.currentPage().getparameters().get('id');
Account a = [select Name, On_Stop__c, Request_Stubbins_Permission__c, Stubbins_Temporary_Permission__c
from Account where id = :aId limit 1];
if(a.On_Stop__c && !a.Stubbins_Temporary_Permission__c)
{
a.Request_Stubbins_Permission__c = true;
update a;
// submit for approval
Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
req1.setComments('Requested by agent ' + UserInfo.getName() + ' (' + UserInfo.getUserId() + ').');
req1.setObjectId(a.id);
try
{
Approval.ProcessResult result = Approval.process(req1);
hasError = !result.isSuccess();
if(hasError)
{
for(Database.error err : result.getErrors())
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,err.getMessage()));
}
}
}
catch(exception e)
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,e.getMessage()));
hasError = true;
}
}
else
{
hasError = false;
}
}
}<file_sep>/classes/FieldSetUtil.cls
/**
* File Name : FieldSetUtil.cls
* Description : Make using fieldsets easier
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 07/07/2014 <NAME> Intial
*
*/
public with sharing class FieldSetUtil {
// replace charaters that can't appear in the Developer Name of the fieldset
/*public static String formFieldSetBaseName(String assetTypeName)
{
String fieldSetName = assetTypeName;
fieldSetName = fieldSetName.replace('(','');
fieldSetName = fieldSetName.replace(')','');
fieldSetName = fieldSetName.replace('"','');
fieldSetName = fieldSetName.replace('\'','');
fieldSetName = fieldSetName.replace(' & ',' ');
fieldSetName = fieldSetName.replace(' / ',' ');
fieldSetName = fieldSetName.replace(' \\ ',' ');
fieldSetName = fieldSetName.replace(' ','_');
return fieldSetName;
}*/
// query database based on passed in fieldset
public static List<Sobject> queryViaFieldSet(List<Schema.FieldSetMember> fieldSet, String queryObject, String whereClause)
{
String q = 'SELECT id, Name, ';
for(Schema.FieldSetMember fld : fieldSet)
{
if(fld.getFieldPath() != 'Name' && fld.getFieldPath() != 'Id') // hrow out preselected fields
{
q += fld.getFieldPath() + ', ';
}
}
q = q.removeEnd(', ');
q += ' FROM ' + queryObject;
q += String.isBlank(whereClause) ? '' : (' WHERE ' + whereClause);
return Database.query(q);
}
// pass in Schema.sObjectType.Object__c.fields.getMap().values() for flds
/*public static List<sObject> queryAllFields(List<Schema.SObjectField> flds, String queryObject, String whereClause)
{
String queryString = 'SELECT ';
for (Schema.SObjectField f : flds)
{
queryString += f.getDescribe().getName() + ', ';
}
queryString = queryString.removeEnd(', ');
queryString += ' FROM ' + queryObject;
queryString += String.isBlank(whereClause) ? '' : (' WHERE ' + whereClause);
return Database.query(queryString);
}*/
// check if object has populated fields which have been marked as requiered in either fild set or definition
public static String checkRequiredFieldsFS(sObject obj, List<Schema.FieldSetMember> fieldSet)
{
final String sep = ', ';
String retStr = '';
for(Schema.FieldSetMember fsm : fieldSet)
{
if(fsm.getRequired() || fsm.getDBRequired()) // if field is required in field set or definition
{
Object ob = obj.get(fsm.getFieldPath());
if(ob == null || (ob instanceof String && String.isBlank((String)ob)))
{
retStr += fsm.getLabel() + sep;
}
}
}
return String.isBlank(retStr) ? retStr : ('Required fields missing: ' + retStr.removeEnd(sep) + '<br/>');
}
// find field set based on a label/api name, return empty list if none found
/*public static List<Schema.FieldSetMember> getFieldSet(Map<String,Schema.FieldSet> fieldSetMap, String fieldSetLabel)
{
String fieldSetName = formFieldSetBaseName(fieldSetLabel);
Schema.FieldSet fs = fieldSetMap.get(fieldSetName);
return fs != null ? fs.getFields() : new List<Schema.FieldSetMember>();
}*/
}<file_sep>/reports/Interface_Monitoring_Reports/Major_Accounts_with_CS_Owner_Contacts.report
<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns="http://soap.sforce.com/2006/04/metadata">
<columns>
<field>Account$Name</field>
</columns>
<columns>
<field>Account$Account_Number__c</field>
</columns>
<columns>
<field>Account$Assigned_Agent__c</field>
</columns>
<columns>
<field>Account$Phone</field>
</columns>
<columns>
<field>Account$CS_Owner__c</field>
</columns>
<columns>
<field>Account.Contacts$FirstName</field>
</columns>
<columns>
<field>Account.Contacts$LastName</field>
</columns>
<columns>
<field>Account.Contacts$Phone</field>
</columns>
<columns>
<field>Account.Contacts$Email</field>
</columns>
<description>For Rupa to check contacts have been loaded correctly</description>
<filter>
<criteriaItems>
<column>Account$CS_Owner__c</column>
<operator>notEqual</operator>
<value></value>
</criteriaItems>
</filter>
<format>Tabular</format>
<name>Major Accounts with CS Owner & Contacts</name>
<params>
<name>co</name>
<value>1</value>
</params>
<reportType>Accounts_with_or_without_Contacts__c</reportType>
<scope>organization</scope>
<showDetails>true</showDetails>
<sortColumn>Account$CS_Owner__c</sortColumn>
<sortOrder>Asc</sortOrder>
<timeFrameFilter>
<dateColumn>Account$CreatedDate</dateColumn>
<interval>INTERVAL_CUSTOM</interval>
</timeFrameFilter>
</Report>
<file_sep>/classes/BookingLineItemTriggerHelperTest.cls
/**
* File Name : BookingLineItemTriggerHelperTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 08/09/2014 <NAME> Initial Version TNT-1604
* 0.2 23/10/2015 <NAME> Added and amended code where DH comments to turn off new duplicate checks
*/
@isTest
private class BookingLineItemTriggerHelperTest {
static Booking__c createBaseBooking(String id)
{
//DH added 23/10/15 to allow duplicates whilst testing
Database.DMLOptions dml = new Database.DMLOptions();
dml.DuplicateRuleHeader.AllowSave = true;
//
Account a = TestUtil.createAccountClient();
insert a;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
aaCol.Default__c = true;
insert aaCol;
Contact con = TestUtil.createContact(a.Id);
con.FirstName = con.FirstName + id;
//Modified by DH to use database method instead of insert to alow turn off duplicate checking for testing
database.insert(con,dml);
//insert con;
Account depot = TestUtil.createAccountDepot();
insert depot;
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Collection_Contact__c = con.Id;
bo.Coll_Account_Address__c = aaCol.id;
bo.Collection_Depot__c = depot.id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
return bo;
}
// trigger coverage
static testMethod void quickRun()
{
Booking__c bo = createBaseBooking(null);
insert bo;
Booking_Line_Item__c bli = new Booking_Line_Item__c(Booking__c = bo.id);
bli.Weight__c = 20;
bli.Number_of_Items__c = 1;
bli.Height__c = 100;
bli.Length__c = 100;
bli.Width__c = 100;
Test.startTest();
insert bli;
update bli;
delete bli;
Test.stopTest();
}
static testMethod void testUpdateBookingTotals()
{
//Added by DH 23/10/15
Database.DMLOptions dml = new Database.DMLOptions();
dml.DuplicateRuleHeader.AllowSave = true;
Booking__c bo1 = createBaseBooking(null); // will ovewrite null
bo1.Total_Items__c = null;
bo1.Total_Weight__c = null;
Booking__c bo2 = createBaseBooking('c1'); // will overwrite less
bo2.Total_Items__c = 1;
bo2.Total_Weight__c = 1;
Booking__c bo3 = createBaseBooking('c2'); // will not overwrite more
bo3.Total_Items__c = 1000;
bo3.Total_Weight__c = 1000;
insert new List<Booking__c>{bo1,bo2,bo3};
Double weight = 20;
Double noItems = 3;
List<Booking_Line_Item__c> blis = new List<Booking_Line_Item__c>();
blis.add(new Booking_Line_Item__c(Booking__c = bo1.id, Weight__c = weight, Number_of_Items__c = noItems,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '000'));
blis.add(new Booking_Line_Item__c(Booking__c = bo2.id, Weight__c = weight, Number_of_Items__c = noItems,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '001'));
blis.add(new Booking_Line_Item__c(Booking__c = bo3.id, Weight__c = weight, Number_of_Items__c = noItems,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '010'));
blis.add(new Booking_Line_Item__c(Booking__c = bo1.id, Weight__c = weight, Number_of_Items__c = 0,
Booking_Line_Item_Id__c = '011'));
blis.add(new Booking_Line_Item__c(Booking__c = bo2.id, Weight__c = weight, Number_of_Items__c = 0,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '100'));
blis.add(new Booking_Line_Item__c(Booking__c = bo3.id, Weight__c = weight, Number_of_Items__c = 0,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '101'));
blis.add(new Booking_Line_Item__c(Booking__c = bo1.id, Weight__c = null, Number_of_Items__c = noItems,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '111'));
blis.add(new Booking_Line_Item__c(Booking__c = bo2.id, Weight__c = null, Number_of_Items__c = noItems,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '222'));
blis.add(new Booking_Line_Item__c(Booking__c = bo3.id, Weight__c = null, Number_of_Items__c = noItems,
Length__c = 10, Width__c = 10, Height__c = 10, Booking_Line_Item_Id__c = '333'));
User u = TestUtil.createIntegrationUser(); // avoid all validation rules
insert u;
Test.startTest();
System.runAs(u) { insert blis; }
Test.stopTest();
Double vol = 10*10*10*noItems*2;
system.assertEquals(1,[select count() from Booking__c
where id = :bo1.id and Total_Items__c = :2*noItems and Total_Weight__c = :noItems*weight and Total_Volume__c = :vol]);
system.assertEquals(1,[select count() from Booking__c
where id = :bo2.id and Total_Items__c = :2*noItems and Total_Weight__c = :noItems*weight and Total_Volume__c = :vol]);
system.assertEquals(1,[select count() from Booking__c
where id = :bo3.id and Total_Items__c = :bo3.Total_Items__c and Total_Weight__c = :bo3.Total_Weight__c and Total_Volume__c = :vol]);
}
}<file_sep>/classes/uksvcsTntComBookingService.cls
//Generated by wsdl2apex
public class uksvcsTntComBookingService {
public class createOrUpdateBookingPort {
public String endpoint_x = TNT_Integration__c.getInstance().Booking_Service__c;
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://express.tnt.com/general/schema/enums/generic/v1', 'ukTntComGenericEnums', 'http://express.tnt.com/service/schema/crtorupdbooking/v1', 'uksvcsTntComBooking', 'http://express.tnt.com/service/wsdl/crtorupdbooking/v1', 'uksvcsTntComBookingService', 'http://express.tnt.com/general/schema/tnterror/v1', 'uksvcsTntComError', 'http://express.tnt.com/general/schema/payloadheader/v1', 'uksvcsTntComGenericPayloadHeader', 'http://express.tnt.com/general/schema/objects/generic/v1', 'uksvcsTntComGenericObjects'};
public uksvcsTntComBooking.ResponseMessage_MasterType createOrUpdateBooking(uksvcsTntComGenericPayloadHeader.payloadHeader hdr,uksvcsTntComBooking.BookingRequest_MasterType bkng) {
uksvcsTntComBooking.RequestMessage_MasterType request_x = new uksvcsTntComBooking.RequestMessage_MasterType();
request_x.hdr = hdr;
request_x.bkng = bkng;
uksvcsTntComBooking.ResponseMessage_MasterType response_x;
Map<String, uksvcsTntComBooking.ResponseMessage_MasterType> response_map_x = new Map<String, uksvcsTntComBooking.ResponseMessage_MasterType>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'createOrUpdate',
'http://express.tnt.com/service/schema/crtorupdbooking/v1',
'ceateOrUpdateBookingRequest',
'http://express.tnt.com/service/schema/crtorupdbooking/v1',
'createOrUpdateBookingResponse',
'uksvcsTntComBooking.ResponseMessage_MasterType'}
);
response_x = response_map_x.get('response_x');
return response_x;
}
}
}<file_sep>/classes/OL_BookingQuoteHelper.cls
/**
* File Name : OL_BookingQuoteHelper.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 08/07/2014 <NAME> Initial version
* 0.2 16/07/2014 <NAME> TNT-476,TNT-477
* 0.3 23/07/2014 <NAME> TNT-532, TNT-609
* 0.4 05/08/2014 <NAME> TNT-1293
* 0.5 05/08/2014 <NAME> TNT-1326
* 0.6 06/08/2014 <NAME> TNT-1329
* 0.7 19/08/2014 <NAME> TNT-1560 this extension will only be used for Quotes from now on, instead of both quote and booking
* 0.8 10/10/2014 <NAME> TNT-2030 mimic address behaviour from Bookings
* 0.9 17/10/2014 <NAME> TNT-2218 quote shouldn't save if line items fail
* 0.10 14/07/2015 <NAME> added getNumLongItems from line 361 and 255 to update No_LongLengthITems field
*/
public with sharing class OL_BookingQuoteHelper {
public Id newId {
get{
return '000000000000000000'; // faulty Id to signal that we want new record
}
private set;
}
private sObject record;
public Account currentAccount {get; set;}
/* public Boolean createContact {get; set;} */
private String oldRecordId;
private String bId;
public Boolean hadAccount {get; private set;} // assert if record had account on load - glitch fix
public List<Quote_Line_Item__c> quoteItems {get; set;}
public List<Quote_Line_Item__c> delQuoteItems {get; set;}
public String aaDefPC {get; private set;}
public Boolean hasContactEmail {get; set;}
public OL_BookingQuoteHelper(Apexpages.standardController stdCtrl)
{
record = stdCtrl.getRecord();
hadAccount = ((Id) record.get('Id')) != null && ((Id) record.get(ConstantUtil.FLD_ACCOUNT_APINAME)) != null;
//clone old record for editing
oldRecordId = ApexPages.currentPage().getParameters().get('oId');
bId = ApexPages.currentPage().getParameters().get('bId');
copyDataFromBooking();
if(!String.isEmpty(oldRecordId)){
cloneRecord();
}
if(record instanceof Quote__c){
initQuoteLines();
}
Id accountId = (Id) record.get(ConstantUtil.FLD_ACCOUNT_APINAME);
if(accountId != null)
{
currentAccount = new Account(id = accountId); // referencing account field in page gives null always for soem reason :(
if(((Id) record.get('id')) == null && String.isBlank(oldRecordId) && String.isBlank(bId))
{
resetAddresses();
}
}
findContactEmail();
}
public void resetAddresses()
{
findCurrentAccount();
removeAddresses();
if(record instanceof Quote__c)
{
Quote__c q = (Quote__c) record;
q.Collection_Postcode__c = aaDefPC;
}
}
public void collectionPostcodeChanged()
{
if(String.isNotBlank(aaDefPC))
{
if(record instanceof Quote__c)
{
Quote__c q = (Quote__c) record;
if(q.Collection_Postcode__c != aaDefPC)
{
q.Delivery_Postcode__c = aaDefPC;
q.Carriage_Forward__c = true;
}
else
{
q.Carriage_Forward__c = false;
if(q.Delivery_Postcode__c == aaDefPC)
{
q.Delivery_Postcode__c = null;
}
}
}
}
}
public void clearAccount()
{
currentAccount = null;
aaDefPC = null;
record.put(ConstantUtil.FLD_ACCOUNT_APINAME,null);
removeAddresses();
}
public void removeAddresses()
{
if(record instanceof Quote__c) // reset address fields
{
for(Schema.FieldSetMember fsm : sObjectType.Quote__c.FieldSets.AddressFields.getFields())
{
if(fsm.getType() == Schema.DisplayType.String)
{
record.put(fsm.getFieldPath(),null);
}
else
{
if(fsm.getType() == Schema.DisplayType.Boolean)
{
record.put(fsm.getFieldPath(),false);
}
}
}
}
}
public void findCurrentAccount()
{
Id accountId = (Id) record.get(ConstantUtil.FLD_ACCOUNT_APINAME);
currentAccount = accountId == null ? new Account() :
(Account) FieldSetUtil.queryViaFieldSet(
sObjectType.Account.FieldSets.AccountInfoFields.getFields(),
sObjectType.Account.getName(),
'Id = \'' + accountId + '\'').get(0);
// this could have been done as an account child query but Im trying to keep the code interventions to a minimum
aaDefPC = null;
for(Account_Address__c aa : [select Postcode__c from Account_Address__c where Default__c = true and Account__c = :accountId])
{
aaDefPC = aa.Postcode__c;
break;
}
}
public String getOnStopURL()
{
Id accountId = (Id) record.get(ConstantUtil.FLD_ACCOUNT_APINAME);
return Page.OL_AccountOnStopSubmitAgent.getUrl() + '?id=' + accountId;
}
public void findContactEmail()
{
Id contactId = (Id) record.get(ConstantUtil.FLD_CONTACT_APINAME);
if(contactId != null)
{
Boolean hasEmail = [select count() from Contact where id = :contactId and Email != null] > 0;
if(hasEmail)
{
record.put('Email_Only__c',null);
}
hasContactEmail = hasEmail;
}
else
{
hasContactEmail = false;
}
}
public void emptyAction() {}
public Boolean processNewAccount(Id accountId)
{
// remove fields if an account selected
if(accountId != null)
{
List<Schema.FieldSetMember> fsms = sObjectType.Quote__c.FieldSets.CompanyFields.getFields();
for(Schema.FieldSetMember fsm : fsms)
{
record.put(fsm.getFieldPath(),null);
}
}
else
{
String errorMsg = FieldSetUtil.checkRequiredFieldsFS(record,sObjectType.Quote__c.FieldSets.CompanyFields.getFields());
if(String.isNotBlank(errorMsg))
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,errorMsg));
return false;
}
}
return true;
}
public Boolean processNewContact(Id contactId)
{
// if no contact selected agent should populate contact fields
if(contactId == null)
{
String errorMsg = FieldSetUtil.checkRequiredFieldsFS(record,sObjectType.Quote__c.FieldSets.ContactFields.getFields());
if(String.isNotBlank(errorMsg))
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,errorMsg));
return false;
}
}
else
{
// remove fields if an contact selected
List<Schema.FieldSetMember> fsms = sObjectType.Quote__c.FieldSets.ContactFields.getFields();
for(Schema.FieldSetMember fsm : fsms)
{
record.put(fsm.getFieldPath(),null);
}
}
return true;
}
public Pagereference customSave()
{
Id accountId = (Id) record.get(ConstantUtil.FLD_ACCOUNT_APINAME);
Id contactId = (Id) record.get(ConstantUtil.FLD_CONTACT_APINAME);
// process additional objects/fields
Boolean noErrors = true;
noErrors &= confirmHasQuoteLineItems();
noErrors &= processNewAccount(accountId);
noErrors &= processNewContact(contactId);
if(!noErrors)
{
return null; // if error while processing, refresh page
}
Savepoint sp = Database.setSavepoint();
Boolean isNew = ((Quote__c) record).id == null;
try
{
// check if required fields for object have been set
String errorMsg = FieldSetUtil.checkRequiredFieldsFS(record,sObjectType.Quote__c.FieldSets.EditFields.getFields());
if(record instanceof Quote__c){
errorMsg += FieldSetUtil.checkRequiredFieldsFS(record, sObjectType.Quote__c.FieldSets.AddressFields.getFields());
}
if(String.isNotBlank(errorMsg))
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,errorMsg));
return null;
}
// if everything ok insert object
//DH
record.put(Quote__c.No_Long_Length_Items__c,getNumLongLengths());
upsert record;
//check if it has been copied from Booking and update Booking
if(bookFrom != null){
bookFrom.Quote__c = record.Id;
update bookFrom;
}
if(record instanceof Quote__c){
saveQuoteLines();
}
}
catch(DmlException ex)
{
ApexPages.addMessages(ex);
if(((Quote__c) record).id != null && isNew) // don't save quote without items
{
Database.rollback(sp); // if you saved quote but got an exception, it means something is wrong with line items
record.put('id',null); // remove the id if it was set by the save
}
return null;
}
return new Pagereference('/' + (String) record.get('Id'));
}
//Method to clone old Quote or Booking while editing
private void cloneRecord(){
String objectType = '';
Schema.sObjectType objType;
Schema.DescribeSObjectResult res;
if(record instanceof Quote__c){
objType = Quote__c.sObjectType;
} else {
objType = Booking__c.sObjectType;
}
res = objType.getDescribe();
Map<String , Schema.SObjectField> mapFieldList = res.fields.getMap();
Schema.SObjectField[] fields = mapFieldList.values();
String qry = getSoqlAllFieldsForObject(objType) + ' WHERE Id = \''+oldRecordId+'\'';
sObject oldObj = Database.query(qry);
List<Schema.FieldSetMember> allFields = SObjectType.Quote__c.FieldSets.EditFields.getFields();
allFields.addAll(SObjectType.Quote__c.FieldSets.AddressFields.getFields());
for(Schema.FieldSetMember f : allFields) {
if(f.getFieldPath() != 'Name'){
record.put(f.getFieldPath(), oldObj.get(f.getFieldPath()));
}
}
}
//Method to clone Booking and Quiote lines
/*private void cloneLines(){
String objectType, parentType;
String qry;
Schema.sObjectType objType;
objType = Booking_Line_Item__c.sObjectType;
parentType = 'Booking__c';
qry = getSoqlAllFieldsForObject(objType) + ' WHERE ' + parentType + ' = \''+oldRecordId+'\'';
List<sObject> newLines = new List<sObject>();
for(sObject so : Database.query(qry)){
sObject nSo = so.clone(false, true);
nSo.put(parentType, record.Id);
newLines.add(nSo);
}
insert newLines;
}*/
//TNT-1329 Add Quote lines to the same edit page with Quote
private void initQuoteLines(){
quoteItems = new List<Quote_Line_Item__c>();
delQuoteItems = new List<Quote_Line_Item__c>();
String qId = (record.Id == null ? oldRecordId : record.Id);
if(qId != null){
String qry;
qry = getSoqlAllFieldsForObject(Quote_Line_Item__c.sObjectType) + ' WHERE Quote__c ' + ' = \''+qId+'\'';
for(Quote_Line_Item__c so : Database.query(qry)){
Quote_Line_Item__c nSo = so;
if(oldRecordId != null){
nSo = so.clone(false, true);
}
quoteItems.add(nSo);
}
} else if(!String.isBlank(bId)){
for(Booking_Line_Item__c bli : [SELECT Height__c, Length__c, Number_of_Items__c, Weight__c, Width__c
FROM Booking_Line_Item__c WHERE Booking__c = : bId]){
Quote_Line_Item__c qli = new Quote_Line_Item__c();
qli.Height__c = bli.Height__c;
qli.Length__c = bli.Length__c;
qli.Number_of_Items__c = bli.Number_of_Items__c;
qli.Weight__c = bli.Weight__c;
qli.Width__c = bli.Width__c;
quoteItems.add(qli);
}
} else {
quoteItems.add(new Quote_Line_Item__c());
}
}
//DH
public decimal getNumLongLengths()
{
Decimal count = 0;
for(Quote_Line_Item__c qi : quoteItems)
{
if(qi.Length__c > 160 || qi.Width__c > 160 || qi.Height__c > 160)
{
count += qi.Number_of_Items__c == null ? 0:qi.Number_of_Items__c;
}
}
return count;
}
public PageReference RefreshDarryl()
{
//getNumLongLengths();
return null;
}
// TNT-1928 check that at least one non-void line item exists
private Boolean confirmHasQuoteLineItems()
{
List<Schema.FieldSetMember> qliFields = SObjectType.Quote_Line_Item__c.FieldSets.EditFields.getFields();
if(!quoteItems.isEmpty())
{
for(Quote_Line_Item__c qli : quoteItems)
{
if(!checkObjIsEmpty(qli, qliFields))
{
return true;
}
}
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,
'At least one line item must be valid: all fields cannot be blank or 0.'));
}
else
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,'You must enter at least one line item.'));
}
return false;
}
//Method saved modified or new lines and delete deleted lines
private void saveQuoteLines(){
List<Quote_Line_Item__c> linesToDelete = new List<Quote_Line_Item__c>();
List<Quote_Line_Item__c> linesToSave = new List<Quote_Line_Item__c>();
Boolean hasData;
List<Schema.FieldSetMember> qliFields = SObjectType.Quote_Line_Item__c.FieldSets.EditFields.getFields();
for(Quote_Line_Item__c qli : quoteItems){
if(qli.Id == null){
qli.Quote__c = record.Id;
}
//check if data is entered
if(!checkObjIsEmpty(qli, qliFields)){
linesToSave.add(qli);
} else if(qli.Id != null){
linesToDelete.add(qli);
}
}
if(!linesToSave.isEmpty()){
upsert linesToSave;
}
for(Quote_Line_Item__c qli : delQuoteItems){
if(qli.Id != null){
linesToDelete.add(qli);
}
}
if(!linesToDelete.isEmpty()){
delete linesToDelete;
}
}
//Method adds line to Quotelines table
public void addLine(){
quoteItems.add(new Quote_Line_Item__c());
}
//Method removes line from Quote lines table
public void removeLine(){
Integer rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
Quote_Line_Item__c del = quoteItems.remove(rowIndex);
delQuoteItems.add(del);
}
/* COPY DATA FROM BOOKING */
private Booking__c bookFrom;
public void copyDataFromBooking(){
if(!String.isBlank(bId) && record.Id == null){
bookFrom = [SELECT Account__c, Coll_Postcode__c, Del_Postcode__c, Enhanced_Liability__c,
Dangerous_Goods__c, Carriage_Forward__c, Company_Name__c, Company_Phone__c,
Order_Contact__c, OC_First_Name__c, OC_Last_Name__c, OC_Phone_Number__c,
OC_Email_Address__c, Collection_Ready_Time__c, Goods_Description__c
FROM Booking__c WHERE Id = : bId];
Quote__c qt = (Quote__c)record;
qt.Account__c = bookFrom.Account__c;
qt.Company_Name__c = bookFrom.Company_Name__c;
qt.Company_Phone__c = bookFrom.Company_Phone__c;
qt.Contact__c = bookFrom.Order_Contact__c;
qt.Contact_First_Name__c = bookFrom.OC_First_Name__c;
qt.Contact_Last_Name__c = bookFrom.OC_Last_Name__c;
qt.Contact_Phone__c = bookFrom.OC_Phone_Number__c;
qt.Contact_Email__c = bookFrom.OC_Email_Address__c;
qt.Collection_Postcode__c = bookFrom.Coll_Postcode__c;
qt.Delivery_Postcode__c = bookFrom.Del_Postcode__c;
qt.Enhanced_Liability_Option__c = bookFrom.Enhanced_Liability__c;
qt.Dangerous_Goods__c = bookFrom.Dangerous_Goods__c;
qt.Carriage_Forward__c = bookFrom.Carriage_Forward__c;
qt.Collection_Date__c = (bookFrom.Collection_Ready_Time__c != null ? bookFrom.Collection_Ready_Time__c.date() : null);
qt.Items_Description__c = bookFrom.Goods_Description__c;
}
}
/* STATIC */
public static String getSoqlAllFieldsForObject(Schema.sObjectType objType){
String res = '';
Schema.DescribeSObjectResult describeRes = objType.getDescribe();
String expr = getAllFieldsForObject(describeRes);
res = expr + ' from ' + describeRes.getName();
return res;
}
public static String getAllFieldsForObject(Schema.DescribeSObjectResult describeRes){
String res = '';
Map<String , Schema.SObjectField> mapFieldList = describeRes.fields.getMap();
Schema.SObjectField[] fields = mapFieldList.values();
String expr = '';
for( Integer i=0; i < fields.size()-1; i++ )
{
Schema.DescribeFieldResult fieldResult = fields[i].getDescribe();
expr += fieldResult.getName() + ', ';
}
Schema.DescribeFieldResult fieldResult = fields[fields.size() - 1].getDescribe();
expr += fieldResult.getName();
res = 'Select ' + expr;
return res;
}
//Check if any data have been added to object
public static Boolean checkObjIsEmpty(sObject obj, List<Schema.FieldSetMember> fieldsList){
Boolean res = true;
for(Schema.FieldSetMember f : fieldsList){
if(obj.get(f.getFieldPath()) != null && obj.get(f.getFieldPath()) != '' && obj.get(f.getFieldPath()) != false
&& (f.getType() != Schema.DisplayType.Double || ((double) obj.get(f.getFieldPath())) != 0))
{
res = false;
break;
}
}
return res;
}
}<file_sep>/classes/uksvcsTntComBookingServiceMock.cls
/**
* File Name : uksvcsTntComBookingServiceMock.cls
* Description : Mock class to test uksvcsTntComBookingService service
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 01/09/2014 <NAME> Initial version, TNT-1414
*/
@isTest
global class uksvcsTntComBookingServiceMock implements WebServiceMock{
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
uksvcsTntComBooking.ResponseMessage_MasterType respElement = new uksvcsTntComBooking.ResponseMessage_MasterType();
respElement.bkng = new uksvcsTntComBooking.BookingResponse_MasterType();
respElement.bkng.ackInd = true;
response.put('response_x', respElement);
}
}<file_sep>/classes/OL_MarketingMessagesControllerTest.cls
/**
* File Name : OL_MarketingMessagesControllerTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 23/07/2014 <NAME> Initial version
*
*
*/
@isTest
private class OL_MarketingMessagesControllerTest {
static testMethod void testQuickRun()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Campaign cBlank = TestUtil.createCampaign();
Campaign cYes = TestUtil.createCampaign();
Campaign cNo = TestUtil.createCampaign();
Campaign cFinished = TestUtil.createCampaign();
cFinished.StartDate = Date.today().addDays(-14);
cFinished.EndDate = Date.today().addDays(-7);
cFinished.Status = 'Completed';
Campaign cInactive = TestUtil.createCampaign();
cInactive.IsActive = false;
insert new List<Campaign>{cBlank,cYes,cNo,cFinished,cInactive};
CampaignMember cmBlank = TestUtil.createCampaignMember(cBlank.Id,c.Id);
CampaignMember cmYes = TestUtil.createCampaignMember(cYes.Id,c.Id);
cmYes.Interested__c = 'Yes';
CampaignMember cmNo = TestUtil.createCampaignMember(cNo.Id,c.Id);
cmNo.Interested__c = 'no';
CampaignMember cmFinished = TestUtil.createCampaignMember(cFinished.Id,c.Id);
CampaignMember cmInactive = TestUtil.createCampaignMember(cInactive.Id,c.Id);
insert new List<CampaignMember>{cmBlank,cmYes,cmNo,cmFinished,cmInactive};
Apexpages.currentPage().getParameters().put(ConstantUtil.PAGEPARAM_CONTACT_ID,c.Id);
Test.startTest();
OL_MarketingMessagesController mmc = new OL_MarketingMessagesController();
System.assert(mmc.getHasMarketingMessages());
mmc.getMarketingMessagesURL();
mmc.getMarketingMessageElement();
System.assertEquals(1,mmc.con.CampaignMembers.size());
for(CampaignMember cm : mmc.con.CampaignMembers)
{
system.assert(cm.Id == cmBlank.Id); // no other campaign selected
}
mmc.saveList();
Test.stopTest();
}
}<file_sep>/classes/OL_AccountOnStopSubmitTest.cls
/**
* File Name : OL_AccountOnStopSubmitTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 05/08/2014 <NAME> Initial version
*
*/
@isTest
public class OL_AccountOnStopSubmitTest {
public static testMethod void testNotOnStop()
{
Account a = TestUtil.createAccountClient();
a.On_Stop__c = false;
insert a;
Test.setCurrentPage(Page.OL_AccountOnStopSubmitAgent);
Apexpages.currentPage().getParameters().put('id',a.id);
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(a);
OL_AccountOnStopSubmit aoss = new OL_AccountOnStopSubmit(sc);
aoss.submitAccount();
Test.stopTest();
}
public static testMethod void testHasTmpPermission()
{
Account a = TestUtil.createAccountClient();
a.On_Stop__c = true;
a.Request_Stubbins_Permission__c = true;
a.Stubbins_Temporary_Permission__c = true;
insert a;
Test.setCurrentPage(Page.OL_AccountOnStopSubmitAgent);
Apexpages.currentPage().getParameters().put('id',a.id);
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(a);
OL_AccountOnStopSubmit aoss = new OL_AccountOnStopSubmit(sc);
aoss.submitAccount();
Test.stopTest();
}
public static testMethod void testOnStop()
{
Account a = TestUtil.createAccountClient();
a.On_Stop__c = true;
insert a;
Test.setCurrentPage(Page.OL_AccountOnStopSubmitAgent);
Apexpages.currentPage().getParameters().put('id',a.id);
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(a);
OL_AccountOnStopSubmit aoss = new OL_AccountOnStopSubmit(sc);
aoss.submitAccount();
// try again to catch error
aoss.submitAccount();
Test.stopTest();
}
}<file_sep>/classes/CalculateBusinessHoursAgesTest.cls
public class CalculateBusinessHoursAgesTest {
public static testMethod void testBusinessHoursBucketer() {
Stop_Status__c ss = new Stop_Status__c(Name = 'On Hold');
insert ss;
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
c.Status = 'New';
c.Last_Status_Change__c = System.Now();
insert c;
c.Status = 'On Hold';
update c;
c.Status = 'New';
update c;
Case updatedCase = [select Time_With_Customer__c,Time_With_Support__c,Case_Age_In_Business_Hours__c from Case where Id=:c.Id];
System.assert(updatedCase.Time_With_Customer__c!=null);
System.assert(updatedCase.Time_With_Support__c!=null);
System.assert(updatedCase.Case_Age_In_Business_Hours__c==null);
c.Status = 'Closed';
update c;
updatedCase = [select Time_With_Customer__c,Time_With_Support__c,Case_Age_In_Business_Hours__c from Case where Id=:c.Id];
System.assert(updatedCase.Time_With_Customer__c!=null);
System.assert(updatedCase.Time_With_Support__c!=null);
System.assert(updatedCase.Case_Age_In_Business_Hours__c!=null);
}
}<file_sep>/classes/ConstantUtil.cls
public with sharing class ConstantUtil {
// days of week
public static final String MONDAY_ABRV = 'Mon';
public static final String TUESDAY_ABRV = 'Tue';
public static final String WEDNESDAY_ABRV = 'Wed';
public static final String THURSDAY_ABRV = 'Thu';
public static final String FRIDAY_ABRV = 'Fri';
public static final String SATURDAY_ABRV = 'Sat';
public static final String SUNDAY_ABRV = 'Sun';
public static final Integer DAYS_IN_WEEK = 7;
public static Map<Integer,String> WEEKDAYS_ABRV_I2S {
get {
if(WEEKDAYS_ABRV_I2S == null) {
WEEKDAYS_ABRV_I2S = new Map<Integer,String>{
1 => MONDAY_ABRV,
2 => TUESDAY_ABRV,
3 => WEDNESDAY_ABRV,
4 => THURSDAY_ABRV,
5 => FRIDAY_ABRV,
6 => SATURDAY_ABRV,
7 => SUNDAY_ABRV
};
}
return WEEKDAYS_ABRV_I2S;
}
private set;
}
// months
public static final String JANUARY = 'January';
public static final String FEBRUARY = 'February';
public static final String MARCH = 'March';
public static final String APRIL = 'April';
public static final String MAY = 'May';
public static final String JUNE = 'June';
public static final String JULY = 'July';
public static final String AUGUST = 'August';
public static final String SEPTEMBER = 'September';
public static final String OCTOBER = 'October';
public static final String NOVEMBER = 'November';
public static final String DECEMBER = 'December';
public static Map<Integer,String> MONTHS_I2S {
get {
if(MONTHS_I2S == null) {
MONTHS_I2S = new Map<Integer,String>{
1 => JANUARY,
2 => FEBRUARY,
3 => MARCH,
4 => APRIL,
5 => MAY,
6 => JUNE,
7 => JULY,
8 => AUGUST,
9 => SEPTEMBER,
10 => OCTOBER,
11 => NOVEMBER,
12 => DECEMBER
};
}
return MONTHS_I2S;
}
private set;
}
public static Map<String,Integer> MONTHS_S2I {
get {
if(MONTHS_S2I == null) {
MONTHS_S2I = new Map<String,Integer>{
JANUARY => 1,
FEBRUARY => 2,
MARCH => 3,
APRIL => 4,
MAY => 5,
JUNE => 6,
JULY => 7,
AUGUST => 8,
SEPTEMBER => 9,
OCTOBER => 10,
NOVEMBER => 11,
DECEMBER => 12
};
}
return MONTHS_S2I;
}
private set;
}
// holiday constants
public static final String HOLIDAY_RECTYPE_YEARLYNTH = 'RecursYearlyNth';
public static final String HOLIDAY_RECTYPE_YEARLY = 'RecursYearly';
public static final String HOLIDAY_RECINSTANCE_FIRST = 'First';
public static final String HOLIDAY_RECINSTANCE_SECOND = 'Second';
public static final String HOLIDAY_RECINSTANCE_THIRD = 'Third';
public static final String HOLIDAY_RECINSTANCE_FOURTH = 'Fourth';
public static final String HOLIDAY_RECINSTANCE_LAST = 'Last';
// object names
public static final String OBJ_ACCOUNTADDRESS_APINAME = 'Account_Address__c';
public static final String OBJ_ACCOUNT_APINAME = 'Account';
// field names
public static final String FLD_ACCOUNT_APINAME = 'Account__c';
public static final String FLD_CONTACT_APINAME = 'Contact__c';
public static final String FLD_ACCOUNTADDRESS_APINAME = OBJ_ACCOUNTADDRESS_APINAME;
// picklist values
public static final String PLVAL_CASE_EXCEPTION_COLLECTION = 'Collection';
public static final String PLVAL_CASE_EXCEPTION_DELIVERY = 'Delivery';
public static final String PLVAL_CASE_ORIGIN_PHONE = 'Phone';
public static final String PLVAL_CASE_ORIGIN_SYSTEM = 'System';
public static final String PLVAL_CASE_STATUS_NEW = 'New';
public static final String PLVAL_CASE_STATUS_WAITING_FOR_CUSTOMER = 'Waiting for customer';
public static final String PLVAL_CASE_STATUS_CLOSED = 'Closed';
public static final String PLVAL_CASE_STATUS_WORKING_ON = 'In Progress';
public static final String PLVAL_CASE_TYPE_BOOKINGS = 'Bookings';
public static final String PLVAL_CASE_TYPE_BOOKING_ADN_QUOTES = 'Bookings and Quotes';
public static final String PLVAL_CASE_TYPE_TRACK = 'Track';
public static final String PLVAL_CASE_TYPE_RECORD_TRACK = 'FCR - Record Track';//Added by DH 24/09/15 for Kish
public static final String PLVAL_CASE_TYPE_SERVICE_CASE = 'Service Case';
public static final String PLVAL_CASE_TYPE_LAVEL1_CS_FAILED_COLLECTION = 'CS - Failed collection';
public static final String PLVAL_CASE_PRIORITY_MEDIUM = 'Medium';
public static final String PLVAL_ACCOUNTADDRESS_COUNTRY_UK = 'United Kingdom';
public static final String PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE = '0 - None';
public static final String PLVAL_CTH_CATEGORY_OWNER = 'Owner';
public static final String PLVAL_CTH_CATEGORY_TYPE = 'Type';
public static final String PLVAL_CTH_CATEGORY_REASON = 'Reason';
public static final String PLVAL_CTH_CATEGORY_STATUS = 'Status';
public static final String PLVAL_CTH_CATEGORY_PRIORITY = 'Priority';
public static final String PLVAL_CTH_CATEGORY_APPROVAL = 'Approval';
public static final String PLVAL_BOOKING_RECORD_TYPE_NEW = 'New Booking';
public static final String PLVAL_BOOKING_RECORD_TYPE_BLOCKED = 'Blocked Booking';
public static final String PLVAL_BOOKING_STATUS_CANCELLED = 'Cancelled';
public static final String PLVAL_BOOKING_STATUS_COLLECTED = 'Collected';
public static final String PLVAL_BOOKING_STATUS_CONFIRMED = 'Confirmed';
public static final String PLVAL_BOOKING_STATUS_REJECTED_TO_CS = 'Rejected to Customer Services';
public static final String PLVAL_BOOKING_LIABILITY_ACCOUNTLEVEL = 'Account Level';
public static final String PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_RAISED = 'Collection Request Raised';
public static final String PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_AMENDED = 'Collection Request Amended';
public static final String PLVAL_POSTCODE_CATEGORY_RESIDENTIAL = 'Residential';
public static final String PLVAL_DAY_DAYTYPE_WORKING = 'Working';
public static final String PLVAL_DAY_DAYTYPE_NONWORKING = 'Non-Working';
public static final String PLVAL_DAY_DAYTYPE_SATURDAY = 'Saturday';
public static final String PLVAL_DEPOTROUTING_ROUNDGROUP_NORMAL = 'Normal';
public static final String PLVAL_DEPOTROUTING_ROUNDGROUP_SATURDAY = 'Saturday';
public static final String PLVAL_DEPOTROUTING_ROUNDGROUP_ALL = 'All';
public static final String PLVAL_TASK_ACTION_TYPE_CONTACT_ACTIONS = 'Contact Actions';
public static final String PLVAL_TASK_ACTION_SUBTYPE_FIRST_CUSTOMER_CONTACT = 'First Customer Contact';
public static final String PLVAL_TASK_ACTION_SUBTYPE_CUSTOMER_CONTACT = 'Customer Contact';
public static final String PLVAL_TASK_STATUS_COMPLETED = 'Completed';
// page parameters
public static final String PAGEPARAM_CONTACT_ID = 'contactId';
// queues
public static final String MAJOR_ACCOUNTS_QUEUE = 'Major_Accounts';
public static Id LOUNT_ADMIN_1_QUEUE_ID {
get {
if(LOUNT_ADMIN_1_QUEUE_ID == null) {
LOUNT_ADMIN_1_QUEUE_ID = [select id from Group where Type = 'Queue' and DeveloperName = 'Lount_Admin_1' limit 1].id;
}
return LOUNT_ADMIN_1_QUEUE_ID;
}
}
public static Id UNASSIGNED_QUEUE_ID {
get {
if(UNASSIGNED_QUEUE_ID == null) {
return [select id from Group where Type = 'Queue' and Name = 'Unassigned' limit 1].id;
}
return UNASSIGNED_QUEUE_ID;
}
}
//DH Added 19/01/2016
public static Id MAURITIUS_QUEUE_ID {
get {
if(MAURITIUS_QUEUE_ID == null) {
return [select id from Group where Type = 'Queue' and DEveloperName = 'Mauritius_Team' limit 1].id;
}
return MAURITIUS_QUEUE_ID;
}
}
// ISO codes
public static final String ISOCODE_UK = 'GBR';
// custom settings
public static Integer CS_ACCOUNTADDRESSROWLIMIT {
get {
Service_Settings__c ss = Service_Settings__c.getInstance();
return ss != null && ss.Account_Address_Picklist_Size__c != null && ss.Account_Address_Picklist_Size__c > 0
? ss.Account_Address_Picklist_Size__c.intValue() : 20;
}
}
public static Integer INTEGRATION_TIMEOUT {
get {
TNT_Integration__c cs = TNT_Integration__c.getInstance();
Decimal val = cs != null ? cs.Timeout__c : null;
return val != null ? val.intValue() : 65000;
}
}
//Added by DH 25/01/2016
public static Set<String> AutoRejectionCaseLOBList
{
get
{
List<RejectionCaseLOBs__c> LOBs = RejectionCaseLOBs__c.getall().values();
Set<String> LOBNames = new Set<String>();
for(RejectionCaseLOBs__c c:LOBs)
{
LOBNames.add(c.Name);
}
return LOBNames;
}
}
//*********************
// record types
public static final String RT_ACCOUNT_DEPOT = 'Depot';
// various
public static final String TASK_SUBJECT_CALL_CLIENT_BACK = 'Contact';
public static final String UNKNOWN_PREFIX = 'UNKNOWN';
public static final Id PRODUCTION_ORGID = '00D20000000lDA7';
public static final String INTEGRATION_USERNAME = 'SFSCPRD';
public static Boolean INTEGRATION_ACCESS {
get {
return Test.isRunningTest()
|| UserInfo.getOrganizationId() == ConstantUtil.PRODUCTION_ORGID
|| (TNT_Integration__c.getInstance() != null
&& TNT_Integration__c.getInstance().Username__c != ConstantUtil.INTEGRATION_USERNAME);
}
}
// exceptions
public class IntegrationAccessDeniedException extends Exception {}
public static final String INTEGRATION_EXMSG = 'Access is not allowed for this organisation with the production integration user.';
}<file_sep>/classes/DefaultAccount.cls
public with sharing class DefaultAccount {
private final Account acct;
public Account_Address__c defAdd {get; set;}
public boolean isDefault {get; set;}
public DefaultAccount(ApexPages.StandardController controller) {
this.acct = (Account)controller.getRecord();
try{
defAdd = [Select Legacy_Address_Id__c,Org_Name__c,Premise_Name__c,Street_1__c,Street_2__c,City__c,District__c,County__c,Postcode__c,Contact__c,Last_Used__c,Comments_on_account_address__c
from Account_Address__c where Account__c =: acct.Id and Default__c =: true limit 1];
isDefault = true;
}
catch(exception e) {
isDefault = false;
}
}
}<file_sep>/classes/CS_Claims_Test.cls
/**
Test class for CS_Claims_Form_Controller class and CS_Claims_Form_PDF_Controller class
*/
@isTest
private class CS_Claims_Test {
TestMethod static void test_Claim_form_excpetion_scenario_closed_stage(){
try{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
CS_Claims__c testClaim = new CS_Claims__c(Depot_no__c='067', Reference_no__c='45678999', TNT_account_no__c='203456789', Sender_Email_Address__c='<EMAIL>',Claims_Stage__c = 'Closed',Declarant_Full_Name_of__c='test',Declarant_Date__c= Date.today());
testClaim.Account__c = a.Id;
testClaim.Depot__c = d.Id;
insert testClaim;
ApexPages.CurrentPage().getParameters().put('cid',testClaim.Id);
Test.StartTest();
CS_Claims_Form_Controller claimForm = new CS_Claims_Form_Controller(new ApexPages.StandardController(testClaim));
claimForm.claim.Declarant_Date__c = Date.today();
claimForm.save_m();
Test.stopTest();
}catch(Exception ex){
system.debug(ex);
}
}
TestMethod static void test_Claim_form_excpetion_scenario_no_id(){
try{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
CS_Claims__c testClaim = new CS_Claims__c(Depot_no__c='067', Reference_no__c='45678999', TNT_account_no__c='203456789', Sender_Email_Address__c='<EMAIL>',Claims_Stage__c = 'In Progress',Declarant_Full_Name_of__c='test',Declarant_Date__c= Date.today());
testClaim.Account__c = a.Id;
testClaim.Depot__c = d.Id;
insert testClaim;
ApexPages.CurrentPage().getParameters().put('cid','');
Test.StartTest();
CS_Claims_Form_Controller claimForm = new CS_Claims_Form_Controller(new ApexPages.StandardController(testClaim));
claimForm.claim.Declarant_Full_Name_of__c = 'test';
claimForm.save_m();
Test.stopTest();
}catch(Exception ex){
system.debug(ex);
}
}
TestMethod static void test_Claim_form_excpetion_scenario_check_validation(){
try{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
CS_Claims__c testClaim = new CS_Claims__c(Depot_no__c='067', Reference_no__c='45678999', TNT_account_no__c='203456789', Sender_Email_Address__c='<EMAIL>',Claims_Stage__c = 'In Progress');
testClaim.Account__c = a.Id;
testClaim.Depot__c = d.Id;
insert testClaim;
ApexPages.CurrentPage().getParameters().put('cid','');
Test.StartTest();
CS_Claims_Form_Controller claimForm = new CS_Claims_Form_Controller(new ApexPages.StandardController(testClaim));
claimForm.claim.Declarant_Date__c = Date.today();
claimForm.claim.Declarant_Full_Name_of__c = 'test';
claimForm.claim.cheque__c = true;
claimForm.claim.Credit_your_TNT_account__c = true;
claimForm.save_m();
Test.stopTest();
}catch(Exception ex){
system.debug(ex);
}
}
TestMethod static void test_Claim_form_excpetion_scenario_check_validation_2(){
try{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
CS_Claims__c testClaim = new CS_Claims__c(Depot_no__c='067', Reference_no__c='45678999', TNT_account_no__c='203456789', Sender_Email_Address__c='<EMAIL>',Claims_Stage__c = 'In Progress');
testClaim.Account__c = a.Id;
testClaim.Depot__c = d.Id;
insert testClaim;
ApexPages.CurrentPage().getParameters().put('cid','');
Test.StartTest();
CS_Claims_Form_Controller claimForm = new CS_Claims_Form_Controller(new ApexPages.StandardController(testClaim));
claimForm.claim.Declarant_Date__c = Date.today();
claimForm.claim.Declarant_Full_Name_of__c = 'test';
claimForm.claim.Lost__c = true;
claimForm.claim.Damaged__c = true;
claimForm.save_m();
claimForm.getClaims(null);
Test.stopTest();
}catch(Exception ex){
system.debug(ex);
}
}
TestMethod static void test_pdf_controller(){
try{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
CS_Claims__c testClaim = new CS_Claims__c(Depot_no__c='067', Reference_no__c='45678999', TNT_account_no__c='203456789', Sender_Email_Address__c='<EMAIL>',Claims_Stage__c = 'In Progress',Declarant_Full_Name_of__c='test',Declarant_Date__c= Date.today());
testClaim.Account__c = a.Id;
testClaim.Depot__c = d.Id;
insert testClaim;
ApexPages.CurrentPage().getParameters().put('id',testClaim.Id);
Test.StartTest();
CS_Claims_Form_PDF_Controller claimForm = new CS_Claims_Form_PDF_Controller();
claimForm.getClaims(null);
claimForm.getClaims(testClaim.Id);
system.debug(claimForm.address);
system.debug(claimForm.check_list_opt_1);
system.debug(claimForm.check_list_opt_2);
system.debug(claimForm.check_list_opt_3);
system.debug(claimForm.check_list_opt_4);
system.debug(claimForm.Claims_damaged_section_title);
system.debug(claimForm.Claims_type_details_section_content);
system.debug(claimForm.Claims_type_details_section_title);
system.debug(claimForm.Claims_type_fieldset_label);
system.debug(claimForm.Cost_value_of_consignment_label);
system.debug(claimForm.Cost_value_of_items_label);
system.debug(claimForm.Declaration_section_title);
system.debug(claimForm.damaged_items_inspection_label);
system.debug(claimForm.emailId);
system.debug(claimForm.header);
system.debug(claimForm.payment_method_label);
system.debug(claimForm.Recipient_section_title);
system.debug(claimForm.replacement_consignement_no_label);
system.debug(claimForm.Sender_section_title);
Test.stopTest();
}catch(Exception ex){
system.debug(ex);
}
}
}<file_sep>/classes/ukTntComGenericEnums.cls
//Generated by wsdl2apex
public class ukTntComGenericEnums {
}<file_sep>/classes/uksvcsTntComGetConsDetlsServiceMock.cls
/**
* File Name : uksvcsTntComGetConsDetlsServiceMock.cls
* Description : Mock class to test uksvcsTntComGetConsignmentDetailsService service
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 27/08/2014 <NAME> Initial version, TNT-547
* 0.2 03/09/2014 <NAME> Updated for new WSDL
*/
@isTest
global class uksvcsTntComGetConsDetlsServiceMock implements WebServiceMock{
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
uksvcsTntComSearchConsignment.ResponseMessage_MasterType respElement = new uksvcsTntComSearchConsignment.ResponseMessage_MasterType();
respElement.con = new uksvcsTntComSearchConsignment.ConsignmentResponse_MasterType();
respElement.con.unqConNum = '12345';
respElement.con.tntConNum = '12345';
respElement.con.orgConNum = '12345';
respElement.con.pod = new uksvcsTntComSearchConsignment.DetailProofOfDelivery_MasterType();
respElement.con.pod.podSts = 'Status';
respElement.con.pod.sosInd = true;
respElement.con.conStss = new uksvcsTntComSearchConsignment.ConsignmentStatusHistory_ContainerType();
respElement.con.conStss.conSts = new List<uksvcsTntComSearchConsignment.DetailConsignmentStatusHistory_MasterType>();
uksvcsTntComSearchConsignment.DetailConsignmentStatusHistory_MasterType conH = new uksvcsTntComSearchConsignment.DetailConsignmentStatusHistory_MasterType();
conH.stsDtTm = DateTime.now();
respElement.con.act = new uksvcsTntComSearchConsignment.Account_MasterType();
respElement.con.addr = new uksvcsTntComSearchConsignment.DetailAddress_MasterType();
respElement.con.rtng = new uksvcsTntComSearchConsignment.ConsignmentRating_MasterType();
respElement.con.dscrps = new uksvcsTntComSearchConsignment.ConsignmentDiscrepancy_ContainerType();
respElement.con.dscrps.dscrp = new List<uksvcsTntComSearchConsignment.ConsignmentDiscrepancy_MasterType>();
uksvcsTntComSearchConsignment.ConsignmentDiscrepancy_MasterType dscrp = new uksvcsTntComSearchConsignment.ConsignmentDiscrepancy_MasterType();
respElement.con.dscrps.dscrp.add(dscrp);
respElement.con.conStss.conSts.add(conH);
response.put('response_x', respElement);
}
}<file_sep>/classes/AccountContactTriggerHandlerTest.cls
/**
* File Name : AccountContactTriggerHandlerTest.cls
* Description : test for Account_Contact trigger handler
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 21/08/2014 <NAME> Initial version (TNT-1334)
*
*
*/
@isTest
private class AccountContactTriggerHandlerTest {
static testMethod void test_updateAccountContactObj_updateAccount()
{
Account a0 = TestUtil.createAccountClient();
insert a0;
Account a1 = TestUtil.createAccountClient();
a1.ParentId = a0.Id;
insert a1;
Contact c1 = TestUtil.createContact(a1.Id);
insert c1;
List<Account_Contact__c> acList = [SELECT Account__c, Contact__c FROM Account_Contact__c];
System.assertEquals(2, acList.size());
c1.AccountId = a0.Id;
update c1;
c1.AccountId = a1.Id;
update c1;
acList = [SELECT Account__c, Contact__c FROM Account_Contact__c];
System.assertEquals(2, acList.size());
}
}<file_sep>/classes/CS_ClaimsTriggerHandlerTest.cls
/**
* File Name : CS_ClaimsTriggerHandlerTest.cls
* Description : Test class for CS_ClaimsTriggerHandler.cls
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 17/07/2014 <NAME> Initial version
*
*
*/
@isTest
private class CS_ClaimsTriggerHandlerTest {
static testMethod void testFillFieldsFromAccountContactDepot() {
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
insert aaDef;
CS_Claims__c claim = new CS_Claims__c();
claim.Account__c = a.Id;
claim.Depot__c = d.Id;
claim.Contact__c = con.Id;
insert claim;
claim = [SELECT Sender_Contact_Name__c, TNT_account_no__c, Depot_no__c FROM CS_Claims__c WHERE Id = : claim.Id];
system.assertEquals(claim.Sender_Contact_Name__c, 'Test Class Contact');
system.assertEquals(claim.TNT_account_no__c, '111');
system.assertEquals(claim.Depot_no__c, '222');
}
}<file_sep>/classes/TestTaggedCustomState.cls
@IsTest
public class TestTaggedCustomState {
static testMethod void insertNewAgentSummary() {
List<NVMStatsSF__NVM_Agent_Summary__c> summaryToCreate = new List<NVMStatsSF__NVM_Agent_Summary__c>();
//Populate fields
//Insert 5 with Custom States
for (Integer i = 0; i < 5; i++) {
NVMStatsSF__NVM_Agent_Summary__c s = new NVMStatsSF__NVM_Agent_Summary__c();
String TEST_STRING = '40385Custom State 320:20|40385Custom State 321:21|40385Custom State 322:22|40385Custom State 323:23|40385Custom State 324:24|40385Custom State 305:20';
s.NVMStatsSF__Key_Event_String__c = TEST_STRING;
s.NVMStatsSF__dateAgentId__c = '201507061006' + i;
s.NVMStatsSF__AgentID__c = '1006' + i;
summaryToCreate.add(s);
}
try {
//Insert the record
System.debug('summaryToCreate is ' + summaryToCreate.size());
insert summaryToCreate;
} catch (DmlException e) {
//
for (Integer i = 0; i < e.getNumDml(); i++) {
// Process exception here
System.debug(e.getDmlMessage(i));
}
}
//Check all records were inserted
Integer i = 0;
for (NVMStatsSF__NVM_Agent_Summary__c tmp : [SELECT Comfort_Break__c, Custom_State_1__c, Custom_State_2__c, Custom_State_3__c, Custom_State_4__c, Custom_State_5__c, Custom_State_6__c, CreatedDate FROM NVMStatsSF__NVM_Agent_Summary__c ORDER By CreatedDate DESC]) {
i++;
System.debug(i);
}
System.debug('Records returned = ' + i);
System.AssertEquals(5, i);
List<NVMStatsSF__NVM_Agent_Summary__c> summaryToCreate2 = new List<NVMStatsSF__NVM_Agent_Summary__c>();
//Insert 5 without any Custom or Minor
for (Integer j = 0; j < 5; j++) {
NVMStatsSF__NVM_Agent_Summary__c m = new NVMStatsSF__NVM_Agent_Summary__c();
String TEST_STRING = '123123123 | 2342 34234 234 | 329472347234 | 53344Training 320:20';
m.NVMStatsSF__Key_Event_String__c = TEST_STRING;
m.NVMStatsSF__dateAgentId__c = '201507061006' + j;
m.NVMStatsSF__AgentID__c = '1006' + j;
summaryToCreate2.add(m);
}
//5 with Custom States
for (Integer h = 0; h < 5; h++) {
NVMStatsSF__NVM_Agent_Summary__c m = new NVMStatsSF__NVM_Agent_Summary__c();
String TEST_STRING = '123123123 | 2342 34234 234 | 329472347234 | 53344Custom State 320:20 | 53344Comfort Break 320:20';
m.NVMStatsSF__Key_Event_String__c = TEST_STRING;
m.NVMStatsSF__dateAgentId__c = '201507061006' + h;
m.NVMStatsSF__AgentID__c = '1006' + h;
summaryToCreate2.add(m);
}
try {
//Insert the record
System.debug('summaryToCreate2 is ' + summaryToCreate2.size());
insert summaryToCreate2;
} catch (DmlException e) {
//
for (Integer j = 0; j < e.getNumDml(); j++) {
// Process exception here
System.debug(e.getDmlMessage(j));
}
}
//Check all records were inserted
Integer j = 0;
for (NVMStatsSF__NVM_Agent_Summary__c tmp2 : [SELECT Comfort_Break__c, Custom_State_1__c, Custom_State_2__c, Custom_State_3__c, Custom_State_4__c, Custom_State_5__c, Custom_State_6__c, CreatedDate FROM NVMStatsSF__NVM_Agent_Summary__c WHERE Custom_State_1__c = 20 ORDER By CreatedDate DESC]) {
j++;
System.debug(i);
}
System.debug('Records returned = ' + j);
System.AssertEquals(5, j);
} //end of method
} //end of test class<file_sep>/classes/uksvcsTntComError.cls
//Generated by wsdl2apex
public class uksvcsTntComError {
public class TNTError_Master {
public String ErrorCode;
public String ErrorType;
public String ErrorDescription;
public DateTime Timestamp;
public String ErrorDetail;
private String[] ErrorCode_type_info = new String[]{'ErrorCode','http://express.tnt.com/general/schema/tnterror/v1',null,'0','1','false'};
private String[] ErrorType_type_info = new String[]{'ErrorType','http://express.tnt.com/general/schema/tnterror/v1',null,'0','1','false'};
private String[] ErrorDescription_type_info = new String[]{'ErrorDescription','http://express.tnt.com/general/schema/tnterror/v1',null,'0','1','false'};
private String[] Timestamp_type_info = new String[]{'Timestamp','http://express.tnt.com/general/schema/tnterror/v1',null,'0','1','false'};
private String[] ErrorDetail_type_info = new String[]{'ErrorDetail','http://express.tnt.com/general/schema/tnterror/v1',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/general/schema/tnterror/v1','true','false'};
private String[] field_order_type_info = new String[]{'ErrorCode','ErrorType','ErrorDescription','Timestamp','ErrorDetail'};
}
}<file_sep>/classes/uksvcsTntGetQuotePricingService.cls
//Generated by wsdl2apex
public class uksvcsTntGetQuotePricingService {
public class getPricingDetailsForQuotePort {
public String endpoint_x = TNT_Integration__c.getInstance().Quote_Service__c;
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://express.tnt.com/general/schema/enums/generic/v1', 'ukTntComGenericEnums', 'http://express.tnt.com/service/schema/gpdfq/v1', 'uksvcsTntGetQuotePricing', 'http://express.tnt.com/service/wsdl/gpdfq/v1', 'uksvcsTntGetQuotePricingService', 'http://express.tnt.com/general/schema/tnterror/v1', 'uksvcsTntComError', 'http://express.tnt.com/general/schema/payloadheader/v1', 'uksvcsTntComGenericPayloadHeader', 'http://express.tnt.com/general/schema/objects/generic/v1', 'uksvcsTntComGenericObjects'};
public uksvcsTntGetQuotePricing.ResponseMessage_MasterType getPricingDetailsForQuote(uksvcsTntComGenericPayloadHeader.payloadHeader hdr,uksvcsTntGetQuotePricing.QuoteRequest_MasterType qt) {
uksvcsTntGetQuotePricing.RequestMessage_MasterType request_x = new uksvcsTntGetQuotePricing.RequestMessage_MasterType();
request_x.hdr = hdr;
request_x.qt = qt;
uksvcsTntGetQuotePricing.ResponseMessage_MasterType response_x;
Map<String, uksvcsTntGetQuotePricing.ResponseMessage_MasterType> response_map_x = new Map<String, uksvcsTntGetQuotePricing.ResponseMessage_MasterType>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'get',
'http://express.tnt.com/service/schema/gpdfq/v1',
'getPricingDetailsForQuoteRequest',
'http://express.tnt.com/service/schema/gpdfq/v1',
'getPricingDetailsForQuoteResponse',
'uksvcsTntGetQuotePricing.ResponseMessage_MasterType'}
);
response_x = response_map_x.get('response_x');
return response_x;
}
}
}<file_sep>/classes/OL_MarketingMessagesController.cls
/**
* File Name : OL_MarketingMessagesController.cls
* Description : Show marketing messages to agent
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 22/07/2014 <NAME> Initial version
*
*
*/
public without sharing class OL_MarketingMessagesController {
public Contact con {get; private set;}
public Id compContactId {get; set;}
public OL_MarketingMessagesController()
{
getInit();
}
public void getInit()
{
Id contactId = String.isBlank(compContactId) ?
(Id) Apexpages.currentPage().getParameters().get(ConstantUtil.PAGEPARAM_CONTACT_ID) :
compContactId;
con = String.isNotBlank(contactId) ? findMarketingMessages(contactId) : new Contact();
}
public void saveList()
{
try
{
update con.CampaignMembers;
}
catch(exception e)
{
Apexpages.addMessages(e);
}
}
public Boolean getHasMarketingMessages()
{
return con.Id != null && !con.CampaignMembers.isEmpty();
}
public String getMarketingMessagesURL()
{
return Page.OL_MarketingMessages.getUrl() + '?' + ConstantUtil.PAGEPARAM_CONTACT_ID + '=' + con.Id;
}
public String getMarketingMessageElement()
{
return '<a href="#" style="color:white;"'
+ 'onClick="window.open(\'' + getMarketingMessagesURL() +'\',\'\',\'width=700,height=450\');return false;">'
+ 'There are Marketing Messages</a>';
}
public static Contact findMarketingMessages(Id contactId)
{
return [select Id, Name, Email, AccountId,
(select Campaign.Name, Campaign.Description, Campaign.StartDate, Campaign.EndDate, Interested__c, Response__c
from CampaignMembers
where Campaign.isActive = true and Campaign.StartDate <= :Date.today() and Campaign.EndDate >= :Date.today()
and Interested__c = null
order by Campaign.EndDate asc)
from Contact
where Id = :contactId limit 1];
// pick up campaigns that are active and in progress
// sort by Campaigns ending the soonest
}
}<file_sep>/classes/TestUtil.cls
/**
* File Name : TestUtil.cls
* Description : help for testing
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 03/07/2014 <NAME> Initial version
*
*
*/
@isTest
public with sharing class TestUtil {
public static Id accountClientRTId = [select id from RecordType where DeveloperName = 'Client' and sObjectType = 'Account' limit 1].id;
public static Id accountDepotRTId = [select id from RecordType where DeveloperName = 'Depot' and sObjectType = 'Account' limit 1].id;
public static Account createAccountClient()
{
Account a = new Account();
a.recordTypeId = accountClientRTId;
a.Name = 'Test Class Account';
a.AccountNumber = '111';
return a;
}
public static Account createAccountDepot()
{
Account a = new Account();
a.recordTypeId = accountDepotRTId;
a.Name = 'Test Class Depot';
a.AccountNumber = '222';
//Added by DH 23/10/15 to accomodate new field filter restraint
a.Operational_for_Bookings__c = true;
return a;
}
public static Contact createContact(Id accountId)
{
Contact c = new Contact();
c.AccountId = accountId;
c.FirstName = '<NAME>';
c.LastName = 'Contact';
c.Email = '<EMAIL>';
c.Phone = '1234554321';
return c;
}
public static Case createCase(Id accountId, Id contactId, Id depotId)
{
// parsing error if first line populated (?????????)
Case c = createCase(accountId, contactId);
c.Collection_Depot__c = depotId;
return c;
}
public static Case createCase(Id accountId, Id contactId)
{
// parsing error if first line populated (?????????)
Case c = new Case();
c.Subject = 'Test Class Case';
c.Description = 'test class';
c.AccountId = accountId;
c.ContactId = contactId;
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
return c;
}
public static Account_Address__c createAccountAddress(Id accountId, Id contactId)
{
Account_Address__c aa = new Account_Address__c();
aa.Account__c = accountId;
aa.Contact__c = contactId;
aa.Org_Name__c = 'test address ' + Math.rint(Math.random()*1000);
aa.Street_1__c = 'my test street';
aa.Postcode__c = 'SW15 1TW';
aa.City__c = 'Testville';
aa.Country__c = ConstantUtil.ISOCODE_UK;
return aa;
}
public static Campaign createCampaign()
{
Campaign c = new Campaign();
c.isActive = true;
c.Name = 'testCampaign';
c.Status = 'In Progress';
c.StartDate = Date.today().addDays(-7);
c.EndDate = Date.today().addDays(7);
c.Description = 'my test campaign';
return c;
}
public static CampaignMember createCampaignMember(Id campaignId, Id contactId)
{
CampaignMember cm = new CampaignMember();
cm.CampaignId = campaignId;
cm.ContactId = contactId;
cm.Status = 'Sent';
return cm;
}
public static User createAgentUser() {
Profile p = [SELECT Id FROM Profile WHERE Name='CS Agent'];
return createUser(p.Id,null);
}
public static User createAdminUser() {
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
return createUser(p.Id,null);
}
public static User createIntegrationUser() {
Profile p = [SELECT Id FROM Profile WHERE Name='Integration User'];
return createUser(p.Id,null);
}
public static User createUser(Id profileId, Id roleId) {
User u = new User(Alias = 'standt', Email='<EMAIL>',
EmailEncodingKey='UTF-8', LastName='Testing',
LocaleSidKey='en_US', LanguageLocaleKey='en_US',
ProfileId = profileId, UserRoleId = roleId,
TimeZoneSidKey='America/Los_Angeles', UserName='<EMAIL>');
return u;
}
public static List<sObject> proxyInsert(List<sObject> sobjs) // use this to avoid mixing insert of setup and non-setup sobject
{
System.runAs(new User(Id = UserInfo.getUserId()))
{
insert sobjs;
}
return sobjs;
}
// create entry with working day and normal depot
public static Account setupDepotRouting(Id lobId, Account_Address__c aa, Date collDate)
{
Account depot = createAccountDepot();
Account dep1 = createAccountDepot(); // calendar linking depot
dep1.AccountNumber = '999';
dep1.Depot_Number__c = '999';
dep1.Name += '999';
insert new List<Account>{depot,dep1};
Calendar__c cal = new Calendar__c();
cal.Name = 'Default Calendar';
insert cal;
Day__c d = new Day__c();
d.Calendar__c = cal.id;
d.Date__c = collDate;
d.Name = collDate.format();
d.Day_Type__c = ConstantUtil.PLVAL_DAY_DAYTYPE_WORKING;
insert d;
dep1.Depot_Calendar__c = cal.id;
update dep1;
Routing_Table__c rt = new Routing_Table__c();
rt.Depot__c = dep1.id;
rt.Routing_Default__c = true;
rt.District__c = aa.District__c;
rt.Town__c = aa.City__c;
rt.Part_Postcode__c = aa.Postcode__c.substring(0, aa.Postcode__c.length()-2);
insert rt;
Depot_Routing__c dr = new Depot_Routing__c();
dr.Collection_Depot__c = depot.id;
dr.Line_of_Business__c = lobId;
dr.Round_Group__c = ConstantUtil.PLVAL_DEPOTROUTING_ROUNDGROUP_NORMAL;
dr.Routing_Table__c = rt.Id;
dr.Routing_Network__c = 'EXP';
insert dr;
return depot;
}
public static void setupBusinessHoursAndHolidays()
{
TimeUtil.bh = newBusinessHours();
TimeUtil.holidays = newHolidays();
}
public static BusinessHours newBusinessHours()
{
return new BusinessHours(
Name='Default',
MondayStartTime=Time.newInstance(8,0,0,0), MondayEndTime=Time.newInstance(18,0,0,0), // 8-18
TuesdayStartTime=Time.newInstance(8,0,0,0), TuesdayEndTime=Time.newInstance(18,0,0,0), // 8-18
WednesdayStartTime=Time.newInstance(0,0,0,0), WednesdayEndTime=Time.newInstance(0,0,0,0), // all day
ThursdayStartTime=Time.newInstance(8,0,0,0), ThursdayEndTime=Time.newInstance(18,0,0,0), // 8-18
FridayStartTime=Time.newInstance(8,0,0,0), FridayEndTime=Time.newInstance(17,30,0,0), // 8-17:30
SaturdayStartTime=Time.newInstance(9,0,0,0), SaturdayEndTime=Time.newInstance(17,30,0,0), // 9-17:30
SundayStartTime=null, SundayEndTime=null, // not a work day
IsDefault=true,
IsActive=true,
TimeZoneSidKey='Europe/London');
}
public static List<Holiday> newHolidays()
{
List<Holiday> hds = new List<Holiday>();
hds.add(new Holiday(
Name='Random Holiday',
ActivityDate=Date.newInstance(2014,4,2), // random holiday on April 2nd 2014 (Wednesday)
IsRecurrence=false,
RecurrenceType=null,
RecurrenceMonthOfYear=null,
RecurrenceDayOfWeekMask=null,
RecurrenceDayOfMonth=null,
RecurrenceInstance=null,
IsAllDay=true));
hds.add(new Holiday(
Name='First Friday in May Holiday',
ActivityDate=Date.newInstance(2014,5,2), // holiday on May 2nd 2014 (Friday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLYNTH,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(5),
RecurrenceDayOfWeekMask=32, // Friday bitmask
RecurrenceDayOfMonth=null,
RecurrenceInstance=ConstantUtil.HOLIDAY_RECINSTANCE_FIRST, // first Friday in May
IsAllDay=true));
hds.add(new Holiday(
Name='Second Friday in May Holiday',
ActivityDate=Date.newInstance(2014,5,9), // holiday on May 9th 2014 (Friday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLYNTH,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(5),
RecurrenceDayOfWeekMask=32, // Friday bitmask
RecurrenceDayOfMonth=null,
RecurrenceInstance=ConstantUtil.HOLIDAY_RECINSTANCE_SECOND, // second Friday in May
IsAllDay=true));
hds.add(new Holiday(
Name='Third Friday in May Holiday',
ActivityDate=Date.newInstance(2014,5,16), // holiday on May 16th 2014 (Friday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLYNTH,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(5),
RecurrenceDayOfWeekMask=32, // Friday bitmask
RecurrenceDayOfMonth=null,
RecurrenceInstance=ConstantUtil.HOLIDAY_RECINSTANCE_THIRD, // third Friday in May
IsAllDay=true));
hds.add(new Holiday(
Name='Fourth Friday in May Holiday',
ActivityDate=Date.newInstance(2014,5,23), // holiday on May 23rd 2014 (Friday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLYNTH,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(5),
RecurrenceDayOfWeekMask=32, // Friday bitmask
RecurrenceDayOfMonth=null,
RecurrenceInstance=ConstantUtil.HOLIDAY_RECINSTANCE_FOURTH, // fourth Friday in May
IsAllDay=true));
hds.add(new Holiday(
Name='Last Friday in May Holiday',
ActivityDate=Date.newInstance(2014,5,30), // holiday on May 30th 2014 (Friday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLYNTH,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(5),
RecurrenceDayOfWeekMask=32, // Friday bitmask
RecurrenceDayOfMonth=null,
RecurrenceInstance=ConstantUtil.HOLIDAY_RECINSTANCE_LAST, // last Friday in May
IsAllDay=true));
hds.add(new Holiday(
Name='Christmas',
ActivityDate=Date.newInstance(2014,12,25), // holiday on Dec 25th (Thursday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLY,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(12),
RecurrenceDayOfWeekMask=null,
RecurrenceDayOfMonth=25,
RecurrenceInstance=null,
IsAllDay=true));
hds.add(new Holiday(
Name='<NAME>',
ActivityDate=Date.newInstance(2014,12,26), // holiday on Dec 26th (Friday)
IsRecurrence=true,
RecurrenceType=ConstantUtil.HOLIDAY_RECTYPE_YEARLY,
RecurrenceMonthOfYear=ConstantUtil.MONTHS_I2S.get(12),
RecurrenceDayOfWeekMask=null,
RecurrenceDayOfMonth=26,
RecurrenceInstance=null,
IsAllDay=true));
return hds;
}
}<file_sep>/classes/OL_SearchConsignmentController.cls
/**
* File Name : OL_SearchConsignmentController.cls
* Description : Controller for OL_SearchConsignment Page
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 09/09/2014 <NAME> Initial version, TNT-546
* D0.1 14/08/2014 <NAME> Initial version, TNT-547
* D0.2 10/09/2014 <NAME> create cases, TNT-1593
* D 0.2 10/09/2014 <NAME> open from case, TNT-1594
* 0.3 20/01/2015 <NAME> merge with OL_SearchConsignmentControllerById
* 0.4 21/01/2015 <NAME> check if related cases already exist TNT-2297
* 0.5 24/09/2015 <NAME>ended to create Case type (constutil.PLVAL_CASE_TYPE_RECORD_TRACK)'FCR - Track' for !runCreateAndSaveCase and removed check for exisiting cases for that scenario
*/
public with sharing class OL_SearchConsignmentController {
//Properties for Advanced Search Page
public uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType consReq {get; set;}
public Quote__c quote {get; set;}
public Quote__c quoteTo {get; set;}
public Integer pageNumber {get; set;}
public uksvcsTntComSearchConsignment.ConsignmentResponse_ContainerType cons {get; set;}
public String conId {get; set;}
public Map<String, String> lobMap {get; set;}
public Map<String, String> serviceMap {get; set;}
public String delimitedServiceCodes {get; set;}
public String delimitedLobCodes {get; set;}
public Integer pageSize {get; set;}
public Boolean isAdvanced {get; set;}
public Boolean showDetails {get; set;}
public uksvcsTntComSearchConsignment.ResponseMessage_MasterType resp {get; set;}
//Properties for Detail Page
public String consignmentId {get; set;}
public uksvcsTntComSearchConsignment.ConsignmentResponse_MasterType consignment {get; set;}
public List<uksvcsTntGetItemsForConsignment.Item_MasterType> consignmentItems {get; set;}
public Integer rowItemForTracking {get; set;}
public Case caseToOpen {get; set;}
public Map<String, Account> depots {get; set;}
public String depotKeys {get; set;}
public Map<String, Service__c> services {get; set;}
public String serviceKeys {get; set;}
public Map<String, Line_of_Business__c> lobs {get; set;}
public String lobKeys {get; set;}
public Boolean isFromSearch {get; set;}
public List<Case> recentCases {get; set;}
public Boolean createAndSave {get; set;}
public Boolean createAndOpen {get; set;}
public OL_SearchConsignmentController(){
//Logic for Advanced Search Page
resetFilters();
pageSize = (TNT_Integration__c.getInstance() != null && TNT_Integration__c.getInstance().Search_Consignment_Page_Size__c != null) ?
(Integer)TNT_Integration__c.getInstance().Search_Consignment_Page_Size__c : 25;
lobMap = OL_CodeForObjectUtil.getLineOfBusinesMap();
serviceMap = OL_CodeForObjectUtil.getServiceMap();
delimitedServiceCodes = OL_CodeForObjectUtil.delimitedServiceCodes;
delimitedLobCodes = OL_CodeForObjectUtil.delimitedLobCodes;
isAdvanced = false;
isFromSearch = false;
//Logic for Detail Page
fillDepots();
fillServices();
fillLobs();
hideCasePanel();
}
//Methods for Advanced Search Page
public PageReference initSearch(){
if(ApexPages.currentPage().getParameters().get('bNum') != null){
consReq.bkgNum = ApexPages.currentPage().getParameters().get('bNum');
return search();
}
return null;
}
public PageReference search(){
isAdvanced = false;
return searchAction();
}
public PageReference searchAdvanced(){
isAdvanced = true;
return searchAction();
}
public PageReference searchAction(){
cons = null;
pageNumber = 1;
searchConsignments();
PageReference res;
return res;
}
public void prew(){
pageNumber--;
searchConsignments();
}
public void next(){
pageNumber++;
searchConsignments();
}
public void searchConsignments(){
showDetails = false;
resp = new uksvcsTntComSearchConsignment.ResponseMessage_MasterType();
//check requered data for search
if(checkSearchData()){
uksvcsTntComSearchConsignmentService.searchConsignment2Port
port = new uksvcsTntComSearchConsignmentService.searchConsignment2Port();
port.inputHttpHeaders_x = new map<string,string> {'Username' => TNT_Integration__c.getInstance().Username__c,
'Password' => <PASSWORD>};
uksvcsTntComGenericPayloadHeader.payloadHeader
hdr = new uksvcsTntComGenericPayloadHeader.payloadHeader();
hdr.srch = new uksvcsTntComGenericPayloadHeader.search_x();
hdr.srch.pgNum = String.valueOf(pageNumber);
if(isAdvanced){
hdr.srch.dtFrom = quote.Collection_Date__c;
hdr.srch.dtTo = quoteTo.Collection_Date__c;
}
uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType newReq = new uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType();
newReq.unqConNum = (!String.isBlank(consReq.unqConNum) ? consReq.unqConNum.toUpperCase() : null);
newReq.tntConNum = (!String.isBlank(consReq.tntConNum) ? consReq.tntConNum.toUpperCase() : null);
newReq.bkgNum = (!String.isBlank(consReq.bkgNum) ? consReq.bkgNum.toUpperCase() : null);
newReq.custRef = (!String.isBlank(consReq.custRef) ? consReq.custRef.toUpperCase().trim() : null);
if(isAdvanced){
newReq.actNum = (!String.isBlank(consReq.actNum) ? consReq.actNum.toUpperCase() : null);
newReq.sndrNm = (!String.isBlank(consReq.sndrNm) ? consReq.sndrNm.toUpperCase().trim() : null);
newReq.delToNm = (!String.isBlank(consReq.delToNm) ? consReq.delToNm.toUpperCase().trim() : null);
newReq.colDep = (!String.isBlank(consReq.colDep) ? consReq.colDep.toUpperCase() : null);
newReq.delDep = (!String.isBlank(consReq.delDep) ? consReq.delDep.toUpperCase() : null);
newReq.colRnd = (!String.isBlank(consReq.colRnd) ? consReq.colRnd.toUpperCase() : (!String.isBlank(consReq.colDep) ? '0' : null));
newReq.delRnd = (!String.isBlank(consReq.delRnd) ? consReq.delRnd.toUpperCase() : (!String.isBlank(consReq.delDep) ? '0' : null));
newReq.delDt = (quote.Delivery_Date__c != null ? quote.Delivery_Date__c : null);
newReq.bayNum = (!String.isBlank(consReq.bayNum) ? consReq.bayNum.toUpperCase() : null);
newReq.orgDep = (!String.isBlank(consReq.orgDep) ? consReq.orgDep : null);
newReq.ntTyp = (!String.isBlank(consReq.ntTyp) ? consReq.ntTyp : null);
newReq.lobRef = (!String.isBlank(consReq.lobRef) ? consReq.lobRef : null);
newReq.svcCd = (!String.isBlank(consReq.svcCd) ? consReq.svcCd : null);
newReq.options = (!String.isBlank(consReq.options) ? consReq.options : null);
if(!String.isBlank(consReq.delAddr.pstCd) || !String.isBlank(consReq.delAddr.twn)){
newReq.delAddr = new uksvcsTntComSearchConsignment.ShortAddress_MasterType();
newReq.delAddr.pstCd = (!String.isBlank(consReq.delAddr.pstCd) ? consReq.delAddr.pstCd.toUpperCase().trim() : null);
newReq.delAddr.twn = (!String.isBlank(consReq.delAddr.twn) ? consReq.delAddr.twn.toUpperCase().trim() : null);
}
if(!String.isBlank(consReq.stsHstry.sts) || !String.isBlank(consReq.stsHstry.subSts) ||
consReq.stsHstry.negStsInd || consReq.stsHstry.negSubStsInd){
newReq.stsHstry = new uksvcsTntComSearchConsignment.ShortConsignmentStatusHistory_MasterType();
newReq.stsHstry.sts = (!String.isBlank(consReq.stsHstry.sts) ? consReq.stsHstry.sts : null);
newReq.stsHstry.subSts = (!String.isBlank(consReq.stsHstry.subSts) ? consReq.stsHstry.subSts : null);
newReq.stsHstry.negStsInd = (consReq.stsHstry.negStsInd ? consReq.stsHstry.negStsInd : null);
newReq.stsHstry.negSubStsInd = (consReq.stsHstry.negSubStsInd ? consReq.stsHstry.negSubStsInd : null);
}
}
try{
if(!ConstantUtil.INTEGRATION_ACCESS) throw new ConstantUtil.IntegrationAccessDeniedException(ConstantUtil.INTEGRATION_EXMSG);
port.timeout_x = ConstantUtil.INTEGRATION_TIMEOUT;
resp = port.searchConsignment2(newReq, hdr);
if(resp.con != null){
consignment = resp.con;
consignment.addDiscrepCommentsToHistoryRecords();
showDetails = true;
}
cons = resp.consearch;
if(resp.hdr != null && !String.isBlank(resp.hdr.infoMsg)){
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.INFO, resp.hdr.infoMsg));
}
} catch(Exception ex) {
if(ex instanceof System.CalloutException || ex instanceof ConstantUtil.IntegrationAccessDeniedException)
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
}
else
{
throw ex;
}
}
}
}
public PageReference viewRes(){
isFromSearch = true;
PageReference res;
if(consignment != null){
res = Page.OL_SearchConsignmentById;
res.setRedirect(false);
}
return res;
}
public PageReference backToSearch(){
return Page.OL_SearchConsignment;
}
public Boolean checkSearchData(){
Boolean res = true;
//check unic numbers
if(String.isBlank(consReq.tntConNum) && String.isBlank(consReq.bkgNum) && String.isBlank(consReq.custRef)){
if(!isAdvanced){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,
'You should specify Con Number or Coll Req Number or Cust Ref Number or use Advanced Search.'));
}
//Check date from and date to
if(quoteTo.Collection_Date__c == null){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, 'You must select Date To.'));
}
if(quote.Collection_Date__c == null){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, 'You must select Date From.'));
}
if(res && (quote.Collection_Date__c > quoteTo.Collection_Date__c)){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, 'Date From must be before Date To.'));
}
if(res && (quote.Collection_Date__c.daysBetween(quoteTo.Collection_Date__c) > 7)){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,
'It should not be more than week between Date From and Date To.'));
}
// Check Collection Depot and Collection Round Num
if(!String.isBlank(consReq.colRnd) && String.isBlank(consReq.colDep)){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,
'If Coll Round No is entered, Coll Depot should be entered as well.'));
}
if((!String.isBlank(consReq.delRnd) || quote.Delivery_Date__c != null ) && String.isBlank(consReq.delDep)){
res = false;
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR,
'If Del Round No or Del Date is entered, Del Depot should be entered as well.'));
}
}
return res;
}
public void resetFilters(){
consReq = new uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType();
consReq.delAddr = new uksvcsTntComSearchConsignment.ShortAddress_MasterType();
consReq.stsHstry = new uksvcsTntComSearchConsignment.ShortConsignmentStatusHistory_MasterType();
quote = new Quote__c();
quoteTo = new Quote__c();
quoteTo.Collection_Date__c = Date.today();
quote.Collection_Date__c = Date.today() - 1;
pageNumber = 1;
}
//GET ITEMS FOR PICKLISTS
public List<SelectOption> getDepotItems() {
List<SelectOption> options = new List<SelectOption>();
for(Account a : [SELECT Name, Depot_Number__c FROM Account
WHERE Depot_Number__c != null AND RecordTypeId = : TestUtil.accountDepotRTId ORDER BY Name]){
options.add(new SelectOption(a.Depot_Number__c, a.Name + ' ('+a.Depot_Number__c+')'));
}
return options;
}
public List<SelectOption> getServiceItems() {
List<SelectOption> options = new List<SelectOption>();
for(Service__c s : [SELECT Name, Service_Code__c FROM Service__c WHERE Service_Code__c != null ORDER BY Name]){
options.add(new SelectOption(s.Service_Code__c, s.Name + ' ('+s.Service_Code__c+')'));
}
return options;
}
public List<SelectOption> getOptionItems() {
List<SelectOption> options = new List<SelectOption>();
for(Option_Settings__c os : [SELECT Name, SF_Description__c FROM Option_Settings__c ORDER BY Name]){
options.add(new SelectOption(os.SF_Description__c, os.SF_Description__c + ' ('+os.Name+')'));
}
return options;
}
public List<SelectOption> getNoteTypeItems() {
List<SelectOption> options = new List<SelectOption>();
for(Note_Type_Settings__c os : [SELECT Name, SF_Description__c FROM Note_Type_Settings__c ORDER BY Name]){
options.add(new SelectOption(os.SF_Description__c, os.SF_Description__c + ' ('+os.Name+')'));
}
return options;
}
public List<SelectOption> getConStatusItems() {
List<SelectOption> options = new List<SelectOption>();
for(Con_Status_Settings__c cs : [SELECT Name, SF_Description__c FROM Con_Status_Settings__c ORDER BY Name]){
options.add(new SelectOption(cs.SF_Description__c, cs.SF_Description__c + ' ('+cs.Name+')'));
}
return options;
}
public List<SelectOption> getConSubStatusItems() {
List<SelectOption> options = new List<SelectOption>();
for(Con_Sub_Status_Settings__c css : [SELECT Name, SF_Description__c FROM Con_Sub_Status_Settings__c ORDER BY Name]){
options.add(new SelectOption(css.SF_Description__c, css.SF_Description__c + ' ('+css.Name+')'));
}
return options;
}
public List<SelectOption> getLobItems() {
List<SelectOption> options = new List<SelectOption>();
for(Line_of_Business__c l : [SELECT Name, Line_of_Business_Reference__c FROM Line_of_Business__c WHERE Line_of_Business_Reference__c != null ORDER BY Name]){
options.add(new SelectOption(l.Line_of_Business_Reference__c, l.Name + ' ('+l.Line_of_Business_Reference__c+')'));
}
return options;
}
//Methods for Detail Page
public void searchConsignment() {
if(consignmentId == null){
consignmentId = ApexPages.currentPage().getParameters().get('conId');
}
consignmentItems = null;
rowItemForTracking = null;
caseToOpen = null;
if(consignmentId != null){
uksvcsTntComSearchConsignmentService.searchConsignment2Port
port = new uksvcsTntComSearchConsignmentService.searchConsignment2Port();
port.inputHttpHeaders_x = new map<string,string> {'Username' => TNT_Integration__c.getInstance().Username__c,
'Password' => TNT_<PASSWORD>c.getInstance().<PASSWORD>};
uksvcsTntComGenericPayloadHeader.payloadHeader
hdr = new uksvcsTntComGenericPayloadHeader.payloadHeader();
uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType newReq = new uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType();
newReq.unqConNum = consignmentId;
try{
if(!ConstantUtil.INTEGRATION_ACCESS) throw new ConstantUtil.IntegrationAccessDeniedException(ConstantUtil.INTEGRATION_EXMSG);
port.timeout_x = ConstantUtil.INTEGRATION_TIMEOUT;
resp = port.searchConsignment2(newReq, hdr);
if(resp.con != null){
consignment = resp.con;
consignment.addDiscrepCommentsToHistoryRecords();
}
if(resp.hdr != null && !String.isBlank(resp.hdr.infoMsg)){
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.INFO, resp.hdr.infoMsg));
}
} catch(Exception ex) {
if(ex instanceof System.CalloutException || ex instanceof ConstantUtil.IntegrationAccessDeniedException)
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
consignment = null;
}
else
{
throw ex;
}
}
}
}
public void searchConsignmentItems() {
uksvcsTntGetItemsForConsignmentService.getItemsForConsignmentPort port = new uksvcsTntGetItemsForConsignmentService.getItemsForConsignmentPort();
port.inputHttpHeaders_x = new map<string,string> {'Username' => TNT_Integration__c.getInstance().Username__c,
'Password' => TNT_Integration__c.getInstance().Password__c};
uksvcsTntComGenericPayloadHeader.payloadHeader
hdr = new uksvcsTntComGenericPayloadHeader.payloadHeader();
uksvcsTntGetItemsForConsignment.ItemRequest_MasterType
con = new uksvcsTntGetItemsForConsignment.ItemRequest_MasterType ();
con.unqConNum = consignment.unqConNum;
uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType resp;
try{
if(!ConstantUtil.INTEGRATION_ACCESS) throw new ConstantUtil.IntegrationAccessDeniedException(ConstantUtil.INTEGRATION_EXMSG);
port.timeout_x = ConstantUtil.INTEGRATION_TIMEOUT;
resp = port.getItemsForConsignment (hdr, con);
consignmentItems = resp.itms.itm;
} catch(System.NullPointerException ex) {
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, 'No Consignment Items found.'));
consignmentItems = null;
}
catch(Exception ex) {
if(ex instanceof System.CalloutException || ex instanceof ConstantUtil.IntegrationAccessDeniedException)
{
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
consignmentItems = null;
}
else
{
throw ex;
}
}
}
public void setSelectedItemRaw(){
//rowItemForTracking = rowNum;
}
public void runCreateAndSaveCase(){
//if(!anyRecentCases()){
createAndSaveCase();//DH modified and commented out
//} else {
// createAndSave = true;
// createAndOpen = false;
//}
}
public void runCreateAndOpenCase(){
if(!anyRecentCases()){
createAndOpenCase();
} else {
createAndSave = false;
createAndOpen = true;
}
}
public void hideCasePanel(){
createAndSave = false;
createAndOpen = false;
}
public void createAndSaveCase(){
hideCasePanel();
Case c = createCase();
c.Type = ConstantUtil.PLVAL_CASE_TYPE_RECORD_TRACK;//Modified by DH 24/09/15 for Kish
c.Status = ConstantUtil.PLVAL_CASE_STATUS_CLOSED;
try{
insert c;
Case tCase = [SELECT CaseNumber, AccountId, Type, Status FROM Case WHERE Id = : c.Id];
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.INFO, 'Case ' + tCase.CaseNumber +
' has been created successfully. <a href="#" onclick="openObject(\'' +
tCase.Id +'\', \''+ tCase.CaseNumber + '\');">Open Case</a>'));
} catch(Exception ex){
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
}
}
public void createAndOpenCase(){
hideCasePanel();
caseToOpen = null;
Case c = createCase();
c.Type = ConstantUtil.PLVAL_CASE_TYPE_TRACK;
c.Status = ConstantUtil.PLVAL_CASE_STATUS_WORKING_ON;
try{
insert c;
caseToOpen = [SELECT CaseNumber, AccountId, Type, Status FROM Case WHERE Id = : c.Id];
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.INFO, 'Case ' + caseToOpen.CaseNumber +
' has been created successfully. <a href="#" onclick="openObject(\'' +
caseToOpen.Id +'\', \''+ caseToOpen.CaseNumber + '\');">Open Case</a>'));
} catch(Exception ex){
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
}
}
public Boolean anyRecentCases(){
Date sixWeeks = Date.today().addDays(-42);
recentCases = new List<Case>([SELECT Id, CaseNumber FROM Case WHERE CreatedDate > : sixWeeks AND Consignment_Number__c = : consignment.tntConNum]);
return !recentCases.isEmpty();
}
public Account account{
get{
if(consignment.act != null && consignment.act.actNum != null){
List<Account> accounts = [SELECT Name FROM Account WHERE Account_Number__c = : consignment.act.actNum];
if(!accounts.isEmpty()){
account = accounts[0];
} else {
account = new Account();
}
} else {
account = null;
}
return account;
}
private set;
}
private Case createCase(){
Case c = new Case();
c.Consignment_Number__c = consignment.tntConNum;
c.UUCN_Number__c = consignment.unqConNum;
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
if(consignment.act != null){
c.AccountId = account.Id;
}
c.Delivery_Depot__c = String.isNotBlank(consignment.orgnDep) && depots.containsKey(consignment.orgnDep)
? depots.get(consignment.orgnDep).Id : null;
return c;
}
public void fillDepots() {
depots = new Map<String, Account>();
depotKeys = '';
for(Account a : [SELECT Name, Depot_Number__c FROM Account
WHERE Depot_Number__c != null AND RecordTypeId = : TestUtil.accountDepotRTId ORDER BY Name]){
depots.put(a.Depot_Number__c, a);
depotKeys += '*' + a.Depot_Number__c + '*';
}
}
public void fillServices() {
services = new Map<String, Service__c>();
serviceKeys = '';
for(Service__c s : [SELECT Name, Service_Code__c FROM Service__c WHERE Service_Code__c != null ORDER BY Name]){
services.put(s.Service_Code__c, s);
serviceKeys += '*' + s.Service_Code__c + '*';
}
}
public void fillLobs() {
lobs = new Map<String, Line_of_Business__c>();
lobKeys = '';
for(Line_of_Business__c l : [SELECT Name, Line_of_Business_Reference__c FROM Line_of_Business__c WHERE Line_of_Business_Reference__c != null ORDER BY Name]){
lobs.put(l.Line_of_Business_Reference__c, l);
lobKeys += '*' + l.Line_of_Business_Reference__c + '*';
}
}
}<file_sep>/classes/CaseTriggerHandler.cls
/**
* File Name : CaseTriggerHandler.cls
* Description : methods called from Case trigger
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 03/07/2014 <NAME> Initial version
* 0.2 07/07/2014 <NAME> Added changeOwner method TNT-483
* 0.3 21/07/2014 <NAME> added assignEscalatedCases() method TNT-455
* 0.4 05/08/2014 <NAME> added assignMajorAccountCases() method TNT-1314
* 0.5 15/08/2014 <NAME> added updateCaseTrackingHistory() method TNT-490,TNT-491,TNT-493
* 0.6 20/08/2014 <NAME> added updateOwnerForCallMeBackTasks() method TNT-1428
* 0.7 10/09/2014 <NAME> Removed changeOwner method TNT-1603
* 0.8 25/09/2014 <NAME> TNT-1911
* 0.9 15/01/2015 <NAME> TNT-2448
* 10.0 19/01/2016 <NAME> Amended depotQueueAssignment() method for Sprint 12 - ETA/HCP/Redelivery
*/
public without sharing class CaseTriggerHandler {
// Boolean to control recursion
public static Boolean isFirstRun = true;
//public static Boolean assignedEscalatedOwner = false; // prevent clash between owner assignment - execute only once
private static String majourAccountQueueId = getMajorAccountsQueueId(ConstantUtil.MAJOR_ACCOUNTS_QUEUE);
// HANDLERS
public static void onBeforeInsertHandler(List<Case> triggerNew)
{
populate24HDeadline(triggerNew);
//assignMajorAccountCases(triggerNew);
assignCases(triggerNew, null);
}
public static void onAfterInsertHandler(List<Case> triggerNew, Map<Id,Case> triggerNewMap)
{
createReminderTask(triggerNew,null);
updateCaseTrackingHistory(triggerNewMap, null);
}
public static void onAfterUpdateHandler(List<Case> triggerNew, Map<Id,Case> triggerNewMap, Map<Id,Case> triggerOldMap)
{
updateOwnerForCallMeBackTasks(triggerNew, triggerOldMap);
createReminderTask(triggerNew, triggerOldMap);
updateCaseTrackingHistory(triggerNewMap, triggerOldMap);
}
public static void onBeforeUpdateHandler(List<Case> triggerNew, Map<Id,Case> triggerOldMap)
{
//assignMajorAccountCases(triggerNew);
assignCases(triggerNew, triggerOldMap);
}
// METHODS
public static List<Task> createReminderTask(List<Case> triggerNew, Map<Id,Case> triggerOldMap)
{
if(!isFirstRun){
return new List<Task>();
}
Boolean isInsert = triggerOldMap == null;
RecordType actionTask = [Select Id from RecordType where sObjectType =: 'Task' and Name = 'Action' limit 1]; //JMV
Map<Id, Case> casesWithTasks;
if(!isInsert){
casesWithTasks = new Map<Id, Case>([SELECT Id, (SELECT Id FROM Tasks WHERE RecordTypeId = : actionTask.Id AND subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK)
FROM Case WHERE Id IN : triggerOldMap.keyset()]);
}
List<Task> tsks = new List<Task>();
for(Case c : triggerNew)
{
// if new value not blank and if changed from previous selection
if(String.isNotBlank(c.Call_me_back__c) && (isInsert || triggerOldMap.get(c.Id).Call_me_back__c != c.Call_me_back__c))
{
Task tsk = new Task();
tsk.WhatId = c.Id;
tsk.WhoId = c.ContactId;
tsk.subject = ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK;
tsk.Status = 'Not Started';
tsk.Priority = 'Normal';
tsk.RecordTypeId = actionTask.Id; //JMV
// calculate reminder time
String cmb = c.Call_me_back__c.split(' ').get(0); // it's either 'Next Working Day' or 'N hours'
tsk.ReminderDateTime = cmb == 'Next' ?
TimeUtil.getNextWorkingDay(Datetime.now()) : getSLATime(Integer.valueOf(cmb),null); //DH Commented 30/09 Datetime.now().addHours(Integer.valueOf(cmb));
tsk.ActivityDate = tsk.ReminderDateTime.date();
tsk.SLA_Deadline__c = tsk.ReminderDateTime;
TimeUtil.getWorkingDayResumeDT(tsk.ReminderDateTime);//DH Modified 24/09tsk.ReminderDateTime;
//*****here****
tsk.ReminderDateTime = tsk.ReminderDateTime.addMinutes(-15); // TNT-2051 reminder 15 minutes before
tsk.IsReminderSet = true;
//tsk.Description = 'Call customer back at : ' + tsk.ReminderDateTime.format();
tsk.OwnerId = UserInfo.getUserId();
tsk.Action_Type__c = ConstantUtil.PLVAL_TASK_ACTION_TYPE_CONTACT_ACTIONS;
tsk.Action_Subtype__c = isInsert || casesWithTasks.get(c.Id).Tasks == null || casesWithTasks.get(c.Id).Tasks.isEmpty() ?
ConstantUtil.PLVAL_TASK_ACTION_SUBTYPE_FIRST_CUSTOMER_CONTACT : ConstantUtil.PLVAL_TASK_ACTION_SUBTYPE_CUSTOMER_CONTACT;
tsks.add(tsk);
}
}
insert tsks;
isFirstRun = false;
return tsks;
}
public static DateTime getSLATime(Integer dt, DateTime lt)
{
Integer CallBack = dt;
DateTime logTime = lt != null ? lt:DateTime.Now();
DateTime effectiveTIme = TimeUtil.getWorkingDayResumeDT(logTime);
DateTime SLA;
If(CallBack == 24)
{
SLA = TimeUtil.getNextWorkingDay(TimeUtil.getWorkingDayResumeDT(effectiveTIme));
}
else if(CallBack == 48)
{
SLA = TimeUtil.getNextWorkingDay(TimeUtil.getNextWorkingDay(TimeUtil.getWorkingDayResumeDT(effectiveTIme)));
}
else
{
if(logTime < effectiveTIme)//Before start time so use effectTime
{
SLA = effectiveTIme.addHours(Callback);
//if(getWorkingDayResumeDT(SLA) != SLA)//Must have move to next working day so need to calculate hours to add
//{
//SLA = TimeUtil.getWorkingDayResumeDT(SLA).AddHOurs(TimeUtil.getDayEndTime(effectiveTime.date()) - (effectiveTime.addHours(CallBack)) * 1000 * 60 * 60);
//}
}
else if( effectiveTIme.addHours(Callback) != TimeUtil.getWorkingDayResumeDT(effectiveTIme.addHours(Callback)))
{
Integer difference = effectiveTime.addHours(Callback).hour() - TimeUtil.getDayEndTime(effectiveTime.Date()).hour();
SLA = (TimeUtil.getNextWorkingDayStartDT(effectiveTIme.addHours(Callback).Date()).addHours(difference)).addMinutes(effectiveTime.Minute());
}
else
{
SLA = LogTime.addHOurs(callBack);
}
}
return SLA;
}
public static void populate24HDeadline(List<Case> triggerNew)
{
for(Case c : triggerNew)
{
Datetime openTime = Datetime.now();
openTime = Datetime.newInstance(openTime.date(),Time.newInstance(openTime.hour(),openTime.minute(),0,0)); // round up to minute
c.Twentyfour_Hour_Deadline__c = TimeUtil.getNextWorkingDay(TimeUtil.getWorkingDayResumeDT(openTime));
}
}
/*public static void assignEscalatedCases(List<Case> triggerNew, Map<Id,Case> triggerOldMap)
{
if(assignedEscalatedOwner)
{
return;
}
Set<Id> reassignCases = new Set<Id>(); // cases with all related account data
for(Case c : triggerNew)
{
if(c.IsEscalated && !triggerOldMap.get(c.Id).IsEscalated && String.isNotBlank(c.Exception__c))
{
reassignCases.add(c.Id);
}
}
if(!reassignCases.isEmpty())
{
depotQueueAssignment(reassignCases,triggerNew);
}
assignedEscalatedOwner = true;
}*/
// we're expecting this method to be triggered by an assignment rule
public static void assignCases(List<Case> triggerNew, Map<Id,Case> triggerOldMap)
{
Set<Id> reassignCases = new Set<Id>(); // cases with all related account data
for(Case c : triggerNew)
{
if(c.OwnerId == ConstantUtil.UNASSIGNED_QUEUE_ID
&& (triggerOldMap == null || triggerOldMap.get(c.Id).OwnerId != ConstantUtil.UNASSIGNED_QUEUE_ID))
{
reassignCases.add(c.Id);
}
else
{
if(c.OwnerId == majourAccountQueueId
&& (triggerOldMap == null || triggerOldMap.get(c.Id).OwnerId != majourAccountQueueId))
{
reassignCases.add(c.Id);
}
}
}
if(!reassignCases.isEmpty())
{
depotQueueAssignment(reassignCases,triggerNew);
}
}
public static void depotQueueAssignment(Set<Id> reassignCases, List<Case> triggerNew)
{
Map<Id,Case> fullCases = new Map<Id,Case>([select Exception__c, AccountId, Type, Case_Types_Level_2__c,//DH added Type, Case_Types_Level_2__c 19/01/2016
Account.Major_Account__c, Account.Assigned_Agent__c,
Account.Collection_Queue__c, Account.Delivery_Queue__c,
Collection_Depot__c, Collection_Depot__r.Collection_Queue__c,
Delivery_Depot__c, Delivery_Depot__r.Delivery_Queue__c
from Case where id in :reassignCases]);
// find queues
Set<String> queueNames = new Set<String>();
for(Case c : fullCases.values())
{
String ex = String.isBlank(c.Exception__c) ? ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY : c.Exception__c;
if(c.AccountId != null)
{
queueNames.add(c.Account.Collection_Queue__c);
queueNames.add(c.Account.Delivery_Queue__c);
}
if(ex == ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION && c.Collection_Depot__c != null)
{
queueNames.add(c.Collection_Depot__r.Collection_Queue__c);
}
if(ex == ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY && c.Delivery_Depot__c != null)
{
queueNames.add(c.Delivery_Depot__r.Delivery_Queue__c);
}
}
Map<String,Group> queues = getQueueNameMap(queueNames);
for(Case originalCase : triggerNew)
{
String ex = String.isBlank(originalCase.Exception__c)
? ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY : originalCase.Exception__c;
if(fullCases.containsKey(originalCase.Id)) // do check to avoid null pointer exceptions
{
Case c = fullCases.get(originalCase.Id);
if(ex == ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION)
{
if(c.AccountId != null && String.isNotBlank(c.Account.Collection_Queue__c))
{
originalCase.OwnerId = queues.get(c.Account.Collection_Queue__c).Id;
}
else
{
if(c.AccountId != null && c.Account.Major_Account__c && c.Account.Assigned_Agent__c != null)
{
originalCase.OwnerId = c.Account.Assigned_Agent__c;
}
else
{
//DH ADded 19/01/2015
if(
(c.Type == 'Track' && (c.Case_Types_Level_2__c == 'Late Delivery' || c.Case_Types_Level_2__c == 'Paperwork Request'))
//|| Comment out as per Kish 02/02/2016
//(c.Type == 'General Enquiry' && c.Case_Types_Level_2__c == 'Redelivery Request')
)
{
originalCase.OwnerId = ConstantUtil.MAURITIUS_QUEUE_ID;
}
//*******************
//DH added else to if clause 19/01/2016
else if(c.Collection_Depot__c != null && String.isNotBlank(c.Collection_Depot__r.Collection_Queue__c))
{
originalCase.OwnerId = queues.get(c.Collection_Depot__r.Collection_Queue__c).Id;
}
}
}
}
if(ex == ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY)
{
if(c.AccountId != null && String.isNotBlank(c.Account.Delivery_Queue__c))
{
originalCase.OwnerId = queues.get(c.Account.Delivery_Queue__c).Id;
}
else
{
if(c.AccountId != null && c.Account.Major_Account__c && c.Account.Assigned_Agent__c != null)
{
originalCase.OwnerId = c.Account.Assigned_Agent__c;
}
else
{
//DH ADded 19/01/2015
if(
(c.Type == 'Track' && (c.Case_Types_Level_2__c == 'Late Delivery' || c.Case_Types_Level_2__c == 'Paperwork Request'))
//||
//(c.Type == 'General Enquiry' && c.Case_Types_Level_2__c == 'Redelivery Request')
)
{
originalCase.OwnerId = ConstantUtil.MAURITIUS_QUEUE_ID;
}
//*******************
//DH added else to if clause 19/01/2016
else if(c.Delivery_Depot__c != null && String.isNotBlank(c.Delivery_Depot__r.Delivery_Queue__c))
{
originalCase.OwnerId = queues.get(c.Delivery_Depot__r.Delivery_Queue__c).Id;
}
}
}
}
}
}
}
public static Map<String,Group> getQueueNameMap(Set<String> queueNames)
{
Map<String,Group> queues = new Map<String,Group>();
for(Group q : [select id, DeveloperName from Group where Type = 'Queue' and DeveloperName in :queueNames])
{
queues.put(q.DeveloperName,q);
}
return queues;
}
/*private static void assignMajorAccountCases(List<Case> cases){
String majourAccountQueueId = getMajorAccountsQueueId(ConstantUtil.MAJOR_ACCOUNTS_QUEUE);
//select Account
Set<Id> accountIds = new Set<Id>();
List<Case> casesToReassign = new List<Case>();
for(Case c : cases){
if(c.OwnerId == majourAccountQueueId && !c.Case_Back_to_Queue_MA__c){
casesToReassign.add(c);
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Major_Account__c, Assigned_Agent__c
FROM Account WHERE Id IN : accountIds]);
for(Case c : casesToReassign){
Account a = accounts.get(c.AccountId);
if(a != null && a.Major_Account__c && a.Assigned_Agent__c != null){
c.OwnerId = a.Assigned_Agent__c;
}
}
}*/
private static String getMajorAccountsQueueId(String name){
Group res = [SELECT Id FROM Group WHERE DeveloperName = : name LIMIT 1];
return res.Id;
}
//Case Tracking History
private static void updateCaseTrackingHistory(Map<Id,Case> triggerNewMap, Map<Id,Case> triggerOldMap){
List<Case_Tracking_History__c> caseHistory = new List<Case_Tracking_History__c>();
Map<Id, Case> casesWithOwners = new Map<Id, Case>([SELECT OwnerId, Owner.Name FROM Case WHERE ID IN : triggerNewMap.keyset()]);
Map<Id, Map<String, Case_Tracking_History__c>> openCaseHistory = new Map<Id, Map<String, Case_Tracking_History__c>>();
if(triggerOldMap != null){
for(Case_Tracking_History__c cth : [SELECT Case__c, Category__c, Main_Field_Current_Value__c,
Secondary_Field_Current_Value__c, Finished_on__c
FROM Case_Tracking_History__c
WHERE Finished_on__c = null AND Case__c IN : triggerOldMap.keyset()]){
if(!openCaseHistory.containsKey(cth.Case__c)){
openCaseHistory.put(cth.Case__c, new Map<String, Case_Tracking_History__c>());
}
openCaseHistory.get(cth.Case__c).put(cth.Category__c, cth);
}
}
for(Case c : triggerNewMap.values()){
for(String cat : categoryToFields.keyset()){
Case_Tracking_History__c oldCth = openCaseHistory.isEmpty() || !openCaseHistory.containsKey(c.Id)
? null : openCaseHistory.get(c.Id).get(cat);
caseHistory.addAll(updateCaseTrackingHistoryObj(cat, c, oldCth, casesWithOwners));
}
}
if(!caseHistory.isEmpty()){
upsert caseHistory;
}
}
private static List<Case_Tracking_History__c> updateCaseTrackingHistoryObj(String categ, Case newCase, Case_Tracking_History__c oldCth, Map<Id, Case> casesWithOwners){
List<Case_Tracking_History__c> res = new List<Case_Tracking_History__c>();
Case_Tracking_History__c cth = null;
String mFieldName = categoryToFields.get(categ)[0];
String sFieldName = categoryToFields.get(categ).size() > 1 ? categoryToFields.get(categ)[1] : null;
String mFieldVal = categ == ConstantUtil.PLVAL_CTH_CATEGORY_OWNER ? (casesWithOwners.get(newCase.Id).Owner.Name ): String.ValueOf(newCase.get(mFieldName));
String sFieldVal = sFieldName != null ? String.ValueOf(newCase.get(sFieldName)) : null;
if(oldCth == null || oldCth.Main_Field_Current_Value__c != mFieldVal || oldCth.Secondary_Field_Current_Value__c != sFieldVal){
cth = new Case_Tracking_History__c();
cth.Case__c = newCase.Id;
cth.Category__c = categ;
cth.Started_On__c = DateTime.now();
cth.Finished_on__c = newCase.isClosed ? DateTime.now() : null;
if(oldCth != null){
oldCth.Finished_on__c = DateTime.now();
res.add(oldCth);
}
cth.Main_Field__c = mFieldName;
cth.Main_Field_Current_Value__c = mFieldVal;
cth.Main_Field_Prior_Value__c = oldCth != null ? oldCth.Main_Field_Current_Value__c : null;
if(categoryToFields.get(categ).size() > 1){
cth.Secondary_Field__c = sFieldName;
cth.Secondary_Field_Current_Value__c = sFieldVal;
cth.Secondary_Field_Prior_Value__c = oldCth != null ? oldCth.Secondary_Field_Current_Value__c : null;
}
cth.User__c = UserInfo.getUserId();
//check if waiting
if((categ == ConstantUtil.PLVAL_CTH_CATEGORY_APPROVAL && mFieldVal == String.valueOf(true)) || (categ == ConstantUtil.PLVAL_CTH_CATEGORY_STATUS && mFieldVal == ConstantUtil.PLVAL_CASE_STATUS_WAITING_FOR_CUSTOMER) ||
(categ == ConstantUtil.PLVAL_CTH_CATEGORY_OWNER && newCase.OwnerId.getSObjectType() != Group.sObjectType)){
cth.Case_Waiting__c = true;
}
res.add(cth);
} else if(oldCth != null && newCase.isClosed){
oldCth.Finished_on__c = DateTime.now();
res.add(oldCth);
}
return res;
}
private static Map<String, List<String>> categoryToFields = new Map<String, List<String>>{
ConstantUtil.PLVAL_CTH_CATEGORY_OWNER => new List<String>{'Owner'},
ConstantUtil.PLVAL_CTH_CATEGORY_TYPE => new List<String>{'Type', 'Case_Types_Level_2__c'},
ConstantUtil.PLVAL_CTH_CATEGORY_REASON => new List<String>{'Reason'},
ConstantUtil.PLVAL_CTH_CATEGORY_STATUS => new List<String>{'Status'},
ConstantUtil.PLVAL_CTH_CATEGORY_PRIORITY => new List<String>{'Priority', 'Priority_Change_Explanation__c'},
ConstantUtil.PLVAL_CTH_CATEGORY_APPROVAL => new List<String>{'In_Approval__c'}};
// Change ownwer for call me back tasks
private static void updateOwnerForCallMeBackTasks(List<Case> cases, Map<Id,Case> triggerOldMap){
Map<Id, Id> caseToOwnerMap = new Map<Id, Id>();
for(Case c : cases){
if(c.OwnerId != triggerOldMap.get(c.Id).OwnerId && c.OwnerId.getSObjectType() != Group.sObjectType){
caseToOwnerMap.put(c.Id, c.OwnerId);
}
}
if(!caseToOwnerMap.isEmpty()){
List<Task> tasksToUpdate = [SELECT WhatId, Subject, OwnerId, IsClosed FROM Task
WHERE WhatId IN : caseToOwnerMap.keyset() AND IsClosed = false AND Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK];
for(Task t : tasksToUpdate){
t.OwnerId = caseToOwnerMap.get(t.WhatId);
}
if(!tasksToUpdate.isEmpty()){
update tasksToUpdate;
}
}
}
}<file_sep>/classes/MFSI_FormatDateTime.cls
// from: http://mindfiresfdcprofessionals.wordpress.com/2013/10/25/how-to-dispaly-locale-formatted-datetime-in-visual-force/
// used to format date
public with sharing class MFSI_FormatDateTime {
public DateTime dateTimeValue { get; set; }
public String getTimeZoneValue() {
if( dateTimeValue != null ) {
String localeFormatDT = dateTimeValue.format('HH:mm, dd MMM yyyy z');
return localeFormatDT;
}
return null;
}
}<file_sep>/classes/BookingLineItemTriggerHelper.cls
/**
* File Name : BookingLineItemTriggerHelper.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 08/09/2014 <NAME> Initial Version TNT-1604
*/
public with sharing class BookingLineItemTriggerHelper {
public static void onAfterInsertHandler(List<Booking_Line_Item__c> triggerNew)
{
updateBookingTotals(triggerNew);
}
public static void onAfterUpdateHandler(List<Booking_Line_Item__c> triggerNew, Map<Id,Booking_Line_Item__c> triggerOldMap)
{
updateBookingTotals(triggerNew);
}
public static void onAfterDeleteHandler(List<Booking_Line_Item__c> triggerOld)
{
updateBookingTotals(triggerOld);
}
public static void updateBookingTotals(List<Booking_Line_Item__c> blis)
{
Set<Id> bookIds = new Set<Id>();
for(Booking_Line_Item__c bli : blis)
{
bookIds.add(bli.Booking__c);
}
// tried to retrieve all info in aggregate query, but can't group on double fields
Map<Id,Booking__c> books = new Map<Id,Booking__c>([select id, Total_Items__c, Total_Weight__c, Total_Volume__c
from Booking__c where id in :bookIds]);
AggregateResult[] bookTotals = [select Booking__c, SUM(Number_of_Items__c), SUM(Total_Item_Weight__c), SUM(Volume__c)
from Booking_Line_Item__c
where Booking__c in :bookIds
group by Booking__c];
for(AggregateResult ar : bookTotals)
{
Booking__c b = books.get((id) ar.get('Booking__c'));
Double totalItems = (Double) ar.get('expr0');
Double totalWeight = (Double) ar.get('expr1');
Double totalVolume = (Double) ar.get('expr2');
Boolean hasChanged = false;
if(b.Total_Items__c == null || totalItems > b.Total_Items__c)
{
b.Total_Items__c = totalItems;
hasChanged = true;
}
if(b.Total_Weight__c == null || totalWeight > b.Total_Weight__c)
{
b.Total_Weight__c = totalWeight;
hasChanged = true;
}
if(b.Total_Volume__c != totalVolume)
{
b.Total_Volume__c = totalVolume;
hasChanged = true;
}
if(!hasChanged) // if there is a need for an update
{
books.remove(b.id);
}
}
if(!books.isEmpty())
{
try{
update books.values();
} catch (System.DmlException ex){
blis[0].addError(ex.getDmlMessage(0));
}
}
}
}<file_sep>/classes/OL_BookingQuoteHelperTest.cls
/**
* File Name : OL_BookingQuoteHelperTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 08/07/2014 <NAME> Initial version
* 0.2 16/07/2014 <NAME> TNT-476,TNT-477
* 0.3 24/07/2014 <NAME> TNT-532, TNT-609
* 0.4 05/08/2014 <NAME> TNT-1326
* 0.5 06/08/2014 <NAME> TNT-1329
* 0.6 19/08/2014 <NAME> TNT-1560 will only be used for Quotes from now on
* 0.7 14/07/2015 <NAME> test numLongLengthItems line 53
*/
@isTest
public with sharing class OL_BookingQuoteHelperTest {
public static testMethod void testNewQuote()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Test.startTest();
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Date__c = System.today();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.findCurrentAccount();
qt.Collection_Postcode__c = 'aa111a';
qt.Delivery_Postcode__c = 'aa111a';
bqh.addLine();
bqh.addLine();
bqh.quoteItems.get(0).Number_Of_Items__c = 5;
bqh.quoteItems.get(0).Height__c = 10;
bqh.quoteItems.get(0).Length__c = 10;
bqh.quoteItems.get(0).Weight__c = 10;
bqh.quoteItems.get(0).Width__c = 10;
ApexPages.currentPage().getParameters().put('rowIndex', '1');
bqh.removeLine();
bqh.customSave();
Test.stopTest();
system.assertEquals(1,[select count() from Quote__c]);
}
//DH
public static testMethod void testNewLongLengthQuote()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Test.startTest();
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Date__c = System.today();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.findCurrentAccount();
qt.Collection_Postcode__c = 'aa111a';
qt.Delivery_Postcode__c = 'aa111a';
bqh.addLine();
bqh.addLine();
bqh.quoteItems.get(0).Number_Of_Items__c = 5;
bqh.quoteItems.get(0).Height__c = 10;
bqh.quoteItems.get(0).Length__c = 10;
bqh.quoteItems.get(0).Weight__c = 10;
bqh.quoteItems.get(0).Width__c = 10;
system.assertEquals(0.0,bqh.getNumLongLengths());
bqh.quoteItems.get(0).Width__c = 161;
system.assertEquals(5.0,bqh.getNumLongLengths());
bqh.RefreshDarryl();
ApexPages.currentPage().getParameters().put('rowIndex', '1');
bqh.removeLine();
bqh.customSave();
Test.stopTest();
system.assertEquals(1,[select count() from Quote__c]);
system.assertEquals(5.0,([select No_Long_Length_Items__c from Quote__c Limit 1]).No_Long_Length_Items__c);
}
public static testMethod void testNewQuoteNoAccountNoContact()
{
Test.startTest();
Quote__c qt = new Quote__c();
qt.Company_Name__c = 'My Company';
qt.Company_Phone__c = '12344321';
qt.Contact_First_Name__c = 'test';
qt.Contact_Last_Name__c = 'guy';
qt.Contact_Phone__c = '123443211';
qt.Contact_Email__c = '<EMAIL>';
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();
Test.stopTest();
//system.assertEquals(1,[select count() from Quote__c where id = :qt.Id]);
}
public static testMethod void testNewQuoteNewContact()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
c.Email = '<EMAIL>';
insert c;
Test.startTest();
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact_First_Name__c = 'test';
qt.Contact_Last_Name__c = 'guy';
qt.Contact_Phone__c = '123443211';
qt.Contact_Email__c = c.Email;
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();
Test.stopTest();
}
public static testMethod void testCatchExceptions()
{
Test.startTest();
Quote__c qt = new Quote__c();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();
Test.stopTest();
}
public static testMethod void testCloneQuote()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Postcode__c = 'NN12 8JA';
qt.Delivery_Postcode__c = 'NN12 8JA';
qt.Collection_Date__c = System.today();
/*Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();*/
insert qt;
qt = [select Id from Quote__c LIMIT 1];
Quote_Line_Item__c qli = new Quote_Line_Item__c();
qli.Number_Of_Items__c = 1;
qli.Height__c = 10;
qli.Length__c = 10;
qli.Weight__c = 10;
qli.Width__c = 10;
qli.Quote__c = qt.Id;
insert qli;
Test.startTest();
ApexPages.currentPage().getParameters().put('oId', qt.Id);
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(new Quote__c());
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();
Test.stopTest();
system.assertEquals(2,[select count() from Quote__c]);
qt = [select Name, Collection_Postcode__c, Email_Only__c, Delivery_Postcode__c from Quote__c WHERE Id != : qt.Id LIMIT 1];
if(c.Email != null) system.assertEquals(null, qt.Email_Only__c);
system.assertEquals('NN12 8JA', qt.Delivery_Postcode__c);
system.assertEquals('NN12 8JA', qt.Collection_Postcode__c);
List<Quote_Line_Item__c> qliList = [SELECT Quote__c, Height__c, Length__c, Weight__c, Width__c FROM Quote_Line_Item__c WHERE Quote__c = : qt.Id];
system.assertEquals(1,qliList.size());
system.assertEquals(10, qliList[0].Height__c);
system.assertEquals(10, qliList[0].Length__c);
system.assertEquals(10, qliList[0].Weight__c);
system.assertEquals(10, qliList[0].Width__c);
system.assertNotEquals(qli.Id, qliList[0].Id);
}
public static testMethod void testEditQuote()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Date__c = System.today();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
qt.Collection_Postcode__c = 'NN12 8JA';
qt.Delivery_Postcode__c = 'NN12 8JA';
Quote_Line_Item__c qli = new Quote_Line_Item__c();
qli.Number_Of_Items__c = 1;
qli.Height__c = 10;
qli.Length__c = 10;
qli.Weight__c = 10;
qli.Width__c = 10;
bqh.quoteItems.add(qli);
bqh.customSave();
qt = [select Id, Account__c, Contact__c from Quote__c LIMIT 1];
List<Quote_Line_Item__c> qliList = [SELECT Quote__c, Height__c, Length__c, Weight__c, Width__c FROM Quote_Line_Item__c WHERE Quote__c = : qt.Id];
system.assertEquals(1,qliList.size());
Test.startTest();
ApexPages.currentPage().getParameters().put('Id', qt.Id);
sc = new Apexpages.Standardcontroller(qt);
bqh = new OL_BookingQuoteHelper(sc);
system.assertEquals(1, bqh.quoteItems.size());
system.assertNotEquals(null, bqh.quoteItems[0].Id);
ApexPages.currentPage().getParameters().put('rowIndex', '0');
bqh.removeLine();
system.assertEquals(0, bqh.quoteItems.size());
// bqh.addLine();
bqh.customSave();
Test.stopTest();
qliList = [SELECT Quote__c, Height__c, Length__c, Weight__c, Width__c FROM Quote_Line_Item__c WHERE Quote__c = : qt.Id];
// system.assertEquals(0,qliList.size());
}
public static testMethod void test_createQuoteFromBooking(){
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaCol.Postcode__c = 'BB1 BB1';
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
Contact c = TestUtil.createContact(a.Id);
insert c;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Coll_Account_Address__c = aaCol.Id;
bo.Del_Account_Address__c = aaDel.Id;
bo.Order_Contact__c = c.Id;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.OC_Email_Address__c = '<EMAIL>';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Coll_Postcode__c = 'BB1 BB1';
bo.Del_Postcode__c = 'BB1 AA1';
bo.Collection_Ready_Time__c = DateTime.now();
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Booking_Line_Item__c bli = new Booking_Line_Item__c();
bli.Number_of_items__c = 1;
bli.Height__c = 10;
bli.Length__c = 10;
bli.Weight__c = 10;
bli.Width__c = 10;
bli.Booking__c = bo.Id;
insert bli;
ApexPages.currentPage().getParameters().put('bId', bo.Id);
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(new Quote__c());
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();
Quote__c q = [SELECT Account__c FROM Quote__c LIMIT 1];
system.assertEquals(a.Id, q.Account__c);
List<Quote_Line_Item__c> qliList = [SELECT Quote__c, Height__c, Length__c, Weight__c, Width__c FROM Quote_Line_Item__c];
system.assertEquals(1,qliList.size());
}
public static testMethod void test_Addresses(){
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
insert aaDef;
Test.startTest();
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
system.AssertEquals(aaDef.Postcode__c,qt.Collection_Postcode__c);
system.assert(!qt.Carriage_Forward__c);
qt.Collection_Postcode__c = 'OO0 0OO';
bqh.collectionPostcodeChanged();
system.AssertEquals(aaDef.Postcode__c,qt.Delivery_Postcode__c);
system.assert(qt.Carriage_Forward__c);
qt.Collection_Postcode__c = aaDef.Postcode__c;
bqh.collectionPostcodeChanged();
system.AssertEquals(null,qt.Delivery_Postcode__c);
system.assert(!qt.Carriage_Forward__c);
bqh.clearAccount();
Test.stopTest();
}
/*public static testMethod void testEditBtnBooking()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Account_Address__c aa = TestUtil.createAccountAddress(a.Id, c.Id);
insert aa;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = c.Id;
bo.Account_Address__c = aa.Id;
insert bo;
bo = [select Id from Booking__c LIMIT 1];
Booking_Line_Item__c bli = new Booking_Line_Item__c();
bli.Height__c = 10;
bli.Length__c = 10;
bli.Weight__c = 10;
bli.Width__c = 10;
bli.Booking__c = bo.Id;
bli.Consignment_Number__c = '111';
bli.Contact_Email_Address__c = '<EMAIL>';
bli.Contact_First_Name__c = 'Name';
bli.Contact_Last_Name__c = 'Surname';
bli.Contact_Phone__c = '07474567899';
insert bli;
Test.startTest();
ApexPages.currentPage().getParameters().put('oId', bo.Id);
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(new Booking__c());
OL_BookingQuoteHelper bqh = new OL_BookingQuoteHelper(sc);
bqh.customSave();
Test.stopTest();
system.assertEquals(2,[select count() from Booking__c]);
bo = [select Name from Booking__c WHERE Id != : bo.Id LIMIT 1];
system.assertEquals('test book - Copied', bo.Name);
List<Booking_Line_Item__c> bliList = [SELECT Booking__c, Height__c, Length__c, Weight__c, Width__c, Consignment_Number__c,
Contact_Email_Address__c, Contact_First_Name__c, Contact_Last_Name__c, Contact_Phone__c
FROM Booking_Line_Item__c WHERE Booking__c = : bo.Id];
system.assertEquals(1,bliList.size());
system.assertEquals(10, bliList[0].Height__c);
system.assertEquals(10, bliList[0].Length__c);
system.assertEquals(10, bliList[0].Weight__c);
system.assertEquals(10, bliList[0].Width__c);
system.assertNotEquals(bli.Id, bliList[0].Id);
}*/
}<file_sep>/classes/CS_Claims_Form_PDF_Controller.cls
/**
This controller is used for the PDF creation, for Claims email-templates.
**/
public with sharing class CS_Claims_Form_PDF_Controller {
public CS_Claims__c claims {get; set;}
public Id claimId {
get;
set{
if(value != null){
claims = getClaims(value);
}
}
}
public String emailId {
get{
return CS_TNT_Claims__c.getInstance().Email_Id__c;
}
}
public String address {
get{
return CS_TNT_Claims__c.getInstance().Claims_postal_address__c;
}
}
public String header {
get{
return CS_TNT_Claims__c.getInstance().Header__c;
}
}
public String Sender_section_title{
get{
return CS_TNT_Claims__c.getInstance().Sender_section_title__c;
}
}
public String Recipient_section_title{
get{
return CS_TNT_Claims__c.getInstance().Recipient_Section_title__c;
}
}
public String Claims_type_fieldset_label{
get{
return CS_TNT_Claims__c.getInstance().Claims_type_fieldset_label__c;
}
}
public String Claims_type_details_section_title{
get{
return CS_TNT_Claims__c.getInstance().Claims_type_details_section_title__c;
}
}
public String Claims_type_details_section_content{
get{
return CS_TNT_Claims__c.getInstance().Claims_type_details_section_content__c;
}
}
public String Claims_damaged_section_title{
get{
return CS_TNT_Claims__c.getInstance().Claims_damaged_section_title__c;
}
}
public String damaged_items_inspection_label{
get{
return CS_TNT_Claims__c.getInstance().damaged_items_inspection_label__c;
}
}
public String payment_method_label{
get{
return CS_TNT_Claims__c.getInstance().Method_of_payment_fieldset_label__c;
}
}
public String Declaration_section_title{
get{
return CS_TNT_Claims__c.getInstance().Declaration_section_title__c;
}
}
public String Cost_value_of_consignment_label{
get{
return CS_TNT_Claims__c.getInstance().Cost_value_of_consignment_label__c;
}
}
public String Cost_value_of_items_label{
get{
return CS_TNT_Claims__c.getInstance().Cost_value_of_items_label__c;
}
}
public String check_list_opt_1{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_1__c;
}
}
public String check_list_opt_2{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_2__c;
}
}
public String check_list_opt_3{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_3__c;
}
}
public String check_list_opt_4{
get{
return CS_TNT_Claims__c.getInstance().Check_list_opt_4__c;
}
}
public String replacement_consignement_no_label{
get{
return CS_TNT_Claims__c.getInstance().Replacement_consignment_no_Label__c;
}
}
public CS_Claims_Form_PDF_Controller(){
claims = getClaims(Apexpages.currentPage().getParameters().get('cid'));
system.debug('==>CLAIMSPDF ' + claims);
}
public CS_Claims__c getClaims(Id id){
CS_Claims__c cl = new CS_Claims__c();
try{
cl = [SELECT
Name,
Copy_of_relevant_commercial_invoice__c,
Copy_of_repair_estimate__c,
Sender_Address_1__c,
Recipient_Address_1__c,
Sender_Address_2__c,
Recipient_Address_2__c,
Sender_Address_3__c,
Recipient_Address_3__c,
All_requested_information__c,
cheque__c,
Claims_Stage__c,
Sender_company_name__c,
Consignment_no__c,
Sender_Contact_Name__c,
Recipient_Contact_Name__c,
Cost_of_consignment_exclcuding_VAT__c,
Cost_of_items_exclcuding_VAT__c,
Credit_your_TNT_account__c,
Sender_Email_Address__c,
Damaged__c,
Declarant_Date__c,
Date_of_dispatch__c,
Depot_no__c,
Detail_description_of_items__c,
Declarant_Full_Name_of__c,
damaged_packing_inspection__c,
Lost__c,
photographs_of_the_items__c,
Sender_Postcode__c,
Recipient_Postcode__c,
Reference_no__c,
Salvage_value__c,
Sender_Telephone_no__c,
Recipient_Telephone_no__c,
TNT_account_no__c,
Weight_of_items__c,
Repair_cost__c,
Replacement_Consignment_No__c
FROM CS_Claims__c
WHERE
id=: id
];
}catch(Exception e){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'If this error persists please contact TNT Customer care for further help. ERROR:' + e.getMessage()));
}
return cl;
}
}<file_sep>/email/Campaigns/Speech_Self_Service_Pack.email-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<EmailTemplate xmlns="http://soap.sforce.com/2006/04/metadata">
<available>true</available>
<description>Used to send SSS pack to contacts who respond to Campaigns</description>
<encodingKey>ISO-8859-1</encodingKey>
<letterhead>TNT_People_Network</letterhead>
<name>Speech Self Service Pack</name>
<style>freeForm</style>
<subject>TNT Speech Self Service Promo</subject>
<textOnly>Hi,
Thanks for your interest in our Speech Self Service facility.
Attached to this email is our welcome pack. It contains everything you need to get started using SSS.
Main features:
Automated Booking Service
Auotmated Consignment tracking Service
If you have any questions regarding this please call Domestic Customer Service on 0800 100 600 quoting your name.
For more information on all TNT services including tracking your consignment, please visit www.tnt.co.uk.
Yours sincerely,
TNT Domestic Customer Service</textOnly>
<type>html</type>
</EmailTemplate>
<file_sep>/classes/BookingHistory_DataDeletion_Tests.cls
@isTest//(SeeAllData=true)
private class BookingHistory_DataDeletion_Tests
{
static testMethod void DataDeletionTest()
{
Booking__c myBooking = new Booking__c();
myBooking.Commodity__c = 'Envelope';
insert myBooking;
List<Booking__c> value = [Select id from Booking__c];
string bookingID;
for (Booking__c record : value )
{
if (record.Id != null)
{
bookingID = record.Id;
}
}
Booking_History__c myBookingHistory = new Booking_History__c();
myBookingHistory.Movement_Date_Time__c = date.newInstance(2015, 08, 01);
myBookingHistory.Booking__c = bookingID;
insert myBookingHistory;
System.debug(logginglevel.ERROR, '££££££££££££££ myBookingHistory1 is' + myBookingHistory.Movement_Date_Time__c);
Booking_History__c myBookingHistory2 = new Booking_History__c();
myBookingHistory2.Movement_Date_Time__c = date.newInstance(2013, 01, 01);
myBookingHistory2.Booking__c = bookingID;
insert myBookingHistory2;
System.debug(logginglevel.ERROR, '££££££££££££££ myBookingHistory2 is' + myBookingHistory2.Movement_Date_Time__c);
Booking_History__c myBookingHistory3 = new Booking_History__c();
myBookingHistory3.Movement_Date_Time__c = date.newInstance(2014, 01, 01);
myBookingHistory3.Booking__c = bookingID;
insert myBookingHistory3;
System.debug(logginglevel.ERROR, '££££££££££££££ myBookingHistory3 is' + myBookingHistory3.Movement_Date_Time__c);
Test.startTest();
BookingHistory_DataDeletion dd = new BookingHistory_DataDeletion();
SchedulableContext sc;
dd.execute(sc);
List<Booking_History__c> bookingHistory = [Select id, Movement_Date_Time__c from Booking_History__c];
integer i = 0;
for (Booking_History__c record : bookingHistory )
{
if (record.Id != null)
{
System.debug(logginglevel.ERROR, '££££££££££££££ existing record is' + record.Movement_Date_Time__c);
i = i+1;
}
}
Test.stopTest();
//System.assertEquals(1, i);
}
}<file_sep>/reportTypes/Contacts_with_Quotes_and_Bookings.reportType
<?xml version="1.0" encoding="UTF-8"?>
<ReportType xmlns="http://soap.sforce.com/2006/04/metadata">
<baseObject>Contact</baseObject>
<category>other</category>
<deployed>false</deployed>
<description>Used so that agents can follow up with contacts for unconverted quotes etc</description>
<join>
<join>
<outerJoin>false</outerJoin>
<relationship>Bookings__r</relationship>
</join>
<outerJoin>false</outerJoin>
<relationship>Quotes__r</relationship>
</join>
<label>Contacts with Quotes & Bookings</label>
<sections>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Account</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Account_Number__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CanAllowPortalSelfReg</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>AssistantName</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>AssistantPhone</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Authorized_for_bookings__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Authorized_to_see_rates__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Birthdate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CleanStatus</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Id</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Contact_Number__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Owner</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CreatedBy</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CreatedDate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Jigsaw</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Department</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Description</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DoNotCall</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Email</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>EmailBouncedDate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>EmailBouncedReason</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>HasOptedOutOfEmail</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Fax</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>HasOptedOutOfFax</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>FirstName</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>true</checkedByDefault>
<field>Name</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>HomePhone</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastActivityDate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastModifiedBy</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastModifiedDate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastName</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastCURequestDate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastCUUpdateDate</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LeadSource</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingAddress</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingCity</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingCountry</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingLatitude</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingLongitude</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingState</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingStreet</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MailingPostalCode</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Middle_Initials__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>MobilePhone</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>NVMContactWorld__NVM_Asst_Phone__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>NVMContactWorld__NVM_Home_Phone__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>NVMContactWorld__NVM_Mobile__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>NVMContactWorld__NVM_Other_Phone__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>NVMContactWorld__NVM_Phone__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherAddress</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherCity</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherCountry</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherLatitude</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherLongitude</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherPhone</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherState</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherStreet</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OtherPostalCode</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Phone</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Phone_Extension__c</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>ReportsTo</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Salutation</field>
<table>Contact</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Title</field>
<table>Contact</table>
</columns>
<masterLabel>Contacts</masterLabel>
</sections>
<sections>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Account__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Account_Number__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Carriage_Forward__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Postcode__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Date__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Company_Name__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Company_Phone__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Contact_Email__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Contact_First_Name__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Contact_Last_Name__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Contact_Phone__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CreatedBy</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CreatedDate</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Dangerous_Goods__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Delivery_Postcode__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Delivery_Town__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Delivery_Date__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Items_Description__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Email_Only__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Email_the_quote__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Enhanced_Liability_Option__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Fuel_Supplement__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Is_Guaranteed_Service__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Is_Premium_Service__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastActivityDate</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastModifiedBy</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastModifiedDate</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>No_Long_Length_Items__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Owner</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Pallet_Pollicy__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Price__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Validation_Deadline__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Id</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Quote_is_Valid__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>true</checkedByDefault>
<field>Name</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>RecordType</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Service_Name__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Special_Instructions__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Supplements_Details__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Number_of_Items__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Volume__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Volume_Rounded__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Weight__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Commodity__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Value__c</field>
<table>Contact.Quotes__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Volumetric_Weight__c</field>
<table>Contact.Quotes__r</table>
</columns>
<masterLabel>Quotes</masterLabel>
</sections>
<sections>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Account__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Account_Address__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Account_Address__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Account_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Booking_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Booking_Id__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Id</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>true</checkedByDefault>
<field>Name</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Booking_Rejected_by_Depot__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Carriage_Forward__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_City__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_City__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Close_Time__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Confirmed__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Contact__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Email_Address__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Fax_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_First_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Last_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Middle_Initials__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Mobile_Phone_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Phone_Extension__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Phone_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CC_Title__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Depot__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Instructions__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Instructions_Comments__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Org_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Postcode__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Collection_Ready_Time__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Commercial_Invoice_Required__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Company_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Company_Phone__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Consignment_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Country__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Country__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_County__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_County__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CreatedBy</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>CreatedDate</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Customer_Reference__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Dangerous_Goods__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Delivery_Contact__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Email_Address__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Fax_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_First_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Last_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Middle_Initials__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Mobile_Phone_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Phone_Extension__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Phone_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>DC_Title__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Delivery_Depot__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Delivery_Instructions__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Org_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Postcode__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Routing_Table__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Depot_Routing__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Goods_Description__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_District__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_District__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Paperwork_Required__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Email_the_booking_reference__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Enhanced_Liability__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_1_Packing_Class__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_2_Packing_Class__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_3_Packing_Class__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_1_Quantity__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_2_Quantity__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_3_Quantity__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_1_Technical_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_2_Technical_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_3_Technical_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_1_UOM__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_2_UOM__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_3_UOM__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_1_UN_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_2_UN_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Hazchem_3_UN_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Is_Synchronisation_Failed__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastActivityDate</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastModifiedBy</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>LastModifiedDate</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Line_of_Business__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Master_Round_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>No_LOB_Ind__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Not_Collected_Reason__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Number_of_Consignments__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Order_Contact__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Email_Address__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Fax_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_First_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Last_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Middle_Initials__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Mobile_Phone_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Phone_Extension__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Phone_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>OC_Title__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Order_Reference_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Origin__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Origin_Depot__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Owner</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Premise_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Premise_Name__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Premise_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Premise_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Reason_for_Depot_Rejection__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>RecordType</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Reference_provided_by_customer__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Reg_Order_Number__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Service__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Special_Instructions__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Special_Instructions_for_the_Driver__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Status__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Street_1__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Street_1__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Street_2__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Street_2__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Coll_Sub_Premise__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Del_Sub_Premise__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Sub_Service__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Synchronisation_Error_Message__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Third_Party_Acknowledgement__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Items__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Volume__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Volume_m3__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Total_Weight__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Commodity__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Lunch_End__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Lunch_Start__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<columns>
<checkedByDefault>false</checkedByDefault>
<field>Value__c</field>
<table>Contact.Quotes__r.Bookings__r</table>
</columns>
<masterLabel>Bookings</masterLabel>
</sections>
</ReportType>
<file_sep>/classes/uksvcsTntComGenericObjects.cls
//Generated by wsdl2apex
public class uksvcsTntComGenericObjects {
}<file_sep>/classes/OL_BookingIntegrationUtil.cls
/**
* File Name : OL_BookingIntegrationUtil.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 03/09/2014 <NAME> TNT-1414
* 0.2 15/01/2015 <NAME> TNT-2038 add Invoice Address mapping
*/
global without sharing class OL_BookingIntegrationUtil {
WebService static String saveBookingToUniverse(String bkId){
String res;
String qry;
qry = OL_BookingQuoteHelper.getAllFieldsForObject(Booking__c.sObjectType.getDescribe())
+ ', Account__r.Account_Number__c, Routing_Table__r.Routing_Table__c'
+ ', Line_of_Business__r.Line_of_Business_Reference__c, Service__r.Service_Code__c, Collection_Depot__r.Depot_Number__c,'
+ ' (Select Movement_Type__c From Booking_History_Records__r) FROM Booking__c WHERE Id ' + ' = \''+bkId+'\'';
Booking__c bookWithData = Database.query(qry);
uksvcsTntComBookingService.createOrUpdatebookingPort port = new uksvcsTntComBookingService.createOrUpdatebookingPort();
port.inputHttpHeaders_x = new map<string,string> {'Username' => TNT_Integration__c.getInstance().Username__c,
'Password' => TNT_Integration__c.getInstance().Password__c};
uksvcsTntComGenericPayloadHeader.payloadHeader
hdr = new uksvcsTntComGenericPayloadHeader.payloadHeader();
uksvcsTntComBooking.bookingRequest_MasterType
bk = generateBookingRequest_MasterType(bookWithData);
bk.bkngItms = generateBookingItems(bookWithData.Id);
Booking_History__c bh = getBookingHistory(bookWithData);
bk.bkngUpds = generateBookingHistory(bh);
uksvcsTntComBooking.ResponseMessage_MasterType resp;
try{
if(!ConstantUtil.INTEGRATION_ACCESS) throw new ConstantUtil.IntegrationAccessDeniedException(ConstantUtil.INTEGRATION_EXMSG);
port.timeout_x = ConstantUtil.INTEGRATION_TIMEOUT;
resp = port.createOrUpdateBooking(hdr, bk);
bookWithData.Is_Synchronisation_Failed__c = false;
} catch(Exception ex) {
if(ex instanceof System.CalloutException || ex instanceof ConstantUtil.IntegrationAccessDeniedException)
{
bookWithData.Is_Synchronisation_Failed__c = true;
bookWithData.Synchronisation_Error_Message__c = ex.getMessage();
res = 'Synchronisation failed "' + ex.getMessage() + '"';
}
else
{
throw ex;
}
}
update bookWithData;
if(bh.Id == null){
insert bh;
}
return res;
}
private static uksvcsTntComBooking.bookingRequest_MasterType generateBookingRequest_MasterType(Booking__c bookWithData){
uksvcsTntComBooking.bookingRequest_MasterType bk = new uksvcsTntComBooking.bookingRequest_MasterType();
bk.bkngNum = bookWithData.booking_Id__c;
bk.actNum = bookWithData.Account__r.Account_Number__c;
bk.orgn = bookWithData.Origin__c;
bk.colAddrOrgNm = bookWithData.Coll_Org_Name__c;
bk.colAddrSubPrem = bookWithData.Coll_Sub_Premise__c;
bk.colAddrPremNum = bookWithData.Coll_Premise_Number__c;
bk.colAddrPremNm = bookWithData.Coll_Premise_Name__c;
bk.colAddrStrAddr1 = bookWithData.Coll_Street_1__c;
bk.colAddrStrAddr2 = bookWithData.Coll_Street_2__c;
//bk.colAddrStrAddr3 = bookWithData.Coll_Street_3__c; // fields removed
//bk.colAddrStrAddr4 = bookWithData.Coll_Street_4__c; // fields removed
bk.colAddrDstct = bookWithData.Coll_District__c;
bk.colAddrTwn = bookWithData.Coll_City__c;
bk.colAddrCnty = bookWithData.Coll_County__c;
bk.colAddrCntry = bookWithData.Coll_Country__c;
bk.colAddrPstCd = bookWithData.Coll_Postcode__c;
bk.ordConTtl = bookWithData.OC_Title__c;
bk.ordConFstNm = bookWithData.OC_First_Name__c;
bk.ordConMidIntls = bookWithData.OC_Middle_Initials__c;
bk.ordConLstNm = bookWithData.OC_Last_Name__c;
bk.ordConPhNum = bookWithData.OC_Phone_Number__c;
bk.ordConPhNumExt = bookWithData.OC_Phone_Extension__c;
bk.ordConFaxNum = bookWithData.OC_Fax_Number__c;
bk.ordConMobNum = bookWithData.OC_Mobile_Phone_Number__c;
bk.ordConEmailAddr = bookWithData.OC_Email_Address__c;
bk.colConTtl = bookWithData.CC_Title__c;
bk.colConFstNm = bookWithData.CC_First_Name__c;
bk.colConMidIntls = bookWithData.CC_Middle_Initials__c;
bk.colConLstNm = bookWithData.CC_Last_Name__c;
bk.colConPhNum = bookWithData.CC_Phone_Number__c;
bk.colConPhNumExt = bookWithData.CC_Phone_Extension__c;
bk.colConFaxNum = bookWithData.CC_Fax_Number__c;
bk.colConMobNum = bookWithData.CC_Mobile_Phone_Number__c;
bk.colConEmailAddr = bookWithData.CC_Email_Address__c;
bk.colDep = (bookWithData.Collection_Depot__c != null ? bookWithData.Collection_Depot__r.Depot_Number__c : null);
bk.custRef = bookWithData.Customer_Reference__c;
bk.lobRef = (bookWithData.Line_of_Business__c != null ? bookWithData.Line_of_Business__r.Line_of_Business_Reference__c : null);
bk.mstrRnd = String.valueOf((bookWithData.Master_Round_Number__c != null ? bookWithData.Master_Round_Number__c : 0));
bk.ordNum = bookWithData.Reg_Order_Number__c;
bk.svcCd = (bookWithData.Service__c != null ? bookWithData.Service__r.Service_Code__c : null);
bk.bkngSts = bookWithData.Status__c;
bk.cmm = bookWithData.Commodity__c;
bk.crgFwd = bookWithData.Carriage_Forward__c;
bk.clsTm = bookWithData.Close_Time__c;
bk.colRdyTm = bookWithData.Collection_Ready_Time__c;
bk.lnchStTm = bookWithData.Lunch_Start__c;
bk.lnchEndTm = bookWithData.Lunch_End__c;
bk.numItms = String.valueOf((bookWithData.Total_Items__c != null ? bookWithData.Total_Items__c : 0));
bk.totWght = String.valueOf(bookWithData.Total_Weight__c);
bk.wghtUOM = 'KG';
bk.numCons = String.valueOf((bookWithData.Number_of_Consignments__c != null ? bookWithData.Number_of_Consignments__c : 1));
bk.trnsLiabLvl = bookWithData.Enhanced_Liability__c;
bk.dgInd = bookWithData.Dangerous_Goods__c;
bk.hazChemCd1 = bookWithData.Hazchem_1_UN_Number__c;
// bk.dgSeq1 = bookWithData.;
bk.hazChemPck1 = bookWithData.Hazchem_1_Packing_Class__c;
bk.hazChemQty1 = String.valueOf(bookWithData.Hazchem_1_Quantity__c);
bk.hazChemUOM1 = bookWithData.Hazchem_1_UOM__c;
bk.hazChemTechNm1 = bookWithData.Hazchem_1_Technical_Name__c;
bk.hazChemCd2 = bookWithData.Hazchem_2_UN_Number__c;
// bk.dgSeq2 = bookWithData.;
bk.hazChemPck2 = bookWithData.Hazchem_2_Packing_Class__c;
bk.hazChemQty2 = String.valueOf(bookWithData.Hazchem_2_Quantity__c);
bk.hazChemUOM2 = bookWithData.Hazchem_2_UOM__c;
bk.hazChemTechNm2 = bookWithData.Hazchem_2_Technical_Name__c;
bk.hazChemCd3 = bookWithData.Hazchem_3_UN_Number__c;
// bk.dgSeq3 = bookWithData.;
bk.hazChemPck3 = bookWithData.Hazchem_3_Packing_Class__c;
bk.hazChemQty3 = String.valueOf(bookWithData.Hazchem_3_Quantity__c);
bk.hazChemUOM3 = bookWithData.Hazchem_3_UOM__c;
bk.hazChemTechNm3 = bookWithData.Hazchem_3_Technical_Name__c;
bk.pprWrkInd = bookWithData.Paperwork_Required__c;
bk.colIns = bookWithData.Collection_Instructions__c;
bk.noLOBAct = bookWithData.No_LOB_Ind__c;
bk.gdsDesc = bookWithData.Goods_Description__c != null ? bookWithData.Goods_Description__c : null;
bk.totColVol = String.valueOf(bookWithData.Total_Volume__c != null ? bookWithData.Total_Volume__c.intValue() : null);
bk.comInvReq = bookWithData.Commercial_Invoice_Required__c;
// bk.delDepBndryRef = bookWithData.;
bk.colDepBndryRef = (bookWithData.Routing_Table__c != null ? bookWithData.Routing_Table__r.Routing_Table__c : null);
bk.delIns = bookWithData.Delivery_Instructions__c;
bk.tntConsNum = bookWithData.Consignment_Number__c;
bk.delAddrOrgNm = bookWithData.Del_Org_Name__c;
bk.delAddrSubPrem = bookWithData.Del_Sub_Premise__c;
bk.delAddrPremNum = bookWithData.Del_Premise_Number__c;
bk.delAddrPremNm = bookWithData.Del_Premise_Name__c;
bk.delAddrStrAddr1 = bookWithData.Del_Street_1__c;
bk.delAddrStrAddr2 = bookWithData.Del_Street_2__c;
//bk.delAddrStrAddr3 = bookWithData.Del_Street_3__c; // fields removed
//bk.delAddrStrAddr4 = bookWithData.Del_Street_4__c; // fields removed
bk.delAddrDstct = bookWithData.Del_District__c;
bk.delAddrTwn = bookWithData.Del_City__c;
bk.delAddrCnty = bookWithData.Del_County__c;
bk.delAddrCntry = bookWithData.Del_Country__c;
bk.delAddrPstCd = bookWithData.Del_Postcode__c;
bk.delConTtl = bookWithData.DC_Title__c;
bk.delConFstNm = bookWithData.DC_First_Name__c;
bk.delConMidIntls = bookWithData.DC_Middle_Initials__c;
bk.delConLstNm = bookWithData.DC_Last_Name__c;
bk.delConPhNum = bookWithData.DC_Phone_Number__c;
bk.delConPhNumExt = bookWithData.DC_Phone_Extension__c;
bk.delConFaxNum = bookWithData.DC_Fax_Number__c;
bk.delConMobNum = bookWithData.DC_Mobile_Phone_Number__c;
bk.delConEmailAddr = bookWithData.DC_Email_Address__c;
bk.crtDtTm = bookWithData.CreatedDate;
//Invoice Address mapping
bk.invAddrOrgNm = bookWithData.Inv_Org_Name__c;
bk.invAddrSubPrem = bookWithData.Inv_Sub_Premise__c;
bk.invAddrPremNm = bookWithData.Inv_Premise_Name__c;
bk.invAddrPremNum = bookWithData.Inv_Premise_Number__c;
bk.invAddrStrAddr1 = bookWithData.Inv_Street_1__c;
bk.invAddrStrAddr2 = bookWithData.Inv_Street_2__c;
bk.invAddrTwn = bookWithData.Inv_City__c;
bk.invAddrDstct = bookWithData.Inv_District__c;
bk.invAddrCnty = bookWithData.Inv_County__c;
bk.invAddrPstCd = bookWithData.Inv_Postcode__c;
bk.invAddrPhone = bookWithData.Inv_Phone__c;
bk.invAddrEmail = bookWithData.Inv_Email__c;
return bk;
}
private static uksvcsTntComBooking.BookingItems_ContainerType generateBookingItems(String bkId){
List<uksvcsTntComBooking.BookingItem_MasterType> items = new List<uksvcsTntComBooking.BookingItem_MasterType>();
for(Booking_Line_Item__c bli : [SELECT Booking_Line_Item_Id__c, Number_of_Items__c, Length__c,
Width__c, Height__c FROM Booking_Line_Item__c WHERE Booking__c = : bkId
ORDER BY Serial_number__c]){
if(bli.Id != null){
uksvcsTntComBooking.BookingItem_MasterType itm = new uksvcsTntComBooking.BookingItem_MasterType();
itm.itmId = bli.Booking_Line_Item_Id__c;
itm.numItms = String.valueOf(bli.Number_of_Items__c);
itm.len = bli.Length__c != null ? String.valueOf(bli.Length__c) : '0';
itm.wdth = bli.Width__c != null ? String.valueOf(bli.Width__c) : '0';
itm.hght = bli.Height__c != null ? String.valueOf(bli.Height__c) : '0';
itm.lenUOM = 'CM';
items.add(itm);
}
}
uksvcsTntComBooking.BookingItems_ContainerType bkngItms = new uksvcsTntComBooking.BookingItems_ContainerType();
bkngItms.bkngItm = items;
return bkngItms;
}
private static Booking_History__c getBookingHistory(Booking__c book){
Booking_History__c bh;
if(book.Is_Synchronisation_Failed__c){
//get last history line
bh = [SELECT User_Id__c, Movement_Type__c, Movement_Sub_Type__c, Movement_Round__c, Movement_Date_Time__c,
Depot__c, Depot__r.AccountNumber, Call_Centre__c, Change_Details__c, Collection_Comments__c
FROM Booking_History__c
WHERE Booking__c = : book.Id AND (Movement_Type__c = : ConstantUtil.PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_RAISED
OR Movement_Type__c = : ConstantUtil.PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_AMENDED)
ORDER BY CreatedDate DESC LIMIT 1];
} else {
//create new one
bh = new Booking_History__c();
bh.Booking__c = book.Id;
bh.Call_Centre__c = true;
bh.Movement_Date_Time__c = DateTime.now();
bh.User_Id__c = getUserAlias(UserInfo.getUserId());
if(book.Booking_History_Records__r != null && !book.Booking_History_Records__r.isEmpty()){
bh.Movement_Type__c = ConstantUtil.PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_AMENDED;
} else {
bh.Movement_Type__c = ConstantUtil.PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_RAISED;
book.Status__c = String.isBlank(book.Status__c) ? ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED : book.Status__c;
}
}
return bh;
}
private static uksvcsTntComBooking.BookingUpdates_ContainerType generateBookingHistory(Booking_History__c bh){
List<uksvcsTntComBooking.BookingUpdate_MasterType> bh_items = new List<uksvcsTntComBooking.BookingUpdate_MasterType>();
uksvcsTntComBooking.BookingUpdate_MasterType itm = new uksvcsTntComBooking.BookingUpdate_MasterType();
itm.mvntDtTm = bh.Movement_Date_Time__c;
itm.mvntDep = Label.Salesforce_Start_Depot;
itm.mvntTypCd = bh.Movement_Type__c;
itm.callCntr = bh.Call_Centre__c;
itm.lstUpdBy = bh.User_Id__c;
bh_items.add(itm);
uksvcsTntComBooking.BookingUpdates_ContainerType bkngUpds = new uksvcsTntComBooking.BookingUpdates_ContainerType();
bkngUpds.bkngUpd = bh_items;
return bkngUpds;
}
private static String getUserAlias(Id uId){
String res;
User u = [Select Alias From User WHERE Id = : uId];
res = u.Alias;
return res;
}
}<file_sep>/objects/LOB_Service__c.object
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<actionOverrides>
<actionName>Accept</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>CancelEdit</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>Clone</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>Delete</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>Edit</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>Follow</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>List</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>New</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>SaveEdit</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>Tab</actionName>
<type>Default</type>
</actionOverrides>
<actionOverrides>
<actionName>View</actionName>
<type>Default</type>
</actionOverrides>
<compactLayoutAssignment>SYSTEM</compactLayoutAssignment>
<deploymentStatus>Deployed</deploymentStatus>
<enableActivities>false</enableActivities>
<enableBulkApi>true</enableBulkApi>
<enableFeeds>false</enableFeeds>
<enableHistory>false</enableHistory>
<enableReports>false</enableReports>
<enableSharing>true</enableSharing>
<enableStreamingApi>true</enableStreamingApi>
<fields>
<fullName>Active__c</fullName>
<defaultValue>true</defaultValue>
<description>Indicates that the service is either active or inactive for the line of business. A status of active allows that service to be selected on a booking.</description>
<externalId>false</externalId>
<label>Active</label>
<trackTrending>false</trackTrending>
<type>Checkbox</type>
</fields>
<fields>
<fullName>LOB_Service_Key__c</fullName>
<caseSensitive>true</caseSensitive>
<externalId>true</externalId>
<label>LOB Service Key</label>
<length>7</length>
<required>false</required>
<trackTrending>false</trackTrending>
<type>Text</type>
<unique>true</unique>
</fields>
<fields>
<fullName>Line_of_Business__c</fullName>
<externalId>false</externalId>
<label>Line of Business</label>
<referenceTo>Line_of_Business__c</referenceTo>
<relationshipLabel>LOBs Services</relationshipLabel>
<relationshipName>LOBs_Services</relationshipName>
<relationshipOrder>0</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<trackTrending>false</trackTrending>
<type>MasterDetail</type>
<writeRequiresMasterRead>false</writeRequiresMasterRead>
</fields>
<fields>
<fullName>Service__c</fullName>
<externalId>false</externalId>
<label>Service</label>
<referenceTo>Service__c</referenceTo>
<relationshipLabel>LOBs Services</relationshipLabel>
<relationshipName>LOBs_Services</relationshipName>
<relationshipOrder>1</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<trackTrending>false</trackTrending>
<type>MasterDetail</type>
<writeRequiresMasterRead>false</writeRequiresMasterRead>
</fields>
<label>LOB Service</label>
<nameField>
<displayFormat>LOBS-{00000}</displayFormat>
<label>LOB Service Name</label>
<type>AutoNumber</type>
</nameField>
<pluralLabel>LOBs Services</pluralLabel>
<searchLayouts/>
<sharingModel>ControlledByParent</sharingModel>
</CustomObject>
<file_sep>/README.md
# SimpleFragment
Code for my project test
<file_sep>/classes/uksvcsTntGetQuotePricing.cls
//Generated by wsdl2apex
public class uksvcsTntGetQuotePricing {
public class RequestMessage_MasterType {
public uksvcsTntComGenericPayloadHeader.payloadHeader hdr;
public uksvcsTntGetQuotePricing.QuoteRequest_MasterType qt;
private String[] hdr_type_info = new String[]{'hdr','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] qt_type_info = new String[]{'qt','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'hdr','qt'};
}
public class QuoteRequest_MasterType {
public String qtNum;
public String actNum;
public Date rqstdColDt;
public String colPstCd;
public String delPstCd;
public String totItms;
public String totVol;
public String totActWght;
public String wghtUOM;
public Boolean hazGdInd;
public Boolean plltInd;
public Boolean crrgFwdInd;
public Boolean enhLbltyInd;
public String fuelSrchrg;
public String LongLengths;
private String[] qtNum_type_info = new String[]{'qtNum','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] actNum_type_info = new String[]{'actNum','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] rqstdColDt_type_info = new String[]{'rqstdColDt','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] colPstCd_type_info = new String[]{'colPstCd','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] delPstCd_type_info = new String[]{'delPstCd','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] totItms_type_info = new String[]{'totItms','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] totVol_type_info = new String[]{'totVol','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] totActWght_type_info = new String[]{'totActWght','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] wghtUOM_type_info = new String[]{'wghtUOM','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] hazGdInd_type_info = new String[]{'hazGdInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] plltInd_type_info = new String[]{'plltInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] crrgFwdInd_type_info = new String[]{'crrgFwdInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] enhLbltyInd_type_info = new String[]{'enhLbltyInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] fuelSrchrg_type_info = new String[]{'fuelSrchrg','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] LongLengths_type_info = new String[]{'LongLengths','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'qtNum','actNum','rqstdColDt','colPstCd','delPstCd','totItms','totVol','totActWght','wghtUOM','hazGdInd','plltInd','crrgFwdInd','enhLbltyInd','fuelSrchrg','LongLengths'};
}
public class Surcharge_MasterType {
public String srchrgTypCd {get; set;}
public String srchrgTypNm {get; set;}
public String chrgAmt {get; set;}
public String curCd {get; set;}
public String chrgPrcnt {get; set;}
private String[] srchrgTypCd_type_info = new String[]{'srchrgTypCd','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] srchrgTypNm_type_info = new String[]{'srchrgTypNm','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] chrgAmt_type_info = new String[]{'chrgAmt','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] curCd_type_info = new String[]{'curCd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] chrgPrcnt_type_info = new String[]{'chrgPrcnt','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'srchrgTypCd','srchrgTypNm','chrgAmt','curCd','chrgPrcnt'};
}
public class DeliveryServices_ContainerType {
public uksvcsTntGetQuotePricing.DeliveryService_MasterType[] delSvc {get; set;}
private String[] delSvc_type_info = new String[]{'delSvc','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'delSvc'};
}
public class DeliveryService_MasterType {
public Boolean selected {get; set;}
public String svcCd {get; set;}
public String cmm {get; set;}
public String qtAmt {get; set;}
public String curCd {get; set;}
public Boolean prSvcInd {get; set;}
public Boolean guarSvcInd {get; set;}
public String discAmt {get; set;}
public uksvcsTntGetQuotePricing.Surcharges_ContainerType srchrgs {get; set;}
private String[] svcCd_type_info = new String[]{'svcCd','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] cmm_type_info = new String[]{'cmm','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] qtAmt_type_info = new String[]{'qtAmt','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] curCd_type_info = new String[]{'curCd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] prSvcInd_type_info = new String[]{'prSvcInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] guarSvcInd_type_info = new String[]{'guarSvcInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] discAmt_type_info = new String[]{'discAmt','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] srchrgs_type_info = new String[]{'srchrgs','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'svcCd','cmm','qtAmt','curCd','prSvcInd','guarSvcInd','discAmt','srchrgs'};
}
public class Deliveries_ContainerType {
public uksvcsTntGetQuotePricing.Delivery_MasterType[] del {get; set;}
private String[] del_type_info = new String[]{'del','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'del'};
}
public class Delivery_MasterType {
public Boolean selected {get; set;}
public Date delDt {get; set;}
public uksvcsTntGetQuotePricing.DeliveryServices_ContainerType delSvcs {get; set;}
private String[] delDt_type_info = new String[]{'delDt','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] delSvcs_type_info = new String[]{'delSvcs','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'delDt','delSvcs'};
}
public class QuoteResponse_MasterType {
public String qtNum;
public String actNm;
public Date avlColDt;
public DateTime qtRqstdDtTm;
public String colDpt;
public String lobRef;
public Boolean enhLbltyInd;
public Boolean hazGdsAlwdInd;
public String ntTyp;
public String options;
public String wghtTyp;
public String rtngDep;
public String rtGrpDesc;
public String pstCdCat;
public uksvcsTntGetQuotePricing.Deliveries_ContainerType dels;
private String[] qtNum_type_info = new String[]{'qtNum','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] actNm_type_info = new String[]{'actNm','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] avlColDt_type_info = new String[]{'avlColDt','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] qtRqstdDtTm_type_info = new String[]{'qtRqstdDtTm','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] colDpt_type_info = new String[]{'colDpt','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] lobRef_type_info = new String[]{'lobRef','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] enhLbltyInd_type_info = new String[]{'enhLbltyInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] hazGdsAlwdInd_type_info = new String[]{'hazGdsAlwdInd','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] ntTyp_type_info = new String[]{'ntTyp','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] options_type_info = new String[]{'options','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] wghtTyp_type_info = new String[]{'wghtTyp','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] rtngDep_type_info = new String[]{'rtngDep','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] rtGrpDesc_type_info = new String[]{'rtGrpDesc','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] pstCdCat_type_info = new String[]{'pstCdCat','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] dels_type_info = new String[]{'dels','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'qtNum','actNm','avlColDt','qtRqstdDtTm','colDpt','lobRef','enhLbltyInd','hazGdsAlwdInd','ntTyp','options','wghtTyp','rtngDep','rtGrpDesc','pstCdCat','dels'};
}
public class Surcharges_ContainerType {
public uksvcsTntGetQuotePricing.Surcharge_MasterType[] srchrg {get; set;}
private String[] srchrg_type_info = new String[]{'srchrg','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'srchrg'};
}
public class ResponseMessage_MasterType {
public uksvcsTntComGenericPayloadHeader.payloadHeader hdr;
public uksvcsTntGetQuotePricing.QuoteResponse_MasterType qt;
private String[] hdr_type_info = new String[]{'hdr','http://express.tnt.com/service/schema/gpdfq/v1',null,'1','1','false'};
private String[] qt_type_info = new String[]{'qt','http://express.tnt.com/service/schema/gpdfq/v1',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://express.tnt.com/service/schema/gpdfq/v1','false','false'};
private String[] field_order_type_info = new String[]{'hdr','qt'};
}
}<file_sep>/classes/OL_GetQuotePricingDetailsExtensionTest.cls
/**
* File Name : OL_GetQuotePricingDetailsExtensionTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 11/08/2014 <NAME> Initial version
*
*
*/
@isTest
private class OL_GetQuotePricingDetailsExtensionTest {
static testMethod void testExceptions(){
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Postcode__c = 'aa111a';
qt.Delivery_Postcode__c = 'aa111a';
insert qt;
Quote_Line_Item__c qli = new Quote_Line_Item__c();
qli.Number_of_Items__c = 1;
qli.Height__c = 10;
qli.Length__c = 10;
qli.Weight__c = 10;
qli.Width__c = 10;
qli.Quote__c = qt.Id;
insert qli;
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_GetQuotePricingDetailsExtension cont = new OL_GetQuotePricingDetailsExtension(sc);
cont.requestPrice();
List<Apexpages.Message> msgs = ApexPages.getMessages();
system.assertEquals(1, msgs.size());
cont.savePrice();
msgs = ApexPages.getMessages();
system.assertEquals(2, msgs.size());
cont.cancel();
}
static testMethod void testService(){
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Postcode__c = 'aa111a';
qt.Delivery_Postcode__c = 'aa111a';
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(qt);
OL_GetQuotePricingDetailsExtension cont = new OL_GetQuotePricingDetailsExtension(sc);
Test.startTest();
cont.quote = qt;
Test.setMock(WebServiceMock.class, new uksvcsTntGetQuotePricingServiceMockImpl());
cont.requestPrice();
cont.savePrice();
cont.responceData.del[0].selected = true;
cont.responceData.del[0].delSvcs.delSvc[0].selected = true;
cont.savePrice();
Test.stopTest();
qt = [SELECT Price__c FROM Quote__c LIMIT 1];
system.assertEquals(50.45, qt.Price__c);
}
static testMethod void cover_uksvcsTntComGenericPayloadHeader(){
uksvcsTntComGenericPayloadHeader.search_x s = new uksvcsTntComGenericPayloadHeader.search_x();
}
}<file_sep>/classes/ContactTriggerHelper.cls
/**
* File Name : ContactTriggerHelper.cls
* Description : handler for contact trigger
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 21/07/2014 <NAME> Initial version (TNT-455)
* 0.2 21/08/2014 <NAME> TNT-1334
*
*/
public with sharing class ContactTriggerHelper {
// HANDLERS
public static void onAfterInsertHandler(List<Contact> triggerNew)
{
updateAccountContactObj(triggerNew, null);
}
public static void onAfterUpdateHandler(List<Contact> triggerNew, Map<Id,Contact> triggerOldMap)
{
updateAccountContactObj(triggerNew, triggerOldMap);
}
// METHODS
public static void updateAccountContactObj(List<Contact> contacts, Map<Id, Contact> oldContacts){
Map<Id, Id> new_contactIdToAccountId = new Map<Id, Id>();
Map<Id, Id> updated_contactIdToAccountId = new Map<Id, Id>();
Map<String, Account_Contact__c> aIdcId_AccountContacts = new Map<String, Account_Contact__c>();
List<Account_Contact__c> newAccountContacts = new List<Account_Contact__c>();
for(Contact c : contacts){
if(c.AccountId != null){
if(oldContacts == null){
new_contactIdToAccountId.put(c.Id, c.AccountId);
} else if(c.AccountId != oldContacts.get(c.Id).AccountId){
updated_contactIdToAccountId.put(c.Id, c.AccountId);
}
}
}
for(Account_Contact__c ac : [SELECT Account__c, Contact__c FROM Account_Contact__c
WHERE Contact__c IN : updated_contactIdToAccountId.keyset() AND Account__c IN : updated_contactIdToAccountId.values()]){
String key = (String)ac.Account__c + (String)ac.Contact__c;
aIdcId_AccountContacts.put(key, ac);
}
if(!new_contactIdToAccountId.isEmpty()){
for(String cId : new_contactIdToAccountId.keyset()){
Account_Contact__c ac = new Account_Contact__c();
ac.Account__c = new_contactIdToAccountId.get(cId);
ac.Contact__c = cId;
newAccountContacts.add(ac);
}
}
if(!updated_contactIdToAccountId.isEmpty()){
for(String cId : updated_contactIdToAccountId.keyset()){
String key = updated_contactIdToAccountId.get(cId) + cId;
if(!aIdcId_AccountContacts.containsKey(key)){
Account_Contact__c ac = new Account_Contact__c();
ac.Account__c = updated_contactIdToAccountId.get(cId);
ac.Contact__c = cId;
newAccountContacts.add(ac);
}
}
}
if(!newAccountContacts.isEmpty()){
insert newAccountContacts;
}
}
}<file_sep>/classes/OL_BookingExtensionTest.cls
/**
* File Name : OL_BookingExtensionTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 22/08/2014 <NAME> TNT-1560
* 0.2 28/08/2014 <NAME> TNT-1328
* 0.3 14/07/2015 <NAME>
*/
@isTest
private class OL_BookingExtensionTest {
public static List<Contact> createContacts(Id aId)
{
Contact co = TestUtil.createContact(aId);
co.LastName += 'CO';
co.Email += 'CO';
co.Phone += '1';
Contact cc = TestUtil.createContact(aId);
cc.LastName += 'CC';
cc.Email += 'CC';
cc.Phone += '2';
Contact cd = TestUtil.createContact(aId);
cd.LastName += 'CD';
cd.Email += 'CD';
cd.Phone += '3';
insert new List<Contact>{co,cc,cd};
return new List<Contact>{co,cc,cd};
}
public static List<Line_Of_Business__c> createLOBs(Id aId)
{
Line_Of_Business__c lob1 = new Line_Of_Business__c();
lob1.Name = 'LOB1';
lob1.Line_Of_Business_Reference__c = '10';
lob1.Commodities__c = 'SACK;CARTON;ROLL';
lob1.Routing_Network__c = 'EXP';
lob1.Active__c = true;
Line_Of_Business__c lob2 = new Line_Of_Business__c();
lob2.Name = 'LOB2';
lob2.Line_Of_Business_Reference__c = '20';
lob2.Commodities__c = 'SACK;CARTON;ROLL';
lob2.Routing_Network__c = 'EWW';
lob2.Active__c = true;
insert new List<Line_Of_Business__c>{lob1,lob2};
insert new List<Account_LOB__c>{new Account_LOB__c(Account__c = aId, Line_Of_Business__c = lob1.id),
new Account_LOB__c(Account__c = aId, Line_Of_Business__c = lob2.id)};
// add services
Service__c s1 = new Service__c();
s1.Name = 'Service 1';
s1.Service_Code__c = 'SER1';
s1.Active__c = true;
Service__c s2 = new Service__c();
s2.Name = 'Service 2';
s2.Service_Code__c = 'SER2';
s2.Active__c = true;
insert new List<Service__c>{s1,s2};
insert new List<LOB_Service__c>{
new LOB_Service__c(Line_Of_Business__c = lob1.id, Service__c = s1.id, Active__c = true),
new LOB_Service__c(Line_Of_Business__c = lob1.id, Service__c = s2.id, Active__c = true),
new LOB_Service__c(Line_Of_Business__c = lob2.id, Service__c = s1.id, Active__c = true)
};
return new List<Line_Of_Business__c>{lob1,lob2};
}
// TESTS
public static testMethod void testNewBooking()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
Test.startTest();
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.commercialInvoiceRequired = 'false';
bex.paperworkRequired = 'false';
system.assert(!bex.getHasLOBs());
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bo.Collection_Contact__c = cc.Id;
bex.loadContactValuesCC();
bo.Delivery_Contact__c = cd.Id;
bex.loadContactValuesDC();
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.aaIdCOL = aaCol.Id;
bex.aaIdDEL = aaDel.Id;
bex.loadAddressCOL();
bex.loadAddressDEL();
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
Test.stopTest();
system.assertEquals(1,[select count() from Booking__c
where Coll_Account_Address__c = :aaCol.Id and Del_Account_Address__c = :aaDel.id]);
}
public static testMethod void testEditBooking()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.Coll_Account_Address__c = aaCol.Id;
bo.Del_Account_Address__c = aaDel.Id;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.aaIdCOL = aaCol.Id;
bex.loadAddressCOL();
bex.aaIdDEL = aaDel.Id;
bex.loadAddressDEL();
bex.createContactOrd = true;
bex.createContactDel = true;
bex.createContactCol = true;
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
Test.stopTest();
List<Contact> cons = [select id from Contact order by Phone asc];
system.assertEquals(3,cons.size());
system.assertEquals(1,[select count() from Booking__c
where Coll_Account_Address__c = :aaCol.Id and Del_Account_Address__c = :aaDel.id
and Order_Contact__c = :cons.get(0).Id and Collection_Contact__c = :cons.get(1).Id and Delivery_Contact__c = :cons.get(2).Id]);
}
public static testMethod void testAddAddressesBookingNoAccount()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Company_Name__c ='test company';
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.Coll_Org_Name__c = aaCol.Org_Name__c;
bo.Coll_Street_1__c = aaCol.Street_1__c;
bo.Coll_Postcode__c = aaCol.Postcode__c;
bo.Coll_City__c = aaCol.City__c;
bo.Coll_Country__c = ConstantUtil.ISOCODE_UK;
bo.Del_Org_Name__c = aaDel.Org_Name__c;
bo.Del_Street_1__c = aaDel.Street_1__c;
bo.Del_Postcode__c = aaDel.Postcode__c;
bo.Del_City__c = aaDel.City__c;
bo.Del_Country__c = ConstantUtil.ISOCODE_UK;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.commercialInvoiceRequired = 'false';
bex.paperworkRequired = 'false';
bex.selectAccount();
system.assertEquals(OL_BookingExtension.newId,bex.aaIdCOL);
system.assertEquals(OL_BookingExtension.newId,bex.aaIdDEL);
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bo.Order_Contact__c = null;
bo.Collection_Contact__c = cc.Id;
bex.loadContactValuesCC();
bo.Collection_Contact__c = null;
bo.Delivery_Contact__c = cd.Id;
bex.loadContactValuesDC();
bo.Delivery_Contact__c = null;
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
Test.stopTest();
system.assertEquals(1,[select count() from Booking__c
where Account__c = null
and Coll_Postcode__c = :aaCol.Postcode__c
and Del_Postcode__c = :aaDel.Postcode__c]);
}
public static testMethod void testGBMailer()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Coll_Postcode__c = 'sw162jp';
bo.Del_Postcode__c = 'sw162jp';
bo.Inv_Postcode__c = 'sw162jp';
Test.startTest();
Test.setMock(WebServiceMock.class, new GBMailer_ServiceMockImpl());
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.commercialInvoiceRequired = 'true';
bex.paperworkRequired = 'true';
bex.getNoGBMailerCOL();
bex.getNoGBMailerDEL();
bex.getNoGBMailerINV();
bex.emptyAction();
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.aaIdCOL = OL_BookingExtension.newId;
bex.aaIdDEL = OL_BookingExtension.newId;
bex.pinpointPostcodeGBMailerCOL();
system.assertEquals(2,bex.getGBMAddressesCOL().size());
system.assert(!bex.getExceededGBMailerCOL());
bex.addressIndexStrCOL = '0';
bex.populateGBMailerAddressCOL();
bex.pinpointPostcodeGBMailerDEL();
system.assertEquals(2,bex.getGBMAddressesDEL().size());
system.assert(!bex.getExceededGBMailerDEL());
bex.addressIndexStrDEL = '0';
bex.populateGBMailerAddressDEL();
bex.pinpointPostcodeGBMailerINV();
system.assertEquals(2,bex.getGBMAddressesINV().size());
system.assert(!bex.getExceededGBMailerINV());
bex.addressIndexStrINV = '0';
bex.populateGBMailerAddressINV();
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
Test.stopTest();
system.assertEquals(1,[select count() from Booking__c
where Coll_Org_Name__c = 'Address Name'
and Del_Org_Name__c = 'Address Name'
and Inv_Org_Name__c = 'Address Name']);
}
public static testMethod void testOnStop()
{
Account a = TestUtil.createAccountClient();
a.On_Stop__c = true;
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Test.startTest();
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
system.assertNotEquals(null,bex.getAccountNotifications());
Test.stopTest();
}
public static testMethod void testAddAddressesBookingCarriageForward()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
Account_Address__c aaReg = TestUtil.createAccountAddress(a.Id,null);
aaReg.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaDef,aaReg};
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
system.assertEquals(aaDef.Id,bex.aaDefId);
system.assertEquals(aaDef.Id,bex.aaIdCOL);
system.assertEquals(null,bex.aaIdDEL);
system.assert(!bo.Carriage_Forward__c);
bex.aaIdCOL = aaReg.Id;
bex.loadAddressCOL();
system.assertEquals(aaDef.Id,bex.aaIdDEL);
system.assert(bo.Carriage_Forward__c);
bex.aaIdCOL = aaDEF.Id;
bex.loadAddressCOL();
system.assertEquals(null,bex.aaIdDEL);
system.assert(!bo.Carriage_Forward__c);
bex.aaIdDEL = OL_BookingExtension.newId;
bex.loadAddressDEL();
bex.aaIdCOL = aaREG.Id;
bex.loadAddressCOL();
system.assertEquals(aaDef.Id,bex.aaIdDEL);
system.assert(bo.Carriage_Forward__c);
bex.aaIdDEL = OL_BookingExtension.newId;
bex.aaIdCOL = aaDEF.Id;
bex.loadAddressCOL();
system.assertEquals(OL_BookingExtension.newId,bex.aaIdDEL);
system.assert(!bo.Carriage_Forward__c);
Test.stopTest();
}
public static testMethod void testAddAddressesFails()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
Account_Address__c aaReg = TestUtil.createAccountAddress(a.Id,null);
aaReg.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaDef,aaReg};
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.commercialInvoiceRequired = 'false';
bex.paperworkRequired = 'false';
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bex.copyContactValuesCO2CC();
bo.Order_Contact__c = null;
bo.Collection_Contact__c = null;
bo.Delivery_Contact__c = cd.Id;
bex.loadContactValuesDC();
bo.Delivery_Contact__c = null;
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
system.assertEquals(aaDef.Id,bex.aaIdCOL);
bex.aaIdCOL = aaReg.Id;
bex.loadAddressCOL();
system.assertEquals(aaDef.Id,bex.aaIdDEL);
system.assert(bo.Carriage_Forward__c);
//TNT-2650 temporary disablement of validation pending revised address validation / automation structure
/*
bex.aaIdCOL = aaDef.Id;
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
system.assertEquals(null,bo.id); // save failed because both addresses are the same
bex.aaIdCOL = aaReg.Id;
bex.aaIdDEL = null;
bo.Carriage_Forward__c = true;
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.book.Del_Postcode__c = null;
bex.customSave();
system.assertEquals(null,bo.id); // save failed because we need delivery address if CF
bo.Carriage_Forward__c = true;
bex.aaIdCOL = OL_BookingExtension.newId;
bex.loadAddressCOL();
bex.aaIdDEL = null;
bex.clearAddressDEL();
bex.loadAddressDEL();
bo.Coll_Org_Name__c = aaDef.Org_Name__c;
bo.Coll_Street_1__c = aaDef.Street_1__c;
bo.Coll_Postcode__c = aaDef.Postcode__c;
bo.Coll_City__c = aaDef.City__c;
bo.Coll_Country__c = ConstantUtil.ISOCODE_UK;
bex.customSave();
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
system.assertEquals(null,bo.id); // save failed because we need delivery address if CF
bo.Carriage_Forward__c = false;
bex.loadAddressDEL();
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
system.assertNotEquals(null,bo.id);
*/
Test.stopTest();
}
public static testMethod void testLOB()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
Account_Address__c aaReg = TestUtil.createAccountAddress(a.Id,null);
aaReg.Postcode__c = 'SW15 1NP';
insert new List<Account_Address__c>{aaDef,aaReg};
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
createLOBs(a.Id);
List<Account_LOB__c> acclobs = [select id, Residential_Collection_Charge__c, Residential_Delivery_Charge__c
from Account_LOB__c];
for(Account_LOB__c alob : acclobs)
{
alob.Residential_Collection_Charge__c = true;
alob.Residential_Delivery_Charge__c = true;
}
update acclobs;
insert new List<Postcode__c>{
new Postcode__c(Name = aaDef.Postcode__c, Category__c = ConstantUtil.PLVAL_POSTCODE_CATEGORY_RESIDENTIAL),
new Postcode__c(Name = aaReg.Postcode__c, Category__c = ConstantUtil.PLVAL_POSTCODE_CATEGORY_RESIDENTIAL)};
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.commercialInvoiceRequired = 'false';
bex.paperworkRequired = 'false';
system.assert(bex.getIsAddressEditMode());
bex.enterAddressEditMode();
bex.clearContactValues(OL_BookingExtension.CONTACT_ORDER_PREFIX);
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bex.copyContactValuesCO2CC();
bo.Delivery_Contact__c = cd.Id;
bex.loadContactValuesDC();
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.aaIdDEL = aaReg.id;
bex.loadAddressDEL();
bex.enterLOBEditMode();
system.assert(bex.getIsLOBEditMode());
bex.resetSubLOB();
system.assertEquals(2,bex.getAvailableLOBs().size());
system.assert(bex.getHasLOBs());
system.assertEquals(3,bex.getAvailableCommodities().size());
system.assert(bex.getHasCommodity());
system.assertNotEquals(null,bex.getLOBNotifications());
bex.getLiabilityOptions();
system.assertEquals(2,bex.getAvailableServices().size());
system.assert(bex.getHasServices());
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bex.customSave();
system.assertNotEquals(null,bo.id);
system.assertNotEquals(null,bo.Line_of_Business__c);
system.assertNotEquals(null,bo.Service__c);
Test.stopTest();
}
public static testMethod void testContactCopy() // make sure contacts are not duplicated
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
Account_Address__c aaReg = TestUtil.createAccountAddress(a.Id,null);
aaReg.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaDef,aaReg};
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
createLOBs(a.Id);
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bo.Order_Contact__c = null;
bex.copyContactValuesCO2CC();
bo.Collection_Contact__c = null;
bex.copyContactValuesCO2DC();
bo.Delivery_Contact__c = null;
bex.createContactOrd = true;
bex.createContactCol = true;
bex.createContactDel = true;
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
system.assertEquals(bo.Order_Contact__c,bo.Collection_Contact__c);
system.assertEquals(bo.Order_Contact__c,bo.Delivery_Contact__c);
Test.stopTest();
}
public static testMethod void testBookingLineItems()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.Coll_Account_Address__c = aaCol.Id;
bo.Del_Account_Address__c = aaDel.Id;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Booking_Line_Item__c bli = new Booking_Line_Item__c();
bli.Number_Of_Items__c = 1;
bli.Height__c = 10;
bli.Length__c = 10;
bli.Weight__c = 10;
bli.Width__c = 10;
bli.Booking__c = bo.Id;
insert bli;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.addLine();
Booking_Line_Item__c bli1 = new Booking_Line_Item__c();
bli1.Number_Of_Items__c = 1;
bli1.Height__c = 10;
bli1.Length__c = 10;
bli1.Weight__c = 10;
bli1.Width__c = 10;
bex.bookingItems.add(bli1);
ApexPages.currentPage().getParameters().put('rowIndex', '0');
bex.removeLine();
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.aaIdCOL = aaCol.id;
bex.loadAddressCOL();
bex.aaIdDEL = aaDel.id;
bex.loadAddressDEL();
bex.customSave();
Test.stopTest();
List<Booking_Line_Item__c> cons = [select id from Booking_Line_Item__c];
system.assertEquals(1,cons.size());
system.assertNotEquals(bli.Id,cons[0].Id);
}
public static testMethod void testDepotRouting()
{
Account a = TestUtil.createAccountClient();
insert a;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
insert aaDef;
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
List<Line_of_Business__c> lobs = createLOBs(a.Id);
Date collDate = Date.newInstance(2014,9,1);
Account depot = TestUtil.setupDepotRouting(lobs.get(0).id,aaDef,collDate);
// we expect only one routing table record, and that 'Service 1' is selected
insert new Service_Guarantee__c(Service__c = [select id from Service__c where Name like '%1' limit 1].id,
Routing_Table__c = [select id from Routing_Table__c limit 1].id);
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
system.assert(bex.getIsAddressEditMode());
bex.enterAddressEditMode();
bex.clearContactValues(OL_BookingExtension.CONTACT_ORDER_PREFIX);
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bex.copyContactValuesCO2CC();
bo.Delivery_Contact__c = cd.Id;
bex.loadContactValuesDC();
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.enterLOBEditMode();
bex.resetSubLOB();
bex.getAvailableLOBs();
bex.getLiabilityOptions();
bex.getAvailableServices();
bex.getAvailableCommodities();
system.assertNotEquals(null,bo.Line_of_Business__c);
bex.overrideCollDepot = true;
bex.onManualOverride();
bex.overrideCollDepot = false;
bo.Collection_Ready_Time__c = Datetime.newInstance(collDate,Time.newInstance(12,0,0,0));
bex.collectionReadyTime = '01/09/2014 12:00';
bex.enterDepotEditMode();
bex.getCollDepotNotifications();
system.assert(bex.getIsDepotEditMode());
bex.customSave(); // save is actually failing because collection date is in the past, but not really relavant for test
system.assertEquals(depot.id,bo.Collection_Depot__c);
system.assertNotEquals(null,bo.Routing_Table__c);
system.assertNotEquals(null,bo.Depot_Routing__c);
Test.stopTest();
}
public static testMethod void testItegration()
{
Account a = TestUtil.createAccountClient();
insert a;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.Coll_Account_Address__c = aaCol.Id;
bo.Del_Account_Address__c = aaDel.Id;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Test.startTest();
Test.setMock(WebServiceMock.class, new uksvcsTntComBookingServiceMock());
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.saveBookingToUniverse();
Test.stopTest();
bo = [SELECT Status__c, Is_Synchronisation_Failed__c, Synchronisation_Error_Message__c
FROM Booking__c WHERE Id = : bo.Id];
system.assertEquals(ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED, bo.Status__c);
/*system.assertEquals(null, bo.Synchronisation_Error_Message__c);
List<Booking_History__c> bh = [SELECT Id, Movement_Type__c FROM Booking_History__c];
system.assertEquals(1, bh.size());
system.assertEquals(ConstantUtil.PLVAL_BOOKING_HISTORY_MOVEMENT_TYPE_RAISED, bh[0].Movement_Type__c);*/
}
public static testMethod void test_createFromQuote()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Quote__c qt = new Quote__c();
qt.Account__c = a.Id;
qt.Contact__c = c.Id;
qt.Email_Only__c = '<EMAIL>';
qt.Collection_Postcode__c = 'aa111a';
qt.Delivery_Postcode__c = 'aa111a';
insert qt;
Quote_Line_Item__c qli = new Quote_Line_Item__c();
qli.Number_of_Items__c = 1;
qli.Height__c = 10;
qli.Length__c = 10;
qli.Weight__c = 10;
qli.Width__c = 10;
qli.Quote__c = qt.Id;
insert qli;
Test.startTest();
ApexPages.currentPage().getParameters().put('qId', qt.Id);
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(new Booking__c());
OL_BookingExtension bex = new OL_BookingExtension(sc);
Test.stopTest();
system.assertEquals(1,bex.bookingItems.size());
system.assertEquals(10,bex.bookingItems[0].Height__c);
system.assert(bex.accountSelected);
}
public static testMethod void test_createFromQuote2()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact c = TestUtil.createContact(a.Id);
insert c;
Quote__c qt = new Quote__c();
qt.Company_Name__c = 'My Company';
qt.Company_Phone__c = '12344321';
qt.Contact_First_Name__c = 'test';
qt.Contact_Last_Name__c = 'guy';
qt.Contact_Phone__c = '123443211';
qt.Contact_Email__c = '<EMAIL>';
qt.Collection_Postcode__c = 'aa111a';
qt.Delivery_Postcode__c = 'aa111a';
qt.Email_the_quote__c = false;
insert qt;
Quote_Line_Item__c qli = new Quote_Line_Item__c();
qli.Number_of_Items__c = 1;
qli.Height__c = 10;
qli.Length__c = 10;
qli.Weight__c = 10;
qli.Width__c = 10;
qli.Quote__c = qt.Id;
insert qli;
Test.startTest();
ApexPages.currentPage().getParameters().put('qId', qt.Id);
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(new Booking__c());
OL_BookingExtension bex = new OL_BookingExtension(sc);
Test.stopTest();
system.assertEquals(1,bex.bookingItems.size());
system.assertEquals(10,bex.bookingItems[0].Height__c);
system.assert(bex.accountSelected);
}
public static testMethod void testFindServiceGuaranteeForDelivery()
{
Account a = TestUtil.createAccountClient();
insert a;
Account_Address__c aaDef = TestUtil.createAccountAddress(a.Id,null);
aaDef.Default__c = true;
insert aaDef;
List<Line_of_Business__c> lobs = createLOBs(a.Id);
Date collDate = Date.newInstance(2014,9,1);
Account depot = TestUtil.setupDepotRouting(lobs.get(0).id,aaDef,collDate);
// we expect only one routing table record, and that 'Service 1' is selected
insert new Service_Guarantee__c(Service__c = [select id from Service__c where Name like '%1' limit 1].id,
Routing_Table__c = [select id from Routing_Table__c limit 1].id);
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
system.assert(bex.getIsAddressEditMode());
bex.enterAddressEditMode();
bex.clearContactValues(OL_BookingExtension.CONTACT_ORDER_PREFIX);
bex.getAccountAddessesCOL();
bex.getAccountAddessesDEL();
bex.aaIdCOL = OL_BookingExtension.newId;
bex.loadAddressCOL();
system.assertEquals(bex.aaIdDEL,aaDef.Id);
bex.enterLOBEditMode();
bex.resetSubLOB();
bex.getAvailableLOBs();
bex.getLiabilityOptions();
bex.getAvailableServices();
bex.getAvailableCommodities();
system.assertNotEquals(null,bo.Line_of_Business__c);
bo.Collection_Ready_Time__c = Datetime.newInstance(collDate,Time.newInstance(12,0,0,0));
bex.enterDepotEditMode();
String errorMsg = bex.getCollDepotNotifications();
Test.stopTest();
system.assert(errorMsg.contains(Label.Service_NOT_Guaranteed_Message));
}
public static testMethod void testQuickClone()
{
Account a = TestUtil.createAccountClient();
insert a;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Coll_Account_Address__c = aaCol.Id;
bo.Del_Account_Address__c = aaDel.Id;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Commodity__c = 'SACK';
bo.Collection_Ready_Time__c = Datetime.now();
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Booking_Line_Item__c bli = new Booking_Line_Item__c();
bli.Booking__c = bo.Id;
bli.Number_of_items__c = 3;
bli.Weight__c = 2;
bli.Height__c = 100;
bli.Width__c = 100;
bli.Length__c = 100;
insert bli;
ApexPages.currentPage().getParameters().put('oId', bo.Id);
Test.startTest();
Booking__c boClone = new Booking__c();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(boClone);
OL_BookingExtension bex = new OL_BookingExtension(sc);
Test.stopTest();
system.assertEquals(null,boClone.id);
system.assertEquals(bo.Account__c,boClone.Account__c);
system.assertEquals(bo.OC_First_Name__c,boClone.OC_First_Name__c);
system.assertEquals(1,bex.bookingItems.size());
system.assertEquals(null,bex.bookingItems.get(0).Id);
system.assertEquals(null,bex.bookingItems.get(0).Booking__c);
}
public static testMethod void testInvoiceAddressesBookingNoAccount()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
List<Contact> cons = createContacts(a.Id);
Contact co = cons.get(0);
Contact cc = cons.get(1);
Contact cd = cons.get(2);
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Company_Name__c ='test company';
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.Coll_Org_Name__c = aaCol.Org_Name__c;
bo.Coll_Street_1__c = aaCol.Street_1__c;
bo.Coll_Postcode__c = aaCol.Postcode__c;
bo.Coll_City__c = aaCol.City__c;
bo.Coll_Country__c = ConstantUtil.ISOCODE_UK;
bo.Del_Org_Name__c = aaDel.Org_Name__c;
bo.Del_Street_1__c = aaDel.Street_1__c;
bo.Del_Postcode__c = aaDel.Postcode__c;
bo.Del_City__c = aaDel.City__c;
bo.Del_Country__c = ConstantUtil.ISOCODE_UK;
bo.Carriage_Forward__c = true;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.commercialInvoiceRequired = 'false';
bex.paperworkRequired = 'false';
bex.selectAccount();
system.assertEquals(OL_BookingExtension.newId,bex.aaIdCOL);
system.assertEquals(OL_BookingExtension.newId,bex.aaIdDEL);
bo.Order_Contact__c = co.Id;
bex.loadContactValuesOC();
bo.Order_Contact__c = null;
bo.Collection_Contact__c = cc.Id;
bex.loadContactValuesCC();
bo.Collection_Contact__c = null;
bo.Delivery_Contact__c = cd.Id;
bex.loadContactValuesDC();
bo.Delivery_Contact__c = null;
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.customSave();
Test.stopTest();
system.assertEquals(0,[select count() from Booking__c
where Account__c = null
and Coll_Postcode__c = :aaCol.Postcode__c
and Del_Postcode__c = :aaDel.Postcode__c]); //save falied because inv address missed
bo.Inv_Org_Name__c = aaDel.Org_Name__c;
bo.Inv_Street_1__c = aaDel.Street_1__c;
bo.Inv_Postcode__c = aaDel.Postcode__c;
bo.Inv_City__c = aaDel.City__c;
bo.Inv_Country__c = ConstantUtil.ISOCODE_UK;
bex.customSave();
system.assertEquals(1,[select count() from Booking__c
where Account__c = null
and Coll_Postcode__c = :aaCol.Postcode__c
and Del_Postcode__c = :aaDel.Postcode__c]);
}
//DH
public static testMethod void testLongLengthBookingLineItems()
{
Account a = TestUtil.createAccountClient();
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'BB1 AA1';
insert new List<Account_Address__c>{aaCol,aaDel};
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Close_Time__c = '20:00';
bo.Enhanced_Liability__c = ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE;
bo.Coll_Account_Address__c = aaCol.Id;
bo.Del_Account_Address__c = aaDel.Id;
bo.OC_First_Name__c = 'OCName';
bo.OC_Last_Name__c = 'OCSurname';
bo.OC_Phone_Number__c = '0000000000';
bo.CC_First_Name__c = 'CCName';
bo.CC_Last_Name__c = 'CCSurname';
bo.CC_Phone_Number__c = '1111111111';
bo.DC_First_Name__c = 'DCName';
bo.DC_Last_Name__c = 'DCSurname';
bo.DC_Phone_Number__c = '2222222222';
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Booking_Line_Item__c bli = new Booking_Line_Item__c();
bli.Number_Of_Items__c = 1;
bli.Height__c = 10;
bli.Length__c = 10;
bli.Weight__c = 10;
bli.Width__c = 10;
bli.Booking__c = bo.Id;
insert bli;
Test.startTest();
Apexpages.Standardcontroller sc = new Apexpages.Standardcontroller(bo);
OL_BookingExtension bex = new OL_BookingExtension(sc);
bex.addLine();
Booking_Line_Item__c bli1 = new Booking_Line_Item__c();
bli1.Number_Of_Items__c = 1;
bli1.Height__c = 10;
bli1.Length__c = 10;
bli1.Weight__c = 10;
bli1.Width__c = 10;
bex.bookingItems.add(bli1);
system.AssertEquals(0.0, bex.getNumLongLengths());
bli1.Height__c = 161;
bli1.Number_of_Items__c = 2;
system.AssertEquals(2.0, bex.getNumLongLengths());
bex.RefreshDarryl();
ApexPages.currentPage().getParameters().put('rowIndex', '0');
bex.removeLine();
bex.enterLOBEditMode();
bo.Commodity__c = 'SACK';
bex.enterDepotEditMode();
bex.book.Collection_Depot__c = depot.id;
bex.aaIdCOL = aaCol.id;
bex.loadAddressCOL();
bex.aaIdDEL = aaDel.id;
bex.loadAddressDEL();
bex.customSave();
Test.stopTest();
List<Booking_Line_Item__c> cons = [select id from Booking_Line_Item__c];
system.assertEquals(1,cons.size());
system.assertNotEquals(bli.Id,cons[0].Id);
}
}<file_sep>/classes/uksvcsTntComSearchConsignmentService.cls
//Generated by wsdl2apex
public class uksvcsTntComSearchConsignmentService {
public class searchConsignmentPort {
public String endpoint_x = TNT_Integration__c.getInstance().Search_Consignment_Service__c;
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://express.tnt.com/service/schema/srchcon/v1', 'uksvcsTntComSearchConsignment', 'http://express.tnt.com/service/wsdl/srchcon/v1', 'uksvcsTntComSearchConsignmentService', 'http://express.tnt.com/general/schema/tnterror/v1', 'uksvcsTntComError', 'http://express.tnt.com/general/schema/payloadheader/v1', 'uksvcsTntComGenericPayloadHeader', 'http://express.tnt.com/general/schema/objects/generic/v1', 'uksvcsTntComGenericObjects'};
public uksvcsTntComSearchConsignment.ResponseMessage_MasterType searchConsignment(uksvcsTntComGenericPayloadHeader.payloadHeader hdr,uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType con) {
uksvcsTntComSearchConsignment.RequestMessage_MasterType request_x = new uksvcsTntComSearchConsignment.RequestMessage_MasterType();
request_x.hdr = hdr;
request_x.con = con;
uksvcsTntComSearchConsignment.ResponseMessage_MasterType response_x;
Map<String, uksvcsTntComSearchConsignment.ResponseMessage_MasterType> response_map_x = new Map<String, uksvcsTntComSearchConsignment.ResponseMessage_MasterType>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'search',
'http://express.tnt.com/service/schema/srchcon/v1',
'searchConsignmentRequest',
'http://express.tnt.com/service/schema/srchcon/v1',
'searchConsignmentResponse',
'uksvcsTntComSearchConsignment.ResponseMessage_MasterType'}
);
response_x = response_map_x.get('response_x');
return response_x;
}
}
public class searchConsignment2Port {
public String endpoint_x = TNT_Integration__c.getInstance().Search_Consignment_Service__c;
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://express.tnt.com/service/wsdl/srchcon/v2', 'uksvcsTntComSearchConsignment', 'http://express.tnt.com/service/schema/srchcon/v2', 'uksvcsTntComSearchConsignmentService', 'http://express.tnt.com/general/schema/tnterror/v1', 'uksvcsTntComError', 'http://express.tnt.com/general/schema/payloadheader/v1', 'uksvcsTntComGenericPayloadHeader', 'http://express.tnt.com/general/schema/objects/generic/v1', 'uksvcsTntComGenericObjects'};
public uksvcsTntComSearchConsignment.ResponseMessage_MasterType searchConsignment2(uksvcsTntComSearchConsignment.ConsignmentRequest_MasterType con,uksvcsTntComGenericPayloadHeader.payloadHeader hdr) {
uksvcsTntComSearchConsignment.RequestMessage_MasterType request_x = new uksvcsTntComSearchConsignment.RequestMessage_MasterType();
request_x.con = con;
request_x.hdr = hdr;
uksvcsTntComSearchConsignment.ResponseMessage_MasterType response_x;
Map<String, uksvcsTntComSearchConsignment.ResponseMessage_MasterType> response_map_x = new Map<String, uksvcsTntComSearchConsignment.ResponseMessage_MasterType>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'search',
'http://express.tnt.com/service/schema/srchcon/v2',
'searchConsignment2Request',
'http://express.tnt.com/service/schema/srchcon/v2',
'searchConsignment2Response',
'uksvcsTntComSearchConsignment.ResponseMessage_MasterType'}
);
response_x = response_map_x.get('response_x');
return response_x;
}
}
}<file_sep>/classes/GBMailer_Util.cls
/**
* File Name : GBMailer_Util.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 05/08/2014 <NAME> Initial version (TNT-549)
*
*/
public with sharing class GBMailer_Util {
// packages
public static final String WS_ACCELERATOR_NAMES = 'WS-AcceleratorAddress';
// login details
public static String GBMAILER_USERNAME { get{ return GB_Mailer_Settings__c.getInstance().Username__c; }}
public static String GBMAILER_PASSWORD { get{ return GB_Mailer_Settings__c.getInstance().Password__c; }}
// codes used to identify address parts by the system
public static final String CODE_POSTCODE = 'PCOD';
public static final String CODE_TOWN = 'TOWN';
public static final String CODE_COUNTY = 'CNTY';
public static final String CODE_ORGANISATION = 'ORGN';
public static final String CODE_BUILDINGNAME = 'BNAM';
public static final String CODE_BUILDINGNUMBER = 'BNUM';
public static final String CODE_STREET = 'THOR'; // Thorofare
public static final String CODE_SUBPREMISE = 'SUBB';
//public static final String CODE_? = 'DPTH';
public static final String CODE_DEPLOC = 'DPLO'; // Dependent Locality
public static final String CODE_DUBDEPLOC = 'DDLO'; // Double Dependent Locality
public static final Integer GBMAILER_SYSTEM_LIMIT = 200;
public static GBMailer_Service.GBPortalWSSoap wsCall = new GBMailer_Service.GBPortalWSSoap();
public static GBMailer_Service.AcceleratorSearchReturn results;
public static String sessionId;
public static List<Map<String, String>> getAddresses(String postcode)
{
GBMailer_Service.AcceleratorAddress searchAddress = new GBMailer_Service.AcceleratorAddress();
searchAddress.text = postcode;
LIST<MAP<String, String>> addresses = new LIST<MAP<String, String>>();
sessionId = createSession();
results = callGBMailerServicePinpoint(sessionId, postcode);
wsCall.TerminateSession(sessionId);
System.debug('===> results = ' + results);
addresses = splitAddress(results);
return addresses;
}
public static String createSession()
{
return wsCall.CreateSession();
}
public static GBMailer_Service.AcceleratorSearchReturn callGBMailerServicePinpoint(String sId, String pc)
{
return wsCall.Pinpoint(WS_ACCELERATOR_NAMES, // name of the GBPortal package to run your search
sId, // your session handle
GBMAILER_USERNAME, // your username
GBMAILER_PASSWORD, // <PASSWORD>
pc, // full or partial postcode for the search
'', // building name, number, company, or PO Box
'Three address lines, town, county and postcode', // name of the GBPortal address format to use
'', // list of related-data mnemonics to be returned with the data
0, // offset
0); // if >0, presents limit
}
public static List<Map<String, String>> splitAddress(GBMailer_Service.AcceleratorSearchReturn sreturn)
{
try {
LIST<MAP<String, String>> addresses = new LIST<MAP<String, String>>();
Set<String> existingNumbers = new Set<String>();
for (GBMailer_Service.AcceleratorAddress address : sreturn.Addresses.AcceleratorAddress)
{
GBMailer_Service.ArrayOfAcceleratorItem items = address.Items;
MAP<String, String> addressItems = new MAP<String, String>();
if (!existingNumbers.contains(address.Text)){
for (GBMailer_Service.AcceleratorItem item : items.AcceleratorItem) {
addressItems.put(item.Key, item.Value);
}
existingNumbers.add(address.Text);
system.debug('==> addressItems ' + addressItems);
addresses.add(addressItems);
}
}
return addresses;
} catch (Exception ex) {
return null;
}
}
}<file_sep>/classes/callSummaryTriggerTest.cls
@IsTest
public class callSummaryTriggerTest {
static testmethod void CheckCallSummaryTrigger()
{
User u = [select id from user where name='NVM User' Limit 1];
NVMStatsSF__NVM_Call_Summary__c callSummary = new NVMStatsSF__NVM_Call_Summary__c (
NVMStatsSF__Agent__c = u.Id
);
insert callSummary;
callSummary = [select NVMStatsSF__Agent__c, OwnerId from NVMStatsSF__NVM_Call_Summary__c where Id = :callSummary.Id Limit 1];
System.assertEquals(callSummary.NVMStatsSF__Agent__c, callSummary.OwnerId);
delete callSummary;
}
}<file_sep>/classes/OL_GetQuotePricingDetailsExtension.cls
/**
* File Name : OL_GetQuotePricingDetailsExtension.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 07/08/2014 <NAME> Initial version, TNT-545
*/
public with sharing class OL_GetQuotePricingDetailsExtension {
public Quote__c quote;
public uksvcsTntGetQuotePricing.Deliveries_ContainerType responceData {get; set;}
public Map<String, Service__c> services {get; set;}
public String serviceKeys {get; set;}
public Boolean errorOnLoad {get; private set;}
private Apexpages.standardController sc;
public OL_GetQuotePricingDetailsExtension(Apexpages.standardController stdCtrl){
sc = stdCtrl;
Id qId = stdCtrl.getRecord().Id;
if(qId != null){
quote = [SELECT Name, Price__c, Total_Number_of_Items__c, Total_Volume_Rounded__c, Total_Weight__c, Collection_Date__c, Collection_Postcode__c,
Delivery_Postcode__c, Account__r.Account_Number__c, Dangerous_Goods__c, Pallet_Pollicy__c, Carriage_Forward__c, Enhanced_Liability_Option__c,
Fuel_Supplement__c, Service_Name__c, Is_Guaranteed_Service__c, Is_Premium_Service__c, Delivery_Date__c, Supplements_Details__c, No_Long_Length_Items__c
FROM Quote__c WHERE Id = : qId];
}
errorOnLoad = false;
fillServices();
}
public void requestPrice(){
try{
errorOnLoad = false;
uksvcsTntGetQuotePricingService.getPricingDetailsForQuotePort port = new uksvcsTntGetQuotePricingService.getPricingDetailsForQuotePort();
port.inputHttpHeaders_x = new map<string,string> {'Username' => TNT_Integration__c.getInstance().Username__c,
'Password' => TNT_Integration__c.getInstance().Password__c};
uksvcsTntComGenericPayloadHeader.payloadHeader
hdr = new uksvcsTntComGenericPayloadHeader.payloadHeader();
uksvcsTntGetQuotePricing.QuoteRequest_MasterType
con = new uksvcsTntGetQuotePricing.QuoteRequest_MasterType ();
if(quote.Account__r.Account_Number__c != null) {
con.actNum = quote.Account__r.Account_Number__c;
}
con.rqstdColDt = quote.Collection_Date__c;
con.colPstCd = quote.Collection_Postcode__c;
con.delPstCd = quote.Delivery_Postcode__c;
con.totItms = String.valueOf(quote.Total_Number_of_Items__c);
con.totVol = String.valueOf(quote.Total_Volume_Rounded__c);
con.totActWght = String.valueOf(quote.Total_Weight__c);
con.wghtUOM = 'KG';
con.hazGdInd = quote.Dangerous_Goods__c;
con.plltInd = quote.Pallet_Pollicy__c > 0 ? true : false;
con.crrgFwdInd = quote.Carriage_Forward__c;
con.enhLbltyInd = (quote.Enhanced_Liability_Option__c == ConstantUtil.PLVAL_QUOTE_ENHANCED_LIABILITY_OPTION_NONE || quote.Enhanced_Liability_Option__c == null) ? false : true;
con.LongLengths = String.valueOf(quote.No_Long_Length_Items__c);
if(quote.Fuel_Supplement__c != null) {
con.fuelSrchrg = String.valueOf(quote.Fuel_Supplement__c);
}
uksvcsTntGetQuotePricing.ResponseMessage_MasterType resp;
if(!ConstantUtil.INTEGRATION_ACCESS) throw new ConstantUtil.IntegrationAccessDeniedException(ConstantUtil.INTEGRATION_EXMSG);
port.timeout_x = ConstantUtil.INTEGRATION_TIMEOUT;
resp = port.getPricingDetailsForQuote(hdr, con);
if(resp.qt != null && resp.qt.dels != null){
responceData = resp.qt.dels;
}
else
{
errorOnLoad = true;
}
if(resp.hdr != null && resp.hdr.infoMsg != null){
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.INFO, resp.hdr.infoMsg));
}
} catch (Exception ex) {
Apexpages.addMessages(ex);
responceData = new uksvcsTntGetQuotePricing.Deliveries_ContainerType();
errorOnLoad = true;
}
}
public PageReference savePrice(){
try{
for(uksvcsTntGetQuotePricing.Delivery_MasterType dt : responceData.del) {
if(dt.selected){
for(uksvcsTntGetQuotePricing.DeliveryService_MasterType ds : dt.delSvcs.delSvc){
if(ds.selected){
//get service Name
List<Service__c> service = [SELECT Name FROM Service__c WHERE Service_Code__c = : ds.svcCd];
quote.Delivery_Date__c = dt.delDt;
quote.Service_Name__c = (service != null && !service.isEmpty()) ? service[0].Name : ds.svcCd;
quote.Is_Guaranteed_Service__c = ds.guarSvcInd;
quote.Is_Premium_Service__c = ds.prSvcInd;
quote.Price__c = Decimal.valueOf(ds.qtAmt);
String supplementsDetails = '';
for(uksvcsTntGetQuotePricing.Surcharge_MasterType sd : ds.srchrgs.srchrg){
supplementsDetails += sd.srchrgTypCd + ' \t' + sd.srchrgTypNm;
supplementsDetails += String.isEmpty(sd.chrgAmt) ? '' : ' \t' + sd.chrgAmt + ' ' + sd.curCd;
supplementsDetails += String.isEmpty(sd.chrgPrcnt) ? '' : ' \t' + sd.chrgPrcnt + '%';
supplementsDetails += '\n';
}
quote.Supplements_Details__c = supplementsDetails;
quote.Reason_for_Not_Booking__c = ((Quote__c)sc.getRecord()).Reason_for_Not_Booking__c;
upsert quote;
return new PageReference('/' + quote.Id);
}
}
break;
}
}
Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.ERROR, 'Please select service.'));
} catch(Exception ex){
Apexpages.addMessages(ex);
}
return null;
}
public PageReference cancel(){
return new PageReference('/' + quote.Id);
}
public void fillServices() {
services = new Map<String, Service__c>();
serviceKeys = '';
for(Service__c a : [SELECT Name, Service_Code__c FROM Service__c
WHERE Service_Code__c != null ORDER BY Name]){
services.put(a.Service_Code__c, a);
serviceKeys += '*' + a.Service_Code__c + '*';
}
}
}<file_sep>/classes/TaggedState.cls
public class TaggedState {
public static void applyCustomStates(NVMStatsSF__NVM_Agent_Summary__c[] agentSummaries) {
final String CHKSTR_END_CHAR_REGEX = '\\|';
List<String> customStates = new List<String>();
//Set up the CustomState variables
String customState1 = 'Return to work 10 mins';
String customState2 = 'Admin at workdesk';
String customState3 = 'Admin Team Duties Walkaway';
String customState4 = 'Computer Related Issues';
String customState5 = 'Debrief with Supervisor';
String customState6 = 'Helping advising Colleagues';
//Set up MinorState variables
String minorState1 = 'Comfort Break';
for (NVMStatsSF__NVM_Agent_Summary__c b :agentSummaries){
String keyString = b.NVMStatsSF__Key_Event_String__c;
//No processing if the Key Events String is empty
if (keyString != null ) {
//We need to replace Custom State 320 etc with acual values
b.NVMStatsSF__Key_Event_String__c = b.NVMStatsSF__Key_Event_String__c.replaceAll('Custom State 305', customState1);
b.NVMStatsSF__Key_Event_String__c = b.NVMStatsSF__Key_Event_String__c.replaceAll('Custom State 320', customState2);
b.NVMStatsSF__Key_Event_String__c = b.NVMStatsSF__Key_Event_String__c.replaceAll('Custom State 321', customState3);
b.NVMStatsSF__Key_Event_String__c = b.NVMStatsSF__Key_Event_String__c.replaceAll('Custom State 322', customState4);
b.NVMStatsSF__Key_Event_String__c = b.NVMStatsSF__Key_Event_String__c.replaceAll('Custom State 323', customState5);
b.NVMStatsSF__Key_Event_String__c = b.NVMStatsSF__Key_Event_String__c.replaceAll('Custom State 324', customState6);
//First lets check for each of the Custom States in the Key Event String:
Boolean cState1 = keyString.contains(customState1);
Boolean cState2 = keyString.contains(customState2);
Boolean cState3 = keyString.contains(customState3);
Boolean cState4 = keyString.contains(customState4);
Boolean cState5 = keyString.contains(customState5);
Boolean cState6 = keyString.contains(customState6);
//Then search for the standard values:
Boolean mState1 = keyString.contains(minorState1);
//Blank the values on the Custom States if no matches
if (!cState1) { b.Custom_State_1__c = 0; }
if (!cState2) { b.Custom_State_2__c = 0; }
if (!cState3) { b.Custom_State_3__c = 0; }
if (!cState4) { b.Custom_State_4__c = 0; }
if (!cState5) { b.Custom_State_5__c = 0; }
if (!cState6) { b.Custom_State_6__c = 0; }
//Blank values on Minor State fields
if (!mState1) { b.Comfort_Break__c = 0; }
//After initial checks split the string by the pipe character
customStates = (''+b.NVMStatsSF__Key_Event_String__c).split(CHKSTR_END_CHAR_REGEX);
String cs1tempValue;
Integer cs1value;
Integer cs1FinalValue;
Integer cState1Value;
String cs2tempValue;
Integer cs2value;
Integer cs2FinalValue;
Integer cState2Value;
String cs3tempValue;
Integer cs3value;
Integer cs3FinalValue;
Integer cState3Value;
String cs4tempValue;
Integer cs4value;
Integer cs4FinalValue;
Integer cState4Value;
String cs5tempValue;
Integer cs5value;
Integer cs5FinalValue;
Integer cState5Value;
String cs6tempValue;
Integer cs6value;
Integer cs6FinalValue;
Integer cState6Value;
String ms1tempValue;
Integer ms1value;
Integer ms1FinalValue;
Integer mState1Value;
for (Integer i = 0; i < customStates.size(); i++) {
//Inner loop addding up values
/* Start of each CustomState */
Boolean i1 = customStates[i].contains(customState1);
if (i1) {
cs1tempValue = customStates[i].right(5);
cs1tempValue = cs1tempValue.replaceAll('[^0-9.]', '');
cs1value = integer.valueOf(cs1tempValue);
system.debug('value is ' + cs1value + ' second value is ' + cs1FinalValue);
if (cs1FinalValue == null){
cs1FinalValue = cs1value;
}
else if (cs1FinalValue != null) {
cs1FinalValue = cs1FinalValue + cs1value;
}
}
/* End of each CustomState */
/* Start of each CustomState */
Boolean i2 = customStates[i].contains(customState2);
if (i2) {
cs2tempValue = customStates[i].right(5);
cs2tempValue = cs2tempValue.replaceAll('[^0-9.]', '');
cs2value = integer.valueOf(cs2tempValue);
system.debug('value is ' + cs2value + ' second value is ' + cs2FinalValue);
if (cs2FinalValue == null){
cs2FinalValue = cs2value;
}
else if (cs2FinalValue != null) {
cs2FinalValue = cs2FinalValue + cs2value;
}
}
/* End of each CustomState */
/* Start of each CustomState */
Boolean i3 = customStates[i].contains(customState3);
if (i3) {
cs3tempValue = customStates[i].right(5);
cs3tempValue = cs3tempValue.replaceAll('[^0-9.]', '');
cs3value = integer.valueOf(cs3tempValue);
system.debug('value is ' + cs3value + ' second value is ' + cs3FinalValue);
if (cs3FinalValue == null){
cs3FinalValue = cs3value;
}
else if (cs3FinalValue != null) {
cs3FinalValue = cs3FinalValue + cs3value;
}
}
/* End of each CustomState */
/* Start of each CustomState */
Boolean i4 = customStates[i].contains(customState4);
if (i4) {
cs4tempValue = customStates[i].right(5);
cs4tempValue = cs4tempValue.replaceAll('[^0-9.]', '');
cs4value = integer.valueOf(cs4tempValue);
system.debug('value is ' + cs4value + ' second value is ' + cs4FinalValue);
if (cs4FinalValue == null){
cs4FinalValue = cs4value;
}
else if (cs4FinalValue != null) {
cs4FinalValue = cs4FinalValue + cs4value;
}
}
/* End of each CustomState */
/* Start of each CustomState */
Boolean i5 = customStates[i].contains(customState5);
if (i5) {
cs5tempValue = customStates[i].right(5);
cs5tempValue = cs5tempValue.replaceAll('[^0-9.]', '');
cs5value = integer.valueOf(cs5tempValue);
system.debug('value is ' + cs5value + ' second value is ' + cs5FinalValue);
if (cs5FinalValue == null){
cs5FinalValue = cs5value;
}
else if (cs5FinalValue != null) {
cs5FinalValue = cs5FinalValue + cs5value;
}
}
/* End of each CustomState */
/* Start of each CustomState */
Boolean i6 = customStates[i].contains(customState6);
if (i6) {
cs6tempValue = customStates[i].right(5);
cs6tempValue = cs6tempValue.replaceAll('[^0-9.]', '');
cs6value = integer.valueOf(cs6tempValue);
system.debug('value is ' + cs6value + ' second value is ' + cs6FinalValue);
if (cs6FinalValue == null){
cs6FinalValue = cs6value;
}
else if (cs6FinalValue != null) {
cs6FinalValue = cs6FinalValue + cs6value;
}
}
/* End of each CustomState */
/* Start of each MinorState */
Boolean m1 = customStates[i].contains(minorState1);
if (m1) {
ms1tempValue = customStates[i].right(5);
ms1tempValue = ms1tempValue.replaceAll('[^0-9.]', '');
ms1value = integer.valueOf(ms1tempValue);
system.debug('value is ' + ms1value + ' second value is ' + ms1FinalValue);
if (ms1FinalValue == null){
ms1FinalValue = ms1value;
}
else if (ms1FinalValue != null) {
ms1FinalValue = ms1FinalValue + ms1value;
}
}
/* End of each MinorState */
/* Start of each MinorState */
} //end for loop
//Time to set Custom State fields
b.Custom_State_1__c = cs1FinalValue;
b.Custom_State_2__c = cs2FinalValue;
b.Custom_State_3__c = cs3FinalValue;
b.Custom_State_4__c = cs4FinalValue;
b.Custom_State_5__c = cs5FinalValue;
b.Custom_State_6__c = cs6FinalValue;
//Minor State fields
b.Comfort_Break__c = ms1FinalValue;
}
} // end of loop
}
}<file_sep>/classes/CaseTriggerHandlerTest.cls
/**
* File Name : CaseTriggerHandlerTest.cls
* Description :
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 03/07/2014 <NAME> Initial version
* 0.2 19/08/2014 <NAME> Tests for updateCaseTrackingHistory() method TNT-490,TNT-491,TNT-493
* 0.3 20/08/2014 <NAME> Tests for updateOwnerForCallMeBackTasks() method TNT-1428
* 0.4 10/09/2014 <NAME> Removed changeOwner method TNT-1603
* 0.4 14/10/2014 <NAME> Reminder now 15 before due date TNT-2051
* 0.5 20/10/2015 <NAME> Added test_getSLATime() method to test SLA Time scenario
* 0.5 20/10/2015 Darrylhopper Amended testCreateReminderTask() to take SLA time into questio
*/
@isTest
private class CaseTriggerHandlerTest {
static Integer mins = -15;
static testMethod void quickCoverTrigger()
{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
Test.startTest();
insert c;
update c;
delete c;
Test.stopTest();
}
static testMethod void testCreateReminderTask()
{
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c1 = TestUtil.createCase(a.Id, con.Id, d.Id);
insert c1;
Case c2 = TestUtil.createCase(a.Id, con.Id, d.Id);
insert c2;
system.assertEquals(0,[select count() from Task]); // no task should be created before Call_me_back__c is set
Map<Id,Case> oldMap = new Map<Id,Case>{c1.Id => c1.clone(true,true), c2.Id => c2.clone(true,true)};
Integer hourDiffA = 1;
Integer hourDiffB = 4;
c1.Call_me_back__c = hourDiffA + ' hour';
//DH Changed 19/10/15
c2.Call_me_back__c = '24 hours';
Test.startTest();
CaseTriggerHandler.isFirstRun = true;
CaseTriggerHandler.createReminderTask(new List<Case>{c1,c2},oldMap);
c1.Call_me_back__c = hourDiffB + ' hours';
oldMap.put(c2.id,c2); // override old value to mimic unchanged field
CaseTriggerHandler.isFirstRun = true;
CaseTriggerHandler.createReminderTask(new List<Case>{c1,c2},oldMap);
Test.stopTest();
Datetime nextWorkingDay = TimeUtil.getNextWorkingDay(Datetime.now());
// give 5 minute leeway as we're working with datetime which has a granularity of milliseconds
// two tasks will be created for first case because we changed the reminder
/*
system.assertEquals(1,[select count() from Task where WhatId = :c1.Id
and ReminderDateTime > :Datetime.now().addHours(hourDiffA).addMinutes(-5+mins)
and ReminderDateTime < :Datetime.now().addHours(hourDiffA).addMinutes(5+mins)]);
system.assertEquals(1,[select count() from Task where WhatId = :c1.Id
and ReminderDateTime > :Datetime.now().addHours(hourDiffB).addMinutes(-5+mins)
and ReminderDateTime < :Datetime.now().addHours(hourDiffB).addMinutes(5+mins)]);
*/
//DH new version of test above
system.assertEquals(1,[select count() from Task where WhatId = :c1.Id
and ReminderDateTime > :CaseTriggerHandler.getSLATime(hourDiffA,Datetime.now()).addMinutes(-5+mins)
and ReminderDateTime < :CaseTriggerHandler.getSLATime(hourDiffA,Datetime.now()).addMinutes(5+mins)]);
system.assertEquals(1,[select count() from Task where WhatId = :c1.Id
and ReminderDateTime > :CaseTriggerHandler.getSLATime(hourDiffB,Datetime.now()).addMinutes(-5+mins)
and ReminderDateTime < :CaseTriggerHandler.getSLATime(hourDiffB,Datetime.now()).addMinutes(5+mins)]);
// only one task for c2 DH Amended for new SLA calculation
system.assertEquals(1,[select count() from Task where WhatId = :c2.Id
and ReminderDateTime > :CaseTriggerHandler.getSLATime(24,Datetime.now()).addMinutes(-5+mins)
and ReminderDateTime < :CaseTriggerHandler.getSLATime(24,Datetime.now()).addMinutes(5+mins) ]);
}
static testMethod void testPopulate24HDeadline()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.Id, con.Id);
Test.startTest();
CaseTriggerHandler.populate24HDeadline(new List<Case>{c});
Test.stopTest();
system.assert(c.Twentyfour_Hour_Deadline__c != null,'Twentyfour_Hour_Deadline__c is not populated'); // can't assert time
}
/*static testMethod void testAssignEscalatedCases()
{
List<Group> queues = new List<Group>();
queues.add(new Group(Type = 'Queue', Name = 'ClientCollection', DeveloperName = 'ClientCollection'));
queues.add(new Group(Type = 'Queue', Name = 'ClientDelivery', DeveloperName = 'ClientDelivery'));
queues.add(new Group(Type = 'Queue', Name = 'DepotCollection', DeveloperName = 'DepotCollection'));
queues.add(new Group(Type = 'Queue', Name = 'DepotDelivery', DeveloperName = 'DepotDelivery'));
queues = (List<Group>) TestUtil.proxyInsert(queues);
Account ac1 = TestUtil.createAccountClient();
ac1.Collection_Queue__c = queues.get(0).DeveloperName;
ac1.Delivery_Queue__c = queues.get(1).DeveloperName;
insert ac1;
Account ac2 = TestUtil.createAccountClient();
ac2.Name += '2';
ac2.AccountNumber += '2';
insert ac2;
Account ad = TestUtil.createAccountDepot();
ad.Collection_Queue__c = queues.get(2).DeveloperName;
ad.Delivery_Queue__c = queues.get(3).DeveloperName;
insert ad;
List<Case> cases = new List<Case>();
Case c;
// will use client queue for collection
c = TestUtil.createCase(ac1.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
cases.add(c);
// will use client queue for delivery
c = TestUtil.createCase(ac1.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
cases.add(c);
// will use depot queue for collection
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
cases.add(c);
// will use depot queue for delivery
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
cases.add(c);
insert cases;
Map<Id,Case> oldMap = new Map<Id,Case>(cases.deepClone(true,true,true));
for(Case cas : cases)
{
cas.IsEscalated = true;
}
Test.startTest();
CaseTriggerHandler.assignEscalatedCases(cases,oldMap);
System.assert(CaseTriggerHandler.assignedEscalatedOwner);
CaseTriggerHandler.assignEscalatedCases(cases,oldMap); // just to cover execution skip
Test.stopTest();
System.assertEquals(cases.get(0).OwnerId,[select Id from Group where DeveloperName = :ac1.Collection_Queue__c].Id);
System.assertEquals(cases.get(1).OwnerId,[select Id from Group where DeveloperName = :ac1.Delivery_Queue__c].Id);
System.assertEquals(cases.get(2).OwnerId,[select Id from Group where DeveloperName = :ad.Collection_Queue__c].Id);
System.assertEquals(cases.get(3).OwnerId,[select Id from Group where DeveloperName = :ad.Delivery_Queue__c].Id);
}*/
static testMethod void testAssignCases()
{
List<Group> queues = new List<Group>();
queues.add(new Group(Type = 'Queue', Name = 'ClientCollection', DeveloperName = 'ClientCollection'));
queues.add(new Group(Type = 'Queue', Name = 'ClientDelivery', DeveloperName = 'ClientDelivery'));
queues.add(new Group(Type = 'Queue', Name = 'DepotCollection', DeveloperName = 'DepotCollection'));
queues.add(new Group(Type = 'Queue', Name = 'DepotDelivery', DeveloperName = 'DepotDelivery'));
//DH added 19/01/2016
//queues.add(new Group(Type = 'Queue', Name = 'Mauritius_Team', DeveloperName = 'Mauritius_Team'));
queues = (List<Group>) TestUtil.proxyInsert(queues);
Account ac1 = TestUtil.createAccountClient();
ac1.Collection_Queue__c = queues.get(0).DeveloperName;
ac1.Delivery_Queue__c = queues.get(1).DeveloperName;
insert ac1;
Account ac2 = TestUtil.createAccountClient();
ac2.Name += '2';
ac2.AccountNumber += '2';
insert ac2;
Account ad = TestUtil.createAccountDepot();
ad.Collection_Queue__c = queues.get(2).DeveloperName;
ad.Delivery_Queue__c = queues.get(3).DeveloperName;
insert ad;
List<Case> cases = new List<Case>();
Case c;
// will use client queue for collection
c = TestUtil.createCase(ac1.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
cases.add(c);
// will use client queue for delivery
c = TestUtil.createCase(ac1.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
cases.add(c);
// will use depot queue for collection
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
cases.add(c);
// will use depot queue for delivery
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
cases.add(c);
//DH added 19/01/2016
// will use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'Track';
c.Case_Types_Level_2__c = 'Late Delivery';
cases.add(c);
// will use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'Track';
c.Case_Types_Level_2__c = 'Late Delivery';
cases.add(c);
// will use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'Track';
c.Case_Types_Level_2__c = 'Paperwork Request';
cases.add(c);
// will use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'Track';
c.Case_Types_Level_2__c = 'Paperwork Request';
cases.add(c);
// will use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'General Enquiry';
c.Case_Types_Level_2__c = 'Redelivery Request';
cases.add(c);
// will use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'General Enquiry';
c.Case_Types_Level_2__c = 'Redelivery Request';
cases.add(c);
//**Negative Test by DH 19/01/2016
// will NOT use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_COLLECTION;
c.Collection_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'Track';
c.Case_Types_Level_2__c = 'Redelivery Request';
cases.add(c);
// will NOT use Mauritius queue
c = TestUtil.createCase(ac2.Id, null);
c.Exception__c = ConstantUtil.PLVAL_CASE_EXCEPTION_DELIVERY;
c.Delivery_Depot__c = ad.id;
c.OwnerId = UserInfo.getUserId();
c.Origin = ConstantUtil.PLVAL_CASE_ORIGIN_PHONE;
c.Type = 'Track';
c.Case_Types_Level_2__c = 'Redelivery Request';
cases.add(c);
insert cases;
Map<Id,Case> oldMap = new Map<Id,Case>(cases.deepClone(true,true,true));
for(Case cas : cases)
{
cas.OwnerId = ConstantUtil.UNASSIGNED_QUEUE_ID;
}
Test.startTest();
CaseTriggerHandler.assignCases(cases,oldMap);
Test.stopTest();
//00G20000001u5UrEAI
ID testMauritiusID = ConstantUtil.MAURITIUS_QUEUE_ID;
//system.assertEquals(testMauritiusID,'00G20000001u5UrEAI');
System.assertEquals(cases.get(0).OwnerId,[select Id from Group where DeveloperName = :ac1.Collection_Queue__c].Id);
System.assertEquals(cases.get(1).OwnerId,[select Id from Group where DeveloperName = :ac1.Delivery_Queue__c].Id);
System.assertEquals(cases.get(2).OwnerId,[select Id from Group where DeveloperName = :ad.Collection_Queue__c].Id);
System.assertEquals(cases.get(3).OwnerId,[select Id from Group where DeveloperName = :ad.Delivery_Queue__c].Id);
//Added by DH 19/01/2016
System.assertEquals(cases.get(4).OwnerId,testMauritiusID);
System.assertEquals(cases.get(5).OwnerId,testMauritiusID);
System.assertEquals(cases.get(6).OwnerId,testMauritiusID);
System.assertEquals(cases.get(7).OwnerId,testMauritiusID);
//Commented out 02/02/2016 ref Kish due to Redelivery status not being included at this time
//System.assertEquals(cases.get(8).OwnerId,testMauritiusID);
//System.assertEquals(cases.get(9).OwnerId,testMauritiusID);
//Negative TEst
System.assertNOTEquals(cases.get(10).OwnerId,testMauritiusID);
System.assertNOTEquals(cases.get(11).OwnerId,testMauritiusID);
}
/*static testMethod void testAssignMajorAccountCases() {
User u = TestUtil.createAgentUser();
insert u;
Account a = TestUtil.createAccountClient();
a.Major_Account__c = true;
a.Assigned_Agent__c = u.Id;
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Group res = [SELECT Id FROM Group WHERE DeveloperName = : ConstantUtil.MAJOR_ACCOUNTS_QUEUE LIMIT 1];
String majourAccountQueueId = res.Id;
Case c = TestUtil.createCase(a.Id, con.Id);
c.OwnerId = majourAccountQueueId;
insert c;
c = [SELECT Id, OwnerId FROM Case WHERE Id = :c.Id];
system.assertEquals(u.Id, c.OwnerId, 'Owner should have been updated to user u');
}*/
/*static testMethod void testAssignMajorAccountCasesToQueue() {
User u = TestUtil.createAgentUser();
insert u;
Account a = TestUtil.createAccountClient();
a.Major_Account__c = true;
a.Assigned_Agent__c = u.Id;
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Group res = [SELECT Id FROM Group WHERE DeveloperName = : ConstantUtil.MAJOR_ACCOUNTS_QUEUE LIMIT 1];
String majourAccountQueueId = res.Id;
Case c = TestUtil.createCase(a.Id, con.Id);
insert c;
c = [SELECT Id, OwnerId, Case_Back_to_Queue_MA__c FROM Case WHERE Id = :c.Id];
//update with Queue to run trigger
c.OwnerId = majourAccountQueueId;
c.Case_Back_to_Queue_MA__c = true;
update c;
c = [SELECT Id, OwnerId, Case_Back_to_Queue_MA__c FROM Case WHERE Id = :c.Id];
system.assertEquals(majourAccountQueueId, c.OwnerId, 'Owner should stay in Queue');
}*/
static testMethod void testCaseHistoryTracking() {
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
insert c;
c.Status = ConstantUtil.PLVAL_CASE_STATUS_WAITING_FOR_CUSTOMER;
update c;
List<Case_Tracking_History__c> cthList = [SELECT Category__c, Case_Waiting__c, Finished_on__c
FROM Case_Tracking_History__c
WHERE Category__c = : ConstantUtil.PLVAL_CTH_CATEGORY_STATUS ORDER BY Case_Waiting__c];
system.assertEquals(2, cthList.size());
system.assertEquals(true, cthList[1].Case_Waiting__c);
system.assertEquals(null, cthList[1].Finished_on__c);
}
static testMethod void testCaseHistoryTracking_CloseCase() {
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
insert c;
c.Status = 'Closed';
update c;
List<Case_Tracking_History__c> cthList = [SELECT Category__c, Case_Waiting__c, Finished_on__c
FROM Case_Tracking_History__c
WHERE Finished_on__c = : null];
system.assertEquals(0, cthList.size());
}
static testMethod void test_updateOwnerForCallMeBackTasks() {
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
User u = TestUtil.createAgentUser();
insert u;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
c.Call_me_back__c = '1 hour';
insert c;
Task t = [SELECT OwnerId FROM Task WHERE Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK LIMIT 1];
system.assertEquals(UserInfo.getUserId(), t.OwnerId);
Test.startTest();
c.OwnerId = u.Id;
update c;
Test.stopTest();
t = [SELECT OwnerId FROM Task WHERE Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK LIMIT 1];
system.assertEquals(u.Id, t.OwnerId);
}
static testMethod void test_updateOwnerForCallMeBackClosedTasks() {
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
User u = TestUtil.createAgentUser();
insert u;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
c.Call_me_back__c = '1 hour';
insert c;
Task t = [SELECT Status, OwnerId FROM Task WHERE Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK LIMIT 1];
system.assertEquals(UserInfo.getUserId(), t.OwnerId);
t.Status = 'Completed';
update t;
Test.startTest();
c.OwnerId = u.Id;
update c;
Test.stopTest();
t = [SELECT OwnerId FROM Task WHERE Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK LIMIT 1];
system.assertEquals(UserInfo.getUserId(), t.OwnerId);
}
static testMethod void test_getSLATime()
{
//All tests assume start and end time are 08:00 and 18:00, respectively
//---Test all callback hours when logged pre start Monday
DateTime logTime = DateTime.newInstance(2015,09,21,04,59,00);
Integer callBack = 1;
DateTime SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,13,0,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,23,8,0,0), SLAResult);
//---Test all callback hours when logged within Monday working day and SLA result doesnot exceed working day or is 24 or 48 hour
logTime = DateTime.newInstance(2015,09,21,10,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,11,59,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,12,59,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,13,59,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,14,59,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,15,59,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,10,59,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,23,10,59,0), SLAResult);
//---Test all callback hours when logged Monday working day buty SLA result is today but then passes end of day or is 24 or 48 hour
logTime = DateTime.newInstance(2015,09,21,15,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,16,59,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,21,17,59,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday Morning here
System.assertEquals(DateTime.newInstance(2015,09,22,08,59,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,09,59,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,10,59,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,15,59,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,23,15,59,0), SLAResult);
//---Test all callback hours when logged Monday after working day
logTime = DateTime.newInstance(2015,09,21,18,01,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday starting from start time e.g. 8:00 here so first hour = 9
System.assertEquals(DateTime.newInstance(2015,09,22,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday Morning here
System.assertEquals(DateTime.newInstance(2015,09,22,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,22,13,0,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Wednesday start time
System.assertEquals(DateTime.newInstance(2015,09,23,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,24,8,0,0), SLAResult);
//*******************************************************
//---Test all callback hours when logged pre start Friday
logTime = DateTime.newInstance(2015,09,25,04,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,13,0,0), SLAResult);
callBack = 24;
//Should be next Monday (weekend)
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,29,8,0,0), SLAResult);
//---Test all callback hours when logged within Friday working day and SLA result doesnot exceed working day or is 24 or 48 hour
logTime = DateTime.newInstance(2015,09,25,10,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,11,59,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,12,59,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,13,59,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,14,59,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,15,59,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,10,59,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,29,10,59,0), SLAResult);
//---Test all callback hours when logged Friday working day buty SLA result is today but then passes end of day or is 24 or 48 hour
logTime = DateTime.newInstance(2015,09,25,15,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,16,59,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,25,17,59,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Monday Morning here
System.assertEquals(DateTime.newInstance(2015,09,28,08,59,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,09,59,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,10,59,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,15,59,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,29,15,59,0), SLAResult);
//---Test all callback hours when logged Fri after working day
logTime = DateTime.newInstance(2015,09,25,18,01,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Monday starting from start time e.g. 8:00 here so first hour = 9
System.assertEquals(DateTime.newInstance(2015,09,28,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday Morning here
System.assertEquals(DateTime.newInstance(2015,09,28,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,13,0,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday start time
System.assertEquals(DateTime.newInstance(2015,09,29,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,30,8,0,0), SLAResult);
//Test login Saturday*********************************
//---Test all callback hours when logged Saturday
logTime = DateTime.newInstance(2015,09,26,04,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,28,13,0,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,29,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,30,8,0,0), SLAResult);
//Test login Saturday*********************************
//---Test all callback hours when logged Bak Holiday
logTime = DateTime.newInstance(2015,08,31,04,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,13,0,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,02,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,03,8,0,0), SLAResult);
//*******************************************************
//---Test all callback hours when logged pre start Friday and Bank Holiday Monday follows
logTime = DateTime.newInstance(2015,08,28,04,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,13,0,0), SLAResult);
callBack = 24;
//Should be next Tuesday (weekend & BH)
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,02,8,0,0), SLAResult);
//---Test all callback hours when logged within Friday working day and SLA result doesnot exceed working day or is 24 or 48 hour
logTime = DateTime.newInstance(2015,08,28,10,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,11,59,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,12,59,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,13,59,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,14,59,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,15,59,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,10,59,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,02,10,59,0), SLAResult);
//---Test all callback hours when logged Friday & BH Monday working day buty SLA result is today but then passes end of day or is 24 or 48 hour
/* Commented out as will fail next year
logTime = DateTime.newInstance(2015,08,28,15,59,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,16,59,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,08,28,17,59,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Monday Morning here
System.assertEquals(DateTime.newInstance(2015,09,01,08,59,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,09,59,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,10,59,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,15,59,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,02,15,59,0), SLAResult);
*/
//---Test all callback hours when logged Fri after working day
logTime = DateTime.newInstance(2015,08,28,18,01,00);
callBack = 1;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday (BH Monday) starting from start time e.g. 8:00 here so first hour = 9
System.assertEquals(DateTime.newInstance(2015,09,01,9,0,0), SLAResult);
callBack = 2;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,10,0,0), SLAResult);
callBack = 3;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday Morning here
System.assertEquals(DateTime.newInstance(2015,09,01,11,0,0), SLAResult);
callBack = 4;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,12,0,0), SLAResult);
callBack = 5;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,01,13,0,0), SLAResult);
callBack = 24;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
//Should go to Tuesday start time
System.assertEquals(DateTime.newInstance(2015,09,02,8,0,0), SLAResult);
callBack = 48;
SLAResult = CaseTriggerHandler.getSLATime(callBack,logtime);
System.assertEquals(DateTime.newInstance(2015,09,03,8,0,0), SLAResult);
}
}<file_sep>/classes/uksvcsTntGetItemsForConsignmentService.cls
//Generated by wsdl2apex
public class uksvcsTntGetItemsForConsignmentService {
public class getItemsForConsignmentPort {
public String endpoint_x = TNT_Integration__c.getInstance().Consignment_Items_Service__c;
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://express.tnt.com/service/schema/getitmsforcon/v1', 'uksvcsTntGetItemsForConsignment', 'http://express.tnt.com/general/schema/enums/generic/v1', 'ukTntComGenericEnums', 'http://express.tnt.com/service/wsdl/getitmsforcon/v1', 'uksvcsTntGetItemsForConsignmentService', 'http://express.tnt.com/general/schema/tnterror/v1', 'uksvcsTntComError', 'http://express.tnt.com/general/schema/payloadheader/v1', 'uksvcsTntComGenericPayloadHeader', 'http://express.tnt.com/general/schema/objects/generic/v1', 'uksvcsTntComGenericObjects'};
public uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType getItemsForConsignment(uksvcsTntComGenericPayloadHeader.payloadHeader hdr,uksvcsTntGetItemsForConsignment.ItemRequest_MasterType itm) {
uksvcsTntGetItemsForConsignment.RequestMessage_MasterType request_x = new uksvcsTntGetItemsForConsignment.RequestMessage_MasterType();
request_x.hdr = hdr;
request_x.itm = itm;
uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType response_x;
Map<String, uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType> response_map_x = new Map<String, uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'get',
'http://express.tnt.com/service/schema/getitmsforcon/v1',
'getItemsForConsignmentRequest',
'http://express.tnt.com/service/schema/getitmsforcon/v1',
'getItemsForConsignmentResponse',
'uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType'}
);
response_x = response_map_x.get('response_x');
return response_x;
}
}
}<file_sep>/classes/uksvcsTntComSearchConsignmentServiceMock.cls
/**
* File Name : uksvcsTntComSearchConsignmentServiceMock.cls
* Description : Mock class to test Search service
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 09/09/2014 <NAME> Initial version, TNT-546
*/
@isTest
global class uksvcsTntComSearchConsignmentServiceMock implements WebServiceMock{
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
uksvcsTntComSearchConsignment.ResponseMessage_MasterType respElement = new uksvcsTntComSearchConsignment.ResponseMessage_MasterType();
respElement.consearch = new uksvcsTntComSearchConsignment.ConsignmentResponse_ContainerType();
respElement.consearch.con = new List<uksvcsTntComSearchConsignment.Consignment_MasterType>();
uksvcsTntComSearchConsignment.Consignment_MasterType con = new uksvcsTntComSearchConsignment.Consignment_MasterType();
con.unqConNum = '111';
con.delAddr = new uksvcsTntComSearchConsignment.ShortAddress_MasterType();
con.pod = new uksvcsTntComSearchConsignment.ShortProofOfDelivery_MasterType();
con.curConSts = new uksvcsTntComSearchConsignment.CurrentConsignmentStatus_MasterType();
respElement.consearch.con.add(con);
response.put('response_x', respElement);
}
}<file_sep>/classes/TNTUtility.cls
public class TNTUtility {
public static void updateCallSummaryOwner(NVMStatsSF__NVM_Call_Summary__c[] callSummaries) {
for (NVMStatsSF__NVM_Call_Summary__c callSummary: callSummaries) {
if (callSummary.NVMStatsSF__Agent__c != null) {
callSummary.OwnerId = callSummary.NVMStatsSF__Agent__c;
}
}
}
public static void updateAgentSummaryOwner(NVMStatsSF__NVM_Agent_Summary__c[] agentSummaries) {
for (NVMStatsSF__NVM_Agent_Summary__c agentSum: agentSummaries) {
if (agentSum.NVMStatsSF__Agent__c != null) {
agentSum.OwnerId = agentSum.NVMStatsSF__Agent__c;
}
}
}
}<file_sep>/classes/BookingHistory_DataDeletion.cls
global class BookingHistory_DataDeletion implements Schedulable
{
global void execute(SchedulableContext sc)
{
BatchDelete BDel = new BatchDelete();
Integer no = 0;
DataRetentionSettings__c myCS1 = DataRetentionSettings__c.getInstance('DayNumber');
if (myCS1 != null)
{
System.debug(logginglevel.ERROR, '££££££££££££££ no is' + myCS1.BookingHistoryRetentionPeriod__c);
no = myCS1.BookingHistoryRetentionPeriod__c.intValue();
}
else
{
no = 180;
}
datetime ddd = SYSTEM.NOW().addDays(-no);
System.debug(logginglevel.ERROR, '££££££££££££££ ddd is' + ddd );
// BDel.query = 'SELECT Id FROM Booking_History__c where Movement_Date_Time__c < 2015-04-22T13:31:00.00Z';
BDel.query = 'SELECT Id FROM Booking_History__c where Movement_Date_Time__c < '+ddd.format('yyyy-MM-dd')+'T'+ ddd.format('HH:mm')+':00.000Z';
ID batchprocessid = Database.executeBatch(BDel);
System.debug('************************** Returned batch process ID: ' + batchProcessId);
}
}<file_sep>/classes/TaskTriggerHandlerTest.cls
/**
* File Name : TaskTriggerHandlerTest.cls
* Description : test for Task trigger handler
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 13/04/2015 <NAME> Initial version (TNT-2697)
*
*
*/
@isTest
private class TaskTriggerHandlerTest {
static testMethod void coverTaskTrigger(){
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.Id, con.Id, d.Id);
c.Call_me_back__c = '1 hour';
insert c;
Task t = [SELECT Status FROM Task WHERE Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK LIMIT 1];
Test.startTest();
t.Status = ConstantUtil.PLVAL_TASK_STATUS_COMPLETED;
update t;
Test.stopTest();
t = [SELECT SLA_Minutes_in_Business_Hours__c FROM Task WHERE Subject = : ConstantUtil.TASK_SUBJECT_CALL_CLIENT_BACK LIMIT 1];
system.assertNotEquals(null, t.SLA_Minutes_in_Business_Hours__c);
}
}<file_sep>/classes/CaseBasedRoutingWebServiceTest.cls
@isTest
public class CaseBasedRoutingWebServiceTest
{
static testMethod void testCaseBasedRoutingServiceWithUserWithAvayaID()
{
//Create USER with Avaya ID
User u = TestUtil.createAgentUser();
u.Avaya_ID__c = '1234';
insert u;
//Create A Case
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.id,con.id,d.id);
c.OwnerId = u.id;
insert c;
Case testCase = [Select CaseNumber from Case where id =: c.Id];
system.assertEquals('1234',CaseBasedRoutingWebService.getCaseOwnerAvayaID(testCase.CaseNumber));
}
static testMethod void testCaseBasedRoutingServiceWithUserWithOUTAvayaID()
{
//Create USER with Avaya ID
User u = TestUtil.createAgentUser();
insert u;
//Create A Case
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.id,con.id,d.id);
c.OwnerId = u.id;
insert c;
Case testCase = [Select CaseNumber from Case where id =: c.Id];
system.assertEquals('Not Found',CaseBasedRoutingWebService.getCaseOwnerAvayaID(testCase.CaseNumber));
}
static testMethod void testCaseBasedRoutingServiceWithQueueOwner()
{
//Create Queue
Group queue = [Select Id from Group where Name = 'Atherstone MAD 1' limit 1];
//Create A Case
Account a = TestUtil.createAccountClient();
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Case c = TestUtil.createCase(a.id,con.id,d.id);
c.OwnerId = queue.id;
insert c;
Case testCase = [Select CaseNumber from Case where id =: c.Id];
system.assertEquals('Not Found',CaseBasedRoutingWebService.getCaseOwnerAvayaID(testCase.CaseNumber));
}
//Test Exception case numbers
static testMethod void testCaseBasedRoutingServiceWithWhiteSpaceCaseNumber()
{
system.assertEquals('ERROR:INVALID CASE NUMBER',CaseBasedRoutingWebService.getCaseOwnerAvayaID(' '));
}
static testMethod void testCaseBasedRoutingServiceWithTooLong()
{
system.assertEquals('ERROR:INVALID CASE NUMBER',CaseBasedRoutingWebService.getCaseOwnerAvayaID('123456789'));
}
static testMethod void testCaseBasedRoutingServiceWithNonNumber()
{
system.assertEquals('ERROR:INVALID CASE NUMBER',CaseBasedRoutingWebService.getCaseOwnerAvayaID('00A123'));
}
}<file_sep>/classes/BookingTriggerHandlerTest.cls
/**
* File Name : BookingTriggerHandlerTest.cls
* Description : Test class for BookingTriggerHandler
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 24/07/2014 <NAME> Initial version
* 0.2 29/08/2014 <NAME> add test for generateBookingId() method TNT-1414
*
*/
@isTest
private class BookingTriggerHandlerTest {
/* tested code is depricated 9 Apr 2015.
static testMethod void testBookingRejection() {
Account a = TestUtil.createAccountClient();
a.Auto_Case_Creation__c = true;
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
Test.startTest();
bo.Booking_Rejected_by_Depot__c = true;
bo.Reason_for_Depot_Rejection__c = 'reason';
update bo;
Test.stopTest();
List<Case> cases = [SELECT Subject, Booking__c, AccountId, ContactId, Description, Origin, Status, Type, Priority FROM Case];
system.assertEquals(1, cases.size());
system.assertEquals(bo.Id, cases[0].Booking__c);
system.assertEquals(bo.Account__c, cases[0].AccountId);
system.assertEquals(bo.Order_Contact__c, cases[0].ContactId);
system.assertEquals(bo.Reason_for_Depot_Rejection__c, cases[0].Description);
}
static testMethod void testBookingRejectedUpdate() {
Account a = TestUtil.createAccountClient();
a.Auto_Case_Creation__c = true;
insert a;
Account d = TestUtil.createAccountDepot();
insert d;
Contact con = TestUtil.createContact(a.Id);
insert con;
Booking__c bo = new Booking__c();
bo.Name = 'test book';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
bo.Booking_Rejected_by_Depot__c = true;
bo.Reason_for_Depot_Rejection__c = 'reason';
bo.Collection_Depot__c = d.Id;
update bo;
Test.startTest();
update bo;
Test.stopTest();
List<Case> cases = [SELECT Subject FROM Case];
system.assertEquals(1, cases.size());
}*/
static testMethod void testUpdateAccountLob()
{
Account a1 = TestUtil.createAccountClient();
a1.Name += '1';
Account a2 = TestUtil.createAccountClient();
a2.Name += '2';
insert new List<Account>{a1,a2};
Contact con1 = TestUtil.createContact(a1.Id);
Contact con2 = TestUtil.createContact(a2.Id);
con2.LastName += 'Second';
con2.Email += '123';
insert new List<Contact>{con1,con2};
Line_Of_Business__c lob1 = new Line_Of_Business__c();
lob1.Name = 'LOB1';
lob1.Line_Of_Business_Reference__c = '10';
Line_Of_Business__c lob2 = new Line_Of_Business__c();
lob2.Name = 'LOB2';
lob2.Line_Of_Business_Reference__c = '20';
insert new List<Line_Of_Business__c>{lob1,lob2};
insert new List<Account_LOB__c>{new Account_LOB__c(Account__c = a1.Id, Line_Of_Business__c = lob1.id),
new Account_LOB__c(Account__c = a1.Id, Line_Of_Business__c = lob2.id),
new Account_LOB__c(Account__c = a2.Id, Line_Of_Business__c = lob2.id)};
Booking__c bo1 = new Booking__c();
bo1.Name = '<NAME>';
bo1.Account__c = a1.Id;
bo1.Order_Contact__c = con1.Id;
bo1.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
bo1.Line_Of_Business__c = lob1.id;
bo1.Commodity__c = 'SACK';
Booking__c bo2 = new Booking__c();
bo2.Name = '<NAME>';
bo2.Account__c = a2.Id;
bo2.Order_Contact__c = con2.Id;
bo2.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
bo2.Line_Of_Business__c = lob2.id;
bo2.Commodity__c = 'SACK';
insert new List<Booking__c>{bo1,bo2};
Booking__c bo1Old = bo1.clone(true,true);
Booking__c bo2Old = bo2.clone(true,true);
bo1.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED;
bo2.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED;
Date refDate = Date.today();
Test.startTest();
BookingTriggerHandler.updateAccountLob(new List<Booking__c>{bo1,bo2}, new Map<Id,Booking__c>{bo1.Id => bo1Old,bo2.Id => bo2Old});
Test.stopTest();
List<Account_LOB__c> als = [select Last_Collection_Date__c from Account_LOB__c
order by Account__r.Name asc, Line_Of_Business__r.Name asc]; // order important!!!
system.assertEquals(3,als.size());
system.assert(als.get(0).Last_Collection_Date__c >= refDate); // a1, lob1 - updated
system.assert(als.get(1).Last_Collection_Date__c == null); // a1, lob2 - not updated
system.assert(als.get(2).Last_Collection_Date__c >= refDate); // a2, lob2 - updated
}
static testMethod void testBookingIdCreation() {
Integer stDepot = Integer.valueOf(Label.Salesforce_Start_Depot);
Booking_Id_Settings__c bis = new Booking_Id_Settings__c();
bis.Name = 'Default';
bis.Prefix__c = stDepot;
bis.Current_Number__c = 9999999;
insert bis;
Account a = TestUtil.createAccountClient();
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
bo = [SELECT Booking_Id__c FROM Booking__c WHERE Id = : bo.Id];
system.assertEquals(Label.Salesforce_Start_Depot+'9999999', bo.Booking_Id__c);
bis = [SELECT Prefix__c, Current_Number__c FROM Booking_Id_Settings__c WHERE Name = 'Default'];
system.assertEquals(stDepot+1, bis.Prefix__c);
system.assertEquals(0, bis.Current_Number__c);
}
static testMethod void testUpdateLastUsedOnAccountAddress()
{
Account a = TestUtil.createAccountClient();
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Account_Address__c aaCol = TestUtil.createAccountAddress(a.Id,null);
aaCol.Default__c = true;
Account_Address__c aaDel = TestUtil.createAccountAddress(a.Id,null);
aaDel.Postcode__c = 'N1 9NL';
insert new List<Account_Address__c>{aaCol,aaDel};
Account depot = TestUtil.createAccountDepot();
insert depot;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Collection_Contact__c = con.Id;
bo.Coll_Account_Address__c = aaCol.id;
bo.Del_Account_Address__c = aaDel.id;
bo.Collection_Depot__c = depot.id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
aaCol.Last_Used__c = null;
aaDel.Last_Used__c = null;
update new List<Account_Address__c>{aaCol,aaDel};
List<Booking__c> newBookList = new List<Booking__c>{bo.clone(true,true)};
bo.Coll_Account_Address__c = null;
bo.Del_Account_Address__c = null;
Map<Id,Booking__c> oldBookMap = new Map<Id,Booking__c>{bo.id => bo};
Test.startTest();
BookingTriggerHandler.updateLastUsedOnAccountAddress(newBookList,oldBookMap);
Test.stopTest();
system.assertEquals(2,[select count() from Account_Address__c where Last_Used__c != null]);
}
static testMethod void testBookingRejectionToCS()
{
//Added by DH 25/01/2016
List<RejectionCaseLOBs__c> rjcs = new List<RejectionCaseLOBs__c>();
rjcs.add(new RejectionCaseLOBs__c(Name = '010'));
rjcs.add(new RejectionCaseLOBs__c(Name = '251'));
rjcs.add(new RejectionCaseLOBs__c(Name = '190'));
rjcs.add(new RejectionCaseLOBs__c(Name = '240'));
rjcs.add(new RejectionCaseLOBs__c(Name = '160'));
rjcs.add(new RejectionCaseLOBs__c(Name = '260'));
rjcs.add(new RejectionCaseLOBs__c(Name = '280'));
rjcs.add(new RejectionCaseLOBs__c(Name = '370'));
insert rjcs;
//Create LOBs ***********
Line_Of_Business__c lobForCase = new Line_Of_Business__c(Line_of_Business_Reference__c = '010');//Will do rejection case creation
insert lobForCase;
Line_Of_Business__c lobForWithoutCase = new Line_Of_Business__c(Line_of_Business_Reference__c = '390');//Will NOT do rejection case creation
insert lobForWithoutCase;
//***********************
Account a = TestUtil.createAccountClient();
a.Auto_Case_Creation__c = true;
a.Collection_Queue__c = 'Lount_Admin_1';
insert a;
Account depot = TestUtil.createAccountDepot();
insert depot;
Contact con = TestUtil.createContact(a.Id);
insert con;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
bo.Collection_Depot__c = depot.Id;
Account b = TestUtil.createAccountClient();
b.Auto_Case_Creation__c = true;
b.Collection_Queue__c = 'Lount_Admin_1';
insert b;
Contact con2 = TestUtil.createContact(b.Id);
insert con2;
Booking__c boLOBNoCase = new Booking__c();
boLOBNoCase.Name = '<NAME>';
boLOBNoCase.Account__c = b.Id;
boLOBNoCase.Order_Contact__c = con2.Id;
boLOBNoCase.Commodity__c = 'SACK';
boLOBNoCase.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
boLOBNoCase.Collection_Depot__c = depot.Id;
Account c = TestUtil.createAccountClient();
c.Auto_Case_Creation__c = false;//Should not create a case even if LOB is in custom list
c.Major_Account__c = true;
c.Collection_Queue__c = 'Lount_Admin_1';
insert c;
Contact con3 = TestUtil.createContact(c.Id);
insert con3;
Booking__c boNotAutoCase = new Booking__c();
boNotAutoCase.Name = 'test book3';
boNotAutoCase.Account__c = c.Id;
boNotAutoCase.Order_Contact__c = con3.Id;
boNotAutoCase.Commodity__c = 'SACK';
boNotAutoCase.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
boNotAutoCase.Collection_Depot__c = depot.Id;
Booking__c boNoAccount = new Booking__c();
boNoAccount.Name = '<NAME>';
//boNotAutoCase.Account__c = c.Id;
//boNotAutoCase.Order_Contact__c = con3.Id;
boNoAccount.Commodity__c = 'SACK';
boNoAccount.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
boNoAccount.Collection_Depot__c = depot.Id;
bo.Line_of_Business__c = lobForCase.id;
boLOBNoCase.Line_of_Business__c = lobForWithoutCase.id;
boNotAutoCase.Line_of_Business__c = lobForCase.id;//In list but should be created as AutoCase not selected
insert bo;
insert boLOBNoCase;
insert boNotAutoCase;
insert boNoAccount;
system.assert(ConstantUtil.AutoRejectionCaseLOBList.size() == 8);
Set<string> testLOB = ConstantUtil.AutoRejectionCaseLOBList;
for(string s:testLOB)
{
system.debug('**Code: ' + s);
}
Test.startTest();
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_REJECTED_TO_CS;
boLOBNoCase.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_REJECTED_TO_CS;
boNotAutoCase.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_REJECTED_TO_CS;
boNoAccount.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_REJECTED_TO_CS;
update bo;
update boLOBNoCase;
update boNotAutoCase;
update boNoAccount;
Test.stopTest();
//Only 1 Case should be created for the bookings whos LOB code matches the custom list RejectionCaseLOBs and has AutoCase selected on Account
List<Case> cases = [SELECT Subject, Booking__c, AccountId, ContactId, Description, Origin, Status, Type, Priority, OwnerId FROM Case order by createdDate];
//Assert that only 2 cases created out of the 4 bookings and that they are the expected as ordered by creation datetime
system.assertEquals(2, cases.size());
system.assertEquals(bo.Id, cases[0].Booking__c);
system.assertEquals(bo.Account__c, cases[0].AccountId);
system.assertEquals(bo.Order_Contact__c, cases[0].ContactId);
system.assertEquals(ConstantUtil.PLVAL_CASE_ORIGIN_SYSTEM, cases[0].Origin);
system.assertEquals(ConstantUtil.LOUNT_ADMIN_1_QUEUE_ID, cases[0].OwnerId);
system.assertEquals(boNoAccount.Id, cases[1].Booking__c);
system.assertEquals(ConstantUtil.PLVAL_CASE_ORIGIN_SYSTEM, cases[1].Origin);
system.debug(cases[1].OwnerId);
Group g = [Select id from Group where Name = 'Unassigned' limit 1];
system.assertEquals(g.id , cases[1].OwnerId);
}
static testMethod void testBookingLocking() {
Account a = TestUtil.createAccountClient();
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
insert bo;
bo = [SELECT Id, RecordType.Name FROM Booking__c WHERE Id = :bo.Id];
System.assertEquals(ConstantUtil.PLVAL_BOOKING_RECORD_TYPE_NEW,bo.RecordType.Name);
Test.startTest();
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED;
update bo;
bo = [SELECT Id, RecordType.Name FROM Booking__c WHERE Id = :bo.Id];
System.assertEquals(ConstantUtil.PLVAL_BOOKING_RECORD_TYPE_BLOCKED,bo.RecordType.Name);
Test.stopTest();
}
static testMethod void testBookingUnlocking() {
Account a = TestUtil.createAccountClient();
insert a;
Contact con = TestUtil.createContact(a.Id);
insert con;
Booking__c bo = new Booking__c();
bo.Name = '<NAME>';
bo.Account__c = a.Id;
bo.Order_Contact__c = con.Id;
bo.Commodity__c = 'SACK';
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_COLLECTED;
insert bo;
bo = [SELECT Id, RecordType.Name FROM Booking__c WHERE Id = :bo.Id];
System.assertEquals(ConstantUtil.PLVAL_BOOKING_RECORD_TYPE_BLOCKED,bo.RecordType.Name);
Test.startTest();
bo.Status__c = ConstantUtil.PLVAL_BOOKING_STATUS_CONFIRMED;
update bo;
bo = [SELECT Id, RecordType.Name FROM Booking__c WHERE Id = :bo.Id];
System.assertEquals(ConstantUtil.PLVAL_BOOKING_RECORD_TYPE_NEW,bo.RecordType.Name);
Test.stopTest();
}
}<file_sep>/classes/TaskTriggerHandler.cls
/**
* File Name : TaskTriggerHandler.cls
* Description : methods called from Task trigger
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 13/04/2015 <NAME> Initial version (TNT-2697)
*
*/
public with sharing class TaskTriggerHandler {
// HANDLERS
public static void onBeforeInsertHandler(List<Task> triggerNew)
{
calculateSLAInBussinessHours(triggerNew);
}
public static void onBeforeUpdateHandler(List<Task> triggerNew)
{
calculateSLAInBussinessHours(triggerNew);
}
// METHODS
private static void calculateSLAInBussinessHours(List<Task> newTasks){
for(Task t : newTasks){
// When should we calculate activity age
if((t.Action_Subtype__c == ConstantUtil.PLVAL_TASK_ACTION_SUBTYPE_FIRST_CUSTOMER_CONTACT
|| t.Action_Subtype__c == ConstantUtil.PLVAL_TASK_ACTION_SUBTYPE_CUSTOMER_CONTACT)
&& t.SLA_Deadline__c != null && t.End_Time__c != null){
t.SLA_Minutes_in_Business_Hours__c = TimeUtil.calculateMinutesInBusinessHours(t.Start_Time__c, t.End_Time__c);
}
}
}
}<file_sep>/classes/uksvcsTntGetItemsForConsignmentSvcMock.cls
/**
* File Name : uksvcsTntGetItemsForConsignmentSvcMock.cls
* Description : Mock class to test uksvcsTntGetItemsForConsignmentService service
*
* Modification Log
* ============================================================================
* Ver Date Author Modification
* --- ---------- -------------- --------------------------
* 0.1 27/08/2014 <NAME> Initial version, TNT-547
* 0.2 03/09/2014 <NAME> Updated for new WSDL
*/
@isTest
global class uksvcsTntGetItemsForConsignmentSvcMock implements WebServiceMock{
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType respElement = new uksvcsTntGetItemsForConsignment.ResponseMessage_MasterType();
respElement.itms = new uksvcsTntGetItemsForConsignment.ItemsResponse_MasterType();
respElement.itms.itm = new List<uksvcsTntGetItemsForConsignment.Item_MasterType>();
uksvcsTntGetItemsForConsignment.Item_MasterType itm = new uksvcsTntGetItemsForConsignment.Item_MasterType();
itm.itmNum = '1111';
itm.itmstrck = new uksvcsTntGetItemsForConsignment.ItemsTracking_MasterType();
itm.itmstrck.itmtrck = new List<uksvcsTntGetItemsForConsignment.ItemTracking_MasterType>();
uksvcsTntGetItemsForConsignment.ItemTracking_MasterType itTr = new uksvcsTntGetItemsForConsignment.ItemTracking_MasterType();
itTr.locCd = '123';
itTr.scnDtTm = DateTime.now();
itm.itmstrck.itmtrck.add(itTr);
respElement.itms.itm.add(itm);
response.put('response_x', respElement);
}
}
|
1ddad0aa0dcf29a53da0d7344fbe68e1c6fffbc9
|
[
"XML",
"Markdown",
"Apex"
] | 71 |
XML
|
hoppertunity/SimpleFragment
|
2d15e738227a62a9f86cc8cd8a864a4bfe96996c
|
5138628107c6336f28ceb2018224078ee7f7da16
|
refs/heads/master
|
<file_sep># pwgen
[](https://travis-ci.org/davidjpeacock/pwgen)
[](https://goreportcard.com/report/github.com/davidjpeacock/pwgen)
[](https://raw.githubusercontent.com/davidjpeacock/pwgen/master/LICENSE)
Cryptographically secure password generator implemented in Golang.
Supports arbitrary password length, and alpha, numeric, and alphanumeric character sets.
## Installation
```
go get github.com/davidjpeacock/pwgen
```
## Usage
```
Usage of pwgen:
-charset string
Character set: alpha, numeric, alphanumeric, special, qwerty (default "alphanumeric")
-length int
Password length (default 16)
-v Prints pwgen version
```
## Example
```
$ pwgen -length 20 -charset alpha
FPxvdWzfhPAmsCnKSGAd
```
## License
MIT
## Contributing
Pull requests welcome.
<file_sep>// Cryptographically secure password generator.
//
// Copyright (c) 2016 <NAME> - <EMAIL>
package main
import (
"crypto/rand"
"flag"
"fmt"
)
const version = "0.0.3"
var length = flag.Int("length", 16, "Password length")
var charset = flag.String("charset", "alphanumeric", "Character set: alpha, numeric, alphanumeric, special, qwerty")
var v = flag.Bool("v", false, "Prints pwgen version")
func main() {
flag.Parse()
if *v {
fmt.Println("pwgen version: " + version)
return
}
charSetOption := characterSets(*charset)
fmt.Println(generator(*length, charSetOption))
}
func characterSets(charSetOption string) string {
var chars string
switch {
case charSetOption == "alpha":
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
case charSetOption == "numeric":
chars = "0123456789"
case charSetOption == "alphanumeric":
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
case charSetOption == "special":
chars = "~`!@#$%^&*()-=_+{}[];':\"|<>,./?\\ "
case charSetOption == "qwerty":
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()-=_+{}[];':\"|<>,./?\\ "
default:
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
}
return string(chars)
}
func generator(length int, charSet string) string {
password := make([]byte, length)
rand.Read(password)
for k, v := range password {
password[k] = charSet[v%byte(len(charSet))]
}
return string(password)
}
|
49d0a1b91a1c301bf1e746e2484e01a248da45fa
|
[
"Markdown",
"Go"
] | 2 |
Markdown
|
davidjpeacock/pwgen
|
336cae2ef4055a28a08e6ccccaf3b415047c1190
|
2472ccfbbeb52971948ed4f9bcf0cbfdb11b5f22
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TowerOfHanoi
{
public class Peg
{
public bool[] _pegArray;
public string _pegName;
public Peg(int n, string pegName)
{
_pegArray = new bool[n];
_pegName = pegName;
}
public override string ToString()
{
return _pegName;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TowerOfHanoi
{
class Program
{
static void Main(string[] args)
{
HanoiInstructions x = new HanoiInstructions(3, "Dog", "Cat", "Cow");
foreach (var instruction in x.InstructionList)
{
Console.WriteLine($"{instruction.Disk} is transferred from {instruction.StartPeg} to {instruction.EndPeg}");
}
Console.Read();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TowerOfHanoi
{
public class HanoiInstructions
{
public Peg _leftPeg;
public Peg _centerPeg;
public Peg _rightPeg;
public List<Instruction> InstructionList = new List<Instruction>();
public HanoiInstructions(int n, string leftPegName, string centerPegName, string rightPegName)
{
_leftPeg = new Peg(n, leftPegName);
_centerPeg = new Peg(n, centerPegName);
_rightPeg = new Peg(n, rightPegName);
GetInstructions(n, _leftPeg, _centerPeg, _rightPeg);
}
public void GetInstructions(int disk, Peg startPeg, Peg auxPeg, Peg endPeg)
{
if (disk == 1)
{
InstructionList.Add(new Instruction(disk, startPeg, endPeg));
}
else
{
GetInstructions(disk - 1, startPeg, endPeg, auxPeg);
InstructionList.Add(new Instruction(disk, startPeg, endPeg));
GetInstructions(disk - 1, auxPeg, startPeg, endPeg);
}
}
}
}
<file_sep>using System;
namespace TowerOfHanoi
{
public class Instruction
{
public int Disk { get; set; }
public Peg StartPeg { get; set; }
public Peg EndPeg { get; set; }
public Instruction(int disk, Peg A, Peg B)
{
Disk = disk;
StartPeg = A;
EndPeg = B;
StartPeg._pegArray[Disk-1] = false;
EndPeg._pegArray[Disk-1] = true;
}
public override string ToString()
{
return $"Disk {Disk} transferred from {StartPeg} to {EndPeg}";
}
}
}
|
1e4cd04b7589edf54678654f80d6a23e56a985bc
|
[
"C#"
] | 4 |
C#
|
gembancud/TowerOfHanoi
|
4a4b9902965f961cbe6a8098a2fbf2cbc817a745
|
c181e27307d5ed28328ad40cba1d6c25c5ee76ef
|
refs/heads/master
|
<repo_name>Totulik/Bip38Sign<file_sep>/README.md
# Bip38Sign
Utility that allows you to sign a message (to prove ownership) of a bip38 encrypted paper wallet
Example usage:
bip38sign.exe 6PnTfmUX2kjDxK2toNJ9WNtybhHvhHEFDLdZCpK9jBy4cWcnUWQ5AQUYJE "<PASSWORD> the passphrase" "this is the message to sign"
Will result in the following output:
Public key:
<KEY>
The signature:
H0BKj3lyM3LJX1PC3MAocJEKQF/zyCAGCOLaLcQ523XHcJjBjH8WNEIiOTcm5bJbPKAfEmhAO5cAdJI7sUqhCtE=
Signature validity: True
<file_sep>/Bip38Sign/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NBitcoin;
namespace Bip38Sign
{
class Program
{
static void Main(string[] args)
{
if(args.Length!=3)
{
Console.WriteLine("Usage: Bip38Sign bip38privatekey passphrase <PASSWORD>");
return;
}
var encryptedPrivateKey = args[0];
var password = args[1];
var messageToSign = args[2];
var encryptedSecret = BitcoinEncryptedSecret.Create(encryptedPrivateKey, Network.Main);
var secret = encryptedSecret.GetSecret(password);
// uncomment the following line to show the private key:
// Console.WriteLine($"Private key (wif):\r\n{secret.ToWif()}");
Console.WriteLine($"Public key:\r\n{secret.PubKey.GetAddress(Network.Main)}");
string signature = secret.PrivateKey.SignMessage(messageToSign);
Console.WriteLine($"The signature:\r\n{signature}");
Console.WriteLine($"Signature validity: {secret.PubKey.VerifyMessage(messageToSign, signature)}");
}
}
}
|
a965a5745919b105b4f594b32dd52311d61debad
|
[
"C#",
"Markdown"
] | 2 |
C#
|
Totulik/Bip38Sign
|
ebde6adadc2c78b6282e316a44834d2176dd088e
|
0c8120e3838d1a424b4e2b87f79e95d62f5fa497
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.